add generics to raw map/lists
refactor accessors in XmlOptions
convert for to for-each loops

git-svn-id: https://svn.apache.org/repos/asf/xmlbeans/trunk@1881284 13f79535-47bb-0310-9956-ffa450edef68
diff --git a/src/main/java/org/apache/xmlbeans/SchemaCodePrinter.java b/src/main/java/org/apache/xmlbeans/SchemaCodePrinter.java
index 8b65366..67821e7 100755
--- a/src/main/java/org/apache/xmlbeans/SchemaCodePrinter.java
+++ b/src/main/java/org/apache/xmlbeans/SchemaCodePrinter.java
@@ -15,26 +15,17 @@
 
 package org.apache.xmlbeans;
 
-import java.io.Writer;
 import java.io.IOException;
+import java.io.Writer;
 
 /**
  * This class is used to provide alternate implementations of the
  * schema Java code generation.
  */
 
-public interface SchemaCodePrinter
-{
-    public void printTypeImpl(Writer writer, SchemaType sType)
-        throws IOException;
-    
-    public void printType(Writer writer, SchemaType sType)
-        throws IOException;
-    
-    /**
-     * @deprecated Obsoleted by functionality in {@link SchemaTypeSystem.save()}
-     */
-    public void printLoader(Writer writer, SchemaTypeSystem system)
-        throws IOException;
+public interface SchemaCodePrinter {
+    void printTypeImpl(Writer writer, SchemaType sType) throws IOException;
+
+    void printType(Writer writer, SchemaType sType) throws IOException;
 }
 
diff --git a/src/main/java/org/apache/xmlbeans/XmlCursor.java b/src/main/java/org/apache/xmlbeans/XmlCursor.java
index 4bf5461..cb49624 100644
--- a/src/main/java/org/apache/xmlbeans/XmlCursor.java
+++ b/src/main/java/org/apache/xmlbeans/XmlCursor.java
@@ -15,74 +15,74 @@
 
 package org.apache.xmlbeans;
 
+import javax.xml.namespace.QName;
 import java.lang.ref.Reference;
 import java.lang.ref.WeakReference;
 import java.util.Collection;
 import java.util.Map;
-import javax.xml.namespace.QName;
 
 /**
- * Represents a position between two logical tokens in an XML document. 
- * 
+ * Represents a position between two logical tokens in an XML document.
+ * <p>
  * The tokens themselves are not exposed as objects, but their type and properties
  * are discoverable through methods on the cursor.  In particular, the general
  * category of token is represented by a {@link XmlCursor.TokenType TokenType}.<br/><br/>
- * 
- * You use an XmlCursor instance to navigate through and manipulate an XML 
- * instance document. 
- * Once you obtain an XML document, you can create a cursor to represent 
- * a specific place in the XML. Because you can use a cursor with or 
- * without a schema corresponding to the XML, cursors are an ideal 
+ * <p>
+ * You use an XmlCursor instance to navigate through and manipulate an XML
+ * instance document.
+ * Once you obtain an XML document, you can create a cursor to represent
+ * a specific place in the XML. Because you can use a cursor with or
+ * without a schema corresponding to the XML, cursors are an ideal
  * way to handle XML without a schema. You can create a new cursor by
- * calling the {@link XmlTokenSource#newCursor() newCursor} method 
+ * calling the {@link XmlTokenSource#newCursor() newCursor} method
  * exposed by an object representing
- * the XML, whether it was parsed into a strong type compiled from 
+ * the XML, whether it was parsed into a strong type compiled from
  * schema or an {@link XmlObject XmlObject} (as in the no-schema case).<br/><br/>
- * 
+ * <p>
  * With an XmlCursor, you can also: <br/><br/>
- * 
+ *
  * <ul>
  * <li>Execute XQuery and XPath expressions against the XML with the
  * execQuery and selectPath methods.</li>
- * 
+ *
  * <li>Edit and reshape the document by inserting, moving, copying, and removing
  * XML.</li>
- * 
+ *
  * <li>Insert bookmarks that "stick" to the XML at the cursor's
  * position even if the cursor or XML moves.</li>
-
+ *
  * <li>Get and set values for containers (elements and whole documents),
  * attributes, processing instructions, and comments.</li>
  * </ul>
- * 
+ * <p>
  * A cursor moves through XML by moving past tokens. A
- * token represents a category of XML markup, such as the start of an element, 
+ * token represents a category of XML markup, such as the start of an element,
  * its end, an attribute, comment, and so on. XmlCursor methods such as
- * toNextToken, toNextSibling, toParent, and so on move the cursor 
- * among tokens. Each token's category is of a particular <em>type</em>, represented 
+ * toNextToken, toNextSibling, toParent, and so on move the cursor
+ * among tokens. Each token's category is of a particular <em>type</em>, represented
  * by one of the nine types defined by the {@link XmlCursor.TokenType TokenType} class. <br/><br/>
- * 
+ * <p>
  * When you get a new cursor for a whole instance document, the cursor is
  * intially located before the STARTDOC token. This token, which has no analogy
  * in the XML specification, is present in this logical model of XML
  * so that you may distinguish between the document as a whole
  * and the content of the document. Terminating the document is an ENDDOC
- * token. This token is also not part of the XML specification. A cursor 
- * located immediately before this token is at the very end of the document. 
- * It is not possible to position the cursor after the ENDDOC token. 
- * Thus, the STARTDOC and ENDDOC tokens are effectively "bookends" for the content of 
+ * token. This token is also not part of the XML specification. A cursor
+ * located immediately before this token is at the very end of the document.
+ * It is not possible to position the cursor after the ENDDOC token.
+ * Thus, the STARTDOC and ENDDOC tokens are effectively "bookends" for the content of
  * the document.<br/><br/>
- * 
+ * <p>
  * For example, for the following XML, if you were the navigate a cursor
- * through the XML document using toNextToken(), the list of token types that 
+ * through the XML document using toNextToken(), the list of token types that
  * follows represents the token sequence you would encounter. <br/><br/>
- * 
+ *
  * <pre>
  * &lt;sample x='y'&gt;
  *     &lt;value&gt;foo&lt;/value&gt;
  * &lt;/sample&gt;
  * </pre>
- * 
+ * <p>
  * STARTDOC <br/>
  * START (sample) <br/>
  * ATTR (x='y') <br/>
@@ -93,331 +93,435 @@
  * TEXT ("\n") <br/>
  * END (sample)<br/>
  * ENDDOC <br/><br/>
- *
+ * <p>
  * When there are no more tokens available, hasNextToken() returns
  * false and toNextToken() returns the special token type NONE and does not move
  * the cursor.
  * <br/><br/>
- * 
- * The {@link #currentTokenType() currentTokenType()} method 
- * will return the type of the token that is immediately after the cursor. 
- * You can also use a number of convenience methods that test for a particular 
- * token type. These include the methods isStart(), 
- * isStartdoc(), isText(), isAttr(), and so on. Each returns a boolean 
- * value indicating whether the token that follows the cursor is the type 
- * in question. 
+ * <p>
+ * The {@link #currentTokenType() currentTokenType()} method
+ * will return the type of the token that is immediately after the cursor.
+ * You can also use a number of convenience methods that test for a particular
+ * token type. These include the methods isStart(),
+ * isStartdoc(), isText(), isAttr(), and so on. Each returns a boolean
+ * value indicating whether the token that follows the cursor is the type
+ * in question.
  * <br/><br/>
- * 
- * A few other methods determine whether the token is of a kind that may include 
+ * <p>
+ * A few other methods determine whether the token is of a kind that may include
  * multiple token types. The isAnyAttr() method, for example, returns true if
- * the token immediately following the cursor is any kind of attribute, 
+ * the token immediately following the cursor is any kind of attribute,
  * including those of the ATTR token type and xmlns attributes.
  * <br/><br/>
- * 
+ * <p>
  * Legitimate sequences of tokens for an XML document are described
  * by the following Backus-Naur Form (BNF): <br/>
- * 
+ *
  * <pre>
  * &lt;doc&gt; ::= STARTDOC &lt;attributes&gt; &lt;content&gt; ENDDOC
  * &lt;element&gt; ::= START &lt;attributes&gt; &lt;content&gt; END
  * &lt;attributes&gt; ::= ( ATTR | NAMESPACE ) *
  * &lt;content&gt; ::= ( COMMENT | PROCINST | TEXT | &lt;element&gt; ) *
  * </pre>
- * 
- * Note that a legitimate sequence is STARTDOC ENDDOC, the result of 
- * creating a brand new instance of an empty document. Also note that 
+ * <p>
+ * Note that a legitimate sequence is STARTDOC ENDDOC, the result of
+ * creating a brand new instance of an empty document. Also note that
  * attributes may only follow container tokens (STARTDOC or START)
  */
-public interface XmlCursor extends XmlTokenSource
-{
+public interface XmlCursor extends XmlTokenSource {
     /**
      * An enumeration that identifies the type of an XML token.
      */
-    public static final class TokenType
-    {
-        public String toString ( ) { return _name;  }
+    public static final class TokenType {
+        public String toString() {
+            return _name;
+        }
 
         /**
          * Returns one of the INT_ values defined in this class.
          */
-        public int intValue ( ) { return _value; }
-        
-        /** No token.  See {@link #intValue}. */ 
-        public static final int INT_NONE      = 0;
-        /** The start-document token.  See {@link #intValue}. */ 
-        public static final int INT_STARTDOC  = 1;
-        /** The end-document token.  See {@link #intValue}. */ 
-        public static final int INT_ENDDOC    = 2;
-        /** The start-element token.  See {@link #intValue}. */ 
-        public static final int INT_START     = 3;
-        /** The end-element token.  See {@link #intValue}. */ 
-        public static final int INT_END       = 4;
-        /** The text token.  See {@link #intValue}. */ 
-        public static final int INT_TEXT      = 5;
-        /** The attribute token.  See {@link #intValue}. */ 
-        public static final int INT_ATTR      = 6;
-        /** The namespace declaration token.  See {@link #intValue}. */ 
+        public int intValue() {
+            return _value;
+        }
+
+        /**
+         * No token.  See {@link #intValue}.
+         */
+        public static final int INT_NONE = 0;
+        /**
+         * The start-document token.  See {@link #intValue}.
+         */
+        public static final int INT_STARTDOC = 1;
+        /**
+         * The end-document token.  See {@link #intValue}.
+         */
+        public static final int INT_ENDDOC = 2;
+        /**
+         * The start-element token.  See {@link #intValue}.
+         */
+        public static final int INT_START = 3;
+        /**
+         * The end-element token.  See {@link #intValue}.
+         */
+        public static final int INT_END = 4;
+        /**
+         * The text token.  See {@link #intValue}.
+         */
+        public static final int INT_TEXT = 5;
+        /**
+         * The attribute token.  See {@link #intValue}.
+         */
+        public static final int INT_ATTR = 6;
+        /**
+         * The namespace declaration token.  See {@link #intValue}.
+         */
         public static final int INT_NAMESPACE = 7;
-        /** The comment token.  See {@link #intValue}. */ 
-        public static final int INT_COMMENT   = 8;
-        /** The processing instruction token.  See {@link #intValue}. */ 
-        public static final int INT_PROCINST  = 9;
-        
-        /** True if no token. */
-        public boolean isNone      ( ) { return this == NONE;      }
-        /** True if is start-document token. */
-        public boolean isStartdoc  ( ) { return this == STARTDOC;  }
-        /** True if is end-document token. */
-        public boolean isEnddoc    ( ) { return this == ENDDOC;    }
-        /** True if is start-element token. */
-        public boolean isStart     ( ) { return this == START;     }
-        /** True if is end-element token. */
-        public boolean isEnd       ( ) { return this == END;       }
-        /** True if is text token. */
-        public boolean isText      ( ) { return this == TEXT;      }
-        /** True if is attribute token. */
-        public boolean isAttr      ( ) { return this == ATTR;      }
-        /** True if is namespace declaration token. */
-        public boolean isNamespace ( ) { return this == NAMESPACE; }
-        /** True if is comment token. */
-        public boolean isComment   ( ) { return this == COMMENT;   }
-        /** True if is processing instruction token. */
-        public boolean isProcinst  ( ) { return this == PROCINST;  }
+        /**
+         * The comment token.  See {@link #intValue}.
+         */
+        public static final int INT_COMMENT = 8;
+        /**
+         * The processing instruction token.  See {@link #intValue}.
+         */
+        public static final int INT_PROCINST = 9;
 
-        /** True if is start-document or start-element token */
-        public boolean isContainer ( ) { return this == STARTDOC  || this == START; }
-        /** True if is end-document or end-element token */
-        public boolean isFinish    ( ) { return this == ENDDOC    || this == END;   }
-        /** True if is attribute or namespace declaration token */
-        public boolean isAnyAttr   ( ) { return this == NAMESPACE || this == ATTR;  }
+        /**
+         * True if no token.
+         */
+        public boolean isNone() {
+            return this == NONE;
+        }
 
-        /** The singleton no-token type */
-        public static final TokenType NONE      = new TokenType( "NONE",      INT_NONE      );
-        /** The singleton start-document token type */
-        public static final TokenType STARTDOC  = new TokenType( "STARTDOC",  INT_STARTDOC  );
-        /** The singleton start-document token type */
-        public static final TokenType ENDDOC    = new TokenType( "ENDDOC",    INT_ENDDOC    );
-        /** The singleton start-element token type */
-        public static final TokenType START     = new TokenType( "START",     INT_START     );
-        /** The singleton end-element token type */
-        public static final TokenType END       = new TokenType( "END",       INT_END       );
-        /** The singleton text token type */
-        public static final TokenType TEXT      = new TokenType( "TEXT",      INT_TEXT      );
-        /** The singleton attribute token type */
-        public static final TokenType ATTR      = new TokenType( "ATTR",      INT_ATTR      );
-        /** The singleton namespace declaration token type */
-        public static final TokenType NAMESPACE = new TokenType( "NAMESPACE", INT_NAMESPACE );
-        /** The singleton comment token type */
-        public static final TokenType COMMENT   = new TokenType( "COMMENT",   INT_COMMENT   );
-        /** The singleton processing instruction token type */
-        public static final TokenType PROCINST  = new TokenType( "PROCINST",  INT_PROCINST  );
+        /**
+         * True if is start-document token.
+         */
+        public boolean isStartdoc() {
+            return this == STARTDOC;
+        }
 
-        private TokenType ( String name, int value )
-        {
+        /**
+         * True if is end-document token.
+         */
+        public boolean isEnddoc() {
+            return this == ENDDOC;
+        }
+
+        /**
+         * True if is start-element token.
+         */
+        public boolean isStart() {
+            return this == START;
+        }
+
+        /**
+         * True if is end-element token.
+         */
+        public boolean isEnd() {
+            return this == END;
+        }
+
+        /**
+         * True if is text token.
+         */
+        public boolean isText() {
+            return this == TEXT;
+        }
+
+        /**
+         * True if is attribute token.
+         */
+        public boolean isAttr() {
+            return this == ATTR;
+        }
+
+        /**
+         * True if is namespace declaration token.
+         */
+        public boolean isNamespace() {
+            return this == NAMESPACE;
+        }
+
+        /**
+         * True if is comment token.
+         */
+        public boolean isComment() {
+            return this == COMMENT;
+        }
+
+        /**
+         * True if is processing instruction token.
+         */
+        public boolean isProcinst() {
+            return this == PROCINST;
+        }
+
+        /**
+         * True if is start-document or start-element token
+         */
+        public boolean isContainer() {
+            return this == STARTDOC || this == START;
+        }
+
+        /**
+         * True if is end-document or end-element token
+         */
+        public boolean isFinish() {
+            return this == ENDDOC || this == END;
+        }
+
+        /**
+         * True if is attribute or namespace declaration token
+         */
+        public boolean isAnyAttr() {
+            return this == NAMESPACE || this == ATTR;
+        }
+
+        /**
+         * The singleton no-token type
+         */
+        public static final TokenType NONE = new TokenType("NONE", INT_NONE);
+        /**
+         * The singleton start-document token type
+         */
+        public static final TokenType STARTDOC = new TokenType("STARTDOC", INT_STARTDOC);
+        /**
+         * The singleton start-document token type
+         */
+        public static final TokenType ENDDOC = new TokenType("ENDDOC", INT_ENDDOC);
+        /**
+         * The singleton start-element token type
+         */
+        public static final TokenType START = new TokenType("START", INT_START);
+        /**
+         * The singleton end-element token type
+         */
+        public static final TokenType END = new TokenType("END", INT_END);
+        /**
+         * The singleton text token type
+         */
+        public static final TokenType TEXT = new TokenType("TEXT", INT_TEXT);
+        /**
+         * The singleton attribute token type
+         */
+        public static final TokenType ATTR = new TokenType("ATTR", INT_ATTR);
+        /**
+         * The singleton namespace declaration token type
+         */
+        public static final TokenType NAMESPACE = new TokenType("NAMESPACE", INT_NAMESPACE);
+        /**
+         * The singleton comment token type
+         */
+        public static final TokenType COMMENT = new TokenType("COMMENT", INT_COMMENT);
+        /**
+         * The singleton processing instruction token type
+         */
+        public static final TokenType PROCINST = new TokenType("PROCINST", INT_PROCINST);
+
+        private TokenType(String name, int value) {
             _name = name;
             _value = value;
         }
-        
+
         private String _name;
-        private int    _value;
+        private int _value;
     }
 
     /**
      * Deallocates resources needed to manage the cursor, rendering this cursor
-     * inoperable. Because cursors are managed by a mechanism which stores the 
+     * inoperable. Because cursors are managed by a mechanism which stores the
      * XML, simply letting a cursor go out of scope and having the garbage collector
      * attempt to reclaim it may not produce desirable performance.<br/><br/>
-     *
+     * <p>
      * So, explicitly disposing a cursor allows the underlying implementation
      * to release its responsibility of maintaining its position.<br/><br/>
-     *
+     * <p>
      * After a cursor has been disposed, it may not be used again.  It can
      * throw IllegalStateException or NullPointerException if used after
      * disposal.<br/><br/>
      */
 
-    void dispose ( );
-    
+    void dispose();
+
     /**
      * Moves this cursor to the same position as the moveTo cursor.  if the
      * moveTo cursor is in a different document from this cursor, this cursor
      * will not be moved, and false returned.
-     * 
-     * @param  moveTo  The cursor at the location to which this cursor
-     * should be moved.
-     * @return  true if the cursor moved; otherwise, false.
+     *
+     * @param moveTo The cursor at the location to which this cursor
+     *               should be moved.
+     * @return true if the cursor moved; otherwise, false.
      */
 
-    boolean toCursor ( XmlCursor moveTo );
-    
+    boolean toCursor(XmlCursor moveTo);
+
     /**
      * Saves the current location of this cursor on an internal stack of saved
      * positions (independent of selection). This location may be restored
      * later by calling the pop() method.
      */
 
-    void push ( );
+    void push();
 
     /**
      * Restores the cursor location most recently saved with the push() method.
-     * 
-     * @return  true if there was a location to restore; otherwise, false.
+     *
+     * @return true if there was a location to restore; otherwise, false.
      */
 
-    boolean pop ( );
+    boolean pop();
 
     /**
-     * Executes the specified XPath expression against the XML that this 
+     * Executes the specified XPath expression against the XML that this
      * cursor is in.  The cursor's position does not change.  To navigate to the
      * selections, use {@link #hasNextSelection} and {@link #toNextSelection} (similar to
      * {@link java.util.Iterator}).<br/><br/>
-     * 
-     * The root referred to by the expression should be given as 
+     * <p>
+     * The root referred to by the expression should be given as
      * a dot. The following is an example path expression:
      * <pre>
      * cursor.selectPath("./purchase-order/line-item");
      * </pre>
-     *
+     * <p>
      * Note that this method does not support top-level XPath functions.
-     * 
-     * @param  path  The path expression to execute.
-     * @throws  XmlRuntimeException  If the query expression is invalid.
+     *
+     * @param path The path expression to execute.
+     * @throws XmlRuntimeException If the query expression is invalid.
      */
-    void selectPath ( String path );
+    void selectPath(String path);
 
     /**
-     * Executes the specified XPath expression against the XML that this 
+     * Executes the specified XPath expression against the XML that this
      * cursor is in. The cursor's position does not change.  To navigate to the
      * selections, use hasNextSelection and toNextSelection (similar to
      * java.util.Iterator).<br/><br/>
-     * 
-     * The root referred to by the expression should be given as 
+     * <p>
+     * The root referred to by the expression should be given as
      * a dot. The following is an example path expression:
      * <pre>
      * cursor.selectPath("./purchase-order/line-item");
      * </pre>
-     *
+     * <p>
      * Note that this method does not support top-level XPath functions.
-     * 
-     * @param  path  The path expression to execute.
-     * @param  options  Options for the query. For example, you can call 
-     * the {@link XmlOptions#setXqueryCurrentNodeVar(String) XmlOptions.setXqueryCurrentNodeVar(String)}
-     * method to specify a particular name for the query expression 
-     * variable that indicates the context node.
-     * @throws  XmlRuntimeException  If the query expression is invalid.
+     *
+     * @param path    The path expression to execute.
+     * @param options Options for the query. For example, you can call
+     *                the {@link XmlOptions#setXqueryCurrentNodeVar(String) XmlOptions.setXqueryCurrentNodeVar(String)}
+     *                method to specify a particular name for the query expression
+     *                variable that indicates the context node.
+     * @throws XmlRuntimeException If the query expression is invalid.
      */
-    void selectPath ( String path, XmlOptions options );
+    void selectPath(String path, XmlOptions options);
 
     /**
      * Returns whether or not there is a next selection.
-     * 
-     * @return  true if there is a next selection; otherwise, false.
+     *
+     * @return true if there is a next selection; otherwise, false.
      */
 
-    boolean hasNextSelection ( );
-    
+    boolean hasNextSelection();
+
     /**
-     * Moves this cursor to the next location in the selection, 
+     * Moves this cursor to the next location in the selection,
      * if any. See the {@link #selectPath} and {@link #addToSelection} methods.
-     * 
-     * @return  true if the cursor moved; otherwise, false.
+     *
+     * @return true if the cursor moved; otherwise, false.
      */
 
-    boolean toNextSelection ( );
-   
+    boolean toNextSelection();
+
     /**
-     * Moves this cursor to the specified location in the selection. 
+     * Moves this cursor to the specified location in the selection.
      * If i is less than zero or greater than or equal to the selection
      * count, this method returns false.
-     *  
+     * <p>
      * See also the selectPath() and addToSelection() methods.
-     * 
-     * @param  i  The index of the desired location.
-     * @return  true if the cursor was moved; otherwise, false.
+     *
+     * @param i The index of the desired location.
+     * @return true if the cursor was moved; otherwise, false.
      */
 
-    boolean toSelection ( int i );
-    
+    boolean toSelection(int i);
+
     /**
-     * Returns the count of the current selection. See also the selectPath() 
+     * Returns the count of the current selection. See also the selectPath()
      * and addToSelection() methods.
-     * 
+     * <p>
      * You may experience better performance if you use the iteration
-     * model using the toNextSelection method, rather than 
-     * the indexing model using the getSelectionCount and 
+     * model using the toNextSelection method, rather than
+     * the indexing model using the getSelectionCount and
      * toSelection methods.
-     * 
-     * @return  A number indicating the size of the current selection.
+     *
+     * @return A number indicating the size of the current selection.
      */
 
-    int getSelectionCount ( );
+    int getSelectionCount();
 
-    
+
     /**
-     * Appends the current location of the cursor to the selection.  
-     * See also the selectPath() method. You can use this as an 
+     * Appends the current location of the cursor to the selection.
+     * See also the selectPath() method. You can use this as an
      * alternative to calling the selectPath method when you want
      * to define your own selection.
      */
 
-    void addToSelection ( );
-    
+    void addToSelection();
+
     /**
      * Clears this cursor's selection, but does not modify the document.
      */
-    void clearSelections ( );    
-    
+    void clearSelections();
+
     /**
      * Moves this cursor to the same position as the bookmark.  If the
-     * bookmark is in a different document from this cursor or if the 
+     * bookmark is in a different document from this cursor or if the
      * bookmark is orphaned, this cursor
      * will not be moved, and false will be returned.
-     * 
-     * @param  bookmark  The bookmark at the location to which this
-     * cursor should be moved.
-     * @return  true if the cursor moved; otherwise, false.
+     *
+     * @param bookmark The bookmark at the location to which this
+     *                 cursor should be moved.
+     * @return true if the cursor moved; otherwise, false.
      */
 
-    boolean toBookmark ( XmlBookmark bookmark );
+    boolean toBookmark(XmlBookmark bookmark);
 
     /**
      * Moves this cursor to the location after its current position
      * where a bookmark with the given key exists.  Returns false if no
      * such bookmark exists.
-     * 
-     * @param  key  The key held by the next bookmark at the location to 
-     * which this cursor should be moved.
-     * @return  The next corresponding bookmark, if it exists; null if there
+     *
+     * @param key The key held by the next bookmark at the location to
+     *            which this cursor should be moved.
+     * @return The next corresponding bookmark, if it exists; null if there
      * is no next bookmark with the specified key.
      */
 
-    XmlBookmark toNextBookmark ( Object key );
-    
+    XmlBookmark toNextBookmark(Object key);
+
     /**
      * Moves this cursor to the location before its current position
      * where a bookmark with the given key exists.  Returns false if no
      * such bookmark exists.
-     * 
-     * @param  key  The key held by the previous bookmark at the location to 
-     * which this cursor should be moved.
-     * @return  The previous corresponding bookmark, if it exists; null if 
+     *
+     * @param key The key held by the previous bookmark at the location to
+     *            which this cursor should be moved.
+     * @return The previous corresponding bookmark, if it exists; null if
      * there is no previous bookmark with the specified key.
      */
 
-    XmlBookmark toPrevBookmark ( Object key );
-    
+    XmlBookmark toPrevBookmark(Object key);
+
     /**
      * Returns the name of the current token. Names may be associated with
      * START, ATTR, NAMESPACE or PROCINST. Returns null if there is no
-     * name associated with the current token. For START and ATTR, the 
-     * name returned identifies the name of the element or attribute. 
-     * For NAMESPACE, the local part of the name is the prefix, while 
-     * the URI is the namespace defined. For PROCINST, the local part 
+     * name associated with the current token. For START and ATTR, the
+     * name returned identifies the name of the element or attribute.
+     * For NAMESPACE, the local part of the name is the prefix, while
+     * the URI is the namespace defined. For PROCINST, the local part
      * is the target and the uri is "".
      * <p>
      * In the following example, <code>xmlObject</code> represents
      * an XML instance whose root element is not preceded by any other XML.
-     * This code prints the root element name (here, the local name, or 
+     * This code prints the root element name (here, the local name, or
      * name without URI).
      * <pre>
      * XmlCursor cursor = xmlObject.newCursor();
@@ -426,21 +530,21 @@
      * System.out.println(elementName);
      * </pre>
      *
-     * @return  The name of the XML at this cursor's location; null if there
+     * @return The name of the XML at this cursor's location; null if there
      * is no name.
      */
 
-    QName getName ( );
-    
+    QName getName();
+
     /**
      * Sets the name of the current token. This token can be START, NAMESPACE,
      * ATTR or PROCINST.
-     * 
-     * @param  name  The new name for the current token.
+     *
+     * @param name The new name for the current token.
      */
 
-    void setName ( QName name );
-    
+    void setName(QName name);
+
     /**
      * Returns the namespace URI indicated by the given prefix. The current
      * context must be at a START or STARTDOC. Namespace prefix mappings
@@ -449,18 +553,18 @@
      * a search for the default namespace.  To conform with the
      * XML spec, the default namespace will return the no-namespace ("")
      * if it is not mapped.<br/><br/>
-     * 
-     * Note that this queries the current state of the document. When the 
-     * document is persisted, the saving mechanism may synthesize namespaces 
-     * (ns1, ns2, and so on) for the purposes of persistence. These namepaces are 
-     * only present in the serialized form, and are not reflected back into 
+     * <p>
+     * Note that this queries the current state of the document. When the
+     * document is persisted, the saving mechanism may synthesize namespaces
+     * (ns1, ns2, and so on) for the purposes of persistence. These namepaces are
+     * only present in the serialized form, and are not reflected back into
      * the document being saved.
-     * 
-     * @param  prefix  The namespace prefix for the requested namespace.
-     * @return  The URI for corresponding to the specified prefix if it
+     *
+     * @param prefix The namespace prefix for the requested namespace.
+     * @return The URI for corresponding to the specified prefix if it
      * exists; otherwise, null.
      */
-    String namespaceForPrefix ( String prefix );
+    String namespaceForPrefix(String prefix);
 
     /**
      * Returns a prefix that can be used to indicate a namespace URI.  The
@@ -469,464 +573,464 @@
      * prefix may be returned. Otherwise, a new prefix for the URI will be
      * defined by adding an xmlns attribute to the current container or a
      * parent container.
-     * 
-     * Note that this queries the current state of the document. When the 
-     * document is persisted, the saving mechanism may synthesize namespaces 
-     * (ns1, ns2, and so on) for the purposes of persistence. These namepaces are 
-     * only present in the serialized form, and are not reflected back into 
+     * <p>
+     * Note that this queries the current state of the document. When the
+     * document is persisted, the saving mechanism may synthesize namespaces
+     * (ns1, ns2, and so on) for the purposes of persistence. These namepaces are
+     * only present in the serialized form, and are not reflected back into
      * the document being saved.
-     * 
-     * @param  namespaceURI  The namespace URI corresponding to the requested
-     * prefix.
-     * @return  The prefix corresponding to the specified URI if it exists; 
+     *
+     * @param namespaceURI The namespace URI corresponding to the requested
+     *                     prefix.
+     * @return The prefix corresponding to the specified URI if it exists;
      * otherwise, a newly generated prefix.
      */
-    String prefixForNamespace ( String namespaceURI );
-    
+    String prefixForNamespace(String namespaceURI);
+
     /**
      * Adds to the specified map, all the namespaces in scope at the container
-     * where this cursor is positioned. This method is useful for 
+     * where this cursor is positioned. This method is useful for
      * container tokens only.
-     * 
-     * @param  addToThis  The Map to add the namespaces to.
+     *
+     * @param addToThis The Map to add the namespaces to.
      */
 
-    void getAllNamespaces ( Map addToThis );
+    void getAllNamespaces(Map<String, String> addToThis);
 
     /**
      * Returns the strongly-typed XmlObject at the current START,
      * STARTDOC, or ATTR. <br/><br/>
-     * 
+     * <p>
      * The strongly-typed object can be cast to the strongly-typed
      * XBean interface corresponding to the XML Schema Type given
      * by result.getSchemaType().<br/><br/>
-     *
+     * <p>
      * If a more specific type cannot be determined, an XmlObject
      * whose schema type is anyType will be returned.
-     * 
-     * @return  The strongly-typed object at the cursor's current location;
+     *
+     * @return The strongly-typed object at the cursor's current location;
      * null if the current location is not a START, STARTDOC, or ATTR.
      */
 
-    XmlObject getObject ( );
-    
+    XmlObject getObject();
+
     /**
      * Returns the type of the current token. By definition, the current
-     * token is the token immediately to the right of the cursor. 
+     * token is the token immediately to the right of the cursor.
      * If you're in the middle of text, before a character, you get TEXT.
      * You can't dive into the text of an ATTR, COMMENT or PROCINST.<br/><br/>
-     * 
-     * As an alternative, it may be more convenient for you to use one of the 
-     * methods that test for a particular token type. These include the methods 
-     * isStart(), isStartdoc(), isText(), isAttr(), and so on. Each returns a boolean 
-     * value indicating whether the token that follows the cursor is the type 
-     * in question. 
+     * <p>
+     * As an alternative, it may be more convenient for you to use one of the
+     * methods that test for a particular token type. These include the methods
+     * isStart(), isStartdoc(), isText(), isAttr(), and so on. Each returns a boolean
+     * value indicating whether the token that follows the cursor is the type
+     * in question.
      * <br/><br/>
      *
-     * @return  The TokenType instance for the token at the cursor's current
+     * @return The TokenType instance for the token at the cursor's current
      * location.
      */
 
-    TokenType currentTokenType ( );
-    
+    TokenType currentTokenType();
+
     /**
-     * True if the current token is a STARTDOC token type, meaning 
+     * True if the current token is a STARTDOC token type, meaning
      * at the very root of the document.
-     * 
-     * @return  true if this token is a STARTDOC token type; 
+     *
+     * @return true if this token is a STARTDOC token type;
      * otherwise, false.
      */
 
-    boolean isStartdoc ( );
-    
+    boolean isStartdoc();
+
     /**
-     * True if this token is an ENDDOC token type, meaning 
+     * True if this token is an ENDDOC token type, meaning
      * at the very end of the document.
-     * 
-     * @return  true if this token is an ENDDOC token type; 
+     *
+     * @return true if this token is an ENDDOC token type;
      * otherwise, false.
      */
 
-    boolean isEnddoc ( );
-    
+    boolean isEnddoc();
+
     /**
-     * True if this token is a START token type, meaning 
+     * True if this token is a START token type, meaning
      * just before an element's start.
-     * 
-     * @return  true if this token is a START token type; 
+     *
+     * @return true if this token is a START token type;
      * otherwise, false.
      */
 
-    boolean isStart ( );
-    
+    boolean isStart();
+
     /**
-     * True if this token is an END token type, meaning 
+     * True if this token is an END token type, meaning
      * just before an element's end.
-     * 
-     * @return  true if this token is an END token type; 
+     *
+     * @return true if this token is an END token type;
      * otherwise, false.
      */
 
-    boolean isEnd ( );
-    
+    boolean isEnd();
+
     /**
-     * True if the this token is a TEXT token type, meaning 
+     * True if the this token is a TEXT token type, meaning
      * just before or inside text.
-     * 
-     * @return  true if this token is a TEXT token type; 
+     *
+     * @return true if this token is a TEXT token type;
      * otherwise, false.
      */
 
-    boolean isText ( );
-    
+    boolean isText();
+
     /**
-     * True if this token is an ATTR token type, meaning 
+     * True if this token is an ATTR token type, meaning
      * just before an attribute.
-     * 
-     * @return  true if this token is an ATTR token type; 
+     *
+     * @return true if this token is an ATTR token type;
      * otherwise, false.
      */
 
-    boolean isAttr ( );
-    
+    boolean isAttr();
+
     /**
-     * True if this token is a NAMESPACE token type, meaning 
+     * True if this token is a NAMESPACE token type, meaning
      * just before a namespace declaration.
-     * 
-     * @return  true if this token is a NAMESPACE token type; 
+     *
+     * @return true if this token is a NAMESPACE token type;
      * otherwise, false.
      */
 
-    boolean isNamespace ( );
-    
+    boolean isNamespace();
+
     /**
-     * True if this token is a COMMENT token type, meaning 
+     * True if this token is a COMMENT token type, meaning
      * just before a comment.
-     * 
-     * @return  true if this token is a COMMENT token type; 
+     *
+     * @return true if this token is a COMMENT token type;
      * otherwise, false.
      */
 
-    boolean isComment ( );
-    
+    boolean isComment();
+
     /**
-     * True if this token is a PROCINST token type, meaning 
+     * True if this token is a PROCINST token type, meaning
      * just before a processing instruction.
-     * 
-     * @return  true if this token is a PROCINST token type; 
+     *
+     * @return true if this token is a PROCINST token type;
      * otherwise, false.
      */
 
-    boolean isProcinst ( );
-    
+    boolean isProcinst();
+
     /**
-     * True if this token is a container token. The STARTDOC and START 
+     * True if this token is a container token. The STARTDOC and START
      * token types are containers. Containers, including documents and elements,
-     * have the same content model. In other words, a document and an element 
-     * may have the same contents. For example, a document may contain attributes 
+     * have the same content model. In other words, a document and an element
+     * may have the same contents. For example, a document may contain attributes
      * or text, without any child elements.
-     * 
-     * @return  true if this token is a container token; otherwise, false.
+     *
+     * @return true if this token is a container token; otherwise, false.
      */
 
-    boolean isContainer ( );
-    
+    boolean isContainer();
+
     /**
      * True if this token is a finish token. A finish token can be an ENDDOC
      * or END token type.
-
-     * @return  true if this token is a finish token; otherwise, false.
+     *
+     * @return true if this token is a finish token; otherwise, false.
      */
 
-    boolean isFinish ( );
-    
+    boolean isFinish();
+
     /**
      * True if this token is any attribute. This includes an ATTR token type and
      * the NAMESPACE token type attribute.
-     * 
-     * @return  true if the current cursor is at any attribute; otherwise, false.
+     *
+     * @return true if the current cursor is at any attribute; otherwise, false.
      */
 
-    boolean isAnyAttr ( );
-    
+    boolean isAnyAttr();
+
     /**
      * Returns the type of the previous token. By definition, the previous
      * token is the token immediately to the left of the cursor.<br/><br/>
-     *
+     * <p>
      * If you're in the middle of text, after a character, you get TEXT.
-     * 
-     * @return  The TokenType instance for the token immediately before the 
+     *
+     * @return The TokenType instance for the token immediately before the
      * token at the cursor's current location.
      */
 
-    TokenType prevTokenType ( );
-    
+    TokenType prevTokenType();
+
     /**
      * True if there is a next token. When this is false, as when the cursor is
-     * at the ENDDOC token, the toNextToken() method returns NONE and does not 
+     * at the ENDDOC token, the toNextToken() method returns NONE and does not
      * move the cursor.
-     * 
-     * @return  true if there is a next token; otherwise, false.
+     *
+     * @return true if there is a next token; otherwise, false.
      */
 
-    boolean hasNextToken ( );
+    boolean hasNextToken();
 
 
     /**
      * True if there is a previous token. When this is false, toPrevToken
      * returns NONE and does not move the cursor.
-     * 
-     * @return  true if there is a previous token; otherwise, false.
+     *
+     * @return true if there is a previous token; otherwise, false.
      */
 
-    boolean hasPrevToken ( );
-    
+    boolean hasPrevToken();
+
     /**
-     * Moves the cursor to the next token. When there are no more tokens 
-     * available, hasNextToken returns false and toNextToken() returns 
-     * NONE and does not move the cursor. Returns the token type 
+     * Moves the cursor to the next token. When there are no more tokens
+     * available, hasNextToken returns false and toNextToken() returns
+     * NONE and does not move the cursor. Returns the token type
      * of the token to the right of the cursor upon a successful move.
-     * 
-     * @return  The token type for the next token if the cursor was moved;
+     *
+     * @return The token type for the next token if the cursor was moved;
      * otherwise, NONE.
      */
 
-    TokenType toNextToken ( );
+    TokenType toNextToken();
 
     /**
      * Moves the cursor to the previous token. When there is no
      * previous token, returns NONE, otherwise returns the token
      * to the left of the new position of the cursor.
-     * 
-     * @return  The token type for the previous token if the cursor was moved;
+     *
+     * @return The token type for the previous token if the cursor was moved;
      * otherwise, NONE.
      */
 
-    TokenType toPrevToken ( );
-    
+    TokenType toPrevToken();
+
     /**
      * Moves the cursor to the first token in the content of the current
      * START or STARTDOC. That is, the first token after all ATTR and NAMESPACE
      * tokens associated with this START.<br/><br/>
-     *
+     * <p>
      * If the current token is not a START or STARTDOC, the cursor is not
      * moved and NONE is returned. If the current START or STARTDOC
      * has no content, the cursor is moved to the END or ENDDOC token.<br/><br/>
-     * 
-     * @return  The new current token type.
+     *
+     * @return The new current token type.
      */
 
-    TokenType toFirstContentToken ( );
+    TokenType toFirstContentToken();
 
 
     /**
      * Moves the cursor to the END or ENDDOC token corresponding to the
      * current START or STARTDOC, and returns END or ENDDOC. <br/><br/>
-     *
+     * <p>
      * If the current token is not a START or STARTDOC, the cursor is not
      * moved and NONE is returned.
-     * 
-     * @return  The new current token type.
+     *
+     * @return The new current token type.
      */
 
-    TokenType toEndToken ( );
-    
+    TokenType toEndToken();
+
     /**
      * Moves the cursor forward by the specified number of characters, and
      * stops at the next non-TEXT token. Returns the number of characters
-     * actually moved across, which is guaranteed to be less than or equal to  
-     * <em>maxCharacterCount</em>. If there is no further text, or if 
+     * actually moved across, which is guaranteed to be less than or equal to
+     * <em>maxCharacterCount</em>. If there is no further text, or if
      * there is no text at all, returns zero.<br/><br/>
-     *
+     * <p>
      * Note this does not dive into attribute values, comment contents,
      * processing instruction contents, etc., but only content text.<br/><br/>
-     *
-     * You can pass maxCharacterCount &lt; 0 to move over all the text to the 
-     * right. This has the same effect as toNextToken, but returns the amount 
+     * <p>
+     * You can pass maxCharacterCount &lt; 0 to move over all the text to the
+     * right. This has the same effect as toNextToken, but returns the amount
      * of text moved over.
      *
-     * @param  maxCharacterCount  The maximum number of characters by which
-     * the cursor should be moved.
-     * @return  The actual number of characters by which the cursor was moved; 
+     * @param maxCharacterCount The maximum number of characters by which
+     *                          the cursor should be moved.
+     * @return The actual number of characters by which the cursor was moved;
      * 0 if the cursor was not moved.
      */
 
-    int toNextChar ( int maxCharacterCount );
-    
+    int toNextChar(int maxCharacterCount);
+
     /**
      * Moves the cursor backwards by the number of characters given.  Has
      * similar characteristics to the {@link #toNextChar(int) toNextChar} method.
-     * 
-     * @param  maxCharacterCount  The maximum number of characters by which
-     * the cursor should be moved.
-     * @return  The actual number of characters by which the cursor was moved; 
+     *
+     * @param maxCharacterCount The maximum number of characters by which
+     *                          the cursor should be moved.
+     * @return The actual number of characters by which the cursor was moved;
      * 0 if the cursor was not moved.
      */
 
-    int toPrevChar ( int maxCharacterCount );
+    int toPrevChar(int maxCharacterCount);
 
     /**
      * Moves the cursor to the next sibling element, or returns
      * false and does not move the cursor if there is no next sibling
      * element. (By definition the position of an element is the same
      * as the position of its START token.)
-     *
-     * If the current token is not s START, the cursor will be 
-     * moved to the next START without moving out of the scope of the 
+     * <p>
+     * If the current token is not s START, the cursor will be
+     * moved to the next START without moving out of the scope of the
      * current element.
-     * 
-     * @return  true if the cursor was moved; otherwise, false.
+     *
+     * @return true if the cursor was moved; otherwise, false.
      */
 
-    boolean toNextSibling ( );
-    
+    boolean toNextSibling();
+
     /**
      * Moves the cursor to the previous sibling element, or returns
      * false and does not move the cursor if there is no previous sibling
      * element. (By definition the position of an element is the same
      * as the position of its START token.)
-     * 
-     * @return  true if the cursor was moved; otherwise, false.
+     *
+     * @return true if the cursor was moved; otherwise, false.
      */
 
-    boolean toPrevSibling ( );
+    boolean toPrevSibling();
 
     /**
      * Moves the cursor to the parent element or STARTDOC, or returns
      * false and does not move the cursor if there is no parent.<br/><br/>
-     *
+     * <p>
      * Works if you're in attributes or content. Returns false only if at
      * STARTDOC. Note that the parent of an END token is the corresponding
      * START token.
-     * 
-     * @return  true if the cursor was moved; false if the cursor is at the STARTDOC
+     *
+     * @return true if the cursor was moved; false if the cursor is at the STARTDOC
      * token.
      */
 
-    boolean toParent ( );
+    boolean toParent();
 
     /**
      * Moves the cursor to the first child element, or returns false and
      * does not move the cursor if there are no element children. <br/><br/>
-     *
-     * If the cursor is not currently in an element, it moves into the 
+     * <p>
+     * If the cursor is not currently in an element, it moves into the
      * first child element of the next element.
-     * 
-     * @return  true if the cursor was moved; otherwise, false.
+     *
+     * @return true if the cursor was moved; otherwise, false.
      */
 
-    boolean toFirstChild ( );
-    
+    boolean toFirstChild();
+
     /**
      * Moves the cursor to the last element child, or returns false and
      * does not move the cursor if there are no element children.
-     * 
-     * @return  true if the cursor was moved; otherwise, false.
+     *
+     * @return true if the cursor was moved; otherwise, false.
      */
 
-    boolean toLastChild ( );
-    
+    boolean toLastChild();
+
     /**
-     * Moves the cursor to the first child element of the specified name in 
+     * Moves the cursor to the first child element of the specified name in
      * no namespace.
-     * 
-     * @param  name  The name of the element to move the cursor to.
-     * @return  true if the cursor was moved; otherwise, false.
+     *
+     * @param name The name of the element to move the cursor to.
+     * @return true if the cursor was moved; otherwise, false.
      */
 
-    boolean toChild ( String name );
-    
+    boolean toChild(String name);
+
     /**
-     * Moves the cursor to the first child element of the specified name in the 
+     * Moves the cursor to the first child element of the specified name in the
      * specified namespace.
-     * 
-     * @param  namespace  The namespace URI for the element to move the cursor 
-     * to.
-     * @param  name  The name of the element to move to.
-     * @return  true if the cursor was moved; otherwise, false.
-     * @throws  IllegalArgumentException  If the name is not a valid local name.
+     *
+     * @param namespace The namespace URI for the element to move the cursor
+     *                  to.
+     * @param name      The name of the element to move to.
+     * @return true if the cursor was moved; otherwise, false.
+     * @throws IllegalArgumentException If the name is not a valid local name.
      */
 
-    boolean toChild ( String namespace, String name );
+    boolean toChild(String namespace, String name);
 
     /**
      * Moves the cursor to the first child element of the specified qualified name.
-     * 
-     * @param  name  The name of the element to move the cursor to.
+     *
+     * @param name The name of the element to move the cursor to.
      */
 
-    boolean toChild ( QName name );
+    boolean toChild(QName name);
 
     /**
      * Moves the cursor to the child element specified by <em>index</em>.
-     * 
-     * @param  index  The position of the element in the sequence of child 
-     * elements.
-     * @return  true if the cursor was moved; otherwise, false.
+     *
+     * @param index The position of the element in the sequence of child
+     *              elements.
+     * @return true if the cursor was moved; otherwise, false.
      */
 
-    boolean toChild ( int index );
-    
+    boolean toChild(int index);
+
     /**
-     * Moves the cursor to the specified <em>index</em> child element of the 
+     * Moves the cursor to the specified <em>index</em> child element of the
      * specified name, where that element is the .
-     * 
-     * @param  name  The name of the child element to move the cursor to.
-     * @param  index  The position of the element in the sequence of child
-     * elements.
-     * @return  true if the cursor was moved; otherwise, false.
+     *
+     * @param name  The name of the child element to move the cursor to.
+     * @param index The position of the element in the sequence of child
+     *              elements.
+     * @return true if the cursor was moved; otherwise, false.
      */
 
-    boolean toChild ( QName name, int index );
-    
+    boolean toChild(QName name, int index);
+
     /**
      * Moves the cursor to the next sibling element of the specified name in no
      * namespace.
-     * 
-     * @param  name  The name of the element to move the cursor to.
-     * @return  true if the cursor was moved; otherwise, false.
+     *
+     * @param name The name of the element to move the cursor to.
+     * @return true if the cursor was moved; otherwise, false.
      */
 
-    boolean toNextSibling ( String name );
-    
+    boolean toNextSibling(String name);
+
     /**
-     * Moves the cursor to the next sibling element of the specified name 
+     * Moves the cursor to the next sibling element of the specified name
      * in the specified namespace.
-     * 
-     * @param  namespace  The namespace URI for the element to move the cursor
-     * to.
-     * @param  name  The name of the element to move the cursor to.
-     * @return  true if the cursor was moved; otherwise, false.
+     *
+     * @param namespace The namespace URI for the element to move the cursor
+     *                  to.
+     * @param name      The name of the element to move the cursor to.
+     * @return true if the cursor was moved; otherwise, false.
      */
 
-    boolean toNextSibling ( String namespace, String name );
+    boolean toNextSibling(String namespace, String name);
 
-    
+
     /**
-     * Moves the cursor to the next sibling element of the specified 
+     * Moves the cursor to the next sibling element of the specified
      * qualified name.
-     * 
-     * @param  name  The name of the element to move the cursor to.
-     * @return  true if the cursor was moved; otherwise, false.
+     *
+     * @param name The name of the element to move the cursor to.
+     * @return true if the cursor was moved; otherwise, false.
      */
 
-    boolean toNextSibling ( QName name );
+    boolean toNextSibling(QName name);
 
     /**
      * Moves the cursor to the first attribute of this element, or
      * returns false and does not move the cursor if there are no
      * attributes. The order of attributes is arbitrary, but stable.<br/><br/>
-     *
+     * <p>
      * If the cursor is on a STARTDOC of a document-fragment, this method will
      * move it to the first top level attribute if one exists.<br></br>
-     *
-     * xmlns attributes (namespace declarations) are not considered 
+     * <p>
+     * xmlns attributes (namespace declarations) are not considered
      * attributes by this function.<br/><br/>
-     *
+     * <p>
      * The cursor must be on a START or STARTDOC (in the case of a
      * document fragment with top level attributes) for this method to
      * succeed.
-     *
+     * <p>
      * Example for looping through attributes:
      * <pre>
      *      XmlCursor cursor = ... //cursor on START or STARTDOC
@@ -941,391 +1045,391 @@
      *          while (cursor.toNextAttribute());
      *      }
      * </pre>
-     * 
-     * @return  true if the cursor was moved; otherwise, false.
+     *
+     * @return true if the cursor was moved; otherwise, false.
      */
 
-    boolean toFirstAttribute ( );
-    
+    boolean toFirstAttribute();
+
     /**
      * Moves the cursor to the last attribute of this element, or
      * returns false and does not move the cursor if there are no
      * attributes. The order of attributes is arbitrary, but stable.<br/><br/>
-     *
-     * xmlns attributes (namespace declarations) are not considered 
+     * <p>
+     * xmlns attributes (namespace declarations) are not considered
      * attributes by this function.<br/><br/>
-     *
+     * <p>
      * The cursor must be on a START or STARTDOC for this method
      * to succeed.
-     * 
-     * @return  true if the cursor was moved; otherwise, false.
+     *
+     * @return true if the cursor was moved; otherwise, false.
      */
 
-    boolean toLastAttribute ( );
+    boolean toLastAttribute();
 
     /**
      * Moves the cursor to the next sibling attribute, or returns
      * false and does not move the cursor if there is no next
      * sibling attribute. The order of attributes is arbitrary, but stable.<br/><br/>
-     * 
-     * xmlns attributes (namespace declarations) are not considered 
+     * <p>
+     * xmlns attributes (namespace declarations) are not considered
      * attributes by this function.<br/><br/>
-     *
+     * <p>
      * The cursor must be on an attribute for this method to succeed.
-     * @see #toFirstAttribute()
      *
-     * @return  true if the cursor was moved; otherwise, false.
+     * @return true if the cursor was moved; otherwise, false.
+     * @see #toFirstAttribute()
      */
 
-    boolean toNextAttribute ( );
+    boolean toNextAttribute();
 
     /**
      * Moves the cursor to the previous sibling attribute, or returns
      * false and does not move the cursor if there is no previous
      * sibling attribute. The order of attributes is arbitrary, but stable.<br/><br/>
-     * 
-     * xmlns attributes (namespace declarations) are not considered 
+     * <p>
+     * xmlns attributes (namespace declarations) are not considered
      * attributes by this function.<br/><br/>
-     *
+     * <p>
      * The cursor must be on an attribute for this method to succeed.
-     * 
-     * @return  true if the cursor was moved; otherwise, false.
+     *
+     * @return true if the cursor was moved; otherwise, false.
      */
 
-    boolean toPrevAttribute ( );
-    
+    boolean toPrevAttribute();
+
     /**
      * When at a START or STARTDOC, returns the attribute text for the given
      * attribute. When not at a START or STARTDOC or the attribute does not
-     * exist, returns null.  
-     * 
-     * @param  attrName  The name of the attribute whose value is requested.
-     * @return  The attribute's value if it has one; otherwise, null.
+     * exist, returns null.
+     *
+     * @param attrName The name of the attribute whose value is requested.
+     * @return The attribute's value if it has one; otherwise, null.
      */
 
-    String getAttributeText ( QName attrName );
-    
+    String getAttributeText(QName attrName);
+
     /**
      * When at a START or STARTDOC, sets the attribute text for the given
      * attribute. When not at a START or STARTDOC returns false.
      * If the attribute does not exist, one is created.
-     * 
-     * @param  attrName  The name of the attribute whose value is being set.
-     * @param  value  The new value for the attribute.
-     * @return  true if the new value was set; otherwise, false.
+     *
+     * @param attrName The name of the attribute whose value is being set.
+     * @param value    The new value for the attribute.
+     * @return true if the new value was set; otherwise, false.
      */
 
-    boolean setAttributeText ( QName attrName, String value );
-  
+    boolean setAttributeText(QName attrName, String value);
+
     /**
      * When at a START or STARTDOC, removes the attribute with the given name.
-     * 
-     * @param  attrName  The name of the attribute that should be removed.
-     * @return  true if the attribute was removed; otherwise, false.
+     *
+     * @param attrName The name of the attribute that should be removed.
+     * @return true if the attribute was removed; otherwise, false.
      */
 
-    boolean removeAttribute ( QName attrName );
+    boolean removeAttribute(QName attrName);
 
     /**
      * Gets the text value of the current document, element, attribute,
      * comment, procinst or text token. <br/><br/>
-     *
+     * <p>
      * When getting the text value of an element, non-text content such
      * as comments and processing instructions are ignored and text is concatenated.
      * For elements that have nested element children, this
      * returns the concatenated text of all mixed content and the
      * text of all the element children, recursing in first-to-last
      * depthfirst order.<br/><br/>
-     *
+     * <p>
      * For attributes, including namespaces, this returns the attribute value.<br/><br/>
-     *
-     * For comments and processing instructions, this returns the text content 
+     * <p>
+     * For comments and processing instructions, this returns the text content
      * of the comment or PI, not including the delimiting sequences &lt;!-- --&gt;, &lt;? ?&gt;.
      * For a PI, the name of the PI is also not included.
-     *<br/><br/>
+     * <br/><br/>
      * The value of an empty tag is the empty string.<br/><br/>
+     * <p>
+     * If the current token is END or ENDDOC, this throws an {@link java.lang.IllegalStateException}.<br/><br/>
      *
-     * If the current token is END or ENDDOC, this throws an {@link java.lang.IllegalStateException}.<br/><br/>     
-     * 
-     * @return  The text value of the current token if the token's type is
-     * START, STARTDOC, TEXT, ATTR, COMMENT, PROCINST, or NAMESPACE; null 
+     * @return The text value of the current token if the token's type is
+     * START, STARTDOC, TEXT, ATTR, COMMENT, PROCINST, or NAMESPACE; null
      * if the type is NONE.
      */
 
-    String getTextValue ( );
-    
+    String getTextValue();
+
     /**
      * Copies the text value of the current document, element, attribute,
-     * comment, processing instruction or text token, counting right from 
+     * comment, processing instruction or text token, counting right from
      * this cursor's location up to <em>maxCharacterCount</em>,
      * and copies the returned text into <em>returnedChars</em>. <br/><br/>
-     * 
+     * <p>
      * When getting the text value of an element, non-text content such
      * as comments and processing instructions are ignored and text is concatenated.
      * For elements that have nested element children, this
      * returns the concatenated text of all mixed content and the
      * text of all the element children, recursing in first-to-last
      * depthfirst order.<br/><br/>
-     *
+     * <p>
      * For attributes, including namespaces, this returns the attribute value.<br/><br/>
-     *
-     * For comments and processing instructions, this returns the text contents 
+     * <p>
+     * For comments and processing instructions, this returns the text contents
      * of the comment or PI, not including the delimiting sequences &lt;!-- --&gt;, &lt;? ?&gt;. For
      * a PI, the text will not include the name of the PI.<br/><br/>
-     * 
+     * <p>
      * If the current token is END or ENDDOC, this throws an {@link java.lang.IllegalStateException}.<br/><br/>
-     *
+     * <p>
      * The value of an empty tag is the empty string.<br/><br/>
-     * 
-     * @param  returnedChars  A character array to hold the returned characters.
-     * @param  offset  The position within returnedChars to which the first of the 
-     * returned characters should be copied.
-     * @param  maxCharacterCount  The maximum number of characters after this cursor's 
-     * location to copy. A negative value specifies that all characters should be copied.
-     * @return  The actual number of characters copied; 0 if no characters 
+     *
+     * @param returnedChars     A character array to hold the returned characters.
+     * @param offset            The position within returnedChars to which the first of the
+     *                          returned characters should be copied.
+     * @param maxCharacterCount The maximum number of characters after this cursor's
+     *                          location to copy. A negative value specifies that all characters should be copied.
+     * @return The actual number of characters copied; 0 if no characters
      * were copied.
      */
 
-    int getTextValue ( char[] returnedChars, int offset, int maxCharacterCount );
-    
+    int getTextValue(char[] returnedChars, int offset, int maxCharacterCount);
+
     /**
      * Returns the characters of the current TEXT token.  If the current token
      * is not TEXT, returns "".  If in the middle of a TEXT token, returns
      * those chars to the right of the cursor of the TEXT token.
-     * 
-     * @return  The requested text; an empty string if the current token type is
+     *
+     * @return The requested text; an empty string if the current token type is
      * not TEXT.
      */
 
     /**
      * Sets the text value of the XML at this cursor's location if that XML's
      * token type is START, STARTDOC, ATTR, COMMENT or PROCINST. <br/><br/>
-     *
+     * <p>
      * For elements that have nested children this first removes all
      * the content of the element and replaces it with the given text.
-     * 
-     * @param  text  The text to use as a new value.
-     * @throws  java.lang.IllegalStateException  If the token type at this
-     * cursor's location is not START, STARTDOC, ATTR, COMMENT or
-     * PROCINST.
+     *
+     * @param text The text to use as a new value.
+     * @throws java.lang.IllegalStateException If the token type at this
+     *                                         cursor's location is not START, STARTDOC, ATTR, COMMENT or
+     *                                         PROCINST.
      */
-    void setTextValue ( String text );
-    
+    void setTextValue(String text);
+
     /**
      * Sets the text value of the XML at this cursor's location (if that XML's
-     * token type is START, STARTDOC, ATTR, COMMENT or PROCINST) to the 
+     * token type is START, STARTDOC, ATTR, COMMENT or PROCINST) to the
      * contents of the specified character array. <br/><br/>
-     *
+     * <p>
      * For elements that have nested children this first removes all
      * the content of the element and replaces it with the given text.
-     * 
-     * @param  sourceChars  A character array containing the XML's new value.
-     * @param  offset  The position within sourceChars from which the first of 
-     * the source characters should be copied.
-     * @param  length  The maximum number of characters to set as the XML's new
-     * value.
-     * @throws  java.lang.IllegalArgumentException  If the token type at this
-     * cursor's location is not START, STARTDOC, ATTR, COMMENT or
-     * PROCINST.
+     *
+     * @param sourceChars A character array containing the XML's new value.
+     * @param offset      The position within sourceChars from which the first of
+     *                    the source characters should be copied.
+     * @param length      The maximum number of characters to set as the XML's new
+     *                    value.
+     * @throws java.lang.IllegalArgumentException If the token type at this
+     *                                            cursor's location is not START, STARTDOC, ATTR, COMMENT or
+     *                                            PROCINST.
      */
-    void setTextValue ( char[] sourceChars, int offset, int length );
+    void setTextValue(char[] sourceChars, int offset, int length);
 
     /**
      * Returns characters to the right of the cursor up to the next token.
      */
-    String getChars ( );
-    
+    String getChars();
+
     /**
-     * Copies characters up to the specified maximum number, counting right from 
-     * this cursor's location to the character at <em>maxCharacterCount</em>.  The 
+     * Copies characters up to the specified maximum number, counting right from
+     * this cursor's location to the character at <em>maxCharacterCount</em>.  The
      * returned characters are added to <em>returnedChars</em>, with the first
-     * character copied to the <em>offset</em> position. The <em>maxCharacterCount</em> 
-     * parameter should be less than or equal to the length of <em>returnedChars</em> 
-     * minus <em>offset</em>. Copies a number of characters, which is 
-     * either <em>maxCharacterCount</em> or the number of characters up to the next token, 
+     * character copied to the <em>offset</em> position. The <em>maxCharacterCount</em>
+     * parameter should be less than or equal to the length of <em>returnedChars</em>
+     * minus <em>offset</em>. Copies a number of characters, which is
+     * either <em>maxCharacterCount</em> or the number of characters up to the next token,
      * whichever is less.
-     * 
-     * @param  returnedChars  A character array to hold the returned characters.
-     * @param  offset  The position within returnedChars at which the first of the 
-     * returned characters should be added.
-     * @param  maxCharacterCount  The maximum number of characters after this cursor's 
-     * location to return.
-     * @return  The actual number of characters returned; 0 if no characters 
-     * were returned or if the current token is not TEXT. 
+     *
+     * @param returnedChars     A character array to hold the returned characters.
+     * @param offset            The position within returnedChars at which the first of the
+     *                          returned characters should be added.
+     * @param maxCharacterCount The maximum number of characters after this cursor's
+     *                          location to return.
+     * @return The actual number of characters returned; 0 if no characters
+     * were returned or if the current token is not TEXT.
      */
 
-    int getChars ( char[] returnedChars, int offset, int maxCharacterCount );
-    
+    int getChars(char[] returnedChars, int offset, int maxCharacterCount);
+
     /**
-     * Moves the cursor to the STARTDOC token, which is the 
+     * Moves the cursor to the STARTDOC token, which is the
      * root of the document.
      */
 
-    void toStartDoc ( );
-    
+    void toStartDoc();
+
     /**
      * Moves the cursor to the ENDDOC token, which is the end
      * of the document.
      */
 
-    void toEndDoc ( );
-    
+    void toEndDoc();
+
     /**
      * Determines if the specified cursor is in the same document as
      * this cursor.
-     * 
-     * @param  cursor  The cursor that may be in the same document
-     * as this cursor.
-     * @return  true if the specified cursor is in the same document;
+     *
+     * @param cursor The cursor that may be in the same document
+     *               as this cursor.
+     * @return true if the specified cursor is in the same document;
      * otherwise, false.
      */
 
-    boolean isInSameDocument ( XmlCursor cursor );
+    boolean isInSameDocument(XmlCursor cursor);
 
     /**
-     * Returns an integer indicating whether this cursor is before, 
+     * Returns an integer indicating whether this cursor is before,
      * after, or at the same position as the specified cursor. <br/><br/>
-     * 
+     *
      * <code>a.comparePosition(b) < 0</code> means a is to the left of b.<br/>
      * <code>a.comparePosition(b) == 0</code> means a is at the same position as b.<br/>
      * <code>a.comparePosition(b) > 0</code> means a is to the right of b.<br/><br/>
-     *
+     * <p>
      * The sort order of cursors in the document is the token order.
      * For example, if cursor "a" is at a START token and the cursor "b"
      * is at a token within the contents of the same element, then
      * a.comparePosition(b) will return -1, meaning that the position
      * of a is before b.
-     * 
-     * @param  cursor  The cursor whose position should be compared
-     * with this cursor.
-     * @return  1 if this cursor is after the specified cursor; 0 if 
-     * this cursor is at the same position as the specified cursor; 
+     *
+     * @param cursor The cursor whose position should be compared
+     *               with this cursor.
+     * @return 1 if this cursor is after the specified cursor; 0 if
+     * this cursor is at the same position as the specified cursor;
      * -1 if this cursor is before the specified cursor.
-     * @throws  java.lang.IllegalArgumentException  If the specified
-     * cursor is not in the same document as this cursor.
+     * @throws java.lang.IllegalArgumentException If the specified
+     *                                            cursor is not in the same document as this cursor.
      */
 
-    int comparePosition ( XmlCursor cursor );
-    
+    int comparePosition(XmlCursor cursor);
+
     /**
      * Determines if this cursor is to the left of (or before)
-     * the specified cursor. Note that this is the same as 
+     * the specified cursor. Note that this is the same as
      * <code>a.comparePosition(b) &lt; 0 </code>
-     * 
-     * @param  cursor  The cursor whose position should be compared
-     * with this cursor.
-     * @return  true if this cursor is to the left of the specified
+     *
+     * @param cursor The cursor whose position should be compared
+     *               with this cursor.
+     * @return true if this cursor is to the left of the specified
      * cursor; otherwise, false.
      */
 
-    boolean isLeftOf ( XmlCursor cursor );
-    
+    boolean isLeftOf(XmlCursor cursor);
+
     /**
      * Determines if this cursor is at the same position as
-     * the specified cursor. Note that this is the same as 
+     * the specified cursor. Note that this is the same as
      * <code>a.comparePosition(b) == 0 </code>
-     * 
-     * @param  cursor  The cursor whose position should be compared
-     * with this cursor.
-     * @return  true if this cursor is at the same position as 
+     *
+     * @param cursor The cursor whose position should be compared
+     *               with this cursor.
+     * @return true if this cursor is at the same position as
      * the specified cursor; otherwise, false.
      */
 
-    boolean isAtSamePositionAs ( XmlCursor cursor );
-    
+    boolean isAtSamePositionAs(XmlCursor cursor);
+
     /**
      * Determines if this cursor is to the right of (or after)
-     * the specified cursor. Note that this is the same as 
+     * the specified cursor. Note that this is the same as
      * <code>a.comparePosition(b) &gt; 0 </code>
-     * 
-     * @param  cursor  The cursor whose position should be compared
-     * with this cursor.
-     * @return  true if this cursor is to the right of the specified
+     *
+     * @param cursor The cursor whose position should be compared
+     *               with this cursor.
+     * @return true if this cursor is to the right of the specified
      * cursor; otherwise, false.
      */
 
-    boolean isRightOf ( XmlCursor cursor );
-    
+    boolean isRightOf(XmlCursor cursor);
+
     /**
      * Executes the specified XQuery expression against the XML this
      * cursor is in. <br/><br/>
-     * 
+     * <p>
      * The query may be a String or a compiled query. You can precompile
      * an XQuery expression using the XmlBeans.compileQuery method. <br/><br>
-     * 
-     * The root referred to by the expression should be given as 
+     * <p>
+     * The root referred to by the expression should be given as
      * a dot. The following is an example path expression:
      * <pre>
      * XmlCursor results = cursor.execQuery("purchase-order/line-item[price &lt;= 20.00]");
      * </pre>
-     * 
-     * @param  query  The XQuery expression to execute.
-     * @return  A cursor containing the results of the query.
-     * @throws  XmlRuntimeException  If the query expression is invalid.
+     *
+     * @param query The XQuery expression to execute.
+     * @return A cursor containing the results of the query.
+     * @throws XmlRuntimeException If the query expression is invalid.
      */
 
-    XmlCursor execQuery ( String query );
-    
+    XmlCursor execQuery(String query);
+
     /**
      * Executes the specified XQuery expression against the XML this
      * cursor is in, and using the specified options. <br/><br/>
-     * 
-     * @param  query  The XQuery expression to execute.
-     * @param  options  Options for the query. For example, you can call 
-     * the {@link XmlOptions#setXqueryCurrentNodeVar(String) XmlOptions.setXqueryCurrentNodeVar(String)}
-     * method to specify a particular name for the query expression 
-     * variable that indicates the context node.
-     * @throws  XmlRuntimeException  If the query expression is invalid.
+     *
+     * @param query   The XQuery expression to execute.
+     * @param options Options for the query. For example, you can call
+     *                the {@link XmlOptions#setXqueryCurrentNodeVar(String) XmlOptions.setXqueryCurrentNodeVar(String)}
+     *                method to specify a particular name for the query expression
+     *                variable that indicates the context node.
+     * @throws XmlRuntimeException If the query expression is invalid.
      */
 
-    XmlCursor execQuery ( String query, XmlOptions options );
-    
+    XmlCursor execQuery(String query, XmlOptions options);
+
     /**
      * Represents the state of a dcoument at a particular point
      * in time.  It is used to determine if a document has been changed
      * since that point in time.
      */
-    interface ChangeStamp
-    {
+    interface ChangeStamp {
         /**
          * Returns whether or not the document assoiated with this ChangeStamp
          * has been altered since the ChangeStamp had been created.
          */
-        public boolean hasChanged ( );
+        public boolean hasChanged();
     }
-    
+
     /**
-     * Returns the current change stamp for the document the current cursor is in. 
+     * Returns the current change stamp for the document the current cursor is in.
      * This change stamp can be queried at a later point in time to find out
      * if the document has changed.
-     * 
-     * @return  The change stamp for the document the current cursor is in.
+     *
+     * @return The change stamp for the document the current cursor is in.
      */
-    ChangeStamp getDocChangeStamp ( );
-    
+    ChangeStamp getDocChangeStamp();
+
     /**
      * Subclasses of XmlBookmark can be used to annotate an XML document.
-     * This class is abstract to prevent parties from inadvertently 
+     * This class is abstract to prevent parties from inadvertently
      * interfering with each others' bookmarks without explicitly
      * sharing a bookmark class.
      */
 
-    abstract class XmlBookmark
-    {
+    abstract class XmlBookmark {
         /**
          * Constructs a strongly-referenced bookmark.
-         */ 
-        public XmlBookmark ( ) { this( false ); }
-        
+         */
+        public XmlBookmark() {
+            this(false);
+        }
+
         /**
          * Constructs a bookmark.
+         *
          * @param weak true if the document's reference to the bookmark should be a WeakReference
-         */ 
-        public XmlBookmark ( boolean weak )
-        {
-            _ref = weak ? new WeakReference( this ) : null;
+         */
+        public XmlBookmark(boolean weak) {
+            _ref = weak ? new WeakReference(this) : null;
         }
-        
+
         /**
          * Call the createCursor method to create a new cursor which is
          * positioned at the same splace as the bookmark.  It is much more
@@ -1339,18 +1443,16 @@
          *
          * @return the new cursor
          */
-        public final XmlCursor createCursor ( )
-        {
+        public final XmlCursor createCursor() {
             return _currentMark == null ? null : _currentMark.createCursor();
         }
 
         /**
          * @param c the cursor to be moved
          * @return the given cursor moved to this bookmark
-         */ 
-        public final XmlCursor toBookmark ( XmlCursor c )
-        {
-            return c == null || !c.toBookmark( this ) ? createCursor() : c;
+         */
+        public final XmlCursor toBookmark(XmlCursor c) {
+            return c == null || !c.toBookmark(this) ? createCursor() : c;
         }
 
         /**
@@ -1362,24 +1464,23 @@
          *
          * @return default key for bookmarks
          */
-        public Object getKey ( )
-        {
+        public Object getKey() {
             return this.getClass();
         }
-        
+
         /**
          * The mark is set by the host document; it is capable of
          * returning an XmlCursor implementation at the location of
          * the bookmark.
-         */ 
-        public       XmlMark   _currentMark;
-        
+         */
+        public XmlMark _currentMark;
+
         /**
          * If non-null, the ref is used by the host document
          * to maintain a reference to the bookmark.  If it is a weak
          * reference, the host document will not prevent the Bookmark
          * from being garbage collected.
-         */ 
+         */
         public final Reference _ref;
     }
 
@@ -1391,428 +1492,427 @@
      * receives the new content.
      */
 
-    interface XmlMark
-    {
-        XmlCursor createCursor ( );
+    interface XmlMark {
+        XmlCursor createCursor();
     }
 
     /**
      * Sets a bookmark to the document at this cursor's location.
-     *
-     * The bookmark is attached to the token in the tree immediately 
+     * <p>
+     * The bookmark is attached to the token in the tree immediately
      * after the cursor. If the tree is manipulated to move
      * that object to a different place, the bookmark moves with it.
      * If the tree is manipulated to delete that token from the
      * tree, the bookmark is orphaned. Copy operations do not copy
      * bookmarks.
-     * 
-     * @param  bookmark  The bookmark to set.
+     *
+     * @param bookmark The bookmark to set.
      */
 
-    void setBookmark ( XmlBookmark bookmark );
-    
+    void setBookmark(XmlBookmark bookmark);
+
     /**
-     * Retrieves the bookmark with the specified key 
-     * at this cursor's location. If there is no bookmark whose key is 
-     * given by the specified key at the current position, null is returned. 
-     * If the {@link XmlCursor.XmlBookmark#getKey() getKey} method is not overridden on 
+     * Retrieves the bookmark with the specified key
+     * at this cursor's location. If there is no bookmark whose key is
+     * given by the specified key at the current position, null is returned.
+     * If the {@link XmlCursor.XmlBookmark#getKey() getKey} method is not overridden on
      * the bookmark, then the bookmark's class is used as the key.
-     * 
-     * @param  key  The key for the bookmark to retrieve.
-     * @return  The requested bookmark; null if there is no bookmark
+     *
+     * @param key The key for the bookmark to retrieve.
+     * @return The requested bookmark; null if there is no bookmark
      * corresponding to the specified key.
      */
 
-    XmlBookmark getBookmark ( Object key );
-    
+    XmlBookmark getBookmark(Object key);
+
     /**
      * Clears the bookmark whose key is specified, if the bookmark
      * exists at this cursor's location.
-     * 
-     * @param  key  The for the bookmark to clear.
+     *
+     * @param key The for the bookmark to clear.
      */
 
-    void clearBookmark ( Object key );
+    void clearBookmark(Object key);
 
     /**
      * Retrieves all the bookmarks at this location, adding them to
      * the specified collection. Bookmarks held by weak references are
      * added to this collection as Weak referenced objects pointing to the
      * bookmark.
-     * 
-     * @param  listToFill  The collection that will contain bookmarks
-     * returned by this method.
+     *
+     * @param listToFill The collection that will contain bookmarks
+     *                   returned by this method.
      */
 
-    void getAllBookmarkRefs ( Collection listToFill );
+    void getAllBookmarkRefs(Collection listToFill);
 
     /**
      * Removes the XML that is immediately after this cursor.
-     * 
-     * For the TEXT, ATTR, NAMESPACE, COMMENT and PROCINST tokens, a single 
-     * token is removed. For a START token, the corresponding element and all 
-     * of its contents are removed. For all other tokens, this is a no-op. 
+     * <p>
+     * For the TEXT, ATTR, NAMESPACE, COMMENT and PROCINST tokens, a single
+     * token is removed. For a START token, the corresponding element and all
+     * of its contents are removed. For all other tokens, this is a no-op.
      * You cannot remove a STARTDOC.
-     * 
-     * The cursors located in the XML that was removed all collapse to the 
+     * <p>
+     * The cursors located in the XML that was removed all collapse to the
      * same location. All bookmarks in this XML will be orphaned.
-     * 
-     * @return true if anything was removed; false only if the cursor is 
+     *
+     * @return true if anything was removed; false only if the cursor is
      * just before END or ENDDOC token.
-     * @throws java.lang.IllegalArgumentException  If the cursor is at a 
-     * STARTDOC token.
+     * @throws java.lang.IllegalArgumentException If the cursor is at a
+     *                                            STARTDOC token.
      */
 
-    boolean removeXml ( );
+    boolean removeXml();
 
     /**
      * Moves the XML immediately after this cursor to the location
-     * specified by the <em>toHere</em> cursor, shifting XML at that location 
-     * to the right to make room. For the TEXT, ATTR, NAMESPACE, 
+     * specified by the <em>toHere</em> cursor, shifting XML at that location
+     * to the right to make room. For the TEXT, ATTR, NAMESPACE,
      * COMMENT and PROCINST tokens, a single token is moved. For a start token, the
      * element and all of its contents are moved. For all other tokens, this
      * is a no-op.
-     * 
+     * <p>
      * The bookmarks located in the XML that was moved also move to the
      * new location; the cursors don't move with the content.
-     * 
-     * @param  toHere  The cursor at the location to which the XML should
-     * be moved.
+     *
+     * @param toHere The cursor at the location to which the XML should
+     *               be moved.
      * @return true if anything was moved.  This only happens when the XML to be
      * moved contains the target of the move.
-     * @throws java.lang.IllegalArgumentException  If the operation is not allowed
-     * at the cursor's location.  This includes attempting to move an end token or the
-     * document as a whole.  Also, moving to a location before the start document or moving
-     * an attribute to a location other than after another attribute or start token
-     * will throw.
+     * @throws java.lang.IllegalArgumentException If the operation is not allowed
+     *                                            at the cursor's location.  This includes attempting to move an end token or the
+     *                                            document as a whole.  Also, moving to a location before the start document or moving
+     *                                            an attribute to a location other than after another attribute or start token
+     *                                            will throw.
      */
 
-    boolean moveXml ( XmlCursor toHere );
-    
+    boolean moveXml(XmlCursor toHere);
+
     /**
      * Copies the XML immediately after this cursor to the location
-     * specified by the <em>toHere</em> cursor. For the TEXT, ATTR, NAMESPACE, 
-     * COMMENT and PROCINST tokens, a single token is copied.  For a start token, 
+     * specified by the <em>toHere</em> cursor. For the TEXT, ATTR, NAMESPACE,
+     * COMMENT and PROCINST tokens, a single token is copied.  For a start token,
      * the element and all of its contents are copied. For all other tokens, this
      * is a no-op.
-     * 
-     * The cursors and bookmarks located in the XML that was copied are also copied 
+     * <p>
+     * The cursors and bookmarks located in the XML that was copied are also copied
      * to the new location.
-     * 
-     * @param  toHere  The cursor at the location to which the XML should
-     * be copied.
+     *
+     * @param toHere The cursor at the location to which the XML should
+     *               be copied.
      * @return true if anything was copied; false if the token supports the operation,
      * but nothing was copied.
-     * @throws java.lang.IllegalArgumentException  If the operation is not allowed
-     * at the cursor's location.
+     * @throws java.lang.IllegalArgumentException If the operation is not allowed
+     *                                            at the cursor's location.
      */
 
-    boolean copyXml ( XmlCursor toHere );
-    
+    boolean copyXml(XmlCursor toHere);
+
     /**
      * Removes the contents of the container (STARTDOC OR START) immediately after
      * this cursor. For all other situations, returns false. Does
      * not remove attributes or namspaces.
-     * 
+     *
      * @return true if anything was copied; otherwise, false.
      */
 
-    boolean removeXmlContents ( );
+    boolean removeXmlContents();
 
     /**
      * Moves the contents of the container (STARTDOC OR START) immediately after
      * this cursor to the location specified by the <em>toHere</em> cursor.
      * For all other situations, returns false. Does not move attributes or
      * namespaces.
-     * 
-     * @param  toHere  The cursor at the location to which the XML should be moved.
+     *
+     * @param toHere The cursor at the location to which the XML should be moved.
      * @return true if anything was moved; otherwise, false.
      */
-    boolean moveXmlContents ( XmlCursor toHere );
-    
+    boolean moveXmlContents(XmlCursor toHere);
+
     /**
      * Copies the contents of the container (STARTDOC OR START) immediately to
      * the right of the cursor to the location specified by the <em>toHere</em> cursor.
      * For all other situations, returns false.  Does not copy attributes or
      * namespaces.
-     * 
-     * @param  toHere  The cursor at the location to which the XML should
-     * be copied.
+     *
+     * @param toHere The cursor at the location to which the XML should
+     *               be copied.
      * @return true if anything was copied; otherwise, false.
      */
-    boolean copyXmlContents ( XmlCursor toHere );
-    
+    boolean copyXmlContents(XmlCursor toHere);
+
     /**
-     * Removes characters up to the specified maximum number, counting right from 
-     * this cursor's location to the character at <em>maxCharacterCount</em>. The 
+     * Removes characters up to the specified maximum number, counting right from
+     * this cursor's location to the character at <em>maxCharacterCount</em>. The
      * space remaining from removing the characters collapses up to this cursor.
-     * 
-     * @param  maxCharacterCount  The maximum number of characters after this cursor's 
-     * location to remove.
-     * @return  The actual number of characters removed.
-     * @throws java.lang.IllegalArgumentException  If the operation is not allowed
-     * at the cursor's location.
+     *
+     * @param maxCharacterCount The maximum number of characters after this cursor's
+     *                          location to remove.
+     * @return The actual number of characters removed.
+     * @throws java.lang.IllegalArgumentException If the operation is not allowed
+     *                                            at the cursor's location.
      */
 
-    int removeChars ( int maxCharacterCount );
+    int removeChars(int maxCharacterCount);
 
     /**
-     * Moves characters immediately after this cursor to the position immediately 
+     * Moves characters immediately after this cursor to the position immediately
      * after the specified cursor. Characters are counted to the right up to the
-     * specified maximum number. XML after the destination cursor is 
-     * shifted to the right to make room. The space remaining from moving the 
+     * specified maximum number. XML after the destination cursor is
+     * shifted to the right to make room. The space remaining from moving the
      * characters collapses up to this cursor.
-     * 
-     * @param  maxCharacterCount  The maximum number of characters after this cursor's 
-     * location to move.
-     * @param  toHere  The cursor to which the characters should be moved.
-     * @return  The actual number of characters moved.
-     * @throws java.lang.IllegalArgumentException  If the operation is not allowed
-     * at the cursor's location.
+     *
+     * @param maxCharacterCount The maximum number of characters after this cursor's
+     *                          location to move.
+     * @param toHere            The cursor to which the characters should be moved.
+     * @return The actual number of characters moved.
+     * @throws java.lang.IllegalArgumentException If the operation is not allowed
+     *                                            at the cursor's location.
      */
 
-    int moveChars ( int maxCharacterCount, XmlCursor toHere );
+    int moveChars(int maxCharacterCount, XmlCursor toHere);
 
     /**
      * Copies characters to the position immediately after the specified cursor.
-     * Characters are counted to the right up to the specified maximum number. 
+     * Characters are counted to the right up to the specified maximum number.
      * XML after the destination cursor is shifted to the right to make room.
-     * 
-     * @param  maxCharacterCount  The maximum number of characters after this cursor's 
-     * location to copy.
-     * @param  toHere  The cursor to which the characters should be copied.
-     * @return  The actual number of characters copied.
-     * @throws java.lang.IllegalArgumentException  If the operation is not allowed
-     * at the cursor's location.
+     *
+     * @param maxCharacterCount The maximum number of characters after this cursor's
+     *                          location to copy.
+     * @param toHere            The cursor to which the characters should be copied.
+     * @return The actual number of characters copied.
+     * @throws java.lang.IllegalArgumentException If the operation is not allowed
+     *                                            at the cursor's location.
      */
 
-    int copyChars ( int maxCharacterCount, XmlCursor toHere );
+    int copyChars(int maxCharacterCount, XmlCursor toHere);
 
     /**
      * Inserts the specified text immediately before this cursor's location.
-     * 
-     * @param  text  The text to insert.
-     * @throws java.lang.IllegalArgumentException  If the insertion is not allowed
-     * at the cursor's location.
+     *
+     * @param text The text to insert.
+     * @throws java.lang.IllegalArgumentException If the insertion is not allowed
+     *                                            at the cursor's location.
      */
 
-    void insertChars ( String text );
-    
+    void insertChars(String text);
+
     /**
-     * Inserts an element immediately before this cursor's location, giving 
+     * Inserts an element immediately before this cursor's location, giving
      * the element the specified qualified name.
-     * 
-     * @param  name  The qualified name for the element.
-     * @throws java.lang.IllegalArgumentException  If the insertion is not allowed
-     * at the cursor's location.
+     *
+     * @param name The qualified name for the element.
+     * @throws java.lang.IllegalArgumentException If the insertion is not allowed
+     *                                            at the cursor's location.
      */
 
-    void insertElement ( QName name );
+    void insertElement(QName name);
 
     /**
-     * Inserts an element immediately before this cursor's location, giving 
+     * Inserts an element immediately before this cursor's location, giving
      * the element the specified local name.
-     * 
-     * @param  localName  The local name for the new element.
-     * @throws java.lang.IllegalArgumentException  If the insertion is not allowed
-     * at the cursor's location.
+     *
+     * @param localName The local name for the new element.
+     * @throws java.lang.IllegalArgumentException If the insertion is not allowed
+     *                                            at the cursor's location.
      */
 
-    void insertElement ( String localName );
+    void insertElement(String localName);
 
     /**
      * Inserts a new element immediately before this cursor's location, giving the
-     * element the specified local name and associating it with specified namespace 
-     * 
-     * @param  localName  The local name for the new element.
-     * @param  uri  The URI for the new element's namespace.
-     * @throws java.lang.IllegalArgumentException  If the insertion is not allowed
-     * at the cursor's location.
+     * element the specified local name and associating it with specified namespace
+     *
+     * @param localName The local name for the new element.
+     * @param uri       The URI for the new element's namespace.
+     * @throws java.lang.IllegalArgumentException If the insertion is not allowed
+     *                                            at the cursor's location.
      */
 
-    void insertElement ( String localName, String uri );
-    
+    void insertElement(String localName, String uri);
+
     /**
-     * Inserts a new element around this cursor, giving the element the specified 
-     * qualified name. After the element is inserted, this cursor is between its start 
-     * and end. This cursor can then be used to insert additional XML into 
+     * Inserts a new element around this cursor, giving the element the specified
+     * qualified name. After the element is inserted, this cursor is between its start
+     * and end. This cursor can then be used to insert additional XML into
      * the new element.
-     * 
-     * @param  name  The qualified name for the new element.
-     * @throws java.lang.IllegalArgumentException  If the insertion is not allowed
-     * at the cursor's location.
+     *
+     * @param name The qualified name for the new element.
+     * @throws java.lang.IllegalArgumentException If the insertion is not allowed
+     *                                            at the cursor's location.
      */
 
-    void beginElement ( QName name );
+    void beginElement(QName name);
 
     /**
-     * Inserts a new element around this cursor, giving the element the specified 
-     * local name. After the element is inserted, this cursor is between its start 
-     * and end. This cursor can then be used to insert additional XML into 
+     * Inserts a new element around this cursor, giving the element the specified
+     * local name. After the element is inserted, this cursor is between its start
+     * and end. This cursor can then be used to insert additional XML into
      * the new element.
-     * 
-     * @param  localName  The local name for the new element.
-     * @throws java.lang.IllegalArgumentException  If the insertion is not allowed
-     * at the cursor's location.
+     *
+     * @param localName The local name for the new element.
+     * @throws java.lang.IllegalArgumentException If the insertion is not allowed
+     *                                            at the cursor's location.
      */
 
-    void beginElement ( String localName );
+    void beginElement(String localName);
 
     /**
-     * Inserts a new element around this cursor, giving the element the specified 
-     * local name and associating it with the specified namespace. After the element 
-     * is inserted, this cursor is between its start and end. This cursor 
+     * Inserts a new element around this cursor, giving the element the specified
+     * local name and associating it with the specified namespace. After the element
+     * is inserted, this cursor is between its start and end. This cursor
      * can then be used to insert additional XML into the new element.
-     * 
-     * @param  localName  The local name for the new element.
-     * @param  uri  The URI for the new element's namespace.
-     * @throws java.lang.IllegalArgumentException  If the insertion is not allowed
-     * at the cursor's location.
+     *
+     * @param localName The local name for the new element.
+     * @param uri       The URI for the new element's namespace.
+     * @throws java.lang.IllegalArgumentException If the insertion is not allowed
+     *                                            at the cursor's location.
      */
 
-    void beginElement ( String localName, String uri );
-    
+    void beginElement(String localName, String uri);
+
     /**
      * Inserts a new element immediately before this cursor's location, giving the
      * element the specified qualified name and content.
-     * 
-     * @param  name  The qualified name for the new element.
-     * @param  text  The content for the new element.
-     * @throws java.lang.IllegalArgumentException  If the insertion is not allowed
-     * at the cursor's location.
+     *
+     * @param name The qualified name for the new element.
+     * @param text The content for the new element.
+     * @throws java.lang.IllegalArgumentException If the insertion is not allowed
+     *                                            at the cursor's location.
      */
 
-    void insertElementWithText ( QName name, String text );
+    void insertElementWithText(QName name, String text);
 
     /**
      * Inserts a new element immediately before this cursor's location, giving the
      * element the specified local name and content.
-     * 
-     * @param  localName  The local name for the new element.
-     * @param  text  The content for the new element.
-     * @throws java.lang.IllegalArgumentException  If the insertion is not allowed
-     * at the cursor's location.
+     *
+     * @param localName The local name for the new element.
+     * @param text      The content for the new element.
+     * @throws java.lang.IllegalArgumentException If the insertion is not allowed
+     *                                            at the cursor's location.
      */
 
-    void insertElementWithText ( String localName, String text );
+    void insertElementWithText(String localName, String text);
 
     /**
      * Inserts a new element immediately before this cursor's location, giving the
-     * element the specified local name, associating it with the specified namespace, 
+     * element the specified local name, associating it with the specified namespace,
      * and giving it the specified content.
-     * 
-     * @param  localName  The local name for the new element.
-     * @param  uri  The URI for the new element's namespace.
-     * @param  text  The content for the new element.
-     * @throws java.lang.IllegalArgumentException  If the insertion is not allowed
-     * at the cursor's location.
+     *
+     * @param localName The local name for the new element.
+     * @param uri       The URI for the new element's namespace.
+     * @param text      The content for the new element.
+     * @throws java.lang.IllegalArgumentException If the insertion is not allowed
+     *                                            at the cursor's location.
      */
 
-    void insertElementWithText ( String localName, String uri, String text );
-    
+    void insertElementWithText(String localName, String uri, String text);
+
     /**
      * Inserts a new attribute immediately before this cursor's location, giving it
      * the specified local name.
-     * 
-     * @param  localName  The local name for the new attribute.
-     * @throws java.lang.IllegalArgumentException  If the insertion is not allowed
-     * at the cursor's location.
+     *
+     * @param localName The local name for the new attribute.
+     * @throws java.lang.IllegalArgumentException If the insertion is not allowed
+     *                                            at the cursor's location.
      */
 
-    void insertAttribute ( String localName );
+    void insertAttribute(String localName);
 
     /**
      * Inserts a new attribute immediately before this cursor's location, giving it
      * the specified local name and associating it with the specified namespace.
-     * 
-     * @param  localName  The local name for the new attribute.
-     * @param  uri  The URI for the new attribute's namespace.
-     * @throws java.lang.IllegalArgumentException  If the insertion is not allowed
-     * at the cursor's location.
+     *
+     * @param localName The local name for the new attribute.
+     * @param uri       The URI for the new attribute's namespace.
+     * @throws java.lang.IllegalArgumentException If the insertion is not allowed
+     *                                            at the cursor's location.
      */
 
-    void insertAttribute ( String localName, String uri );
+    void insertAttribute(String localName, String uri);
 
     /**
      * Inserts a new attribute immediately before this cursor's location, giving it
      * the specified name.
-     * 
-     * @param  name  The local name for the new attribute.
-     * @throws java.lang.IllegalArgumentException  If the insertion is not allowed
-     * at the cursor's location.
+     *
+     * @param name The local name for the new attribute.
+     * @throws java.lang.IllegalArgumentException If the insertion is not allowed
+     *                                            at the cursor's location.
      */
 
-    void insertAttribute ( QName name );
+    void insertAttribute(QName name);
 
     /**
      * Inserts a new attribute immediately before this cursor's location, giving it
      * the specified value and name.
-     * 
-     * @param  Name  The local name for the new attribute.
-     * @param  value  The value for the new attribute.
-     * @throws java.lang.IllegalArgumentException  If the insertion is not allowed
-     * at the cursor's location.
+     *
+     * @param Name  The local name for the new attribute.
+     * @param value The value for the new attribute.
+     * @throws java.lang.IllegalArgumentException If the insertion is not allowed
+     *                                            at the cursor's location.
      */
 
-    void insertAttributeWithValue ( String Name, String value );
+    void insertAttributeWithValue(String Name, String value);
 
     /**
      * Inserts an attribute immediately before the cursor's location, giving it
      * the specified name and value, and associating it with the specified namespace.
-     * 
-     * @param  name  The name for the new attribute.
-     * @param  uri  The URI for the new attribute's namespace.
-     * @param  value  The value for the new attribute.
-     * @throws java.lang.IllegalArgumentException  If the insertion is not allowed
-     * at the cursor's location.
+     *
+     * @param name  The name for the new attribute.
+     * @param uri   The URI for the new attribute's namespace.
+     * @param value The value for the new attribute.
+     * @throws java.lang.IllegalArgumentException If the insertion is not allowed
+     *                                            at the cursor's location.
      */
 
-    void insertAttributeWithValue ( String name, String uri, String value );
+    void insertAttributeWithValue(String name, String uri, String value);
 
     /**
      * Inserts an attribute immediately before the cursor's location, giving it
      * the specified name and value.
-     * 
-     * @param  name  The name for the new attribute.
-     * @param  value  The value for the new attribute.
-     * @throws java.lang.IllegalArgumentException  If the insertion is not allowed
-     * at the cursor's location.
+     *
+     * @param name  The name for the new attribute.
+     * @param value The value for the new attribute.
+     * @throws java.lang.IllegalArgumentException If the insertion is not allowed
+     *                                            at the cursor's location.
      */
 
-    void insertAttributeWithValue ( QName name, String value );
-    
+    void insertAttributeWithValue(QName name, String value);
+
     /**
-     * Inserts a namespace declaration immediately before the cursor's location, 
+     * Inserts a namespace declaration immediately before the cursor's location,
      * giving it the specified prefix and URI.
-     * 
-     * @param  prefix  The prefix for the namespace.
-     * @param  namespace  The URI for the namespace.
-     * @throws java.lang.IllegalArgumentException  If the insertion is not allowed
-     * at the cursor's location.
+     *
+     * @param prefix    The prefix for the namespace.
+     * @param namespace The URI for the namespace.
+     * @throws java.lang.IllegalArgumentException If the insertion is not allowed
+     *                                            at the cursor's location.
      */
 
-    void insertNamespace ( String prefix, String namespace );
-    
+    void insertNamespace(String prefix, String namespace);
+
     /**
-     * Inserts an XML comment immediately before the cursor's location, 
+     * Inserts an XML comment immediately before the cursor's location,
      * giving it the specified content.
-     * 
-     * @param  text  The new comment's content.
-     * @throws java.lang.IllegalArgumentException  If the insertion is not allowed
-     * at the cursor's location.
+     *
+     * @param text The new comment's content.
+     * @throws java.lang.IllegalArgumentException If the insertion is not allowed
+     *                                            at the cursor's location.
      */
 
-    void insertComment ( String text );
+    void insertComment(String text);
 
     /**
-     * Inserts an XML processing instruction immediately before the cursor's location, 
+     * Inserts an XML processing instruction immediately before the cursor's location,
      * giving it the specified target and text.
-     * 
-     * @param  target  The target for the processing instruction.
-     * @param  text  The new processing instruction's text.
-     * @throws java.lang.IllegalStateException  If the insertion is not allowed
-     * at the cursor's location.
+     *
+     * @param target The target for the processing instruction.
+     * @param text   The new processing instruction's text.
+     * @throws java.lang.IllegalStateException If the insertion is not allowed
+     *                                         at the cursor's location.
      */
 
-    void insertProcInst ( String target, String text );
+    void insertProcInst(String target, String text);
 }
diff --git a/src/main/java/org/apache/xmlbeans/XmlOptions.java b/src/main/java/org/apache/xmlbeans/XmlOptions.java
index 7b57fc3..f45d529 100644
--- a/src/main/java/org/apache/xmlbeans/XmlOptions.java
+++ b/src/main/java/org/apache/xmlbeans/XmlOptions.java
@@ -18,13 +18,9 @@
 import org.xml.sax.EntityResolver;
 import org.xml.sax.XMLReader;
 
-import java.net.URI;
-import java.util.HashMap;
-import java.util.Map;
-import java.util.Collection;
-import java.util.Collections;
-import java.util.Set;
 import javax.xml.namespace.QName;
+import java.net.URI;
+import java.util.*;
 
 /**
  * Used to supply options for loading, saving, and compiling, and validating.
@@ -37,13 +33,13 @@
  * opts.setSavePrettyPrintIndent(4);
  * System.out.println(xobj.xmlText(opts));
  * </pre>
- * 
+ * <p>
  * The alternative is single-line usage:
  * <pre>
  * System.out.println(xobj.xmlText(
  *     new XmlOptions().setSavePrettyPrint().setSavePrettyPrintIndent(4)));
  * </pre>
- *
+ * <p>
  * Table showing where each option gets used.
  * Note that:
  * <ul>
@@ -83,117 +79,233 @@
  * </tr>
  * </table>
  */
-public class XmlOptions implements java.io.Serializable
-{
+public class XmlOptions implements java.io.Serializable {
+    //
+    // Complete set of XmlOption's
+    //
+
+    // TODO - Add selectPath option to track the seletion (deault is to clean selections fast).
+
+    public static final String SAVE_NAMESPACES_FIRST = "SAVE_NAMESPACES_FIRST";
+    public static final String SAVE_SYNTHETIC_DOCUMENT_ELEMENT = "SAVE_SYNTHETIC_DOCUMENT_ELEMENT";
+    public static final String SAVE_PRETTY_PRINT = "SAVE_PRETTY_PRINT";
+    public static final String SAVE_PRETTY_PRINT_INDENT = "SAVE_PRETTY_PRINT_INDENT";
+    public static final String SAVE_PRETTY_PRINT_OFFSET = "SAVE_PRETTY_PRINT_OFFSET";
+    public static final String SAVE_AGGRESSIVE_NAMESPACES = "SAVE_AGGRESSIVE_NAMESPACES";
+    public static final String SAVE_USE_DEFAULT_NAMESPACE = "SAVE_USE_DEFAULT_NAMESPACE";
+    public static final String SAVE_IMPLICIT_NAMESPACES = "SAVE_IMPLICIT_NAMESPACES";
+    public static final String SAVE_SUGGESTED_PREFIXES = "SAVE_SUGGESTED_PREFIXES";
+    public static final String SAVE_FILTER_PROCINST = "SAVE_FILTER_PROCINST";
+    public static final String SAVE_USE_OPEN_FRAGMENT = "SAVE_USE_OPEN_FRAGMENT";
+    public static final String SAVE_OUTER = "SAVE_OUTER";
+    public static final String SAVE_INNER = "SAVE_INNER";
+    public static final String SAVE_NO_XML_DECL = "SAVE_NO_XML_DECL";
+    public static final String SAVE_SUBSTITUTE_CHARACTERS = "SAVE_SUBSTITUTE_CHARACTERS";
+    public static final String SAVE_OPTIMIZE_FOR_SPEED = "SAVE_OPTIMIZE_FOR_SPEED";
+    public static final String SAVE_CDATA_LENGTH_THRESHOLD = "SAVE_CDATA_LENGTH_THRESHOLD";
+    public static final String SAVE_CDATA_ENTITY_COUNT_THRESHOLD = "SAVE_CDATA_ENTITY_COUNT_THRESHOLD";
+    public static final String SAVE_SAX_NO_NSDECLS_IN_ATTRIBUTES = "SAVE_SAX_NO_NSDECLS_IN_ATTRIBUTES";
+    public static final String LOAD_REPLACE_DOCUMENT_ELEMENT = "LOAD_REPLACE_DOCUMENT_ELEMENT";
+    public static final String LOAD_STRIP_WHITESPACE = "LOAD_STRIP_WHITESPACE";
+    public static final String LOAD_STRIP_COMMENTS = "LOAD_STRIP_COMMENTS";
+    public static final String LOAD_STRIP_PROCINSTS = "LOAD_STRIP_PROCINSTS";
+    public static final String LOAD_LINE_NUMBERS = "LOAD_LINE_NUMBERS";
+    public static final String LOAD_LINE_NUMBERS_END_ELEMENT = "LOAD_LINE_NUMBERS_END_ELEMENT";
+    public static final String LOAD_SAVE_CDATA_BOOKMARKS = "LOAD_SAVE_CDATA_BOOKMARKS";
+    public static final String LOAD_SUBSTITUTE_NAMESPACES = "LOAD_SUBSTITUTE_NAMESPACES";
+    public static final String LOAD_TRIM_TEXT_BUFFER = "LOAD_TRIM_TEXT_BUFFER";
+    public static final String LOAD_ADDITIONAL_NAMESPACES = "LOAD_ADDITIONAL_NAMESPACES";
+    public static final String LOAD_MESSAGE_DIGEST = "LOAD_MESSAGE_DIGEST";
+    public static final String LOAD_USE_DEFAULT_RESOLVER = "LOAD_USE_DEFAULT_RESOLVER";
+    public static final String LOAD_USE_XMLREADER = "LOAD_USE_XMLREADER";
+    public static final String XQUERY_CURRENT_NODE_VAR = "XQUERY_CURRENT_NODE_VAR";
+    public static final String XQUERY_VARIABLE_MAP = "XQUERY_VARIABLE_MAP";
+    public static final String CHARACTER_ENCODING = "CHARACTER_ENCODING";
+    public static final String ERROR_LISTENER = "ERROR_LISTENER";
+    public static final String DOCUMENT_TYPE = "DOCUMENT_TYPE";
+    public static final String DOCUMENT_SOURCE_NAME = "DOCUMENT_SOURCE_NAME";
+    public static final String COMPILE_SUBSTITUTE_NAMES = "COMPILE_SUBSTITUTE_NAMES";
+    public static final String COMPILE_NO_VALIDATION = "COMPILE_NO_VALIDATION";
+    public static final String COMPILE_NO_UPA_RULE = "COMPILE_NO_UPA_RULE";
+    public static final String COMPILE_NO_PVR_RULE = "COMPILE_NO_PVR_RULE";
+    public static final String COMPILE_NO_ANNOTATIONS = "COMPILE_NO_ANNOTATIONS";
+    public static final String COMPILE_DOWNLOAD_URLS = "COMPILE_DOWNLOAD_URLS";
+    public static final String COMPILE_MDEF_NAMESPACES = "COMPILE_MDEF_NAMESPACES";
+    public static final String VALIDATE_ON_SET = "VALIDATE_ON_SET";
+    public static final String VALIDATE_TREAT_LAX_AS_SKIP = "VALIDATE_TREAT_LAX_AS_SKIP";
+    public static final String VALIDATE_STRICT = "VALIDATE_STRICT";
+    public static final String VALIDATE_TEXT_ONLY = "VALIDATE_TEXT_ONLY";
+    public static final String UNSYNCHRONIZED = "UNSYNCHRONIZED";
+    public static final String ENTITY_RESOLVER = "ENTITY_RESOLVER";
+    public static final String BASE_URI = "BASE_URI";
+    public static final String SCHEMA_CODE_PRINTER = "SCHEMA_CODE_PRINTER";
+    public static final String GENERATE_JAVA_VERSION = "GENERATE_JAVA_VERSION";
+    public static final String COPY_USE_NEW_SYNC_DOMAIN = "COPY_USE_NEW_LOCALE";
+    public static final String LOAD_ENTITY_BYTES_LIMIT = "LOAD_ENTITY_BYTES_LIMIT";
+    public static final String ENTITY_EXPANSION_LIMIT = "ENTITY_EXPANSION_LIMIT";
+    public static final String LOAD_DTD_GRAMMAR = "LOAD_DTD_GRAMMAR";
+    public static final String LOAD_EXTERNAL_DTD = "LOAD_EXTERNAL_DTD";
+
+    public static final int DEFAULT_ENTITY_EXPANSION_LIMIT = 2048;
+    public static final String GENERATE_JAVA_14 = "1.4";
+    public static final String GENERATE_JAVA_15 = "1.5";
+
+    private static final XmlOptions EMPTY_OPTIONS;
+
+    static {
+        EMPTY_OPTIONS = new XmlOptions();
+        EMPTY_OPTIONS._map = Collections.unmodifiableMap(EMPTY_OPTIONS._map);
+    }
+
+
     private static final long serialVersionUID = 1L;
-    
-    private Map _map = new HashMap();
+
+    private Map<String, Object> _map = new HashMap<>();
 
 
     /**
      * Construct a new blank XmlOptions.
      */
-    public XmlOptions ( ) { }
+    public XmlOptions() {
+    }
 
     /**
      * Construct a new XmlOptions, copying the options.
      */
-    public XmlOptions (XmlOptions other) {
-        if (other != null) _map.putAll(other._map);
+    public XmlOptions(XmlOptions other) {
+        if (other != null) {
+            _map.putAll(other._map);
+        }
     }
-            
+
     //
     // Handy-dandy helper methods for setting some options
     //
 
     /**
      * This option will cause the saver to save namespace attributes first.
-     * 
+     *
      * @see XmlTokenSource#save(java.io.File, XmlOptions)
      * @see XmlTokenSource#xmlText(XmlOptions)
      */
-    public XmlOptions setSaveNamespacesFirst() { 
-        return set( SAVE_NAMESPACES_FIRST ); 
+    public XmlOptions setSaveNamespacesFirst() {
+        return setSaveNamespacesFirst(true);
     }
+
+    public XmlOptions setSaveNamespacesFirst(boolean b) {
+        return set(SAVE_NAMESPACES_FIRST, b);
+    }
+
+    public boolean isSaveNamespacesFirst() {
+        return hasOption(SAVE_NAMESPACES_FIRST);
+    }
+
+
     /**
      * This option will cause the saver to reformat white space for easier reading.
-     * 
+     *
      * @see XmlTokenSource#save(java.io.File, XmlOptions)
      * @see XmlTokenSource#xmlText(XmlOptions)
      */
-    public XmlOptions setSavePrettyPrint() { 
-        return set( SAVE_PRETTY_PRINT ); 
+    public XmlOptions setSavePrettyPrint() {
+        return setSavePrettyPrint(true);
     }
 
+    public XmlOptions setSavePrettyPrint(boolean b) {
+        return set(SAVE_PRETTY_PRINT, b);
+    }
+
+    public boolean isSavePrettyPrint() {
+        return hasOption(SAVE_PRETTY_PRINT);
+    }
+
+
     /**
      * When used with <code>setSavePrettyPrint</code> this sets the indent
      * amount to use.
-     * 
+     *
      * @param indent the indent amount to use
      * @see #setSavePrettyPrint
      * @see XmlTokenSource#save(java.io.File, XmlOptions)
      * @see XmlTokenSource#xmlText(XmlOptions)
      */
-    public XmlOptions setSavePrettyPrintIndent(int indent) { 
-        return set( SAVE_PRETTY_PRINT_INDENT, indent ); 
+    public XmlOptions setSavePrettyPrintIndent(int indent) {
+        return set(SAVE_PRETTY_PRINT_INDENT, indent);
+    }
+
+    public Integer getSavePrettyPrintIndent() {
+        return (Integer) get(SAVE_PRETTY_PRINT_INDENT);
     }
 
     /**
      * When used with <code>setSavePrettyPrint</code> this sets the offset
      * amount to use.
-     * 
+     *
      * @param offset the offset amount to use
      * @see #setSavePrettyPrint
      * @see XmlTokenSource#save(java.io.File, XmlOptions)
      * @see XmlTokenSource#xmlText(XmlOptions)
      */
-    public XmlOptions setSavePrettyPrintOffset(int offset) { 
-        return set( SAVE_PRETTY_PRINT_OFFSET, offset ); 
+    public XmlOptions setSavePrettyPrintOffset(int offset) {
+        return set(SAVE_PRETTY_PRINT_OFFSET, offset);
+    }
+
+    public Integer getSavePrettyPrintOffset() {
+        return (Integer) get(SAVE_PRETTY_PRINT_OFFSET);
     }
 
     /**
      * When writing a document, this sets the character
      * encoding to use.
-     * 
+     *
      * @param encoding the character encoding
      * @see XmlObject.Factory#parse(java.io.File, XmlOptions)
      * @see XmlTokenSource#save(java.io.File, XmlOptions)
      */
-    public XmlOptions setCharacterEncoding(String encoding) { 
-        return set( CHARACTER_ENCODING, encoding ); 
+    public XmlOptions setCharacterEncoding(String encoding) {
+        return set(CHARACTER_ENCODING, encoding);
+    }
+
+    public String getCharacterEncoding() {
+        return (String) get(CHARACTER_ENCODING);
     }
 
     /**
      * When parsing a document, this sets the type of the root
      * element. If this is set, the parser will not try to guess
      * the type based on the document's <code>QName</code>.
-     * 
+     *
      * @param type The root element's document type.
      * @see XmlObject.Factory#parse(java.io.File, XmlOptions)
      */
     public XmlOptions setDocumentType(SchemaType type) {
-        return set( DOCUMENT_TYPE, type ); 
+        return set(DOCUMENT_TYPE, type);
     }
 
+    public SchemaType getDocumentType() {
+        return (SchemaType) get(DOCUMENT_TYPE);
+    }
+
+
     /**
-     * <p>Sets a collection object for collecting {@link XmlError} objects 
-     * during parsing, validation, and compilation. When set, the collection 
+     * <p>Sets a collection object for collecting {@link XmlError} objects
+     * during parsing, validation, and compilation. When set, the collection
      * will contain all the errors after the operation takes place.  Notice that
      * the errors will only have line numbers if the document was
      * loaded with line numbers enabled.</p>
-     * 
+     *
      * <p>The following simple example illustrates using an error listener
      * during validation.</p>
-     * 
+     *
      * <pre>
      * // Create an XmlOptions instance and set the error listener.
      * XmlOptions validateOptions = new XmlOptions();
      * ArrayList errorList = new ArrayList();
      * validateOptions.setErrorListener(errorList);
-     * 
+     *
      * // Validate the XML.
      * boolean isValid = newEmp.validate(validateOptions);
-     * 
+     *
      * // If the XML isn't valid, loop through the listener's contents,
      * // printing contained messages.
      * if (!isValid)
@@ -201,26 +313,30 @@
      *      for (int i = 0; i < errorList.size(); i++)
      *      {
      *          XmlError error = (XmlError)errorList.get(i);
-     *          
+     *
      *          System.out.println("\n");
      *          System.out.println("Message: " + error.getMessage() + "\n");
-     *          System.out.println("Location of invalid XML: " + 
+     *          System.out.println("Location of invalid XML: " +
      *              error.getCursorLocation().xmlText() + "\n");
      *      }
      * }
      * </pre>
-     * 
-     * @param c A collection that will be filled with {@link XmlError} objects 
-     * via {@link Collection#add}
-     * 
+     *
+     * @param c A collection that will be filled with {@link XmlError} objects
+     *          via {@link Collection#add}
      * @see XmlError
      * @see XmlObject.Factory#parse(java.io.File, XmlOptions)
      * @see XmlObject#validate(XmlOptions)
      * @see XmlBeans#compileXsd
      * @see XmlOptions#setLoadLineNumbers
      */
-    public XmlOptions setErrorListener (Collection c) { 
-        return set( ERROR_LISTENER, c ); 
+    public XmlOptions setErrorListener(Collection<XmlError> c) {
+        return set(ERROR_LISTENER, c);
+    }
+
+    @SuppressWarnings("unchecked")
+    public Collection<XmlError> getErrorListener() {
+        return (Collection<XmlError>) get(ERROR_LISTENER);
     }
 
     /**
@@ -234,142 +350,203 @@
      * @see XmlTokenSource#xmlText(XmlOptions)
      */
     public XmlOptions setSaveAggressiveNamespaces() {
-        return set( SAVE_AGGRESSIVE_NAMESPACES ); 
+        return setSaveAggressiveNamespaces(true);
     }
 
-    /**
-     * @deprecated replaced by {@link #setSaveAggressiveNamespaces}
-     */
-    public XmlOptions setSaveAggresiveNamespaces() { 
-        return setSaveAggressiveNamespaces(); 
+    public XmlOptions setSaveAggressiveNamespaces(boolean b) {
+        return set(SAVE_AGGRESSIVE_NAMESPACES, b);
     }
 
+    public boolean isSaveAggressiveNamespaces() {
+        return hasOption(SAVE_AGGRESSIVE_NAMESPACES);
+    }
+
+
     /**
      * This option causes the saver to wrap the current fragment in
      * an element with the given name.
-     * 
+     *
      * @param name the name to use for the top level element
-     * 
      * @see XmlTokenSource#save(java.io.File, XmlOptions)
      * @see XmlTokenSource#xmlText(XmlOptions)
      */
-    public XmlOptions setSaveSyntheticDocumentElement (QName name) { 
-        return set( SAVE_SYNTHETIC_DOCUMENT_ELEMENT, name ); 
+    public XmlOptions setSaveSyntheticDocumentElement(QName name) {
+        return set(SAVE_SYNTHETIC_DOCUMENT_ELEMENT, name);
     }
 
+    public QName getSaveSyntheticDocumentElement() {
+        return (QName) get(SAVE_SYNTHETIC_DOCUMENT_ELEMENT);
+    }
+
+
     /**
      * If this option is set, the saver will try to use the default
      * namespace for the most commonly used URI. If it is not set
      * the saver will always created named prefixes.
-     * 
+     *
      * @see XmlTokenSource#save(java.io.File, XmlOptions)
      * @see XmlTokenSource#xmlText(XmlOptions)
      */
-    public XmlOptions setUseDefaultNamespace () { 
-        return set( SAVE_USE_DEFAULT_NAMESPACE ); 
+    public XmlOptions setUseDefaultNamespace() {
+        return setUseDefaultNamespace(true);
+    }
+
+    public XmlOptions setUseDefaultNamespace(boolean b) {
+        return set(SAVE_USE_DEFAULT_NAMESPACE, b);
+    }
+
+    public boolean isUseDefaultNamespace() {
+        return hasOption(SAVE_USE_DEFAULT_NAMESPACE);
     }
 
     /**
      * If namespaces have already been declared outside the scope of the
      * fragment being saved, this allows those mappings to be passed
      * down to the saver, so the prefixes are not re-declared.
-     * 
+     *
      * @param implicitNamespaces a map of prefixes to uris that can be
-     *  used by the saver without being declared
-     * 
+     *                           used by the saver without being declared
      * @see XmlTokenSource#save(java.io.File, XmlOptions)
      * @see XmlTokenSource#xmlText(XmlOptions)
-     */ 
-    public XmlOptions setSaveImplicitNamespaces (Map implicitNamespaces) { 
-        return set( SAVE_IMPLICIT_NAMESPACES, implicitNamespaces ); 
+     */
+    public XmlOptions setSaveImplicitNamespaces(Map<String, String> implicitNamespaces) {
+        return set(SAVE_IMPLICIT_NAMESPACES, implicitNamespaces);
+    }
+
+    @SuppressWarnings("unchecked")
+    public Map<String, String> getSaveImplicitNamespaces() {
+        return (Map<String, String>) get(SAVE_IMPLICIT_NAMESPACES);
     }
 
     /**
      * A map of hints to pass to the saver for which prefixes to use
      * for which namespace URI.
-     * 
+     *
      * @param suggestedPrefixes a map from URIs to prefixes
-     * 
      * @see XmlTokenSource#save(java.io.File, XmlOptions)
      * @see XmlTokenSource#xmlText(XmlOptions)
      */
-    public XmlOptions setSaveSuggestedPrefixes (Map suggestedPrefixes) { 
-        return set( SAVE_SUGGESTED_PREFIXES, suggestedPrefixes ); 
+    public XmlOptions setSaveSuggestedPrefixes(Map<String, String> suggestedPrefixes) {
+        return set(SAVE_SUGGESTED_PREFIXES, suggestedPrefixes);
+    }
+
+    @SuppressWarnings("unchecked")
+    public Map<String, String> getSaveSuggestedPrefixes() {
+        return (Map<String, String>) get(SAVE_SUGGESTED_PREFIXES);
     }
 
     /**
      * This option causes the saver to filter a Processing Instruction
      * with the given target
-     * 
+     *
      * @param filterProcinst the name of a Processing Instruction to filter
-     *   on save
-     * 
+     *                       on save
      * @see XmlTokenSource#save(java.io.File, XmlOptions)
      * @see XmlTokenSource#xmlText(XmlOptions)
      */
-    public XmlOptions setSaveFilterProcinst (String filterProcinst) { 
-        return set( SAVE_FILTER_PROCINST, filterProcinst ); 
+    public XmlOptions setSaveFilterProcinst(String filterProcinst) {
+        return set(SAVE_FILTER_PROCINST, filterProcinst);
+    }
+
+    public String getSaveFilterProcinst() {
+        return (String) get(SAVE_FILTER_PROCINST);
     }
 
     /**
      * This option causes the saver to replace characters with other values in
      * the output stream.  It is intended to be used for escaping non-standard
      * characters during output.
-     * 
+     *
      * @param characterReplacementMap is an XmlOptionCharEscapeMap containing
-     * the characters to be escaped.
-     * 
+     *                                the characters to be escaped.
      * @see XmlTokenSource#save(java.io.File, XmlOptions)
      * @see XmlTokenSource#xmlText(XmlOptions)
      * @see XmlOptionCharEscapeMap
      */
-    public XmlOptions setSaveSubstituteCharacters (
+    public XmlOptions setSaveSubstituteCharacters(
         XmlOptionCharEscapeMap characterReplacementMap) {
-        return set( SAVE_SUBSTITUTE_CHARACTERS, characterReplacementMap );
+        return set(SAVE_SUBSTITUTE_CHARACTERS, characterReplacementMap);
+    }
+
+    public XmlOptionCharEscapeMap getSaveSubstituteCharacters() {
+        return (XmlOptionCharEscapeMap) get(SAVE_SUBSTITUTE_CHARACTERS);
     }
 
     /**
      * When saving a fragment, this option changes the qname of the synthesized
      * root element.  Normally &lt;xml-fragment&gt; is used.
-     * 
+     *
      * @see XmlTokenSource#save(java.io.File, XmlOptions)
      * @see XmlTokenSource#xmlText(XmlOptions)
      */
-    public XmlOptions setSaveUseOpenFrag () { 
-        return set( SAVE_USE_OPEN_FRAGMENT ); 
+    public XmlOptions setSaveUseOpenFrag() {
+        return setSaveUseOpenFrag(true);
+    }
+
+    public XmlOptions setSaveUseOpenFrag(boolean b) {
+        return set(SAVE_USE_OPEN_FRAGMENT, b);
+    }
+
+    public boolean isSaveUseOpenFrag() {
+        return hasOption(SAVE_USE_OPEN_FRAGMENT);
     }
 
     /**
      * This option controls whether saving begins on the element or its contents
-     * 
+     *
      * @see XmlTokenSource#save(java.io.File, XmlOptions)
      * @see XmlTokenSource#xmlText(XmlOptions)
      */
-    public XmlOptions setSaveOuter () { 
-        return set( SAVE_OUTER ); 
+    public XmlOptions setSaveOuter() {
+        return setSaveOuter(true);
+    }
+
+    public XmlOptions setSaveOuter(boolean b) {
+        return set(SAVE_OUTER, b);
+    }
+
+    public boolean isSaveOuter() {
+        return hasOption(SAVE_OUTER);
     }
 
     /**
      * This option controls whether saving begins on the element or its contents
-     * 
+     *
      * @see XmlTokenSource#save(java.io.File, XmlOptions)
      * @see XmlTokenSource#xmlText(XmlOptions)
      */
-    public XmlOptions setSaveInner () { 
-        return set( SAVE_INNER ); 
+    public XmlOptions setSaveInner() {
+        return setSaveInner(true);
+    }
+
+    public XmlOptions setSaveInner(boolean b) {
+        return set(SAVE_INNER, b);
+    }
+
+    public boolean isSaveInner() {
+        return hasOption(SAVE_INNER);
     }
 
     /**
      * This option controls whether saving saves out the XML
      * declaration (<?xml ... ?>
-     * 
+     *
      * @see XmlTokenSource#save(java.io.File, XmlOptions)
      * @see XmlTokenSource#xmlText(XmlOptions)
      */
-    public XmlOptions setSaveNoXmlDecl () { 
-        return set( SAVE_NO_XML_DECL ); 
+    public XmlOptions setSaveNoXmlDecl() {
+        return setSaveNoXmlDecl(true);
     }
 
+    public XmlOptions setSaveNoXmlDecl(boolean b) {
+        return set(SAVE_NO_XML_DECL, b);
+    }
+
+    public boolean isSaveNoXmlDecl() {
+        return hasOption(SAVE_NO_XML_DECL);
+    }
+
+
     /**
      * This option controls when saving will use CDATA blocks.
      * CDATA will be used if the folowing condition is true:
@@ -385,12 +562,18 @@
      * <tr><td>Only text that has y entitazable chars is CDATA</td> <td>0</td> <td>y</td></tr>
      * <tr><td>Only text longer than x chars and has y entitazable chars is CDATA</td> <td>x</td> <td>y</td></tr>
      * </table>
+     *
      * @see XmlOptions#setSaveCDataEntityCountThreshold(int)
      */
-    public XmlOptions setSaveCDataLengthThreshold (int cdataLengthThreshold) {
-        return set( SAVE_CDATA_LENGTH_THRESHOLD, cdataLengthThreshold );
+    public XmlOptions setSaveCDataLengthThreshold(int cdataLengthThreshold) {
+        return set(SAVE_CDATA_LENGTH_THRESHOLD, cdataLengthThreshold);
     }
 
+    public Integer getSaveCDataLengthThreshold() {
+        return (Integer) get(SAVE_CDATA_LENGTH_THRESHOLD);
+    }
+
+
     /**
      * This option controls when saving will use CDATA blocks.
      * CDATA will be used if the folowing condition is true:
@@ -399,8 +582,12 @@
      *
      * @see XmlOptions#setSaveCDataLengthThreshold(int)
      */
-    public XmlOptions setSaveCDataEntityCountThreshold (int cdataEntityCountThreshold) {
-        return set( SAVE_CDATA_ENTITY_COUNT_THRESHOLD, cdataEntityCountThreshold );
+    public XmlOptions setSaveCDataEntityCountThreshold(int cdataEntityCountThreshold) {
+        return set(SAVE_CDATA_ENTITY_COUNT_THRESHOLD, cdataEntityCountThreshold);
+    }
+
+    public Integer getSaveCDataEntityCountThreshold() {
+        return (Integer) get(SAVE_CDATA_ENTITY_COUNT_THRESHOLD);
     }
 
     /**
@@ -426,32 +613,35 @@
      *
      * <p>Sample code:
      * <pre>
-        String xmlText = "&lt;a>\n" +
-                "&lt;a>&lt;![CDATA[cdata text]]>&lt;/a>\n" +
-                "&lt;b>&lt;![CDATA[cdata text]]> regular text&lt;/b>\n" +
-                "&lt;c>text &lt;![CDATA[cdata text]]>&lt;/c>\n" +
-                "&lt;/a>";
-        System.out.println(xmlText);
-
-        XmlOptions opts = new XmlOptions();
-        opts.setUseCDataBookmarks();
-
-        XmlObject xo = XmlObject.Factory.parse( xmlText , opts);
-
-        System.out.println("xo1:\n" + xo.xmlText(opts));
-        System.out.println("\n");
-
-        opts.setSavePrettyPrint();
-        System.out.println("xo2:\n" + xo.xmlText(opts));
+     * String xmlText = "&lt;a>\n" +
+     * "&lt;a>&lt;![CDATA[cdata text]]>&lt;/a>\n" +
+     * "&lt;b>&lt;![CDATA[cdata text]]> regular text&lt;/b>\n" +
+     * "&lt;c>text &lt;![CDATA[cdata text]]>&lt;/c>\n" +
+     * "&lt;/a>";
+     * System.out.println(xmlText);
+     *
+     * XmlOptions opts = new XmlOptions();
+     * opts.setUseCDataBookmarks();
+     *
+     * XmlObject xo = XmlObject.Factory.parse( xmlText , opts);
+     *
+     * System.out.println("xo1:\n" + xo.xmlText(opts));
+     * System.out.println("\n");
+     *
+     * opts.setSavePrettyPrint();
+     * System.out.println("xo2:\n" + xo.xmlText(opts));
      * </pre>
      * </p>
      *
      * @see CDataBookmark
      * @see CDataBookmark#CDATA_BOOKMARK
      */
-    public XmlOptions setUseCDataBookmarks()
-    {
-        return set( LOAD_SAVE_CDATA_BOOKMARKS );        
+    public XmlOptions setUseCDataBookmarks() {
+        return set(LOAD_SAVE_CDATA_BOOKMARKS);
+    }
+
+    public boolean isUseCDataBookmarks() {
+        return hasOption(LOAD_SAVE_CDATA_BOOKMARKS);
     }
 
     /**
@@ -459,50 +649,87 @@
      * startElement event. By default, up to and including XMLBeans 2.3.0 they were included, in
      * subsequent versions, they are no longer included.
      */
-    public XmlOptions setSaveSaxNoNSDeclsInAttributes () {
-        return set( SAVE_SAX_NO_NSDECLS_IN_ATTRIBUTES );
+    public XmlOptions setSaveSaxNoNSDeclsInAttributes() {
+        return setSaveSaxNoNSDeclsInAttributes(true);
     }
 
+    public XmlOptions setSaveSaxNoNSDeclsInAttributes(boolean b) {
+        return set(SAVE_SAX_NO_NSDECLS_IN_ATTRIBUTES, b);
+    }
+
+    public boolean isSaveSaxNoNSDeclsInAttributes() {
+        return hasOption(SAVE_SAX_NO_NSDECLS_IN_ATTRIBUTES);
+    }
+
+
     /**
      * If this option is set, the document element is replaced with the
      * given QName when parsing.  If null is supplied, the document element
      * is removed.
-     * 
+     *
      * @see XmlObject.Factory#parse(java.io.File, XmlOptions)
      */
-    public XmlOptions setLoadReplaceDocumentElement ( QName replacement ) { 
-        return set( LOAD_REPLACE_DOCUMENT_ELEMENT, replacement ); 
+    public XmlOptions setLoadReplaceDocumentElement(QName replacement) {
+        return set(LOAD_REPLACE_DOCUMENT_ELEMENT, replacement);
+    }
+
+    public QName getLoadReplaceDocumentElement() {
+        return (QName) get(LOAD_REPLACE_DOCUMENT_ELEMENT);
     }
 
     /**
      * If this option is set, all insignificant whitespace is stripped
      * when parsing a document.  Can be used to save memory on large
      * documents when you know there is no mixed content.
-     * 
+     *
      * @see XmlObject.Factory#parse(java.io.File, XmlOptions)
      */
-    public XmlOptions setLoadStripWhitespace () { 
-        return set( LOAD_STRIP_WHITESPACE); 
+    public XmlOptions setLoadStripWhitespace() {
+        return setLoadStripWhitespace(true);
+    }
+
+    public XmlOptions setLoadStripWhitespace(boolean b) {
+        return set(LOAD_STRIP_WHITESPACE, b);
+    }
+
+    public boolean isSetLoadStripWhitespace() {
+        return hasOption(LOAD_STRIP_WHITESPACE);
     }
 
     /**
      * If this option is set, all comments are stripped when parsing
      * a document.
-     * 
+     *
      * @see XmlObject.Factory#parse(java.io.File, XmlOptions)
      */
     public XmlOptions setLoadStripComments() {
-        return set( LOAD_STRIP_COMMENTS ); 
+        return setLoadStripComments(true);
+    }
+
+    public XmlOptions setLoadStripComments(boolean b) {
+        return set(LOAD_STRIP_COMMENTS, b);
+    }
+
+    public boolean isLoadStripComments() {
+        return hasOption(LOAD_STRIP_COMMENTS);
     }
 
     /**
-     * If this option is set, all processing instructions 
+     * If this option is set, all processing instructions
      * are stripped when parsing a document.
-     * 
+     *
      * @see XmlObject.Factory#parse(java.io.File, XmlOptions)
      */
-    public XmlOptions setLoadStripProcinsts () { 
-        return set( LOAD_STRIP_PROCINSTS ); 
+    public XmlOptions setLoadStripProcinsts() {
+        return setLoadStripProcinsts(true);
+    }
+
+    public XmlOptions setLoadStripProcinsts(boolean b) {
+        return set(LOAD_STRIP_PROCINSTS, b);
+    }
+
+    public boolean isLoadStripProcinsts() {
+        return hasOption(LOAD_STRIP_PROCINSTS);
     }
 
     /**
@@ -512,30 +739,41 @@
      * line numbers.
      * <br/>Note: This adds line numbers info only for start tags.
      * For line number info on end tags use:
-     *   {@link XmlOptions#setLoadLineNumbers(java.lang.String)}
-     * <br/>Example: xmlOptions.setLoadLineNumbers(XmlOptions.LOAD_LINE_NUMBERS_END_ELEMENT)
-     * 
-     * @see XmlObject.Factory#parse(java.io.File, XmlOptions)
-     * @see XmlError
-     */
-    public XmlOptions setLoadLineNumbers () { 
-        return set( LOAD_LINE_NUMBERS ); 
-    }
-
-     /**
-     * If this option is set, line number annotations are placed
-     * in the store when parsing a document.  This is particularly
-     * useful when you want {@link XmlError} objects to contain
-     * line numbers. Use the option to load line numbers at the end of an element.
-     * <br/>Example: xmlOptions.setLoadLineNumbers(XmlOptions.LOAD_LINE_NUMBERS_END_ELEMENT)
+     * {@link XmlOptions#setLoadLineNumbersEndElement()}
      *
      * @see XmlObject.Factory#parse(java.io.File, XmlOptions)
      * @see XmlError
      */
-    public XmlOptions setLoadLineNumbers (String option) {
-        XmlOptions temp = setLoadLineNumbers();
-        temp = temp.set( option );
-        return temp;
+    public XmlOptions setLoadLineNumbers() {
+        return setLoadLineNumbers(true);
+    }
+
+    public XmlOptions setLoadLineNumbers(boolean b) {
+        return set(LOAD_LINE_NUMBERS, b);
+    }
+
+    public boolean isLoadLineNumbers() {
+        return hasOption(LOAD_LINE_NUMBERS);
+    }
+
+
+    /**
+     * If this option is set, line number annotations are placed
+     * in the store when parsing a document.  This is particularly
+     * useful when you want {@link XmlError} objects to contain
+     * line numbers. Use the option to load line numbers at the end of an element.
+     */
+    public XmlOptions setLoadLineNumbersEndElement() {
+        return setLoadLineNumbersEndElement(true);
+    }
+
+    public XmlOptions setLoadLineNumbersEndElement(boolean b) {
+        setLoadLineNumbers(true);
+        return set(LOAD_LINE_NUMBERS_END_ELEMENT, b);
+    }
+
+    public boolean isLoadLineNumbersEndElement() {
+        return hasOption(LOAD_LINE_NUMBERS_END_ELEMENT);
     }
 
     /**
@@ -553,13 +791,17 @@
      * to type the instance according to a schema in a nonempty namespace,
      * and therefore avoid the problematic practice of using schema
      * definitions without a target namespace.
-     * 
+     *
      * @param substNamespaces a map of document URIs to replacement URIs
-     * 
      * @see XmlObject.Factory#parse(java.io.File, XmlOptions)
      */
-    public XmlOptions setLoadSubstituteNamespaces (Map substNamespaces) { 
-        return set( LOAD_SUBSTITUTE_NAMESPACES, substNamespaces ); 
+    public XmlOptions setLoadSubstituteNamespaces(Map<String, String> substNamespaces) {
+        return set(LOAD_SUBSTITUTE_NAMESPACES, substNamespaces);
+    }
+
+    @SuppressWarnings("unchecked")
+    public Map<String, String> getLoadSubstituteNamespaces() {
+        return (Map<String, String>) get(LOAD_SUBSTITUTE_NAMESPACES);
     }
 
     /**
@@ -567,23 +809,35 @@
      * immediately after parsing a document resulting in a smaller memory
      * footprint.  Use this option if you are loading a large number
      * of unchanging documents that will stay in memory for some time.
-     * 
+     *
      * @see XmlObject.Factory#parse(java.io.File, XmlOptions)
      */
-    public XmlOptions setLoadTrimTextBuffer () { 
-        return set( LOAD_TRIM_TEXT_BUFFER ); 
+    public XmlOptions setLoadTrimTextBuffer() {
+        return setLoadTrimTextBuffer(true);
+    }
+
+    public XmlOptions setLoadTrimTextBuffer(boolean b) {
+        return set(LOAD_TRIM_TEXT_BUFFER, b);
+    }
+
+    public boolean isLoadTrimTextBuffer() {
+        return hasOption(LOAD_TRIM_TEXT_BUFFER);
     }
 
     /**
      * Set additional namespace mappings to be added when parsing
      * a document.
-     * 
+     *
      * @param nses additional namespace mappings
-     * 
      * @see XmlObject.Factory#parse(java.io.File, XmlOptions)
      */
-    public XmlOptions setLoadAdditionalNamespaces (Map nses) { 
-        return set( LOAD_ADDITIONAL_NAMESPACES, nses ); 
+    public XmlOptions setLoadAdditionalNamespaces(Map<String, String> nses) {
+        return set(LOAD_ADDITIONAL_NAMESPACES, nses);
+    }
+
+    @SuppressWarnings("unchecked")
+    public Map<String, String> getLoadAdditionalNamespaces() {
+        return (Map<String, String>) get(LOAD_ADDITIONAL_NAMESPACES);
     }
 
     /**
@@ -594,24 +848,41 @@
      * <br>
      * The schema compiler uses message digests to detect and eliminate
      * duplicate imported xsd files.
-     * 
+     *
      * @see XmlObject.Factory#parse(java.io.File, XmlOptions)
      */
-    public XmlOptions setLoadMessageDigest () { 
-        return set( LOAD_MESSAGE_DIGEST ); 
+    public XmlOptions setLoadMessageDigest() {
+        return setLoadMessageDigest(true);
+    }
+
+    public XmlOptions setLoadMessageDigest(boolean b) {
+        return set(LOAD_MESSAGE_DIGEST, b);
+    }
+
+    public boolean isLoadMessageDigest() {
+        return hasOption(LOAD_MESSAGE_DIGEST);
     }
 
     /**
      * By default, XmlBeans does not resolve entities when parsing xml
      * documents (unless an explicit entity resolver is specified).
      * Use this option to turn on entity resolving by default.
-     * 
+     *
      * @see XmlObject.Factory#parse(java.io.File, XmlOptions)
      */
-    public XmlOptions setLoadUseDefaultResolver () { 
-        return set( LOAD_USE_DEFAULT_RESOLVER ); 
+    public XmlOptions setLoadUseDefaultResolver() {
+        return setLoadUseDefaultResolver(true);
     }
 
+    public XmlOptions setLoadUseDefaultResolver(boolean b) {
+        return set(LOAD_USE_DEFAULT_RESOLVER, b);
+    }
+
+    public boolean isLoadUseDefaultResolver() {
+        return hasOption(LOAD_USE_DEFAULT_RESOLVER);
+    }
+
+
     /**
      * By default, XmlBeans creates a JAXP parser,
      * other parsers can be used by providing an XMLReader.
@@ -620,21 +891,28 @@
      *
      * @see XmlObject.Factory#parse(java.io.File, XmlOptions)
      */
-    public XmlOptions setLoadUseXMLReader (XMLReader xmlReader) {
-        return set( LOAD_USE_XMLREADER, xmlReader );
+    public XmlOptions setLoadUseXMLReader(XMLReader xmlReader) {
+        return set(LOAD_USE_XMLREADER, xmlReader);
+    }
+
+    public XMLReader getLoadUseXMLReader() {
+        return (XMLReader) get(LOAD_USE_XMLREADER);
     }
 
     /**
      * Sets the name of the variable that represents
      * the current node in a query expression.
-     * 
+     *
      * @param varName The new variable name to use for the query.
-     * 
      * @see XmlObject#execQuery
      * @see XmlCursor#execQuery
      */
-    public XmlOptions setXqueryCurrentNodeVar (String varName) { 
-        return set( XQUERY_CURRENT_NODE_VAR, varName ); 
+    public XmlOptions setXqueryCurrentNodeVar(String varName) {
+        return set(XQUERY_CURRENT_NODE_VAR, varName);
+    }
+
+    public String getXqueryCurrentNodeVar() {
+        return (String) get(XQUERY_CURRENT_NODE_VAR);
     }
 
     /**
@@ -646,12 +924,16 @@
      * xquery and has no effect on xpath expressions.
      *
      * @param varMap a map from Strings to variable instances.
-     *
      * @see XmlObject#execQuery
      * @see XmlCursor#execQuery
      */
-    public XmlOptions setXqueryVariables (Map varMap) {
-        return set( XQUERY_VARIABLE_MAP, varMap );
+    public XmlOptions setXqueryVariables(Map<String, Object> varMap) {
+        return set(XQUERY_VARIABLE_MAP, varMap);
+    }
+
+    @SuppressWarnings("unchecked")
+    public Map<String, Object> getXqueryVariables() {
+        return (Map<String, Object>) get(XQUERY_VARIABLE_MAP);
     }
 
     /**
@@ -659,33 +941,45 @@
      * when parsing a document.  If a document is parsed from a
      * File or URI, it is automatically set to the URI of the
      * source; otherwise, for example, when parsing a String,
-     * you can use this option to specify the source name yourself. 
-     * 
+     * you can use this option to specify the source name yourself.
+     *
      * @see XmlObject.Factory#parse(java.lang.String, XmlOptions)
      */
-    public XmlOptions setDocumentSourceName (String documentSourceName) { 
-        return set( DOCUMENT_SOURCE_NAME, documentSourceName ); 
+    public XmlOptions setDocumentSourceName(String documentSourceName) {
+        return set(DOCUMENT_SOURCE_NAME, documentSourceName);
+    }
+
+    public String getDocumentSourceName() {
+        return (String) get(DOCUMENT_SOURCE_NAME);
     }
 
     /**
      * This option allows for <code>QName</code> substitution during schema compilation.
-     * 
+     *
      * @param nameMap a map from <code>QName</code>s to substitute <code>QName</code>s.
-     * 
      * @see XmlBeans#compileXsd
      */
-    public XmlOptions setCompileSubstituteNames (Map nameMap) { 
-        return set( COMPILE_SUBSTITUTE_NAMES, nameMap ); 
+    public XmlOptions setCompileSubstituteNames(Map<QName, QName> nameMap) {
+        return set(COMPILE_SUBSTITUTE_NAMES, nameMap);
     }
-    
+
+    @SuppressWarnings("unchecked")
+    public Map<QName, QName> getCompileSubstituteNames() {
+        return (Map<QName, QName>) get(COMPILE_SUBSTITUTE_NAMES);
+    }
+
     /**
      * If this option is set, validation is not done on the Schema XmlBeans
      * when building a <code>SchemaTypeSystem</code>
-     * 
+     *
      * @see XmlBeans#compileXsd
      */
-    public XmlOptions setCompileNoValidation () { 
-        return set( COMPILE_NO_VALIDATION ); 
+    public XmlOptions setCompileNoValidation() {
+        return set(COMPILE_NO_VALIDATION);
+    }
+
+    public boolean isCompileNoValidation() {
+        return hasOption(COMPILE_NO_VALIDATION);
     }
 
     /**
@@ -693,59 +987,94 @@
      * enforced when building a <code>SchemaTypeSystem</code>. See
      * <a target="_blank" href="http://www.w3.org/TR/xmlschema-1/#non-ambig">Appendix H of the XML Schema specification</a>
      * for information on the UPA rule.
-     * 
+     *
      * @see XmlBeans#compileXsd
      */
-    public XmlOptions setCompileNoUpaRule () { 
-        return set( COMPILE_NO_UPA_RULE ); 
+    public XmlOptions setCompileNoUpaRule() {
+        return setCompileNoUpaRule(true);
     }
-    
+
+    public XmlOptions setCompileNoUpaRule(boolean b) {
+        return set(COMPILE_NO_UPA_RULE, b);
+    }
+
+    public boolean isCompileNoUpaRule() {
+        return hasOption(COMPILE_NO_UPA_RULE);
+    }
+
     /**
      * If this option is set, the particle valid (restriciton) rule is not
      * enforced when building a <code>SchemaTypeSystem</code>. See
      * <a target="_blank" href="http://www.w3.org/TR/xmlschema-1/#cos-particle-restrict">Section 3.9.6 of the XML Schema specification</a>
      * for information on the PVR rule.
-     * 
+     *
      * @see XmlBeans#compileXsd
      */
-    public XmlOptions setCompileNoPvrRule () { 
-        return set( COMPILE_NO_PVR_RULE ); 
+    public XmlOptions setCompileNoPvrRule() {
+        return setCompileNoPvrRule(true);
+    }
+
+    public XmlOptions setCompileNoPvrRule(boolean b) {
+        return set(COMPILE_NO_PVR_RULE, b);
+    }
+
+    public boolean isCompileNoPvrRule() {
+        return hasOption(COMPILE_NO_PVR_RULE);
     }
 
     /**
      * if this option is set, the schema compiler will skip annotations when
      * processing Schema components.
-     * 
+     *
      * @see XmlBeans#compileXsd
      */
     public XmlOptions setCompileNoAnnotations() {
-        return set( COMPILE_NO_ANNOTATIONS );
+        return setCompileNoAnnotations(true);
+    }
+
+    public XmlOptions setCompileNoAnnotations(boolean b) {
+        return set(COMPILE_NO_ANNOTATIONS, b);
+    }
+
+    public boolean isCompileNoAnnotations() {
+        return hasOption(COMPILE_NO_ANNOTATIONS);
     }
 
     /**
      * If this option is set, then the schema compiler will try to download
      * schemas that appear in imports and includes from network based URLs.
-     * 
+     *
      * @see XmlBeans#compileXsd
      */
-    public XmlOptions setCompileDownloadUrls () { 
-        return set( COMPILE_DOWNLOAD_URLS); 
+    public XmlOptions setCompileDownloadUrls() {
+        return setCompileDownloadUrls(true);
     }
-    
+
+    public XmlOptions setCompileDownloadUrls(boolean b) {
+        return set(COMPILE_DOWNLOAD_URLS, b);
+    }
+
+    public boolean isCompileDownloadUrls() {
+        return hasOption(COMPILE_DOWNLOAD_URLS);
+    }
+
     /**
      * If this option is set, then the schema compiler will permit and
      * ignore multiple definitions of the same component (element, attribute,
      * type, etc) names in the given namespaces.  If multiple definitions
      * with the same name appear, the definitions that happen to be processed
      * last will be ignored.
-     * 
+     *
      * @param mdefNamespaces a set of namespace URIs as Strings
-     * 
      * @see XmlBeans#compileXsd
-     */ 
-    public XmlOptions setCompileMdefNamespaces(Set mdefNamespaces)
-    {
-        return set( COMPILE_MDEF_NAMESPACES, mdefNamespaces );
+     */
+    public XmlOptions setCompileMdefNamespaces(Set<String> mdefNamespaces) {
+        return set(COMPILE_MDEF_NAMESPACES, mdefNamespaces);
+    }
+
+    @SuppressWarnings("unchecked")
+    public Set<String> getCompileMdefNamespaces() {
+        return (Set<String>) get(COMPILE_MDEF_NAMESPACES);
     }
 
     /**
@@ -756,11 +1085,19 @@
      * thrown immediately.  This option is useful for finding code that
      * is introducing invalid values in an XML document, but it
      * slows performance.
-     * 
+     *
      * @see XmlObject.Factory#parse(java.io.File, XmlOptions)
      */
     public XmlOptions setValidateOnSet() {
-        return set( VALIDATE_ON_SET );
+        return setValidateOnSet(true);
+    }
+
+    public XmlOptions setValidateOnSet(boolean b) {
+        return set(VALIDATE_ON_SET, b);
+    }
+
+    public boolean isValidateOnSet() {
+        return hasOption(VALIDATE_ON_SET);
     }
 
     /**
@@ -770,7 +1107,15 @@
      * classpath that the document author did not anticipate.
      */
     public XmlOptions setValidateTreatLaxAsSkip() {
-        return set ( VALIDATE_TREAT_LAX_AS_SKIP );
+        return setValidateTreatLaxAsSkip(true);
+    }
+
+    public XmlOptions setValidateTreatLaxAsSkip(boolean b) {
+        return set(VALIDATE_TREAT_LAX_AS_SKIP, b);
+    }
+
+    public boolean isValidateTreatLaxAsSkip() {
+        return hasOption(VALIDATE_TREAT_LAX_AS_SKIP);
     }
 
     /**
@@ -778,9 +1123,30 @@
      * default for better compatibility.
      */
     public XmlOptions setValidateStrict() {
-        return set ( VALIDATE_STRICT );
+        return setValidateStrict(true);
     }
 
+    public XmlOptions setValidateStrict(boolean b) {
+        return set(VALIDATE_STRICT, b);
+    }
+
+    public boolean isValidateStrict() {
+        return hasOption(VALIDATE_STRICT);
+    }
+
+    public XmlOptions setValidateTextOnly() {
+        return setValidateTextOnly(true);
+    }
+
+    public XmlOptions setValidateTextOnly(boolean b) {
+        return set(VALIDATE_TEXT_ONLY, b);
+    }
+
+    public boolean isValidateTextOnly() {
+        return hasOption(VALIDATE_TEXT_ONLY);
+    }
+
+
     /**
      * This option controls whether or not operations on XmlBeans are
      * thread safe.  When not on, all XmlBean operations will be syncronized.
@@ -788,46 +1154,66 @@
      * XmlBeans simultainously, but has a perf impact.  If set, then
      * only one thread may access an XmlBean.
      */
-    public XmlOptions setUnsynchronized ( )
-    {
-        return set( UNSYNCHRONIZED );
+    public XmlOptions setUnsynchronized() {
+        return setUnsynchronized(true);
+    }
+
+    public XmlOptions setUnsynchronized(boolean b) {
+        return set(UNSYNCHRONIZED, b);
+    }
+
+    public boolean isUnsynchronized() {
+        return hasOption(UNSYNCHRONIZED);
     }
 
     /**
      * If this option is set when compiling a schema, then the given
      * EntityResolver will be consulted in order to resolve any
      * URIs while downloading imported schemas.
-     *
+     * <p>
      * EntityResolvers are currently only used by compileXsd; they
      * are not consulted by other functions, for example, parse.
      * This will likely change in the future.
-     * 
+     *
      * @see XmlBeans#compileXsd
      */
     public XmlOptions setEntityResolver(EntityResolver resolver) {
-        return set( ENTITY_RESOLVER, resolver );
+        return set(ENTITY_RESOLVER, resolver);
+    }
+
+    public EntityResolver getEntityResolver() {
+        return (EntityResolver) get(ENTITY_RESOLVER);
     }
 
     /**
      * If this option is set when compiling a schema, then the given
      * URI will be considered as base URI when deciding the directory
      * structure for saving the sources inside the generated JAR file.
+     *
      * @param baseURI the URI to be considered as "base"
      * @see XmlBeans#compileXsd
      */
     public XmlOptions setBaseURI(URI baseURI) {
-        return set( BASE_URI, baseURI );
+        return set(BASE_URI, baseURI);
+    }
+
+    public URI getBaseURI() {
+        return (URI) get(BASE_URI);
     }
 
     /**
      * If this option is set when compiling a schema, then the given
      * SchemaTypeCodePrinter.Printer will be used to generate the
      * Java code.
-     * 
+     *
      * @see XmlBeans#compileXsd
      */
     public XmlOptions setSchemaCodePrinter(SchemaCodePrinter printer) {
-        return set( SCHEMA_CODE_PRINTER, printer );
+        return set(SCHEMA_CODE_PRINTER, printer);
+    }
+
+    public SchemaCodePrinter getSchemaCodePrinter() {
+        return (SchemaCodePrinter) get(SCHEMA_CODE_PRINTER);
     }
 
     /**
@@ -837,13 +1223,16 @@
      * supported.
      *
      * @param source A Java version number
-     *
      * @see #GENERATE_JAVA_14
      * @see #GENERATE_JAVA_15
      * @see XmlBeans#compileXmlBeans
      */
-    public XmlOptions setGenerateJavaVersion (String source) {
-        return set( GENERATE_JAVA_VERSION, source );
+    public XmlOptions setGenerateJavaVersion(String source) {
+        return set(GENERATE_JAVA_VERSION, source);
+    }
+
+    public String getGenerateJavaVersion() {
+        return (String) get(GENERATE_JAVA_VERSION);
     }
 
     /**
@@ -852,227 +1241,169 @@
      * will share the same synchronization domain, requiring explicit synchronization
      * when concurent accessing the two objects.
      *
-     * @param useNewSyncDomain  A flag representing the usage of new domain
-     *
+     * @param useNewSyncDomain A flag representing the usage of new domain
      * @see XmlObject#copy()
      */
-    public XmlOptions setCopyUseNewSynchronizationDomain (boolean useNewSyncDomain)
-    {
+    public XmlOptions setCopyUseNewSynchronizationDomain(boolean useNewSyncDomain) {
         return set(COPY_USE_NEW_SYNC_DOMAIN, useNewSyncDomain);
     }
 
+    public boolean isCopyUseNewSynchronizationDomain() {
+        Boolean flag = (Boolean)get(COPY_USE_NEW_SYNC_DOMAIN);
+        return flag != null && flag;
+    }
+
     /**
      * Sets the maximum number of bytes allowed when an Entity is expanded during parsing.
      * The default value is 10240 bytes.
-     * @param entityBytesLimit
-     * @return
+     *
+     * @param entityBytesLimit the maximum number of bytes allowed when an Entity is expanded during parsing
+     * @return this
      */
-    public XmlOptions setLoadEntityBytesLimit (int entityBytesLimit)
-    {
-        return set(LOAD_ENTITY_BYTES_LIMIT,entityBytesLimit);
+    public XmlOptions setLoadEntityBytesLimit(int entityBytesLimit) {
+        return set(LOAD_ENTITY_BYTES_LIMIT, entityBytesLimit);
     }
 
+    public Integer getLoadEntityBytesLimit() {
+        return (Integer) get(LOAD_ENTITY_BYTES_LIMIT);
+    }
+
+
     /**
      * Sets the maximum number of entity expansions allowed during parsing.
      * The default value is 2048.
-     * @param entityExpansionLimit
+     *
+     * @param entityExpansionLimit the maximum number of entity expansions allowed during parsing
      * @return this
      */
-    public XmlOptions setEntityExpansionLimit (int entityExpansionLimit)
-    {
+    public XmlOptions setEntityExpansionLimit(int entityExpansionLimit) {
         return set(ENTITY_EXPANSION_LIMIT, entityExpansionLimit);
     }
 
+    public int getEntityExpansionLimit() {
+        Integer limit = (Integer) get(ENTITY_EXPANSION_LIMIT);
+        return limit == null ? DEFAULT_ENTITY_EXPANSION_LIMIT : limit;
+    }
+
     /**
      * Controls whether DTD grammar is loaded during parsing.
      * The default value is false.
      *
-     * @param loadDTDGrammar
+     * @param loadDTDGrammar {@code true}, if DTD grammar is loaded during parsing
      * @return this
      */
-    public XmlOptions setLoadDTDGrammar (boolean loadDTDGrammar)
-    {
+    public XmlOptions setLoadDTDGrammar(boolean loadDTDGrammar) {
         return set(LOAD_DTD_GRAMMAR, loadDTDGrammar);
     }
 
+    public boolean isLoadDTDGrammar() {
+        Boolean flag = (Boolean) get(LOAD_DTD_GRAMMAR);
+        return flag != null && flag;
+    }
+
     /**
      * Controls whether external DTDs are loaded during parsing.
      * The default value is false.
      *
-     * @param loadExternalDTD
+     * @param loadExternalDTD {@code true}, if external DTDs are loaded during parsing
      * @return this
      */
-    public XmlOptions setLoadExternalDTD (boolean loadExternalDTD)
-    {
+    public XmlOptions setLoadExternalDTD(boolean loadExternalDTD) {
         return set(LOAD_EXTERNAL_DTD, loadExternalDTD);
     }
 
-    public static final String GENERATE_JAVA_14 = "1.4";
-    public static final String GENERATE_JAVA_15 = "1.5";
-
-
-    //
-    // Complete set of XmlOption's
-    //
-            
-    // TODO - Add selectPath option to track the seletion (deault is to clean selections fast). 
-    
-    /** @exclude */
-    public static final String SAVE_NAMESPACES_FIRST           = "SAVE_NAMESPACES_FIRST";
-    /** @exclude */
-    public static final String SAVE_SYNTHETIC_DOCUMENT_ELEMENT = "SAVE_SYNTHETIC_DOCUMENT_ELEMENT";
-    /** @exclude */
-    public static final String SAVE_PRETTY_PRINT               = "SAVE_PRETTY_PRINT";
-    /** @exclude */
-    public static final String SAVE_PRETTY_PRINT_INDENT        = "SAVE_PRETTY_PRINT_INDENT";
-    /** @exclude */
-    public static final String SAVE_PRETTY_PRINT_OFFSET        = "SAVE_PRETTY_PRINT_OFFSET";
-    /** @exclude */
-    public static final String SAVE_AGGRESSIVE_NAMESPACES      = "SAVE_AGGRESSIVE_NAMESPACES";
-    /** @exclude */
-    public static final String SAVE_USE_DEFAULT_NAMESPACE      = "SAVE_USE_DEFAULT_NAMESPACE";
-    /** @exclude */
-    public static final String SAVE_IMPLICIT_NAMESPACES        = "SAVE_IMPLICIT_NAMESPACES";
-    /** @exclude */
-    public static final String SAVE_SUGGESTED_PREFIXES         = "SAVE_SUGGESTED_PREFIXES";
-    /** @exclude */
-    public static final String SAVE_FILTER_PROCINST            = "SAVE_FILTER_PROCINST";
-    /** @exclude */
-    public static final String SAVE_USE_OPEN_FRAGMENT          = "SAVE_USE_OPEN_FRAGMENT";
-    /** @exclude */
-    public static final String SAVE_OUTER                      = "SAVE_OUTER";
-    /** @exclude */
-    public static final String SAVE_INNER                      = "SAVE_INNER";
-    /** @exclude */
-    public static final String SAVE_NO_XML_DECL                = "SAVE_NO_XML_DECL";
-    /** @exclude */
-    public static final String SAVE_SUBSTITUTE_CHARACTERS      = "SAVE_SUBSTITUTE_CHARACTERS";
-    /** @exclude */
-    public static final String SAVE_OPTIMIZE_FOR_SPEED         = "SAVE_OPTIMIZE_FOR_SPEED";
-    /** @exclude */
-    public static final String SAVE_CDATA_LENGTH_THRESHOLD     = "SAVE_CDATA_LENGTH_THRESHOLD";
-    /** @exclude */
-    public static final String SAVE_CDATA_ENTITY_COUNT_THRESHOLD = "SAVE_CDATA_ENTITY_COUNT_THRESHOLD";
-    /** @exclude */
-    public static final String SAVE_SAX_NO_NSDECLS_IN_ATTRIBUTES = "SAVE_SAX_NO_NSDECLS_IN_ATTRIBUTES";
-    /** @exclude */
-    public static final String LOAD_REPLACE_DOCUMENT_ELEMENT   = "LOAD_REPLACE_DOCUMENT_ELEMENT";
-    /** @exclude */
-    public static final String LOAD_STRIP_WHITESPACE           = "LOAD_STRIP_WHITESPACE";
-    /** @exclude */
-    public static final String LOAD_STRIP_COMMENTS             = "LOAD_STRIP_COMMENTS";
-    /** @exclude */
-    public static final String LOAD_STRIP_PROCINSTS            = "LOAD_STRIP_PROCINSTS";
-    /** @exclude */
-    public static final String LOAD_LINE_NUMBERS               = "LOAD_LINE_NUMBERS";
-    /** @exclude */
-    public static final String LOAD_LINE_NUMBERS_END_ELEMENT   = "LOAD_LINE_NUMBERS_END_ELEMENT";
-    /** @exclude */
-    public static final String LOAD_SAVE_CDATA_BOOKMARKS       = "LOAD_SAVE_CDATA_BOOKMARKS";
-    /** @exclude */
-    public static final String LOAD_SUBSTITUTE_NAMESPACES      = "LOAD_SUBSTITUTE_NAMESPACES";
-    /** @exclude */
-    public static final String LOAD_TRIM_TEXT_BUFFER           = "LOAD_TRIM_TEXT_BUFFER";
-    /** @exclude */
-    public static final String LOAD_ADDITIONAL_NAMESPACES      = "LOAD_ADDITIONAL_NAMESPACES";
-    /** @exclude */
-    public static final String LOAD_MESSAGE_DIGEST             = "LOAD_MESSAGE_DIGEST";
-    /** @exclude */
-    public static final String LOAD_USE_DEFAULT_RESOLVER       = "LOAD_USE_DEFAULT_RESOLVER";
-    /** @exclude */
-    public static final String LOAD_USE_XMLREADER              = "LOAD_USE_XMLREADER";
-
-    /** @exclude */
-    public static final String XQUERY_CURRENT_NODE_VAR         = "XQUERY_CURRENT_NODE_VAR";
-    /** @exclude */
-    public static final String XQUERY_VARIABLE_MAP             =  "XQUERY_VARIABLE_MAP";
-
-    /** @exclude */
-    public static final String CHARACTER_ENCODING              = "CHARACTER_ENCODING";
-    /** @exclude */
-    public static final String ERROR_LISTENER                  = "ERROR_LISTENER";
-    /** @exclude */
-    public static final String DOCUMENT_TYPE                   = "DOCUMENT_TYPE";
-    /** @exclude */
-    public static final String DOCUMENT_SOURCE_NAME            = "DOCUMENT_SOURCE_NAME";
-    /** @exclude */
-    public static final String COMPILE_SUBSTITUTE_NAMES        = "COMPILE_SUBSTITUTE_NAMES";
-    /** @exclude */
-    public static final String COMPILE_NO_VALIDATION           = "COMPILE_NO_VALIDATION";
-    /** @exclude */
-    public static final String COMPILE_NO_UPA_RULE             = "COMPILE_NO_UPA_RULE";
-    /** @exclude */
-    public static final String COMPILE_NO_PVR_RULE             = "COMPILE_NO_PVR_RULE";
-    /** @exclude */
-    public static final String COMPILE_NO_ANNOTATIONS          = "COMPILE_NO_ANNOTATIONS";
-    /** @exclude */
-    public static final String COMPILE_DOWNLOAD_URLS           = "COMPILE_DOWNLOAD_URLS";
-    /** @exclude */
-    public static final String COMPILE_MDEF_NAMESPACES         = "COMPILE_MDEF_NAMESPACES";
-    /** @exclude */
-    public static final String VALIDATE_ON_SET                 = "VALIDATE_ON_SET";
-    /** @exclude */
-    public static final String VALIDATE_TREAT_LAX_AS_SKIP      = "VALIDATE_TREAT_LAX_AS_SKIP";
-    /** @exclude */
-    public static final String VALIDATE_STRICT                 = "VALIDATE_STRICT";
-    /** @exclude */
-    public static final String VALIDATE_TEXT_ONLY              = "VALIDATE_TEXT_ONLY";
-    /** @exclude */
-    public static final String UNSYNCHRONIZED                  = "UNSYNCHRONIZED";
-    /** @exclude */
-    public static final String ENTITY_RESOLVER                 = "ENTITY_RESOLVER";
-    /** @exclude */
-    public static final String BASE_URI                        = "BASE_URI";
-    /** @exclude */
-    public static final String SCHEMA_CODE_PRINTER             = "SCHEMA_CODE_PRINTER";
-    /** @exclude */
-    public static final String GENERATE_JAVA_VERSION           = "GENERATE_JAVA_VERSION";
-    /** @exclude */
-    public static final String COPY_USE_NEW_SYNC_DOMAIN        = "COPY_USE_NEW_LOCALE";
-    /** @exclude */
-    public static final String LOAD_ENTITY_BYTES_LIMIT         = "LOAD_ENTITY_BYTES_LIMIT";
-    /** @exclude */
-    public static final String ENTITY_EXPANSION_LIMIT          = "ENTITY_EXPANSION_LIMIT";
-    /** @exclude */
-    public static final String LOAD_DTD_GRAMMAR                = "LOAD_DTD_GRAMMAR";
-    /** @exclude */
-    public static final String LOAD_EXTERNAL_DTD               = "LOAD_EXTERNAL_DTD";
-
-    public static final int DEFAULT_ENTITY_EXPANSION_LIMIT = 2048;
-
-    private static final XmlOptions EMPTY_OPTIONS;
-    static {
-        EMPTY_OPTIONS = new XmlOptions();
-        EMPTY_OPTIONS._map = Collections.unmodifiableMap(EMPTY_OPTIONS._map);
+    public boolean isLoadExternalDTD() {
+        Boolean flag = (Boolean) get(LOAD_EXTERNAL_DTD);
+        return flag != null && flag;
     }
 
-    /** If passed null, returns an empty options object.  Otherwise, returns its argument. */
+    public XmlOptions setSaveOptimizeForSpeed(boolean saveOptimizeForSpeed) {
+        return set(SAVE_OPTIMIZE_FOR_SPEED, saveOptimizeForSpeed);
+    }
+
+    public boolean isSaveOptimizeForSpeed() {
+        Boolean flag = (Boolean) get(SAVE_OPTIMIZE_FOR_SPEED);
+        return flag != null && flag;
+    }
+
+
+    /**
+     * If passed null, returns an empty options object.  Otherwise, returns its argument.
+     */
     public static XmlOptions maskNull(XmlOptions o) {
         return (o == null) ? EMPTY_OPTIONS : o;
     }
 
-    
-    /** Used to set a generic option */
-    public void  put ( Object option               ) { put( option, null ); }
-    /** Used to set a generic option */
-    public void  put ( Object option, Object value ) { _map.put(option, value); }
-    /** Used to set a generic option */
-    public void put  ( Object option, int value    ) { put( option, new Integer( value ) ); }
 
-    private XmlOptions set(Object option)               { return set(option, null); }
-    private XmlOptions set(Object option, Object value) { _map.put(option, value); return this;}
-    private XmlOptions set(Object option, int value)    { return set(option, new Integer(value)); }
+    /**
+     * Used to set a generic option
+     */
+    public void put(String option) {
+        put(option, null);
+    }
 
-    /** Used to test a generic option */
-    public boolean hasOption   ( Object option ) { return _map.containsKey( option ); }
-    public static boolean hasOption ( XmlOptions options, Object option ) { return options == null ? false : options.hasOption( option ); }
-    
-    /** Used to get a generic option */
-    public Object  get         ( Object option ) { return _map.get( option ); }
-    public void    remove      ( Object option ) { _map.remove( option ); }
+    /**
+     * Used to set a generic option
+     */
+    public void put(String option, Object value) {
+        _map.put(option, value);
+    }
 
-    /** Used to test a generic option on an options object that may be null */
-    public static Object safeGet(XmlOptions o, Object option) {
+    /**
+     * Used to set a generic option
+     */
+    public void put(String option, int value) {
+        put(option, new Integer(value));
+    }
+
+    private XmlOptions set(String option) {
+        return set(option, null);
+    }
+
+    private XmlOptions set(String option, Object value) {
+        _map.put(option, value);
+        return this;
+    }
+
+    private XmlOptions set(String option, int value) {
+        return set(option, new Integer(value));
+    }
+
+    private XmlOptions set(String option, boolean value) {
+        if (value) {
+            set(option, Boolean.TRUE);
+        } else {
+            remove(option);
+        }
+        return this;
+    }
+
+    /**
+     * Used to test a generic option
+     */
+    public boolean hasOption(String option) {
+        return _map.containsKey(option);
+    }
+
+    public static boolean hasOption(XmlOptions options, String option) {
+        return options != null && options.hasOption(option);
+    }
+
+    /**
+     * Used to get a generic option
+     */
+    public Object get(String option) {
+        return _map.get(option);
+    }
+
+    public void remove(String option) {
+        _map.remove(option);
+    }
+
+    /**
+     * Used to test a generic option on an options object that may be null
+     */
+    public static Object safeGet(XmlOptions o, String option) {
         return o == null ? null : o.get(option);
     }
 
diff --git a/src/main/java/org/apache/xmlbeans/XmlOptionsBean.java b/src/main/java/org/apache/xmlbeans/XmlOptionsBean.java
index a148758..7ab1a51 100644
--- a/src/main/java/org/apache/xmlbeans/XmlOptionsBean.java
+++ b/src/main/java/org/apache/xmlbeans/XmlOptionsBean.java
@@ -15,464 +15,25 @@
 

 package org.apache.xmlbeans;

 

-import org.xml.sax.XMLReader;

-import org.xml.sax.EntityResolver;

-

-import javax.xml.namespace.QName;

-import java.util.Map;

-import java.util.Set;

-

 /**

  * Same as {@link XmlOptions} but adhering to JavaBean conventions

+ *

+ * @deprecated use XmlOptions instead

  */

-public class XmlOptionsBean extends XmlOptions

-{

+@Deprecated

+public class XmlOptionsBean extends XmlOptions {

     /**

      * Construct a new blank XmlOptions.

      */

-    public XmlOptionsBean ( ) { }

+    public XmlOptionsBean() {

+    }

 

     /**

      * Construct a new XmlOptions, copying the options.

+     *

      * @param other the source <code>XmlOptions</code> object

      */

-    public XmlOptionsBean (XmlOptions other) {

-        super( other );

-    }

-

-

-    public void setSaveNamespacesFirst(boolean b)

-    {

-        if (b)

-            super.setSaveNamespacesFirst();

-        else

-            remove( SAVE_NAMESPACES_FIRST );

-    }

-

-    public boolean isSaveNamespacesFirst()

-    {

-        return hasOption( SAVE_NAMESPACES_FIRST );

-    }

-

-    public void setSavePrettyPrint(boolean b)

-    {

-        if (b)

-            super.setSavePrettyPrint();

-        else

-            remove( SAVE_PRETTY_PRINT );

-    }

-

-    public boolean isSavePrettyPrint()

-    {

-        return hasOption( SAVE_PRETTY_PRINT );

-    }

-

-    public Integer getSavePrettyPrintIndent()

-    {

-        return (Integer) get( SAVE_PRETTY_PRINT_INDENT );

-    }

-

-    public Integer getSavePrettyPrintOffset()

-    {

-        return (Integer) get( SAVE_PRETTY_PRINT_OFFSET );

-    }

-

-    public String getCharacterEncoding()

-    {

-        return (String) get( CHARACTER_ENCODING );

-    }

-

-    public SchemaType getDocumentType()

-    {

-        return (SchemaType) get ( DOCUMENT_TYPE );

-    }

-

-    public void setSaveAggressiveNamespaces(boolean b)

-    {

-        if (b)

-            super.setSaveAggressiveNamespaces();

-        else

-            remove( SAVE_AGGRESSIVE_NAMESPACES );

-    }

-

-    public boolean isSaveAggressiveNamespaces()

-    {

-        return hasOption( SAVE_AGGRESSIVE_NAMESPACES );

-    }

-

-    public QName getSaveSyntheticDocumentElement()

-    {

-        return (QName) get( SAVE_SYNTHETIC_DOCUMENT_ELEMENT );

-    }

-

-    public void setUseDefaultNamespace(boolean b)

-    {

-        if (b)

-            super.setUseDefaultNamespace();

-        else

-            remove( SAVE_USE_DEFAULT_NAMESPACE );

-    }

-

-    public boolean isUseDefaultNamespace()

-    {

-        return hasOption( SAVE_USE_DEFAULT_NAMESPACE );

-    }

-

-    public Map getSaveImplicitNamespaces()

-    {

-        return (Map) get( SAVE_IMPLICIT_NAMESPACES );

-    }

-

-    public Map getSaveSuggestedPrefixes()

-    {

-        return (Map) get( SAVE_SUGGESTED_PREFIXES );

-    }

-

-    public String getSaveFilterProcinst()

-    {

-        return (String) get( SAVE_FILTER_PROCINST );

-    }

-

-    public XmlOptionCharEscapeMap getSaveSubstituteCharacters()

-    {

-        return (XmlOptionCharEscapeMap) get( SAVE_SUBSTITUTE_CHARACTERS );

-    }

-

-    public void setSaveUseOpenFrag(boolean b)

-    {

-        if (b)

-            super.setSaveUseOpenFrag();

-        else

-            remove( SAVE_USE_OPEN_FRAGMENT );

-    }

-

-    public boolean isSaveUseOpenFrag()

-    {

-        return hasOption( SAVE_USE_OPEN_FRAGMENT );

-    }

-

-    public void setSaveOuter(boolean b)

-    {

-        if (b)

-            super.setSaveOuter();

-        else

-            remove( SAVE_OUTER );

-    }

-

-    public boolean isSaveOuter()

-    {

-        return hasOption( SAVE_OUTER );

-    }

-

-    public void setSaveInner(boolean b)

-    {

-        if (b)

-            super.setSaveInner();

-        else

-            remove( SAVE_INNER );

-    }

-

-    public boolean isSaveInner()

-    {

-        return hasOption( SAVE_INNER );

-    }

-

-    public void setSaveNoXmlDecl(boolean b)

-    {

-        if (b)

-            super.setSaveNoXmlDecl();

-        else

-            remove( SAVE_NO_XML_DECL );

-    }

-

-    public boolean isSaveNoXmlDecl()

-    {

-        return hasOption( SAVE_NO_XML_DECL );

-    }

-

-    public Integer getSaveCDataLengthThreshold()

-    {

-        return (Integer) get( SAVE_CDATA_LENGTH_THRESHOLD );

-    }

-

-    public Integer getSaveCDataEntityCountThreshold()

-    {

-        return (Integer) get( SAVE_CDATA_ENTITY_COUNT_THRESHOLD );

-    }

-

-    public void setSaveSaxNoNSDeclsInAttributes(boolean b)

-    {

-        if (b)

-            super.setSaveSaxNoNSDeclsInAttributes();

-        else

-            remove( SAVE_SAX_NO_NSDECLS_IN_ATTRIBUTES );

-    }

-

-    public boolean isSaveSaxNoNSDeclsInAttributes()

-    {

-        return hasOption( SAVE_SAX_NO_NSDECLS_IN_ATTRIBUTES );

-    }

-

-    public QName getLoadReplaceDocumentElement()

-    {

-        return (QName) get( LOAD_REPLACE_DOCUMENT_ELEMENT );

-    }

-

-    public void setLoadStripWhitespace(boolean b)

-    {

-        if (b)

-            super.setLoadStripWhitespace();

-        else

-            remove( LOAD_STRIP_WHITESPACE );

-    }

-

-    public boolean isSetLoadStripWhitespace()

-    {

-        return hasOption( LOAD_STRIP_WHITESPACE );

-    }

-

-    public void setLoadStripComments(boolean b)

-    {

-        if (b)

-            super.setLoadStripComments();

-        else

-            remove( LOAD_STRIP_COMMENTS );

-    }

-

-    public boolean isLoadStripComments()

-    {

-        return hasOption( LOAD_STRIP_COMMENTS );

-    }

-

-    public void setLoadStripProcinsts(boolean b)

-    {

-        if (b)

-            super.setLoadStripProcinsts();

-        else

-            remove( LOAD_STRIP_PROCINSTS );

-    }

-

-    public boolean isLoadStripProcinsts()

-    {

-        return hasOption( LOAD_STRIP_PROCINSTS );

-    }

-

-    public void setLoadLineNumbers(boolean b)

-    {

-        if (b)

-            super.setLoadLineNumbers();

-        else

-            remove( LOAD_LINE_NUMBERS );

-    }

-

-    public boolean isLoadLineNumbers()

-    {

-        return hasOption( LOAD_LINE_NUMBERS );

-    }

-

-    public Map getLoadSubstituteNamespaces()

-    {

-        return (Map) get( LOAD_SUBSTITUTE_NAMESPACES );

-    }

-

-    public void setLoadTrimTextBuffer(boolean b)

-    {

-        if (b)

-            super.setLoadTrimTextBuffer();

-        else

-            remove( LOAD_TRIM_TEXT_BUFFER );

-    }

-

-    public boolean isLoadTrimTextBuffer()

-    {

-        return hasOption( LOAD_TRIM_TEXT_BUFFER );

-    }

-

-    public Map getLoadAdditionalNamespaces()

-    {

-        return (Map) get( LOAD_ADDITIONAL_NAMESPACES );

-    }

-

-    public void setLoadMessageDigest(boolean b)

-    {

-        if (b)

-            super.setLoadMessageDigest();

-        else

-            remove( LOAD_MESSAGE_DIGEST );

-    }

-

-    public boolean isLoadMessageDigest()

-    {

-        return hasOption( LOAD_MESSAGE_DIGEST );

-    }

-

-    public void setLoadUseDefaultResolver(boolean b)

-    {

-        if (b)

-            super.setLoadUseDefaultResolver();

-        else

-            remove( LOAD_USE_DEFAULT_RESOLVER );

-    }

-

-    public boolean isLoadUseDefaultResolver()

-    {

-        return hasOption( LOAD_USE_DEFAULT_RESOLVER );

-    }

-

-    public String getXqueryCurrentNodeVar()

-    {

-        return (String) get( XQUERY_CURRENT_NODE_VAR );

-    }

-

-    public Map getXqueryVariables()

-    {

-        return (Map) get( XQUERY_VARIABLE_MAP );

-    }

-

-    public String getDocumentSourceName()

-    {

-        return (String) get( DOCUMENT_SOURCE_NAME );

-    }

-

-    public Map getCompileSubstituteNames()

-    {

-        return (Map) get( COMPILE_SUBSTITUTE_NAMES );

-    }

-

-    public void setCompileNoUpaRule(boolean b)

-    {

-        if (b)

-            super.setCompileNoUpaRule();

-        else

-            remove( COMPILE_NO_UPA_RULE );

-    }

-

-    public boolean isCompileNoUpaRule()

-    {

-        return hasOption( COMPILE_NO_UPA_RULE );

-    }

-

-    public void setCompileNoPvrRule(boolean b)

-    {

-        if (b)

-            super.setCompileNoPvrRule();

-        else

-            remove( COMPILE_NO_PVR_RULE );

-    }

-

-    public boolean isCompileNoPvrRule()

-    {

-        return hasOption( COMPILE_NO_PVR_RULE );

-    }

-

-    public void setCompileNoAnnotations(boolean b)

-    {

-        if (b)

-            super.setCompileNoAnnotations();

-        else

-            remove( COMPILE_NO_ANNOTATIONS );

-    }

-

-    public boolean isCompileNoAnnotations()

-    {

-        return hasOption( COMPILE_NO_ANNOTATIONS );

-    }

-

-    public void setCompileDownloadUrls(boolean b)

-    {

-        if (b)

-            super.setCompileDownloadUrls();

-        else

-            remove( COMPILE_DOWNLOAD_URLS );

-    }

-

-    public boolean isCompileDownloadUrls()

-    {

-        return hasOption( COMPILE_DOWNLOAD_URLS );

-    }

-

-    public Set getCompileMdefNamespaces()

-    {

-        return (Set) get( COMPILE_MDEF_NAMESPACES );

-    }

-

-    public void setValidateOnSet(boolean b)

-    {

-        if (b)

-            super.setValidateOnSet();

-        else

-            remove( VALIDATE_ON_SET );

-    }

-

-    public boolean isValidateOnSet()

-    {

-        return hasOption( VALIDATE_ON_SET );

-    }

-

-    public void setValidateTreatLaxAsSkip(boolean b)

-    {

-        if (b)

-            super.setValidateTreatLaxAsSkip();

-        else

-            remove( VALIDATE_TREAT_LAX_AS_SKIP );

-    }

-

-    public boolean isValidateTreatLaxAsSkip()

-    {

-        return hasOption( VALIDATE_TREAT_LAX_AS_SKIP );

-    }

-

-    public void setValidateStrict(boolean b)

-    {

-        if (b)

-            super.setValidateStrict();

-        else

-            remove( VALIDATE_STRICT );

-    }

-

-    public boolean isValidateStrict()

-    {

-        return hasOption( VALIDATE_STRICT );

-    }

-

-    public void setUnsynchronized(boolean b)

-    {

-        if (b)

-            super.setUnsynchronized();

-        else

-            remove( UNSYNCHRONIZED );

-    }

-

-    public boolean isUnsynchronized()

-    {

-        return hasOption( UNSYNCHRONIZED );

-    }

-

-    public EntityResolver getEntityResolver()

-    {

-        return (EntityResolver) get( ENTITY_RESOLVER );

-    }

-

-    public String getGenerateJavaVersion()

-    {

-        return (String) get( GENERATE_JAVA_VERSION );

-    }

-

-    public int getEntityExpansionLimit()

-    {

-        Integer limit = (Integer) get( ENTITY_EXPANSION_LIMIT );

-        return limit == null ? DEFAULT_ENTITY_EXPANSION_LIMIT : limit;

-    }

-

-    public boolean isLoadDTDGrammar()

-    {

-        Boolean flag = (Boolean) get( LOAD_DTD_GRAMMAR );

-        return flag == null ? false : flag;

-    }

-

-    public boolean isLoadExternalDTD()

-    {

-        Boolean flag = (Boolean) get( LOAD_EXTERNAL_DTD );

-        return flag == null ? false : flag;

+    public XmlOptionsBean(XmlOptions other) {

+        super(other);

     }

 }

diff --git a/src/main/java/org/apache/xmlbeans/XmlTokenSource.java b/src/main/java/org/apache/xmlbeans/XmlTokenSource.java
index 2c57fd1..0cf0c11 100644
--- a/src/main/java/org/apache/xmlbeans/XmlTokenSource.java
+++ b/src/main/java/org/apache/xmlbeans/XmlTokenSource.java
@@ -16,21 +16,13 @@
 package org.apache.xmlbeans;
 
 import org.apache.xmlbeans.xml.stream.XMLInputStream;
-
-import java.io.InputStream;
-import java.io.OutputStream;
-import java.io.Reader;
-import java.io.Writer;
-import java.io.File;
-import java.io.IOException;
+import org.w3c.dom.Node;
+import org.xml.sax.ContentHandler;
+import org.xml.sax.SAXException;
+import org.xml.sax.ext.LexicalHandler;
 
 import javax.xml.stream.XMLStreamReader;
-
-import org.w3c.dom.Node;
-
-import org.xml.sax.ContentHandler;
-import org.xml.sax.ext.LexicalHandler;
-import org.xml.sax.SAXException;
+import java.io.*;
 
 /**
  * Represents a holder of XML that can return an {@link XmlCursor}
@@ -39,12 +31,11 @@
  * Both {@link XmlObject}
  * (and thus all XML Beans) and {@link XmlCursor} are
  * XmlTokenSource implementations.
- * 
+ *
  * @see XmlObject
  * @see XmlCursor
- */ 
-public interface XmlTokenSource
-{
+ */
+public interface XmlTokenSource {
     /**
      * Returns the synchronization object for the document.  If concurrent
      * multithreaded access to a document is required, the access should should
@@ -52,7 +43,7 @@
      * monitor per XML document tree.
      */
     Object monitor();
-    
+
     /**
      * Returns the XmlDocumentProperties object for the document this token
      * source is associated with.
@@ -61,12 +52,12 @@
 
     /**
      * Returns a new XML cursor.
-     *
+     * <p>
      * A cursor provides random access to all the tokens in the XML
      * data, plus the ability to extract strongly-typed XmlObjects
      * for the data. If the data is not read-only, the XML cursor
      * also allows modifications to the data.
-     *
+     * <p>
      * Using a cursor for the first time typically forces the XML
      * document into memory.
      */
@@ -74,33 +65,34 @@
 
     /**
      * Returns a new XmlInputStream.
-     *
+     * <p>
      * The stream starts at the current begin-tag or begin-document
      * position and ends at the matching end-tag or end-document.
-     *
+     * <p>
      * This is a fail-fast stream, so if the underlying data is changed
      * while the stream is being read, the stream throws a
      * ConcurrentModificationException.
-     *
+     * <p>
      * Throws an IllegalStateException if the XmlTokenSource is not
      * positioned at begin-tag or begin-document (e.g., if it is at
      * an attribute).
+     *
      * @deprecated XMLInputStream was deprecated by XMLStreamReader from STaX - jsr173 API.
      */
     XMLInputStream newXMLInputStream();
-    
+
     /**
      * Returns a new XMLStreamReader.
-     *
+     * <p>
      * The stream starts at the current begin-tag or begin-document
      * position and ends at the matching end-tag or end-document.
-     *
+     * <p>
      * This is a fail-fast stream, so if the underlying data is changed
      * while the stream is being read, the stream throws a
      * ConcurrentModificationException.
      */
     XMLStreamReader newXMLStreamReader();
-    
+
     /**
      * Returns standard XML text.
      * <p>
@@ -113,8 +105,8 @@
      * positioned at begin-tag or begin-document (e.g., if it is at
      * an attribute).
      * <p>
-     * Note that this method does not produce XML with the XML declaration, 
-     * including the encoding information. To save the XML declaration with 
+     * Note that this method does not produce XML with the XML declaration,
+     * including the encoding information. To save the XML declaration with
      * the XML, see {@link #save(OutputStream)} or {@link #save(OutputStream, XmlOptions)}.
      */
     String xmlText();
@@ -122,16 +114,16 @@
     /**
      * Returns a new stream containing standard XML text, encoded
      * according to the given encoding.
-     *
+     * <p>
      * The byte stream contains contents starting at the current
      * begin-tag or begin-document and ending at the matching
      * end-tag or end-document.  The specified encoding is used
      * and also emitted in a PI at the beginning of the stream.
-     *
+     * <p>
      * This is a fail-fast stream, so if the underlying data is changed
      * while the stream is being read, the stream throws a
      * ConcurrentModificationException.
-     *
+     * <p>
      * Throws an IllegalStateException if the XmlTokenSource is not
      * positioned at begin-tag or begin-document (e.g., if it is at
      * an attribute).
@@ -140,22 +132,22 @@
 
     /**
      * Returns a new character reader containing XML text.
-     *
+     * <p>
      * The contents of the reader represents the document contents
      * starting at the current begin-tag or begin-document and ending at
      * the matching end-tag or end-document.  No encoding annotation
      * will be made in the text itself.
-     *
+     * <p>
      * This is a fail-fast reader, so if the underlying data is changed
      * while the reader is being read, the reader throws a
      * ConcurrentModificationException.
-     *
+     * <p>
      * Throws an IllegalStateException if the XmlTokenSource is not
      * positioned at begin-tag or begin-document (e.g., if it is at
      * an attribute).
      */
     Reader newReader();
-    
+
     /**
      * Returns a W3C DOM Node containing the XML
      * represented by this source.  This is a copy of the XML, it is
@@ -177,38 +169,38 @@
     /**
      * Writes the XML represented by this source to the given SAX content and
      * lexical handlers.
-     * Note that this method does not save the XML declaration, including the encoding information. 
-     * To save the XML declaration with the XML, see {@link #save(OutputStream)}, 
+     * Note that this method does not save the XML declaration, including the encoding information.
+     * To save the XML declaration with the XML, see {@link #save(OutputStream)},
      * {@link #save(OutputStream, XmlOptions)}, {@link #save(File)} or {@link #save(File, XmlOptions)}.
      */
-    void save ( ContentHandler ch, LexicalHandler lh ) throws SAXException;
-    
+    void save(ContentHandler ch, LexicalHandler lh) throws SAXException;
+
     /**
      * Writes the XML represented by this source to the given File.
      * This method will save the XML declaration, including encoding information,
      * with the XML.
      */
-    void save ( File file ) throws IOException;
-    
+    void save(File file) throws IOException;
+
     /**
      * Writes the XML represented by this source to the given output stream.
      * This method will save the XML declaration, including encoding information,
      * with the XML.
      */
-    void save ( OutputStream os ) throws IOException;
+    void save(OutputStream os) throws IOException;
 
     /**
      * Writes the XML represented by this source to the given output.
-     * Note that this method does not save the XML declaration, including the encoding information. 
-     * To save the XML declaration with the XML, see {@link #save(OutputStream)}, 
+     * Note that this method does not save the XML declaration, including the encoding information.
+     * To save the XML declaration with the XML, see {@link #save(OutputStream)},
      * {@link #save(OutputStream, XmlOptions)}, {@link #save(File)} or {@link #save(File, XmlOptions)}.
      */
-    void save ( Writer w ) throws IOException;
+    void save(Writer w) throws IOException;
 
     /**
-     * <p>Just like newXMLInputStream() but with any of a number of options. Use the 
+     * <p>Just like newXMLInputStream() but with any of a number of options. Use the
      * <em>options</em> parameter to specify the following:</p>
-     * 
+     *
      * <table>
      * <tr><th>To specify this</th><th>Use this method</th></tr>
      * <tr>
@@ -219,8 +211,8 @@
      * <tr>
      *  <td>Prefix-to-namespace mappings that should be assumed
      *  when saving this XML. This is useful when the resulting
-     *  XML will be part of a larger XML document, ensuring that this 
-     *  inner document will take advantage of namespaces defined in 
+     *  XML will be part of a larger XML document, ensuring that this
+     *  inner document will take advantage of namespaces defined in
      *  the outer document.</td>
      *  <td>{@link XmlOptions#setSaveImplicitNamespaces}</td>
      * </tr>
@@ -235,12 +227,12 @@
      *  <td>{@link XmlOptions#setSaveNamespacesFirst}</td>
      * </tr>
      * <tr>
-     *  <td>The XML should be pretty printed when saved. Note that this 
+     *  <td>The XML should be pretty printed when saved. Note that this
      *  should only be used for debugging.</td>
      *  <td>{@link XmlOptions#setSavePrettyPrint}</td>
      * </tr>
      * <tr>
-     *  <td>The number of spaces to use when indenting for pretty printing. 
+     *  <td>The number of spaces to use when indenting for pretty printing.
      *  The default is 2.</td>
      *  <td>{@link XmlOptions#setSavePrettyPrintIndent}</td>
      * </tr>
@@ -250,14 +242,14 @@
      *  <td>{@link XmlOptions#setSavePrettyPrintOffset}</td>
      * </tr>
      * <tr>
-     *  <td>To minimize the number of namespace attributes generated for the 
+     *  <td>To minimize the number of namespace attributes generated for the
      *  saved XML. Note that this can reduce performance significantly.</td>
-     *  <td>{@link XmlOptions#setSaveAggresiveNamespaces}</td>
+     *  <td>{@link XmlOptions#setSaveAggressiveNamespaces}</td>
      * </tr>
      * <tr>
      *  <td>To reduce the size of the saved document
-     *  by allowing the use of the default namespace. Note that this can 
-     *  potentially change the semantic meaning of the XML if unprefixed QNames are 
+     *  by allowing the use of the default namespace. Note that this can
+     *  potentially change the semantic meaning of the XML if unprefixed QNames are
      *  present as the value of an attribute or element.</td>
      *  <td>{@link XmlOptions#setUseDefaultNamespace}</td>
      * </tr>
@@ -266,8 +258,8 @@
      *  <td>{@link XmlOptions#setSaveFilterProcinst}</td>
      * </tr>
      * <tr>
-     *  <td>Change the QName of the synthesized root element when saving. This 
-     *  replaces "xml-fragment" with "fragment" in the namespace 
+     *  <td>Change the QName of the synthesized root element when saving. This
+     *  replaces "xml-fragment" with "fragment" in the namespace
      *  http://www.openuri.org/fragment</td>
      *  <td>{@link XmlOptions#setSaveUseOpenFrag}</td>
      * </tr>
@@ -285,11 +277,10 @@
      *  <td>{@link XmlOptions#setSaveSyntheticDocumentElement}</td>
      * </tr>
      * </table>
-     * 
-     * @see XmlOptions
-     * 
+     *
      * @param options Any of the described options.
      * @return A new validating XMLInputStream.
+     * @see XmlOptions
      * @deprecated XMLInputStream was deprecated by XMLStreamReader from STaX - jsr173 API.
      */
     XMLInputStream newXMLInputStream(XmlOptions options);
@@ -297,75 +288,78 @@
     /**
      * Just like newXMLInputStream() but with options.
      * Options map may be null.
+     *
      * @see XmlOptions
      */
     XMLStreamReader newXMLStreamReader(XmlOptions options);
-    
+
     /**
      * Just like xmlText() but with options.
      * Options map may be null.
      * <p>
-     * Note that this method does not produce XML with the XML declaration, 
-     * including the encoding information. To save the XML declaration with 
+     * Note that this method does not produce XML with the XML declaration,
+     * including the encoding information. To save the XML declaration with
      * the XML, see {@link #save(OutputStream)} or {@link #save(OutputStream, XmlOptions)}.
      *
      * @see XmlOptions
      */
     String xmlText(XmlOptions options);
-    
+
     /**
-     *
      * Just like newInputStream(String encoding) but with options.
      * Options map may be null.
+     *
      * @see XmlOptions
      */
     InputStream newInputStream(XmlOptions options);
-    
+
     /**
      * Just like newReader() but with options.
      * Options map may be null.
+     *
      * @see XmlOptions
      */
     Reader newReader(XmlOptions options);
-    
+
     /**
      * Just like newDomNode() but with options.
      * Options map may be null.
+     *
      * @see XmlOptions
      */
 
     Node newDomNode(XmlOptions options);
-    
+
     /**
      * Writes the XML represented by this source to the given SAX content and
      * lexical handlers.
-     * Note that this method does not save the XML declaration, including the encoding information. 
-     * To save the XML declaration with the XML, see {@link #save(OutputStream)}, 
+     * Note that this method does not save the XML declaration, including the encoding information.
+     * To save the XML declaration with the XML, see {@link #save(OutputStream)},
      * {@link #save(OutputStream, XmlOptions)}, {@link #save(File)} or {@link #save(File, XmlOptions)}.
      */
-    void save ( ContentHandler ch, LexicalHandler lh, XmlOptions options ) throws SAXException;
-    
+    void save(ContentHandler ch, LexicalHandler lh, XmlOptions options) throws SAXException;
+
     /**
      * Writes the XML represented by this source to the given File.
      * This method will save the XML declaration, including encoding information,
      * with the XML.
      */
-    void save ( File file, XmlOptions options ) throws IOException;
-    
+    void save(File file, XmlOptions options) throws IOException;
+
     /**
      * Writes the XML represented by this source to the given output stream.
      * This method will save the XML declaration, including encoding information,
      * with the XML.
      */
-    void save ( OutputStream os, XmlOptions options ) throws IOException;
+    void save(OutputStream os, XmlOptions options) throws IOException;
 
     /**
      * Writes the XML represented by this source to the given output.
-     * Note that this method does not save the XML declaration, including the encoding information. 
-     * To save the XML declaration with the XML, see {@link #save(OutputStream)}, 
+     * Note that this method does not save the XML declaration, including the encoding information.
+     * To save the XML declaration with the XML, see {@link #save(OutputStream)},
      * {@link #save(OutputStream, XmlOptions)}, {@link #save(File)} or {@link #save(File, XmlOptions)}.
      */
-    void save ( Writer w, XmlOptions options ) throws IOException;
+    void save(Writer w, XmlOptions options) throws IOException;
 
     /**
      * Prints to stdout the state of the document in which this token source is positioned.
@@ -374,5 +368,5 @@
      * XML text which only approximates the actual state of the document.
      */
 
-    void dump ( );
+    void dump();
 }
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 e3040c9..a66f293 100644
--- a/src/main/java/org/apache/xmlbeans/impl/common/SAXHelper.java
+++ b/src/main/java/org/apache/xmlbeans/impl/common/SAXHelper.java
@@ -15,21 +15,21 @@
 
 package org.apache.xmlbeans.impl.common;
 
-import java.io.IOException;
-import java.io.StringReader;
-import java.lang.reflect.Method;
-import java.util.concurrent.TimeUnit;
-
-import javax.xml.XMLConstants;
-import javax.xml.parsers.ParserConfigurationException;
-import javax.xml.parsers.SAXParserFactory;
-
+import org.apache.xmlbeans.XmlOptions;
 import org.apache.xmlbeans.XmlOptionsBean;
 import org.xml.sax.EntityResolver;
 import org.xml.sax.InputSource;
 import org.xml.sax.SAXException;
 import org.xml.sax.XMLReader;
 
+import javax.xml.XMLConstants;
+import javax.xml.parsers.ParserConfigurationException;
+import javax.xml.parsers.SAXParserFactory;
+import java.io.IOException;
+import java.io.StringReader;
+import java.lang.reflect.Method;
+import java.util.concurrent.TimeUnit;
+
 /**
  * Provides handy methods for working with SAX parsers and readers
  */
@@ -37,23 +37,24 @@
     private static final XBLogger logger = XBLogFactory.getLogger(SAXHelper.class);
     private static long lastLog;
 
-    private SAXHelper() {}
+    private SAXHelper() {
+    }
 
     /**
      * Creates a new SAX XMLReader, with sensible defaults
      */
-    public static XMLReader newXMLReader(XmlOptionsBean options) throws SAXException, ParserConfigurationException {
+    public static XMLReader newXMLReader(XmlOptions options) throws SAXException, ParserConfigurationException {
         XMLReader xmlReader = saxFactory(options).newSAXParser().getXMLReader();
         xmlReader.setEntityResolver(IGNORING_ENTITY_RESOLVER);
         trySetSAXFeature(xmlReader, XMLConstants.FEATURE_SECURE_PROCESSING);
         trySetXercesSecurityManager(xmlReader, options);
         return xmlReader;
     }
-    
+
     public static final EntityResolver IGNORING_ENTITY_RESOLVER = new EntityResolver() {
         @Override
         public InputSource resolveEntity(String publicId, String systemId)
-                throws SAXException, IOException {
+            throws SAXException, IOException {
             return new InputSource(new StringReader(""));
         }
     };
@@ -62,7 +63,7 @@
         return saxFactory(new XmlOptionsBean());
     }
 
-    static SAXParserFactory saxFactory(XmlOptionsBean options) {
+    static SAXParserFactory saxFactory(XmlOptions options) {
         SAXParserFactory saxFactory = SAXParserFactory.newInstance();
         saxFactory.setValidating(false);
         saxFactory.setNamespaceAware(true);
@@ -91,12 +92,12 @@
             logger.log(XBLogger.WARN, "Cannot set SAX feature because outdated XML parser in classpath", feature, ame);
         }
     }
-    
-    private static void trySetXercesSecurityManager(XMLReader xmlReader, XmlOptionsBean options) {
+
+    private static void trySetXercesSecurityManager(XMLReader xmlReader, XmlOptions options) {
         // Try built-in JVM one first, standalone if not
-        for (String securityManagerClassName : new String[] {
-                //"com.sun.org.apache.xerces.internal.util.SecurityManager",
-                "org.apache.xerces.util.SecurityManager"
+        for (String securityManagerClassName : new String[]{
+            //"com.sun.org.apache.xerces.internal.util.SecurityManager",
+            "org.apache.xerces.util.SecurityManager"
         }) {
             try {
                 Object mgr = Class.forName(securityManagerClassName).newInstance();
@@ -107,7 +108,7 @@
                 return;
             } catch (Throwable e) {     // NOSONAR - also catch things like NoClassDefError here
                 // throttle the log somewhat as it can spam the log otherwise
-                if(System.currentTimeMillis() > lastLog + TimeUnit.MINUTES.toMillis(5)) {
+                if (System.currentTimeMillis() > lastLog + TimeUnit.MINUTES.toMillis(5)) {
                     logger.log(XBLogger.WARN, "SAX Security Manager could not be setup [log suppressed for 5 minutes]", e);
                     lastLog = System.currentTimeMillis();
                 }
@@ -119,7 +120,7 @@
             xmlReader.setProperty(XMLBeansConstants.ENTITY_EXPANSION_LIMIT, options.getEntityExpansionLimit());
         } catch (SAXException e) {     // NOSONAR - also catch things like NoClassDefError here
             // throttle the log somewhat as it can spam the log otherwise
-            if(System.currentTimeMillis() > lastLog + TimeUnit.MINUTES.toMillis(5)) {
+            if (System.currentTimeMillis() > lastLog + TimeUnit.MINUTES.toMillis(5)) {
                 logger.log(XBLogger.WARN, "SAX Security Manager could not be setup [log suppressed for 5 minutes]", e);
                 lastLog = System.currentTimeMillis();
             }
diff --git a/src/main/java/org/apache/xmlbeans/impl/common/XmlErrorPrinter.java b/src/main/java/org/apache/xmlbeans/impl/common/XmlErrorPrinter.java
index eae88ac..2183252 100644
--- a/src/main/java/org/apache/xmlbeans/impl/common/XmlErrorPrinter.java
+++ b/src/main/java/org/apache/xmlbeans/impl/common/XmlErrorPrinter.java
@@ -17,43 +17,37 @@
 
 import org.apache.xmlbeans.XmlError;
 
-import java.util.AbstractCollection;
-import java.util.Iterator;
-import java.util.Collections;
 import java.net.URI;
+import java.util.AbstractCollection;
+import java.util.Collections;
+import java.util.Iterator;
 
-public class XmlErrorPrinter extends AbstractCollection
-{
-    private boolean _noisy;
-    private URI _baseURI;
+public class XmlErrorPrinter extends AbstractCollection<XmlError> {
+    private final boolean _noisy;
+    private final URI _baseURI;
 
-    public XmlErrorPrinter(boolean noisy, URI baseURI)
-    {
+    public XmlErrorPrinter(boolean noisy, URI baseURI) {
         _noisy = noisy;
         _baseURI = baseURI;
     }
 
-    public boolean add(Object o)
-    {
-        if (o instanceof XmlError)
-        {
-            XmlError err = (XmlError)o;
+    public boolean add(XmlError err) {
+        if (err != null) {
             if (err.getSeverity() == XmlError.SEVERITY_ERROR ||
-                err.getSeverity() == XmlError.SEVERITY_WARNING)
+                err.getSeverity() == XmlError.SEVERITY_WARNING) {
                 System.err.println(err.toString(_baseURI));
-            else if (_noisy)
+            } else if (_noisy) {
                 System.out.println(err.toString(_baseURI));
+            }
         }
         return false;
     }
 
-    public Iterator iterator()
-    {
-        return Collections.EMPTY_LIST.iterator();
+    public Iterator<XmlError> iterator() {
+        return Collections.emptyIterator();
     }
 
-    public int size()
-    {
+    public int size() {
         return 0;
     }
 }
diff --git a/src/main/java/org/apache/xmlbeans/impl/common/XmlErrorWatcher.java b/src/main/java/org/apache/xmlbeans/impl/common/XmlErrorWatcher.java
index d802590..b13ab5e 100644
--- a/src/main/java/org/apache/xmlbeans/impl/common/XmlErrorWatcher.java
+++ b/src/main/java/org/apache/xmlbeans/impl/common/XmlErrorWatcher.java
@@ -19,51 +19,48 @@
 
 import java.util.AbstractCollection;
 import java.util.Collection;
-import java.util.Iterator;
 import java.util.Collections;
+import java.util.Iterator;
 
-public class XmlErrorWatcher extends AbstractCollection
-{
-    private Collection _underlying;
+public class XmlErrorWatcher extends AbstractCollection<XmlError> {
+    private final Collection<XmlError> _underlying;
     private XmlError _firstError;
 
-    public XmlErrorWatcher(Collection underlying)
-    {
+    public XmlErrorWatcher(Collection<XmlError> underlying) {
         _underlying = underlying;
     }
 
-    public boolean add(Object o)
-    {
-        if (_firstError == null && o instanceof XmlError && ((XmlError)o).getSeverity() == XmlError.SEVERITY_ERROR)
-            _firstError = (XmlError)o;
-        if (_underlying == null)
+    public boolean add(XmlError o) {
+        if (_firstError == null && o != null && o.getSeverity() == XmlError.SEVERITY_ERROR) {
+            _firstError = o;
+        }
+        if (_underlying == null) {
             return false;
+        }
         return _underlying.add(o);
     }
 
-    public Iterator iterator()
-    {
-        if (_underlying == null)
-            return Collections.EMPTY_LIST.iterator();
+    public Iterator<XmlError> iterator() {
+        if (_underlying == null) {
+            return Collections.emptyIterator();
+        }
 
         return _underlying.iterator();
     }
 
-    public int size()
-    {
-        if (_underlying == null)
+    public int size() {
+        if (_underlying == null) {
             return 0;
+        }
 
         return _underlying.size();
     }
 
-    public boolean hasError()
-    {
+    public boolean hasError() {
         return _firstError != null;
     }
 
-    public XmlError firstError()
-    {
+    public XmlError firstError() {
         return _firstError;
     }
 }
diff --git a/src/main/java/org/apache/xmlbeans/impl/schema/SchemaDependencies.java b/src/main/java/org/apache/xmlbeans/impl/schema/SchemaDependencies.java
index 3f4b6c7..2693b1d 100644
--- a/src/main/java/org/apache/xmlbeans/impl/schema/SchemaDependencies.java
+++ b/src/main/java/org/apache/xmlbeans/impl/schema/SchemaDependencies.java
@@ -15,51 +15,40 @@
 
 package org.apache.xmlbeans.impl.schema;
 
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
+import java.util.*;
+import java.util.stream.Collectors;
 
-public class SchemaDependencies
-{
+public class SchemaDependencies {
     // This class is NOT synchronized
 
-    void registerDependency(String source, String target)
-    {
-        Set depSet = (Set) _dependencies.get(target);
-        if (depSet == null)
-        {
-            depSet = new HashSet();
-            _dependencies.put(target, depSet);
-        }
-        depSet.add(source);
-    }
-
-    
+    /**
+     * Records the list of files associated to each namespace.
+     * This is needed so that we can return a list of files that
+     * need to be compiled once we get a set of altered namespaces
+     */
+    private final Map<String, List<String>> _contributions = new HashMap<>();
 
     /**
      * Records anti-dependencies. Keys are namespaces and values are
      * the lists of namespaces that depend on each key
      */
-    private Map/*<String,Set<String>>*/ _dependencies;
+    private final Map<String, Set<String>> _dependencies = new HashMap<>();
 
-    Set computeTransitiveClosure(List modifiedNamespaces)
-    {
-        List nsList = new ArrayList(modifiedNamespaces);
-        Set result = new HashSet(modifiedNamespaces);
-        for (int i = 0; i < nsList.size(); i++)
-        {
-            Set deps = (Set) _dependencies.get(nsList.get(i));
-            if (deps == null)
+    void registerDependency(String source, String target) {
+        _dependencies.computeIfAbsent(target, k -> new HashSet<>()).add(source);
+    }
+
+
+    Set<String> computeTransitiveClosure(List<String> modifiedNamespaces) {
+        List<String> nsList = new ArrayList<>(modifiedNamespaces);
+        Set<String> result = new HashSet<>(modifiedNamespaces);
+        for (int i = 0; i < nsList.size(); i++) {
+            Set<String> deps = _dependencies.get(nsList.get(i));
+            if (deps == null) {
                 continue;
-            for (Iterator it = deps.iterator(); it.hasNext(); )
-            {
-                String ns = (String) it.next();
-                if (!result.contains(ns))
-                {
+            }
+            for (String ns : deps) {
+                if (!result.contains(ns)) {
                     nsList.add(ns);
                     result.add(ns);
                 }
@@ -68,95 +57,52 @@
         return result;
     }
 
-    SchemaDependencies()
-    {
-        _dependencies = new HashMap();
-        _contributions = new HashMap();
+    SchemaDependencies() {
     }
 
-    SchemaDependencies(SchemaDependencies base, Set updatedNs)
-    {
-        _dependencies = new HashMap();
-        _contributions = new HashMap();
-        for (Iterator it = base._dependencies.keySet().iterator(); it.hasNext(); )
-        {
-            String target = (String) it.next();
-            if (updatedNs.contains(target))
+    SchemaDependencies(SchemaDependencies base, Set<String> updatedNs) {
+        for (String target : base._dependencies.keySet()) {
+            if (updatedNs.contains(target)) {
                 continue;
-            Set depSet = new HashSet();
+            }
+            Set<String> depSet = new HashSet<>();
             _dependencies.put(target, depSet);
-            Set baseDepSet = (Set) base._dependencies.get(target);
-            for (Iterator it2 = baseDepSet.iterator(); it2.hasNext(); )
-            {
-                String source = (String) it2.next();
-                if (updatedNs.contains(source))
+            Set<String> baseDepSet = base._dependencies.get(target);
+            for (String source : baseDepSet) {
+                if (updatedNs.contains(source)) {
                     continue;
+                }
                 depSet.add(source);
             }
         }
-        for (Iterator it = base._contributions.keySet().iterator(); it.hasNext(); )
-        {
-            String ns = (String) it.next();
-            if (updatedNs.contains(ns))
+        for (String ns : base._contributions.keySet()) {
+            if (updatedNs.contains(ns)) {
                 continue;
-            List fileList = new ArrayList();
+            }
+            List<String> fileList = new ArrayList<>();
             _contributions.put(ns, fileList);
-            List baseFileList = (List) base._contributions.get(ns);
-            for (Iterator it2 = baseFileList.iterator(); it2.hasNext(); )
-                fileList.add(it2.next());
+            fileList.addAll(base._contributions.get(ns));
         }
     }
 
-    /**
-     * Records the list of files associated to each namespace.
-     * This is needed so that we can return a list of files that
-     * need to be compiled once we get a set of altered namespaces
-     */
-    private Map/*<String,List<String>>*/ _contributions;
-
-    void registerContribution(String ns, String fileURL)
-    {
-        List fileList = (List) _contributions.get(ns);
-        if (fileList == null)
-        {
-            fileList = new ArrayList();
-            _contributions.put(ns, fileList);
-        }
-        fileList.add(fileURL);
+    void registerContribution(String ns, String fileURL) {
+        _contributions.computeIfAbsent(ns, k -> new ArrayList<>()).add(fileURL);
     }
 
-    boolean isFileRepresented(String fileURL)
-    {
-        for (Iterator it = _contributions.values().iterator(); it.hasNext(); )
-        {
-            List fileList = (List) it.next();
-            if (fileList.contains(fileURL))
-                return true;
-        }
-        return false;
+    boolean isFileRepresented(String fileURL) {
+        return _contributions.values().stream().anyMatch(l -> l.contains(fileURL));
     }
 
-    List getFilesTouched(Set updatedNs)
-    {
-        List result = new ArrayList();
-        for (Iterator it = updatedNs.iterator(); it.hasNext(); )
-        {
-            result.addAll((List) _contributions.get(it.next()));
-        }
-        return result;
+    List<String> getFilesTouched(Set<String> updatedNs) {
+        return updatedNs.stream().map(_contributions::get).
+            filter(Objects::nonNull).flatMap(List::stream).
+            collect(Collectors.toList());
     }
 
-    List getNamespacesTouched(Set modifiedFiles)
-    {
-        List result = new ArrayList();
-        for (Iterator it = _contributions.keySet().iterator(); it.hasNext(); )
-        {
-            String ns = (String) it.next();
-            List files = (List) _contributions.get(ns);
-            for (int i = 0; i < files.size(); i++)
-                if (modifiedFiles.contains(files.get(i)))
-                    result.add(ns);
-        }
-        return result;
+    List<String> getNamespacesTouched(Set<String> modifiedFiles) {
+        return _contributions.entrySet().stream().
+            filter(e -> e.getValue().stream().anyMatch(modifiedFiles::contains)).
+            map(Map.Entry::getKey).
+            collect(Collectors.toList());
     }
 }
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 f548cf0..6793074 100644
--- a/src/main/java/org/apache/xmlbeans/impl/schema/SchemaTypeCodePrinter.java
+++ b/src/main/java/org/apache/xmlbeans/impl/schema/SchemaTypeCodePrinter.java
@@ -57,32 +57,15 @@
         getPrinter(opt).printType(writer, sType);
     }
 
-    /**
-     * @deprecated
-     */
-    public static void printLoader(Writer writer, SchemaTypeSystem system,
-                                   XmlOptions opt)
-        throws IOException {
-        getPrinter(opt).printLoader(writer, system);
-    }
-
     private static SchemaCodePrinter getPrinter(XmlOptions opt) {
-        Object printer = XmlOptions.safeGet
-            (opt, XmlOptions.SCHEMA_CODE_PRINTER);
-        if (printer == null || !(printer instanceof SchemaCodePrinter)) {
-            printer = new SchemaTypeCodePrinter(opt);
-        }
-        return (SchemaCodePrinter) printer;
+        SchemaCodePrinter printer = opt == null ? null : opt.getSchemaCodePrinter();
+        return printer == null ? new SchemaTypeCodePrinter(opt) : printer;
     }
 
     public SchemaTypeCodePrinter(XmlOptions opt) {
         _indent = 0;
 
-        String genversion = null;
-
-        if (opt != null && XmlOptions.hasOption(opt, XmlOptions.GENERATE_JAVA_VERSION)) {
-            genversion = (String) opt.get(XmlOptions.GENERATE_JAVA_VERSION);
-        }
+        String genversion = (opt == null) ? null : opt.getGenerateJavaVersion();
 
         if (genversion == null) {
             genversion = XmlOptions.GENERATE_JAVA_14;
@@ -99,39 +82,6 @@
         _indent -= INDENT_INCREMENT;
     }
 
-    String encodeString(String s) {
-        StringBuilder sb = new StringBuilder();
-
-        sb.append('"');
-
-        for (int i = 0; i < s.length(); i++) {
-            char ch = s.charAt(i);
-
-            if (ch == '"') {
-                sb.append('\\');
-                sb.append('\"');
-            } else if (ch == '\\') {
-                sb.append('\\');
-                sb.append('\\');
-            } else if (ch == '\r') {
-                sb.append('\\');
-                sb.append('r');
-            } else if (ch == '\n') {
-                sb.append('\\');
-                sb.append('n');
-            } else if (ch == '\t') {
-                sb.append('\\');
-                sb.append('t');
-            } else {
-                sb.append(ch);
-            }
-        }
-
-        sb.append('"');
-
-        return sb.toString();
-    }
-
     void emit(String s) throws IOException {
         int indent = _indent;
 
@@ -157,9 +107,6 @@
 
     private static String makeSafe(String s) {
         Charset charset = Charset.forName(System.getProperty("file.encoding"));
-        if (charset == null) {
-            throw new IllegalStateException("Default character set is null!");
-        }
         CharsetEncoder cEncoder = charset.newEncoder();
         StringBuilder result = new StringBuilder();
         int i;
@@ -174,7 +121,7 @@
             if (cEncoder.canEncode(c)) {
                 result.append(c);
             } else {
-                String hexValue = Integer.toHexString((int) c);
+                String hexValue = Integer.toHexString(c);
                 switch (hexValue.length()) {
                     case 1:
                         result.append("\\u000").append(hexValue);
@@ -269,8 +216,8 @@
             case SchemaType.UNION:
                 emit(" * This is a union type. Instances are of one of the following types:");
                 SchemaType[] members = sType.getUnionConstituentTypes();
-                for (int i = 0; i < members.length; i++) {
-                    emit(" *     " + members[i].getFullJavaName());
+                for (SchemaType member : members) {
+                    emit(" *     " + member.getFullJavaName());
                 }
                 break;
         }
@@ -310,26 +257,13 @@
         return name + "." + INDEX_CLASSNAME;
     }
 
-    static String shortIndexClassForSystem(SchemaTypeSystem system) {
-        return INDEX_CLASSNAME;
-    }
-
     void printStaticTypeDeclaration(SchemaType sType, SchemaTypeSystem system) throws IOException {
-        String interfaceShortName = sType.getShortJavaName();
         emit("public static final org.apache.xmlbeans.SchemaType type = (org.apache.xmlbeans.SchemaType)");
         indent();
         emit("Factory.getTypeLoader().resolveHandle(\"" + ((SchemaTypeSystemImpl) system).handleForType(sType) + "\");");
         outdent();
     }
 
-    /**
-     * @deprecated
-     */
-    public void printLoader(Writer writer, SchemaTypeSystem system)
-        throws IOException {
-        // deprecated
-    }
-
     void printInnerType(SchemaType sType, SchemaTypeSystem system) throws IOException {
         emit("");
 
@@ -350,9 +284,7 @@
 
             SchemaProperty[] props = getDerivedProperties(sType);
 
-            for (int i = 0; i < props.length; i++) {
-                SchemaProperty prop = props[i];
-
+            for (SchemaProperty prop : props) {
                 printPropertyGetters(
                     prop.getName(),
                     prop.isAttribute(),
@@ -549,11 +481,11 @@
                                sType.getName().equals(sType.getBaseType().getName());
         while (sType != null) {
             SchemaType[] anonTypes = sType.getAnonymousTypes();
-            for (int i = 0; i < anonTypes.length; i++) {
-                if (anonTypes[i].isSkippedAnonymousType()) {
-                    printNestedInnerTypes(anonTypes[i], system);
+            for (SchemaType anonType : anonTypes) {
+                if (anonType.isSkippedAnonymousType()) {
+                    printNestedInnerTypes(anonType, system);
                 } else {
-                    printInnerType(anonTypes[i], system);
+                    printInnerType(anonType, system);
                 }
             }
             // For redefinition other than by extension for complex types, go ahead and print
@@ -658,8 +590,8 @@
 
         InterfaceExtension[] exts = sImpl.getInterfaceExtensions();
         if (exts != null) {
-            for (int i = 0; i < exts.length; i++) {
-                sb.append(", " + exts[i].getInterface());
+            for (InterfaceExtension ext : exts) {
+                sb.append(", " + ext.getInterface());
             }
         }
 
@@ -808,10 +740,6 @@
         emit(" */");
     }
 
-    void printShortJavaDoc(String sentence) throws IOException {
-        emit("/** " + sentence + " */");
-    }
-
     public static String javaStringEscape(String str) {
         // forbidden: \n, \r, \", \\.
         test:
@@ -864,17 +792,17 @@
 
         emit("");
         SchemaStringEnumEntry[] entries = sType.getStringEnumEntries();
-        HashSet seenValues = new HashSet();
-        HashSet repeatValues = new HashSet();
-        for (int i = 0; i < entries.length; i++) {
-            String enumValue = entries[i].getString();
+        HashSet<String> seenValues = new HashSet<>();
+        HashSet<String> repeatValues = new HashSet<>();
+        for (SchemaStringEnumEntry entry : entries) {
+            String enumValue = entry.getString();
             if (seenValues.contains(enumValue)) {
                 repeatValues.add(enumValue);
                 continue;
             } else {
                 seenValues.add(enumValue);
             }
-            String constName = entries[i].getEnumName();
+            String constName = entry.getEnumName();
             if (hasBase) {
                 emit("static final " + baseEnumClass + ".Enum " + constName + " = " + baseEnumClass + "." + constName + ";");
             } else {
@@ -882,11 +810,11 @@
             }
         }
         emit("");
-        for (int i = 0; i < entries.length; i++) {
-            if (repeatValues.contains(entries[i].getString())) {
+        for (SchemaStringEnumEntry entry : entries) {
+            if (repeatValues.contains(entry.getString())) {
                 continue;
             }
-            String constName = "INT_" + entries[i].getEnumName();
+            String constName = "INT_" + entry.getEnumName();
             if (hasBase) {
                 emit("static final int " + constName + " = " + baseEnumClass + "." + constName + ";");
             } else {
@@ -929,9 +857,9 @@
             emit("private Enum(java.lang.String s, int i)");
             emit("    { super(s, i); }");
             emit("");
-            for (int i = 0; i < entries.length; i++) {
-                String constName = "INT_" + entries[i].getEnumName();
-                int intValue = entries[i].getIntValue();
+            for (SchemaStringEnumEntry entry : entries) {
+                String constName = "INT_" + entry.getEnumName();
+                int intValue = entry.getIntValue();
                 emit("static final int " + constName + " = " + intValue + ";");
             }
             emit("");
@@ -942,9 +870,9 @@
             emit("new Enum[]");
             emit("{");
             indent();
-            for (int i = 0; i < entries.length; i++) {
-                String enumValue = entries[i].getString();
-                String constName = "INT_" + entries[i].getEnumName();
+            for (SchemaStringEnumEntry entry : entries) {
+                String enumValue = entry.getString();
+                String constName = "INT_" + entry.getEnumName();
                 emit("new Enum(\"" + javaStringEscape(enumValue) + "\", " + constName + "),");
             }
             outdent();
@@ -984,8 +912,7 @@
     }
 
     static boolean isJavaPrimitive(int javaType) {
-        return (javaType < SchemaProperty.JAVA_FIRST_PRIMITIVE ? false :
-            (javaType > SchemaProperty.JAVA_LAST_PRIMITIVE ? false : true));
+        return (javaType >= SchemaProperty.JAVA_FIRST_PRIMITIVE && (javaType <= SchemaProperty.JAVA_LAST_PRIMITIVE));
     }
 
     /**
@@ -1356,8 +1283,8 @@
 
         if (sType.getSimpleVariety() == SchemaType.UNION) {
             SchemaType[] memberTypes = sType.getUnionMemberTypes();
-            for (int i = 0; i < memberTypes.length; i++) {
-                interfaces.append(", " + memberTypes[i].getFullJavaName().replace('$', '.'));
+            for (SchemaType memberType : memberTypes) {
+                interfaces.append(", " + memberType.getFullJavaName().replace('$', '.'));
             }
         }
 
@@ -1739,17 +1666,17 @@
         }
     }
 
-    String getIdentifier(Map qNameMap, QName qName) {
-        return ((String[]) qNameMap.get(qName))[0];
+    String getIdentifier(Map<QName, String[]> qNameMap, QName qName) {
+        return qNameMap.get(qName)[0];
     }
 
-    String getSetIdentifier(Map qNameMap, QName qName) {
-        String[] identifiers = (String[]) qNameMap.get(qName);
+    String getSetIdentifier(Map<QName, String[]> qNameMap, QName qName) {
+        String[] identifiers = qNameMap.get(qName);
         return identifiers[1] == null ? identifiers[0] : identifiers[1];
     }
 
-    Map printStaticFields(SchemaProperty[] properties) throws IOException {
-        final Map results = new HashMap();
+    Map<QName, String[]> printStaticFields(SchemaProperty[] properties) throws IOException {
+        final Map<QName, String[]> results = new HashMap<>();
 
         emit("");
         for (int i = 0; i < properties.length; i++) {
@@ -1777,9 +1704,9 @@
                     emit("private static final org.apache.xmlbeans.QNameSet " + identifiers[1] +
                          " = org.apache.xmlbeans.QNameSet.forArray( new javax.xml.namespace.QName[] { ");
                     indent();
-                    for (int j = 0; j < qnames.length; j++) {
-                        emit("new javax.xml.namespace.QName(\"" + qnames[j].getNamespaceURI() +
-                             "\", \"" + qnames[j].getLocalPart() + "\"),");
+                    for (QName qname : qnames) {
+                        emit("new javax.xml.namespace.QName(\"" + qname.getNamespaceURI() +
+                             "\", \"" + qname.getLocalPart() + "\"),");
                     }
 
                     outdent();
@@ -2499,21 +2426,6 @@
         }
     }
 
-    static void getTypeName(Class c, StringBuffer sb) {
-        int arrayCount = 0;
-        while (c.isArray()) {
-            c = c.getComponentType();
-            arrayCount++;
-        }
-
-        sb.append(c.getName());
-
-        for (int i = 0; i < arrayCount; i++) {
-            sb.append("[]");
-        }
-
-    }
-
     void printInnerTypeImpl(
         SchemaType sType, SchemaTypeSystem system, boolean isInner) throws IOException {
         String shortName = sType.getShortJavaImplName();
@@ -2538,16 +2450,16 @@
                 // but we still need to implement them because this class is supposed to
                 // also implement all the interfaces
                 SchemaType baseType = sType.getBaseType();
-                List extraProperties = null;
+                List<SchemaProperty> extraProperties = null;
                 while (!baseType.isSimpleType() && !baseType.isBuiltinType()) {
                     SchemaProperty[] baseProperties = baseType.getDerivedProperties();
-                    for (int i = 0; i < baseProperties.length; i++) {
-                        if (!(baseProperties[i].isAttribute() &&
-                              sType.getAttributeProperty(baseProperties[i].getName()) != null)) {
+                    for (SchemaProperty baseProperty : baseProperties) {
+                        if (!(baseProperty.isAttribute() &&
+                              sType.getAttributeProperty(baseProperty.getName()) != null)) {
                             if (extraProperties == null) {
-                                extraProperties = new ArrayList();
+                                extraProperties = new ArrayList<>();
                             }
-                            extraProperties.add(baseProperties[i]);
+                            extraProperties.add(baseProperty);
                         }
                     }
                     baseType = baseType.getBaseType();
@@ -2555,11 +2467,8 @@
 
                 properties = sType.getProperties();
                 if (extraProperties != null) {
-                    for (int i = 0; i < properties.length; i++) {
-                        extraProperties.add(properties[i]);
-                    }
-                    properties = (SchemaProperty[]) extraProperties.
-                        toArray(new SchemaProperty[extraProperties.size()]);
+                    Collections.addAll(extraProperties, properties);
+                    properties = extraProperties.toArray(new SchemaProperty[0]);
                 }
             } else {
                 // complex content type implementations derive from base type impls
@@ -2568,11 +2477,9 @@
                 properties = getDerivedProperties(sType);
             }
 
-            Map qNameMap = printStaticFields(properties);
+            Map<QName, String[]> qNameMap = printStaticFields(properties);
 
-            for (int i = 0; i < properties.length; i++) {
-                SchemaProperty prop = properties[i];
-
+            for (SchemaProperty prop : properties) {
                 QName name = prop.getName();
                 String xmlType = xmlTypeForProperty(prop);
 
@@ -2631,20 +2538,20 @@
             // not present in sType, because the redefined types do not
             // have a generated class to represent them
             SchemaProperty[] props = sType.getDerivedProperties();
-            Map propsByName = new LinkedHashMap();
-            for (int i = 0; i < props.length; i++) {
-                propsByName.put(props[i].getName(), props[i]);
+            Map<QName, SchemaProperty> propsByName = new LinkedHashMap<>();
+            for (SchemaProperty prop : props) {
+                propsByName.put(prop.getName(), prop);
             }
             while (sType2 != null && name.equals(sType2.getName())) {
                 props = sType2.getDerivedProperties();
-                for (int i = 0; i < props.length; i++) {
-                    if (!propsByName.containsKey(props[i].getName())) {
-                        propsByName.put(props[i].getName(), props[i]);
+                for (SchemaProperty prop : props) {
+                    if (!propsByName.containsKey(prop.getName())) {
+                        propsByName.put(prop.getName(), prop);
                     }
                 }
                 sType2 = sType2.getBaseType();
             }
-            return (SchemaProperty[]) propsByName.values().toArray(new SchemaProperty[0]);
+            return propsByName.values().toArray(new SchemaProperty[0]);
         } else {
             return sType.getDerivedProperties();
         }
@@ -2658,14 +2565,14 @@
 
         InterfaceExtension[] exts = sImpl.getInterfaceExtensions();
         if (exts != null) {
-            for (int i = 0; i < exts.length; i++) {
-                InterfaceExtension.MethodSignature[] methods = exts[i].getMethods();
+            for (InterfaceExtension ext : exts) {
+                InterfaceExtension.MethodSignature[] methods = ext.getMethods();
                 if (methods != null) {
-                    for (int j = 0; j < methods.length; j++) {
-                        printJavaDoc("Implementation method for interface " + exts[i].getStaticHandler());
-                        printInterfaceMethodDecl(methods[j]);
+                    for (InterfaceExtension.MethodSignature method : methods) {
+                        printJavaDoc("Implementation method for interface " + ext.getStaticHandler());
+                        printInterfaceMethodDecl(method);
                         startBlock();
-                        printInterfaceMethodImpl(exts[i].getStaticHandler(), methods[j]);
+                        printInterfaceMethodImpl(ext.getStaticHandler(), method);
                         endBlock();
                     }
                 }
@@ -2721,11 +2628,11 @@
                                sType.getName().equals(sType.getBaseType().getName());
         while (sType != null) {
             SchemaType[] anonTypes = sType.getAnonymousTypes();
-            for (int i = 0; i < anonTypes.length; i++) {
-                if (anonTypes[i].isSkippedAnonymousType()) {
-                    printNestedTypeImpls(anonTypes[i], system);
+            for (SchemaType anonType : anonTypes) {
+                if (anonType.isSkippedAnonymousType()) {
+                    printNestedTypeImpls(anonType, system);
                 } else {
-                    printInnerTypeImpl(anonTypes[i], system, true);
+                    printInnerTypeImpl(anonType, system, true);
                 }
             }
             // For redefinition by extension, go ahead and print the anonymous
diff --git a/src/main/java/org/apache/xmlbeans/impl/schema/SchemaTypeLoaderBase.java b/src/main/java/org/apache/xmlbeans/impl/schema/SchemaTypeLoaderBase.java
index d0c2b46..ff80dcb 100644
--- a/src/main/java/org/apache/xmlbeans/impl/schema/SchemaTypeLoaderBase.java
+++ b/src/main/java/org/apache/xmlbeans/impl/schema/SchemaTypeLoaderBase.java
@@ -15,172 +15,134 @@
 
 package org.apache.xmlbeans.impl.schema;
 
+import org.apache.xmlbeans.*;
 import org.apache.xmlbeans.impl.common.QNameHelper;
-import org.apache.xmlbeans.impl.validator.ValidatingXMLInputStream;
-
 import org.apache.xmlbeans.impl.store.Locale;
-
-import org.apache.xmlbeans.SchemaAttributeGroup;
-import org.apache.xmlbeans.SchemaField;
-import org.apache.xmlbeans.SchemaGlobalAttribute;
-import org.apache.xmlbeans.SchemaGlobalElement;
-import org.apache.xmlbeans.SchemaModelGroup;
-import org.apache.xmlbeans.SchemaType;
-import org.apache.xmlbeans.SchemaTypeLoader;
-import org.apache.xmlbeans.XmlSaxHandler;
-import org.apache.xmlbeans.XmlException;
-import org.apache.xmlbeans.XmlObject;
-import org.apache.xmlbeans.XmlOptions;
-import org.apache.xmlbeans.XmlFactoryHook;
-import org.apache.xmlbeans.XmlBeans;
-
-import java.lang.reflect.Method;
-import java.lang.reflect.InvocationTargetException;
-import java.io.InputStream;
-import java.io.Reader;
-import java.io.File;
-import java.io.IOException;
-import java.io.FileInputStream;
-import java.util.List;
-import java.util.ArrayList;
-import java.net.URL;
-import java.net.URLConnection;
-import java.net.HttpURLConnection;
-import java.security.DigestInputStream;
-import java.security.MessageDigest;
-import java.security.NoSuchAlgorithmException;
+import org.apache.xmlbeans.impl.validator.ValidatingXMLInputStream;
+import org.apache.xmlbeans.xml.stream.XMLInputStream;
+import org.apache.xmlbeans.xml.stream.XMLStreamException;
+import org.w3c.dom.DOMImplementation;
+import org.w3c.dom.Node;
 
 import javax.xml.namespace.QName;
 import javax.xml.stream.XMLStreamReader;
+import java.io.*;
+import java.lang.reflect.InvocationTargetException;
+import java.lang.reflect.Method;
+import java.net.HttpURLConnection;
+import java.net.URL;
+import java.net.URLConnection;
+import java.security.DigestInputStream;
+import java.security.MessageDigest;
+import java.security.NoSuchAlgorithmException;
+import java.util.ArrayList;
+import java.util.List;
 
-import org.w3c.dom.Node;
-import org.w3c.dom.DOMImplementation;
-
-import org.apache.xmlbeans.xml.stream.XMLInputStream;
-import org.apache.xmlbeans.xml.stream.XMLStreamException;
-
-public abstract class SchemaTypeLoaderBase implements SchemaTypeLoader
-{
+public abstract class SchemaTypeLoaderBase implements SchemaTypeLoader {
     private static final String USER_AGENT = "XMLBeans/" + XmlBeans.getVersion() + " (" + XmlBeans.getTitle() + ")";
 
-    private static final Method _pathCompiler = getMethod( "org.apache.xmlbeans.impl.store.Path", "compilePath", new Class[] { String.class, XmlOptions.class } );
-    private static final Method _queryCompiler = getMethod( "org.apache.xmlbeans.impl.store.Query", "compileQuery", new Class[] { String.class, XmlOptions.class } );
+    private static final Method _pathCompiler = getMethod("org.apache.xmlbeans.impl.store.Path", "compilePath", new Class[]{String.class, XmlOptions.class});
+    private static final Method _queryCompiler = getMethod("org.apache.xmlbeans.impl.store.Query", "compileQuery", new Class[]{String.class, XmlOptions.class});
 
-    private static Method getMethod ( String className, String methodName, Class[] args )
-    {
-        try
-        {
+    private static Method getMethod(String className, String methodName, Class[] args) {
+        try {
             return
-                Class.forName( className ).
-                    getDeclaredMethod( methodName, args );
-        }
-        catch (Exception e)
-        {
+                Class.forName(className).
+                    getDeclaredMethod(methodName, args);
+        } catch (Exception e) {
             throw new IllegalStateException(
                 "Cannot find " + className + "." + methodName +
-                    ".  verify that xmlstore " +
-                        "(from xbean.jar) is on classpath" );
+                ".  verify that xmlstore " +
+                "(from xbean.jar) is on classpath");
         }
     }
 
-    private static Object invokeMethod ( Method method, Object[] args )
-    {
-        try
-        {
-            return method.invoke( method, args );
-        }
-        catch ( InvocationTargetException e )
-        {
+    private static Object invokeMethod(Method method, Object[] args) {
+        try {
+            return method.invoke(method, args);
+        } catch (InvocationTargetException e) {
             Throwable t = e.getCause();
-            IllegalStateException ise = new IllegalStateException( t.getMessage() );
-            ise.initCause( t ); // need initCause() to support Java1.4
-            throw ise;
-        }
-        catch ( Exception e )
-        {
-            IllegalStateException ise = new IllegalStateException( e.getMessage() );
-            ise.initCause( e );
-            throw ise;
+            throw new IllegalStateException(t.getMessage(), t);
+        } catch (Exception e) {
+            throw new IllegalStateException(e.getMessage(), e);
         }
     }
 
-    private static String doCompilePath ( String pathExpr, XmlOptions options )
-    {
-        return (String) invokeMethod( _pathCompiler, new Object[] { pathExpr, options } );
+    private static String doCompilePath(String pathExpr, XmlOptions options) {
+        return (String) invokeMethod(_pathCompiler, new Object[]{pathExpr, options});
     }
 
-    private static String doCompileQuery ( String queryExpr, XmlOptions options )
-    {
-        return (String) invokeMethod( _queryCompiler, new Object[] { queryExpr, options } );
+    private static String doCompileQuery(String queryExpr, XmlOptions options) {
+        return (String) invokeMethod(_queryCompiler, new Object[]{queryExpr, options});
     }
 
-    public SchemaType findType(QName name)
-    {
+    public SchemaType findType(QName name) {
         SchemaType.Ref ref = findTypeRef(name);
-        if (ref == null)
+        if (ref == null) {
             return null;
+        }
         SchemaType result = ref.get();
-        assert(result != null);
+        assert (result != null);
         return result;
     }
 
-    public SchemaType findDocumentType(QName name)
-    {
+    public SchemaType findDocumentType(QName name) {
         SchemaType.Ref ref = findDocumentTypeRef(name);
-        if (ref == null)
+        if (ref == null) {
             return null;
+        }
         SchemaType result = ref.get();
-        assert(result != null);
+        assert (result != null);
         return result;
     }
 
-    public SchemaType findAttributeType(QName name)
-    {
+    public SchemaType findAttributeType(QName name) {
         SchemaType.Ref ref = findAttributeTypeRef(name);
-        if (ref == null)
+        if (ref == null) {
             return null;
+        }
         SchemaType result = ref.get();
-        assert(result != null);
+        assert (result != null);
         return result;
     }
 
-    public SchemaModelGroup findModelGroup(QName name)
-    {
+    public SchemaModelGroup findModelGroup(QName name) {
         SchemaModelGroup.Ref ref = findModelGroupRef(name);
-        if (ref == null)
+        if (ref == null) {
             return null;
+        }
         SchemaModelGroup result = ref.get();
-        assert(result != null);
+        assert (result != null);
         return result;
     }
 
-    public SchemaAttributeGroup findAttributeGroup(QName name)
-    {
+    public SchemaAttributeGroup findAttributeGroup(QName name) {
         SchemaAttributeGroup.Ref ref = findAttributeGroupRef(name);
-        if (ref == null)
+        if (ref == null) {
             return null;
+        }
         SchemaAttributeGroup result = ref.get();
-        assert(result != null);
+        assert (result != null);
         return result;
     }
 
-    public SchemaGlobalElement findElement(QName name)
-    {
+    public SchemaGlobalElement findElement(QName name) {
         SchemaGlobalElement.Ref ref = findElementRef(name);
-        if (ref == null)
+        if (ref == null) {
             return null;
+        }
         SchemaGlobalElement result = ref.get();
-        assert(result != null);
+        assert (result != null);
         return result;
     }
 
-    public SchemaGlobalAttribute findAttribute(QName name)
-    {
+    public SchemaGlobalAttribute findAttribute(QName name) {
         SchemaGlobalAttribute.Ref ref = findAttributeRef(name);
-        if (ref == null)
+        if (ref == null) {
             return null;
+        }
         SchemaGlobalAttribute result = ref.get();
-        assert(result != null);
+        assert (result != null);
         return result;
     }
 
@@ -188,264 +150,225 @@
     //
     //
 
-    public XmlObject newInstance ( SchemaType type, XmlOptions options )
-    {
+    public XmlObject newInstance(SchemaType type, XmlOptions options) {
         XmlFactoryHook hook = XmlFactoryHook.ThreadContext.getHook();
-        
-        if (hook != null)
-            return hook.newInstance( this, type, options );
 
-        return Locale.newInstance( this, type, options );
+        if (hook != null) {
+            return hook.newInstance(this, type, options);
+        }
+
+        return Locale.newInstance(this, type, options);
     }
 
-    public XmlObject parse ( String xmlText, SchemaType type, XmlOptions options ) throws XmlException
-    {
+    public XmlObject parse(String xmlText, SchemaType type, XmlOptions options) throws XmlException {
         XmlFactoryHook hook = XmlFactoryHook.ThreadContext.getHook();
-        
-        if (hook != null)
-            return hook.parse( this, xmlText, type, options );
 
-        return Locale.parseToXmlObject( this, xmlText, type, options );
+        if (hook != null) {
+            return hook.parse(this, xmlText, type, options);
+        }
+
+        return Locale.parseToXmlObject(this, xmlText, type, options);
     }
 
     /**
      * @deprecated XMLInputStream was deprecated by XMLStreamReader from STaX - jsr173 API.
      */
-    public XmlObject parse ( XMLInputStream xis, SchemaType type, XmlOptions options ) throws XmlException, XMLStreamException
-    {
+    public XmlObject parse(XMLInputStream xis, SchemaType type, XmlOptions options) throws XmlException, XMLStreamException {
         XmlFactoryHook hook = XmlFactoryHook.ThreadContext.getHook();
-        
-        if (hook != null)
-            return hook.parse( this, xis, type, options );
-        
-        return Locale.parseToXmlObject( this, xis, type, options );
+
+        if (hook != null) {
+            return hook.parse(this, xis, type, options);
+        }
+
+        return Locale.parseToXmlObject(this, xis, type, options);
     }
 
-    public XmlObject parse ( XMLStreamReader xsr, SchemaType type, XmlOptions options ) throws XmlException
-    {
+    public XmlObject parse(XMLStreamReader xsr, SchemaType type, XmlOptions options) throws XmlException {
         XmlFactoryHook hook = XmlFactoryHook.ThreadContext.getHook();
-        
-        if (hook != null)
-            return hook.parse( this, xsr, type, options );
 
-        return Locale.parseToXmlObject( this, xsr, type, options );
+        if (hook != null) {
+            return hook.parse(this, xsr, type, options);
+        }
+
+        return Locale.parseToXmlObject(this, xsr, type, options);
     }
-    
-    public XmlObject parse ( File file, SchemaType type, XmlOptions options ) throws XmlException, IOException
-    {
-        if (options == null)
-        {
+
+    public XmlObject parse(File file, SchemaType type, XmlOptions options) throws XmlException, IOException {
+        String fileName = file.toURI().normalize().toString();
+        if (options == null) {
             options = new XmlOptions();
-            options.put( XmlOptions.DOCUMENT_SOURCE_NAME, file.toURI().normalize().toString() );
+            options.setDocumentSourceName(fileName);
+        } else if (options.getDocumentSourceName() == null) {
+            options = new XmlOptions(options);
+            options.setDocumentSourceName(fileName);
         }
 
-        else if (! options.hasOption(XmlOptions.DOCUMENT_SOURCE_NAME))
-        {
-            options = new XmlOptions( options );
-            options.put( XmlOptions.DOCUMENT_SOURCE_NAME, file.toURI().normalize().toString() );
-        }
-
-        InputStream fis = new FileInputStream( file );
-
-        try
-        {
-            return parse( fis, type, options );
-        }
-        finally
-        {
-            fis.close();
+        try (InputStream fis = new FileInputStream(file)) {
+            return parse(fis, type, options);
         }
     }
 
-    public XmlObject parse ( URL url, SchemaType type, XmlOptions options ) throws XmlException, IOException
-    {
-        if (options == null)
-        {
+    public XmlObject parse(URL url, SchemaType type, XmlOptions options) throws XmlException, IOException {
+        if (options == null) {
             options = new XmlOptions();
-            options.put( XmlOptions.DOCUMENT_SOURCE_NAME, url.toString() );
+            options.setDocumentSourceName(url.toString());
+        } else if (options.getDocumentSourceName() == null) {
+            options = new XmlOptions(options);
+            options.setDocumentSourceName(url.toString());
         }
 
-        else if (! options.hasOption(XmlOptions.DOCUMENT_SOURCE_NAME))
-        {
-            options = new XmlOptions( options );
-            options.put( XmlOptions.DOCUMENT_SOURCE_NAME, url.toString() );
-        }
 
-        URLConnection conn = null;
-        InputStream stream = null;
-        download: try
-        {
+        boolean redirected = false;
+        int count = 0;
+        URLConnection conn;
 
-            boolean redirected = false;
-            int count = 0;
+        do {
+            conn = url.openConnection();
+            conn.addRequestProperty("User-Agent", USER_AGENT);
+            conn.addRequestProperty("Accept", "application/xml, text/xml, */*");
+            if (conn instanceof HttpURLConnection) {
+                HttpURLConnection httpcon = (HttpURLConnection) conn;
+                int code = httpcon.getResponseCode();
+                redirected = (code == HttpURLConnection.HTTP_MOVED_PERM || code == HttpURLConnection.HTTP_MOVED_TEMP);
+                if (redirected && count > 5) {
+                    redirected = false;
+                }
 
-            do {
-                conn = url.openConnection();
-                conn.addRequestProperty("User-Agent", USER_AGENT);
-                conn.addRequestProperty("Accept", "application/xml, text/xml, */*");
-                if (conn instanceof HttpURLConnection)
-                {
-                    HttpURLConnection httpcon = (HttpURLConnection)conn;
-                    int code = httpcon.getResponseCode();
-                    redirected = (code == HttpURLConnection.HTTP_MOVED_PERM || code == HttpURLConnection.HTTP_MOVED_TEMP);
-                    if (redirected && count > 5)
+                if (redirected) {
+                    String newLocation = httpcon.getHeaderField("Location");
+                    if (newLocation == null) {
                         redirected = false;
-
-                    if (redirected)
-                    {
-                        String newLocation = httpcon.getHeaderField("Location");
-                        if (newLocation == null)
-                            redirected = false;
-                        else
-                        {
-                            url = new URL(newLocation);
-                            count ++;
-                        }
+                    } else {
+                        url = new URL(newLocation);
+                        count++;
                     }
                 }
-            } while (redirected);
+            }
+        } while (redirected);
 
-            stream = conn.getInputStream();
-            return parse( stream, type, options );
-        }
-        finally
-        {
-            if (stream != null)
-                stream.close();
+        try (InputStream stream = conn.getInputStream()) {
+            return parse(stream, type, options);
         }
     }
 
-    public XmlObject parse ( InputStream jiois, SchemaType type, XmlOptions options ) throws XmlException, IOException
-    {
+    public XmlObject parse(InputStream jiois, SchemaType type, XmlOptions options) throws XmlException, IOException {
         XmlFactoryHook hook = XmlFactoryHook.ThreadContext.getHook();
-        
+
         DigestInputStream digestStream = null;
-        
+
         setupDigest:
-        if (options != null && options.hasOption( XmlOptions.LOAD_MESSAGE_DIGEST ))
-        {
+        if (options != null && options.isLoadMessageDigest()) {
             MessageDigest sha;
-            
-            try
-            {
+
+            try {
                 sha = MessageDigest.getInstance("SHA");
-            }
-            catch (NoSuchAlgorithmException e)
-            {
+            } catch (NoSuchAlgorithmException e) {
                 break setupDigest;
             }
 
-            digestStream = new DigestInputStream( jiois, sha );
+            digestStream = new DigestInputStream(jiois, sha);
             jiois = digestStream;
         }
 
-        if (hook != null)
-            return hook.parse( this, jiois, type, options );
+        if (hook != null) {
+            return hook.parse(this, jiois, type, options);
+        }
 
-        XmlObject result = Locale.parseToXmlObject( this, jiois, type, options );
+        XmlObject result = Locale.parseToXmlObject(this, jiois, type, options);
 
-        if (digestStream != null)
-            result.documentProperties().setMessageDigest( digestStream.getMessageDigest().digest() );
+        if (digestStream != null) {
+            result.documentProperties().setMessageDigest(digestStream.getMessageDigest().digest());
+        }
 
         return result;
     }
 
-    public XmlObject parse ( Reader jior, SchemaType type, XmlOptions options ) throws XmlException, IOException
-    {
+    public XmlObject parse(Reader jior, SchemaType type, XmlOptions options) throws XmlException, IOException {
         XmlFactoryHook hook = XmlFactoryHook.ThreadContext.getHook();
-        
-        if (hook != null)
-            return hook.parse( this, jior, type, options );
 
-        return Locale.parseToXmlObject( this, jior, type, options );
+        if (hook != null) {
+            return hook.parse(this, jior, type, options);
+        }
+
+        return Locale.parseToXmlObject(this, jior, type, options);
     }
 
-    public XmlObject parse ( Node node, SchemaType type, XmlOptions options ) throws XmlException
-    {
+    public XmlObject parse(Node node, SchemaType type, XmlOptions options) throws XmlException {
         XmlFactoryHook hook = XmlFactoryHook.ThreadContext.getHook();
-        
-        if (hook != null)
-            return hook.parse( this, node, type, options );
 
-        return Locale.parseToXmlObject( this, node, type, options );
+        if (hook != null) {
+            return hook.parse(this, node, type, options);
+        }
+
+        return Locale.parseToXmlObject(this, node, type, options);
     }
 
-    public XmlSaxHandler newXmlSaxHandler ( SchemaType type, XmlOptions options )
-    {
+    public XmlSaxHandler newXmlSaxHandler(SchemaType type, XmlOptions options) {
         XmlFactoryHook hook = XmlFactoryHook.ThreadContext.getHook();
-        
-        if (hook != null)
-            return hook.newXmlSaxHandler( this, type, options );
 
-        return Locale.newSaxHandler( this, type, options );
+        if (hook != null) {
+            return hook.newXmlSaxHandler(this, type, options);
+        }
+
+        return Locale.newSaxHandler(this, type, options);
     }
 
-    public DOMImplementation newDomImplementation ( XmlOptions options )
-    {
-        return Locale.newDomImplementation( this, options );
+    public DOMImplementation newDomImplementation(XmlOptions options) {
+        return Locale.newDomImplementation(this, options);
     }
 
     /**
      * @deprecated XMLInputStream was deprecated by XMLStreamReader from STaX - jsr173 API.
      */
-    public XMLInputStream newValidatingXMLInputStream ( XMLInputStream xis, SchemaType type, XmlOptions options ) throws XmlException, XMLStreamException
-    {
-        return new ValidatingXMLInputStream( xis, this, type, options );
+    public XMLInputStream newValidatingXMLInputStream(XMLInputStream xis, SchemaType type, XmlOptions options) throws XmlException, XMLStreamException {
+        return new ValidatingXMLInputStream(xis, this, type, options);
     }
 
     //
     //
     //
 
-    public String compilePath ( String pathExpr )
-    {
-        return compilePath( pathExpr, null );
+    public String compilePath(String pathExpr) {
+        return compilePath(pathExpr, null);
     }
 
-    public String compilePath ( String pathExpr, XmlOptions options )
-    {
-        return doCompilePath( pathExpr, options );
+    public String compilePath(String pathExpr, XmlOptions options) {
+        return doCompilePath(pathExpr, options);
     }
 
-    public String compileQuery ( String queryExpr )
-    {
-        return compileQuery( queryExpr, null );
+    public String compileQuery(String queryExpr) {
+        return compileQuery(queryExpr, null);
     }
 
-    public String compileQuery ( String queryExpr, XmlOptions options )
-    {
-        return doCompileQuery( queryExpr, options );
+    public String compileQuery(String queryExpr, XmlOptions options) {
+        return doCompileQuery(queryExpr, options);
     }
 
     /**
      * Utility function to load a type from a signature.
-     *
+     * <p>
      * A signature is the string you get from type.toString().
      */
-    public SchemaType typeForSignature(String signature)
-    {
+    public SchemaType typeForSignature(String signature) {
         int end = signature.indexOf('@');
         String uri;
 
-        if (end < 0)
-        {
+        if (end < 0) {
             uri = "";
             end = signature.length();
-        }
-        else
-        {
+        } else {
             uri = signature.substring(end + 1);
         }
 
-        List parts = new ArrayList();
+        List<String> parts = new ArrayList<>();
 
-        for (int index = 0; index < end; )
-        {
+        for (int index = 0; index < end; ) {
             int nextc = signature.indexOf(':', index);
             int nextd = signature.indexOf('|', index);
-            int next = (nextc < 0 ? nextd : nextd < 0 ? nextc : nextc < nextd ? nextc : nextd);
-            if (next < 0 || next > end)
+            int next = (nextc < 0 ? nextd : nextd < 0 ? nextc : Math.min(nextc, nextd));
+            if (next < 0 || next > end) {
                 next = end;
+            }
             String part = signature.substring(index, next);
             parts.add(part);
             index = next + 1;
@@ -453,149 +376,143 @@
 
         SchemaType curType = null;
 
-        outer: for (int i = parts.size() - 1; i >= 0; i -= 1)
-        {
-            String part = (String)parts.get(i);
-            if (part.length() < 1)
+        for (int i = parts.size() - 1; i >= 0; i -= 1) {
+            String part = parts.get(i);
+            if (part.length() < 1) {
                 throw new IllegalArgumentException();
+            }
             int offset = (part.length() >= 2 && part.charAt(1) == '=') ? 2 : 1;
-            cases: switch (part.charAt(0))
-            {
+            cases:
+            switch (part.charAt(0)) {
                 case 'T':
-                    if (curType != null)
+                    if (curType != null) {
                         throw new IllegalArgumentException();
+                    }
                     curType = findType(QNameHelper.forLNS(part.substring(offset), uri));
-                    if (curType == null)
+                    if (curType == null) {
                         return null;
+                    }
                     break;
 
                 case 'D':
-                    if (curType != null)
+                    if (curType != null) {
                         throw new IllegalArgumentException();
+                    }
                     curType = findDocumentType(QNameHelper.forLNS(part.substring(offset), uri));
-                    if (curType == null)
+                    if (curType == null) {
                         return null;
+                    }
                     break;
 
                 case 'C': // deprecated
                 case 'R': // current
-                    if (curType != null)
+                    if (curType != null) {
                         throw new IllegalArgumentException();
+                    }
                     curType = findAttributeType(QNameHelper.forLNS(part.substring(offset), uri));
-                    if (curType == null)
+                    if (curType == null) {
                         return null;
+                    }
                     break;
 
                 case 'E':
                 case 'U': // distinguish qualified/unqualified TBD
-                    if (curType != null)
-                    {
-                        if (curType.getContentType() < SchemaType.ELEMENT_CONTENT)
+                    if (curType != null) {
+                        if (curType.getContentType() < SchemaType.ELEMENT_CONTENT) {
                             return null;
+                        }
                         SchemaType[] subTypes = curType.getAnonymousTypes();
                         String localName = part.substring(offset);
-                        for (int j = 0; j < subTypes.length; j++)
-                        {
-                            SchemaField field = subTypes[j].getContainerField();
-                            if (field != null && !field.isAttribute() && field.getName().getLocalPart().equals(localName))
-                            {
-                                curType = subTypes[j];
+                        for (SchemaType subType : subTypes) {
+                            SchemaField field = subType.getContainerField();
+                            if (field != null && !field.isAttribute() && field.getName().getLocalPart().equals(localName)) {
+                                curType = subType;
                                 break cases;
                             }
                         }
                         return null;
-                    }
-                    else
-                    {
+                    } else {
                         SchemaGlobalElement elt = findElement(QNameHelper.forLNS(part.substring(offset), uri));
-                        if (elt == null)
+                        if (elt == null) {
                             return null;
+                        }
                         curType = elt.getType();
                     }
                     break;
 
                 case 'A':
                 case 'Q': // distinguish qualified/unqualified TBD
-                    if (curType != null)
-                    {
-                        if (curType.isSimpleType())
+                    if (curType != null) {
+                        if (curType.isSimpleType()) {
                             return null;
+                        }
                         SchemaType[] subTypes = curType.getAnonymousTypes();
                         String localName = part.substring(offset);
-                        for (int j = 0; j < subTypes.length; j++)
-                        {
-                            SchemaField field = subTypes[j].getContainerField();
-                            if (field != null && field.isAttribute() && field.getName().getLocalPart().equals(localName))
-                            {
-                                curType = subTypes[j];
+                        for (SchemaType subType : subTypes) {
+                            SchemaField field = subType.getContainerField();
+                            if (field != null && field.isAttribute() && field.getName().getLocalPart().equals(localName)) {
+                                curType = subType;
                                 break cases;
                             }
                         }
                         return null;
-                    }
-                    else
-                    {
+                    } else {
                         SchemaGlobalAttribute attr = findAttribute(QNameHelper.forLNS(part.substring(offset), uri));
-                        if (attr == null)
+                        if (attr == null) {
                             return null;
+                        }
                         curType = attr.getType();
                     }
                     break;
 
                 case 'B':
-                    if (curType == null)
-                    {
+                    if (curType == null) {
                         throw new IllegalArgumentException();
-                    }
-                    else
-                    {
-                        if (curType.getSimpleVariety() != SchemaType.ATOMIC)
+                    } else {
+                        if (curType.getSimpleVariety() != SchemaType.ATOMIC) {
                             return null;
+                        }
                         SchemaType[] subTypes = curType.getAnonymousTypes();
-                        if (subTypes.length != 1)
+                        if (subTypes.length != 1) {
                             return null;
+                        }
                         curType = subTypes[0];
                     }
                     break;
 
                 case 'I':
-                    if (curType == null)
-                    {
+                    if (curType == null) {
                         throw new IllegalArgumentException();
-                    }
-                    else
-                    {
-                        if (curType.getSimpleVariety() != SchemaType.LIST)
+                    } else {
+                        if (curType.getSimpleVariety() != SchemaType.LIST) {
                             return null;
+                        }
                         SchemaType[] subTypes = curType.getAnonymousTypes();
-                        if (subTypes.length != 1)
+                        if (subTypes.length != 1) {
                             return null;
+                        }
                         curType = subTypes[0];
                     }
                     break;
 
                 case 'M':
-                    if (curType == null)
-                    {
+                    if (curType == null) {
                         throw new IllegalArgumentException();
-                    }
-                    else
-                    {
+                    } else {
                         int index;
-                        try
-                        {
+                        try {
                             index = Integer.parseInt(part.substring(offset));
-                        }
-                        catch (Exception e)
-                        {
+                        } catch (Exception e) {
                             throw new IllegalArgumentException();
                         }
 
-                        if (curType.getSimpleVariety() != SchemaType.UNION)
+                        if (curType.getSimpleVariety() != SchemaType.UNION) {
                             return null;
+                        }
                         SchemaType[] subTypes = curType.getAnonymousTypes();
-                        if (subTypes.length <= index)
+                        if (subTypes.length <= index) {
                             return null;
+                        }
                         curType = subTypes[index];
                     }
                     break;
diff --git a/src/main/java/org/apache/xmlbeans/impl/schema/SchemaTypeSystemCompiler.java b/src/main/java/org/apache/xmlbeans/impl/schema/SchemaTypeSystemCompiler.java
index eaaca47..a6673cd 100644
--- a/src/main/java/org/apache/xmlbeans/impl/schema/SchemaTypeSystemCompiler.java
+++ b/src/main/java/org/apache/xmlbeans/impl/schema/SchemaTypeSystemCompiler.java
@@ -34,10 +34,10 @@
         private BindingConfig config;
         private SchemaTypeLoader linkTo;
         private XmlOptions options;
-        private Collection errorListener;
+        private Collection<XmlError> errorListener;
         private boolean javaize;
         private URI baseURI;
-        private Map sourcesToCopyMap;
+        private Map<String, String> sourcesToCopyMap;
         private File schemasDir;
 
         public SchemaTypeSystem getExistingTypeSystem() {
@@ -88,11 +88,11 @@
             this.options = options;
         }
 
-        public Collection getErrorListener() {
+        public Collection<XmlError> getErrorListener() {
             return errorListener;
         }
 
-        public void setErrorListener(Collection errorListener) {
+        public void setErrorListener(Collection<XmlError> errorListener) {
             this.errorListener = errorListener;
         }
 
@@ -112,11 +112,11 @@
             this.baseURI = baseURI;
         }
 
-        public Map getSourcesToCopyMap() {
+        public Map<String, String> getSourcesToCopyMap() {
             return sourcesToCopyMap;
         }
 
-        public void setSourcesToCopyMap(Map sourcesToCopyMap) {
+        public void setSourcesToCopyMap(Map<String, String> sourcesToCopyMap) {
             this.sourcesToCopyMap = sourcesToCopyMap;
         }
 
@@ -152,12 +152,12 @@
                                                XmlObject[] input, BindingConfig config, SchemaTypeLoader linkTo, Filer filer, XmlOptions options)
         throws XmlException {
         options = XmlOptions.maskNull(options);
-        ArrayList schemas = new ArrayList();
+        ArrayList<Schema> schemas = new ArrayList<>();
 
         if (input != null) {
             for (int i = 0; i < input.length; i++) {
                 if (input[i] instanceof Schema) {
-                    schemas.add(input[i]);
+                    schemas.add((Schema) input[i]);
                 } else if (input[i] instanceof SchemaDocument && ((SchemaDocument) input[i]).getSchema() != null) {
                     schemas.add(((SchemaDocument) input[i]).getSchema());
                 } else {
@@ -166,12 +166,12 @@
             }
         }
 
-        Collection userErrors = (Collection) options.get(XmlOptions.ERROR_LISTENER);
+        Collection<XmlError> userErrors = options.getErrorListener();
         XmlErrorWatcher errorWatcher = new XmlErrorWatcher(userErrors);
 
         SchemaTypeSystemImpl stsi = compileImpl(existingSTS, name,
-            (Schema[]) schemas.toArray(new Schema[schemas.size()]),
-            config, linkTo, options, errorWatcher, filer != null, (URI) options.get(XmlOptions.BASE_URI),
+            schemas.toArray(new Schema[0]),
+            config, linkTo, options, errorWatcher, filer != null, options.getBaseURI(),
             null, null);
 
         // if there is an error and compile didn't recover (stsi==null), throw exception
@@ -193,8 +193,8 @@
     /* package */
     static SchemaTypeSystemImpl compileImpl(SchemaTypeSystem system, String name,
                                             Schema[] schemas, BindingConfig config, SchemaTypeLoader linkTo,
-                                            XmlOptions options, Collection outsideErrors, boolean javaize,
-                                            URI baseURI, Map sourcesToCopyMap, File schemasDir) {
+                                            XmlOptions options, Collection<XmlError> outsideErrors, boolean javaize,
+                                            URI baseURI, Map<String, String> sourcesToCopyMap, File schemasDir) {
         if (linkTo == null) {
             throw new IllegalArgumentException("Must supply linkTo");
         }
@@ -204,7 +204,7 @@
 
         // construct the state
         StscState state = StscState.start();
-        boolean validate = (options == null || !options.hasOption(XmlOptions.COMPILE_NO_VALIDATION));
+        boolean validate = (options == null || !options.isCompileNoValidation());
         try {
             state.setErrorListener(errorWatcher);
             state.setBindingConfig(config);
@@ -219,27 +219,27 @@
             linkTo = SchemaTypeLoaderImpl.build(new SchemaTypeLoader[]{BuiltinSchemaTypeSystem.get(), linkTo}, null, null);
             state.setImportingTypeLoader(linkTo);
 
-            List validSchemas = new ArrayList(schemas.length);
+            List<Schema> validSchemas = new ArrayList<>(schemas.length);
 
             // load all the xsd files into it
             if (validate) {
                 XmlOptions validateOptions = new XmlOptions().setErrorListener(errorWatcher);
-                if (options.hasOption(XmlOptions.VALIDATE_TREAT_LAX_AS_SKIP)) {
+                if (options != null && options.isValidateTreatLaxAsSkip()) {
                     validateOptions.setValidateTreatLaxAsSkip();
                 }
-                for (int i = 0; i < schemas.length; i++) {
-                    if (schemas[i].validate(validateOptions)) {
-                        validSchemas.add(schemas[i]);
+                for (Schema schema : schemas) {
+                    if (schema.validate(validateOptions)) {
+                        validSchemas.add(schema);
                     }
                 }
             } else {
                 validSchemas.addAll(Arrays.asList(schemas));
             }
 
-            Schema[] startWith = (Schema[]) validSchemas.toArray(new Schema[validSchemas.size()]);
+            Schema[] startWith = validSchemas.toArray(new Schema[0]);
 
             if (incremental) {
-                Set namespaces = new HashSet();
+                Set<String> namespaces = new HashSet<>();
                 startWith = getSchemasToRecompile((SchemaTypeSystemImpl) system, startWith, namespaces);
                 state.initFromTypeSystem((SchemaTypeSystemImpl) system, namespaces);
             } else {
@@ -262,7 +262,7 @@
             StscJavaizer.javaizeAllTypes(javaize);
 
             // construct the loader out of the state
-            state.get().sts().loadFromStscState(state);
+            StscState.get().sts().loadFromStscState(state);
 
             // fill in the source-copy map
             if (sourcesToCopyMap != null) {
@@ -273,7 +273,7 @@
                 // EXPERIMENTAL: recovery from compilation errors and partial type system
                 if (state.allowPartial() && state.getRecovered() == errorWatcher.size()) {
                     // if partial type system allowed and all errors were recovered
-                    state.get().sts().setIncomplete(true);
+                    StscState.get().sts().setIncomplete(true);
                 } else {
                     // if any non-recoverable errors, return null
                     return null;
@@ -284,7 +284,7 @@
                 ((SchemaTypeSystemImpl) system).setIncomplete(true);
             }
 
-            return state.get().sts();
+            return StscState.get().sts();
         } finally {
             StscState.end();
         }
@@ -297,29 +297,28 @@
      * and of the entity resolvers that have been set up
      */
     private static Schema[] getSchemasToRecompile(SchemaTypeSystemImpl system,
-                                                  Schema[] modified, Set namespaces) {
-        Set modifiedFiles = new HashSet();
-        Map haveFile = new HashMap();
-        List result = new ArrayList();
-        for (int i = 0; i < modified.length; i++) {
-            String fileURL = modified[i].documentProperties().getSourceName();
+                                                  Schema[] modified, Set<String> namespaces) {
+        Set<String> modifiedFiles = new HashSet<>();
+        Map<String, SchemaDocument.Schema> haveFile = new HashMap<>();
+        List<SchemaDocument.Schema> result = new ArrayList<>();
+        for (Schema schema : modified) {
+            String fileURL = schema.documentProperties().getSourceName();
             if (fileURL == null) {
                 throw new IllegalArgumentException("One of the Schema files passed in" +
                                                    " doesn't have the source set, which prevents it to be incrementally" +
                                                    " compiled");
             }
             modifiedFiles.add(fileURL);
-            haveFile.put(fileURL, modified[i]);
-            result.add(modified[i]);
+            haveFile.put(fileURL, schema);
+            result.add(schema);
         }
         SchemaDependencies dep = system.getDependencies();
-        List nss = dep.getNamespacesTouched(modifiedFiles);
+        List<String> nss = dep.getNamespacesTouched(modifiedFiles);
         namespaces.addAll(dep.computeTransitiveClosure(nss));
-        List needRecompilation = dep.getFilesTouched(namespaces);
+        List<String> needRecompilation = dep.getFilesTouched(namespaces);
         StscState.get().setDependencies(new SchemaDependencies(dep, namespaces));
-        for (int i = 0; i < needRecompilation.size(); i++) {
-            String url = (String) needRecompilation.get(i);
-            Schema have = (Schema) haveFile.get(url);
+        for (String url : needRecompilation) {
+            Schema have = haveFile.get(url);
             if (have == null) {
                 // We have to load the file from the entity resolver
                 try {
@@ -337,17 +336,14 @@
                     result.add(sDoc.getSchema());
                 } catch (java.net.MalformedURLException mfe) {
                     StscState.get().error(XmlErrorCodes.EXCEPTION_LOADING_URL, new Object[]{"MalformedURLException", url, mfe.getMessage()}, null);
-                    continue;
-                } catch (java.io.IOException ioe) {
+                } catch (IOException ioe) {
                     StscState.get().error(XmlErrorCodes.EXCEPTION_LOADING_URL, new Object[]{"IOException", url, ioe.getMessage()}, null);
-                    continue;
                 } catch (XmlException xmle) {
                     StscState.get().error(XmlErrorCodes.EXCEPTION_LOADING_URL, new Object[]{"XmlException", url, xmle.getMessage()}, null);
-                    continue;
                 }
             }
         }
-        return (Schema[]) result.toArray(new Schema[result.size()]);
+        return result.toArray(new Schema[0]);
     }
 
 
@@ -369,13 +365,12 @@
 
         boolean success = true;
 
-        List types = new ArrayList();
+        List<SchemaType> types = new ArrayList<>();
         types.addAll(Arrays.asList(system.globalTypes()));
         types.addAll(Arrays.asList(system.documentTypes()));
         types.addAll(Arrays.asList(system.attributeTypes()));
 
-        for (Iterator i = types.iterator(); i.hasNext(); ) {
-            SchemaType type = (SchemaType) i.next();
+        for (SchemaType type : types) {
             if (type.isBuiltinType()) {
                 continue;
             }
@@ -385,40 +380,22 @@
 
             String fjn = type.getFullJavaName();
 
-            Writer writer = null;
-
-            try {
+            try (Writer writer = filer.createSourceFile(fjn)) {
                 // Generate interface class
-                writer = filer.createSourceFile(fjn);
                 SchemaTypeCodePrinter.printType(writer, type, options);
             } catch (IOException e) {
                 System.err.println("IO Error " + e);
                 success = false;
-            } finally {
-                try {
-                    if (writer != null) {
-                        writer.close();
-                    }
-                } catch (IOException e) {
-                }
             }
 
-            try {
-                // Generate Implementation class
-                fjn = type.getFullJavaImplName();
-                writer = filer.createSourceFile(fjn);
+            fjn = type.getFullJavaImplName();
 
+            try (Writer writer = filer.createSourceFile(fjn)) {
+                // Generate Implementation class
                 SchemaTypeCodePrinter.printTypeImpl(writer, type, options);
             } catch (IOException e) {
                 System.err.println("IO Error " + e);
                 success = false;
-            } finally {
-                try {
-                    if (writer != null) {
-                        writer.close();
-                    }
-                } catch (IOException e) {
-                }
             }
         }
 
diff --git a/src/main/java/org/apache/xmlbeans/impl/schema/StscChecker.java b/src/main/java/org/apache/xmlbeans/impl/schema/StscChecker.java
index 375f37f..9f056a7 100644
--- a/src/main/java/org/apache/xmlbeans/impl/schema/StscChecker.java
+++ b/src/main/java/org/apache/xmlbeans/impl/schema/StscChecker.java
@@ -28,17 +28,17 @@
         // walk the tree of types
         StscState state = StscState.get();
 
-        List allSeenTypes = new ArrayList();
+        List<SchemaType> allSeenTypes = new ArrayList<>();
         allSeenTypes.addAll(Arrays.asList(state.documentTypes()));
         allSeenTypes.addAll(Arrays.asList(state.attributeTypes()));
         allSeenTypes.addAll(Arrays.asList(state.redefinedGlobalTypes()));
         allSeenTypes.addAll(Arrays.asList(state.globalTypes()));
 
         for (int i = 0; i < allSeenTypes.size(); i++) {
-            SchemaType gType = (SchemaType) allSeenTypes.get(i);
-            if (!state.noPvr() &&  // option to turn off particle restriction checking
-                !gType.isDocumentType()) // Don't check doc types for restriction.
-            {
+            SchemaType gType = allSeenTypes.get(i);
+            // option to turn off particle restriction checking
+            // Don't check doc types for restriction.
+            if (!state.noPvr() && !gType.isDocumentType()) {
                 checkRestriction((SchemaTypeImpl) gType);
             }
             checkFields((SchemaTypeImpl) gType);
@@ -64,32 +64,32 @@
         if (sAttrModel != null) {
             SchemaLocalAttribute[] sAttrs = sAttrModel.getAttributes();
             QName idAttr = null;
-            for (int i = 0; i < sAttrs.length; i++) {
-                XmlObject attrLocation = ((SchemaLocalAttributeImpl) sAttrs[i])._parseObject;
-                if (XmlID.type.isAssignableFrom(sAttrs[i].getType())) {
+            for (SchemaLocalAttribute sAttr : sAttrs) {
+                XmlObject attrLocation = ((SchemaLocalAttributeImpl) sAttr)._parseObject;
+                if (XmlID.type.isAssignableFrom(sAttr.getType())) {
                     if (idAttr == null) {
-                        idAttr = sAttrs[i].getName();
+                        idAttr = sAttr.getName();
                     } else {
                         StscState.get().error(XmlErrorCodes.ATTR_GROUP_PROPERTIES$TWO_IDS,
-                            new Object[]{QNameHelper.pretty(idAttr), sAttrs[i].getName()},
+                            new Object[]{QNameHelper.pretty(idAttr), sAttr.getName()},
                             attrLocation != null ? attrLocation : location);
                     }
-                    if (sAttrs[i].getDefaultText() != null) {
+                    if (sAttr.getDefaultText() != null) {
                         StscState.get().error(XmlErrorCodes.ATTR_PROPERTIES$ID_FIXED_OR_DEFAULT,
                             null, attrLocation != null ? attrLocation : location);
                     }
-                } else if (XmlNOTATION.type.isAssignableFrom(sAttrs[i].getType())) {
-                    if (sAttrs[i].getType().getBuiltinTypeCode() == SchemaType.BTC_NOTATION) {
+                } else if (XmlNOTATION.type.isAssignableFrom(sAttr.getType())) {
+                    if (sAttr.getType().getBuiltinTypeCode() == SchemaType.BTC_NOTATION) {
                         StscState.get().recover(XmlErrorCodes.ATTR_NOTATION_TYPE_FORBIDDEN,
-                            new Object[]{QNameHelper.pretty(sAttrs[i].getName())},
+                            new Object[]{QNameHelper.pretty(sAttr.getName())},
                             attrLocation != null ? attrLocation : location);
                     } else {
-                        if (sAttrs[i].getType().getSimpleVariety() == SchemaType.UNION) {
-                            SchemaType[] members = sAttrs[i].getType().getUnionConstituentTypes();
-                            for (int j = 0; j < members.length; j++) {
-                                if (members[j].getBuiltinTypeCode() == SchemaType.BTC_NOTATION) {
+                        if (sAttr.getType().getSimpleVariety() == SchemaType.UNION) {
+                            SchemaType[] members = sAttr.getType().getUnionConstituentTypes();
+                            for (SchemaType member : members) {
+                                if (member.getBuiltinTypeCode() == SchemaType.BTC_NOTATION) {
                                     StscState.get().recover(XmlErrorCodes.ATTR_NOTATION_TYPE_FORBIDDEN,
-                                        new Object[]{QNameHelper.pretty(sAttrs[i].getName())},
+                                        new Object[]{QNameHelper.pretty(sAttr.getName())},
                                         attrLocation != null ? attrLocation : location);
                                 }
                             }
@@ -97,7 +97,7 @@
                         // Check that the Schema in which this is present doesn't have a targetNS
                         boolean hasNS;
                         if (sType.isAttributeType()) {
-                            hasNS = sAttrs[i].getName().getNamespaceURI().length() > 0;
+                            hasNS = sAttr.getName().getNamespaceURI().length() > 0;
                         } else {
                             SchemaType t = sType;
                             while (t.getOuterType() != null) {
@@ -111,26 +111,26 @@
                         }
                         if (hasNS) {
                             StscState.get().warning(XmlErrorCodes.ATTR_COMPATIBILITY_TARGETNS,
-                                new Object[]{QNameHelper.pretty(sAttrs[i].getName())},
+                                new Object[]{QNameHelper.pretty(sAttr.getName())},
                                 attrLocation != null ? attrLocation : location);
                         }
                     }
                 } else {
-                    String valueConstraint = sAttrs[i].getDefaultText();
+                    String valueConstraint = sAttr.getDefaultText();
                     if (valueConstraint != null) {
                         try {
-                            XmlAnySimpleType val = sAttrs[i].getDefaultValue();
+                            XmlAnySimpleType val = sAttr.getDefaultValue();
                             if (!val.validate()) {
                                 throw new Exception();
                             }
 
-                            SchemaPropertyImpl sProp = (SchemaPropertyImpl) sType.getAttributeProperty(sAttrs[i].getName());
+                            SchemaPropertyImpl sProp = (SchemaPropertyImpl) sType.getAttributeProperty(sAttr.getName());
                             if (sProp != null && sProp.getDefaultText() != null) {
                                 sProp.setDefaultValue(new XmlValueRef(val));
                             }
                         } catch (Exception e) {
                             // move to 'fixed' or 'default' attribute on the attribute definition
-                            String constraintName = (sAttrs[i].isFixed() ? "fixed" : "default");
+                            String constraintName = (sAttr.isFixed() ? "fixed" : "default");
                             XmlObject constraintLocation = location;
                             if (attrLocation != null) {
                                 constraintLocation = attrLocation.selectAttribute("", constraintName);
@@ -140,10 +140,10 @@
                             }
 
                             StscState.get().error(XmlErrorCodes.ATTR_PROPERTIES$CONSTRAINT_VALID,
-                                new Object[]{QNameHelper.pretty(sAttrs[i].getName()),
+                                new Object[]{QNameHelper.pretty(sAttr.getName()),
                                     constraintName,
                                     valueConstraint,
-                                    QNameHelper.pretty(sAttrs[i].getType().getName())},
+                                    QNameHelper.pretty(sAttr.getType().getName())},
                                 constraintLocation);
                         }
                     }
@@ -172,8 +172,8 @@
             case SchemaParticle.CHOICE:
             case SchemaParticle.ALL:
                 SchemaParticle[] children = model.getParticleChildren();
-                for (int i = 0; i < children.length; i++) {
-                    checkElementDefaults(children[i], location, parentType);
+                for (SchemaParticle child : children) {
+                    checkElementDefaults(child, location, parentType);
                 }
                 break;
             case SchemaParticle.ELEMENT:
@@ -183,7 +183,7 @@
                         try {
                             XmlAnySimpleType val = model.getDefaultValue();
                             XmlOptions opt = new XmlOptions();
-                            opt.put(XmlOptions.VALIDATE_TEXT_ONLY);
+                            opt.setValidateTextOnly();
                             if (!val.validate(opt)) {
                                 throw new Exception();
                             }
@@ -259,8 +259,8 @@
                     } else {
                         if (model.getType().getSimpleVariety() == SchemaType.UNION) {
                             SchemaType[] members = model.getType().getUnionConstituentTypes();
-                            for (int i = 0; i < members.length; i++) {
-                                if (members[i].getBuiltinTypeCode() == SchemaType.BTC_NOTATION) {
+                            for (SchemaType member : members) {
+                                if (member.getBuiltinTypeCode() == SchemaType.BTC_NOTATION) {
                                     StscState.get().recover(XmlErrorCodes.ELEM_NOTATION_TYPE_FORBIDDEN,
                                         new Object[]{QNameHelper.pretty(model.getName())},
                                         ((SchemaLocalElementImpl) model)._parseObject == null ? location :
@@ -593,11 +593,9 @@
         //  for match
         SchemaParticle[] derivedParticleArray = derivedModel.getParticleChildren();
         SchemaParticle[] baseParticleArray = baseModel.getParticleChildren();
-        for (int i = 0; i < derivedParticleArray.length; i++) {
-            SchemaParticle derivedParticle = derivedParticleArray[i];
+        for (SchemaParticle derivedParticle : derivedParticleArray) {
             boolean foundMatch = false;
-            for (int j = 0; j < baseParticleArray.length; j++) {
-                SchemaParticle baseParticle = baseParticleArray[j];
+            for (SchemaParticle baseParticle : baseParticleArray) {
                 // recurse to check if there is a match
                 if (isParticleValidRestriction(baseParticle, derivedParticle, errors, context)) {
                     // if there is a match then no need to check base particles anymore
@@ -618,9 +616,8 @@
 
         // Sum step
         BigInteger derivedRangeMin = derivedModel.getMinOccurs().multiply(BigInteger.valueOf(derivedModel.getParticleChildren().length));
-        BigInteger derivedRangeMax = null;
-        BigInteger UNBOUNDED = null;
-        if (derivedModel.getMaxOccurs() == UNBOUNDED) {
+        BigInteger derivedRangeMax;
+        if (derivedModel.getMaxOccurs() == null) {
             derivedRangeMax = null;
         } else {
             derivedRangeMax = derivedModel.getMaxOccurs().multiply(BigInteger.valueOf(derivedModel.getParticleChildren().length));
@@ -639,10 +636,10 @@
             errors.add(XmlError.forObject(XmlErrorCodes.PARTICLE_DERIVATION_MAP_AND_SUM$SUM_MIN_OCCURS_GTE_MIN_OCCURS,
                 new Object[]{derivedRangeMin.toString(), baseModel.getMinOccurs().toString()},
                 context));
-        } else if (baseModel.getMaxOccurs() != UNBOUNDED && (derivedRangeMax == UNBOUNDED || derivedRangeMax.compareTo(baseModel.getMaxOccurs()) > 0)) {
+        } else if (baseModel.getMaxOccurs() != null && (derivedRangeMax == null || derivedRangeMax.compareTo(baseModel.getMaxOccurs()) > 0)) {
             mapAndSumValid = false;
             errors.add(XmlError.forObject(XmlErrorCodes.PARTICLE_DERIVATION_MAP_AND_SUM$SUM_MAX_OCCURS_LTE_MAX_OCCURS,
-                new Object[]{derivedRangeMax == UNBOUNDED ? "unbounded" : derivedRangeMax.toString(), baseModel.getMaxOccurs().toString()},
+                new Object[]{derivedRangeMax == null ? "unbounded" : derivedRangeMax.toString(), baseModel.getMaxOccurs().toString()},
                 context));
         }
 
@@ -706,7 +703,7 @@
         SchemaParticle[] derivedParticleArray = derivedModel.getParticleChildren();
         SchemaParticle[] baseParticleArray = baseModel.getParticleChildren();
         int i = 0, j = 0;
-        for (; i < derivedParticleArray.length && j < baseParticleArray.length; ) {
+        while (i < derivedParticleArray.length && j < baseParticleArray.length) {
             SchemaParticle derivedParticle = derivedParticleArray[i];
             SchemaParticle baseParticle = baseParticleArray[j];
             // try to match the two particles by recursing
@@ -764,21 +761,21 @@
 
         // read baseParticle array QNames into hashmap
         SchemaParticle[] baseParticles = baseModel.getParticleChildren();
-        HashMap baseParticleMap = new HashMap(10);
-        Object MAPPED = new Object();
+        HashMap<QName, Object> baseParticleMap = new HashMap<>(10);
+        final Object MAPPED = new Object();
         // Initialize the hashmap
-        for (int i = 0; i < baseParticles.length; i++) {
-            baseParticleMap.put(baseParticles[i].getName(), baseParticles[i]);
+        for (SchemaParticle particle : baseParticles) {
+            baseParticleMap.put(particle.getName(), particle);
         }
 
         // go thru the sequence (derived model's children) and check off from base particle map
         SchemaParticle[] derivedParticles = derivedModel.getParticleChildren();
-        for (int i = 0; i < derivedParticles.length; i++) {
-            Object baseParticle = baseParticleMap.get(derivedParticles[i].getName());
+        for (SchemaParticle derivedParticle : derivedParticles) {
+            Object baseParticle = baseParticleMap.get(derivedParticle.getName());
             if (baseParticle == null) {
                 recurseUnorderedValid = false;
                 errors.add(XmlError.forObject(XmlErrorCodes.PARTICLE_DERIVATION_RECURSE_UNORDERED$MAP,
-                    new Object[]{printParticle(derivedParticles[i])}, context));
+                    new Object[]{printParticle(derivedParticle)}, context));
                 break;
             } else {
                 // got a match
@@ -786,26 +783,26 @@
                     // whoa, this base particle has already been matched (see 2.1 above)
                     recurseUnorderedValid = false;
                     errors.add(XmlError.forObject(XmlErrorCodes.PARTICLE_DERIVATION_RECURSE_UNORDERED$MAP_UNIQUE,
-                        new Object[]{printParticle(derivedParticles[i])}, context));
+                        new Object[]{printParticle(derivedParticle)}, context));
                     break;
                 } else {
                     SchemaParticle matchedBaseParticle = (SchemaParticle) baseParticle;
-                    if (derivedParticles[i].getMaxOccurs() == null ||
-                        derivedParticles[i].getMaxOccurs().compareTo(BigInteger.ONE) > 0) {
+                    if (derivedParticle.getMaxOccurs() == null ||
+                        derivedParticle.getMaxOccurs().compareTo(BigInteger.ONE) > 0) {
                         // no derived particles can have a max occurs greater than 1
                         recurseUnorderedValid = false;
                         errors.add(XmlError.forObject(XmlErrorCodes.PARTICLE_DERIVATION_RECURSE_UNORDERED$MAP_MAX_OCCURS_1,
-                            new Object[]{printParticle(derivedParticles[i]), printMaxOccurs(derivedParticles[i].getMinOccurs())},
+                            new Object[]{printParticle(derivedParticle), printMaxOccurs(derivedParticle.getMinOccurs())},
                             context));
                         break;
                     }
-                    if (!isParticleValidRestriction(matchedBaseParticle, derivedParticles[i], errors, context)) {
+                    if (!isParticleValidRestriction(matchedBaseParticle, derivedParticle, errors, context)) {
                         // already have an error
                         recurseUnorderedValid = false;
                         break;
                     }
                     // everything is cool, got a match, update to MAPPED
-                    baseParticleMap.put(derivedParticles[i].getName(), MAPPED);
+                    baseParticleMap.put(derivedParticle.getName(), MAPPED);
                 }
             }
         }
@@ -813,9 +810,8 @@
         // if everything is cool so far then check to see if any base particles are not matched
         if (recurseUnorderedValid) {
             // get all the hashmap keys and loop thru looking for NOT_MAPPED
-            Set baseParticleCollection = baseParticleMap.keySet();
-            for (Iterator iterator = baseParticleCollection.iterator(); iterator.hasNext(); ) {
-                QName baseParticleQName = (QName) iterator.next();
+            Set<QName> baseParticleCollection = baseParticleMap.keySet();
+            for (QName baseParticleQName : baseParticleCollection) {
                 if (baseParticleMap.get(baseParticleQName) != MAPPED && !((SchemaParticle) baseParticleMap.get(baseParticleQName)).isSkippable()) {
                     // this base particle was not mapped and is not "particle emptiable" (skippable)
                     recurseUnorderedValid = false;
@@ -863,7 +859,7 @@
         SchemaParticle[] derivedParticleArray = derivedModel.getParticleChildren();
         SchemaParticle[] baseParticleArray = baseModel.getParticleChildren();
         int i = 0, j = 0;
-        for (; i < derivedParticleArray.length && j < baseParticleArray.length; ) {
+        while (i < derivedParticleArray.length && j < baseParticleArray.length) {
             SchemaParticle derivedParticle = derivedParticleArray[i];
             SchemaParticle baseParticle = baseParticleArray[j];
             // try to match the two particles by recursing
@@ -901,7 +897,7 @@
             // if at end of derived particle array and not at end of base particle array then chck remaining
             //  base particles to assure they are skippable
             if (j < baseParticleArray.length) {
-                ArrayList particles = new ArrayList(baseParticleArray.length);
+                ArrayList<SchemaParticle> particles = new ArrayList<>(baseParticleArray.length);
                 for (int k = j; k < baseParticleArray.length; k++) {
                     if (!baseParticleArray[k].isSkippable()) {
                         particles.add(baseParticleArray[k]);
@@ -948,8 +944,7 @@
         asIfPart.setTransitionNotes(baseModel.getWildcardSet(), true);
 
         SchemaParticle[] particleChildren = derivedModel.getParticleChildren();
-        for (int i = 0; i < particleChildren.length; i++) {
-            SchemaParticle particle = particleChildren[i];
+        for (SchemaParticle particle : particleChildren) {
             switch (particle.getParticleType()) {
                 case SchemaParticle.ELEMENT:
                     // Check for valid Wildcard/Element derivation
@@ -1011,9 +1006,8 @@
         // one of the following must be true:
         // The base model's {max occurs} is unbounded.
         // or both {max occurs} are numbers, and the particle's is less than or equal to the other's
-        BigInteger UNBOUNDED = null;
-        if (baseModel.getMaxOccurs() != UNBOUNDED) {
-            if (maxRange == UNBOUNDED) {
+        if (baseModel.getMaxOccurs() != null) {
+            if (maxRange == null) {
                 groupOccurrenceOK = false;
                 errors.add(XmlError.forObject(XmlErrorCodes.OCCURRENCE_RANGE$MAX_LTE_MAX,
                     new Object[]{printParticle(derivedModel), printParticle(baseModel)},
@@ -1032,7 +1026,6 @@
 
     private static BigInteger getEffectiveMaxRangeChoice(SchemaParticle derivedModel) {
         BigInteger maxRange = BigInteger.ZERO;
-        BigInteger UNBOUNDED = null;
         // Schema Component Constraint: Effective Total Range (choice)
         // The effective total range of a particle whose {term} is a group whose {compositor} is choice
         // is a pair of minimum and maximum, as follows:
@@ -1051,14 +1044,13 @@
         BigInteger maxOccursInWildCardOrElement = BigInteger.ZERO;
         BigInteger maxOccursInGroup = BigInteger.ZERO;
         SchemaParticle[] particleChildren = derivedModel.getParticleChildren();
-        for (int i = 0; i < particleChildren.length; i++) {
-            SchemaParticle particle = particleChildren[i];
+        for (SchemaParticle particle : particleChildren) {
             switch (particle.getParticleType()) {
                 case SchemaParticle.WILDCARD:
                 case SchemaParticle.ELEMENT:
                     // if unbounded then maxoccurs will be null
-                    if (particle.getMaxOccurs() == UNBOUNDED) {
-                        maxRange = UNBOUNDED;
+                    if (particle.getMaxOccurs() == null) {
+                        maxRange = null;
                     } else {
                         if (particle.getIntMaxOccurs() > 0) {
                             // show tht at least one non-zero particle is found for later test
@@ -1072,7 +1064,7 @@
                 case SchemaParticle.ALL:
                 case SchemaParticle.SEQUENCE:
                     maxRange = getEffectiveMaxRangeAllSeq(particle);
-                    if (maxRange != UNBOUNDED) {
+                    if (maxRange != null) {
                         // keep highest maxoccurs found
                         if (maxRange.compareTo(maxOccursInGroup) > 0) {
                             maxOccursInGroup = maxRange;
@@ -1081,7 +1073,7 @@
                     break;
                 case SchemaParticle.CHOICE:
                     maxRange = getEffectiveMaxRangeChoice(particle);
-                    if (maxRange != UNBOUNDED) {
+                    if (maxRange != null) {
                         // keep highest maxoccurs found
                         if (maxRange.compareTo(maxOccursInGroup) > 0) {
                             maxOccursInGroup = maxRange;
@@ -1090,7 +1082,7 @@
                     break;
             }
             // if an unbounded has been found then we are done
-            if (maxRange == UNBOUNDED) {
+            if (maxRange == null) {
                 break;
             }
         }
@@ -1098,10 +1090,10 @@
         // 1) unbounded if the {max occurs} of any wildcard or element declaration particle in the group's {particles} or
         // the maximum part of the effective total range of any of the group particles in the group's {particles} is
         // unbounded
-        if (maxRange != UNBOUNDED) {
+        if (maxRange != null) {
             // 2) if any of those is non-zero and the {max occurs} of the particle itself is unbounded
-            if (nonZeroParticleChildFound && derivedModel.getMaxOccurs() == UNBOUNDED) {
-                maxRange = UNBOUNDED;
+            if (nonZeroParticleChildFound && derivedModel.getMaxOccurs() == null) {
+                maxRange = null;
             } else {
                 // 3) the product of the particle's {max occurs} and the maximum of the {max occurs} of every
                 // wildcard or element declaration particle in the group's {particles} and the *maximum*
@@ -1115,7 +1107,6 @@
 
     private static BigInteger getEffectiveMaxRangeAllSeq(SchemaParticle derivedModel) {
         BigInteger maxRange = BigInteger.ZERO;
-        BigInteger UNBOUNDED = null;
         // Schema Component Constraint: Effective Total Range (all and sequence)
         // The effective total range of a particle whose {term} is a group whose {compositor} is all or sequence is a
         // pair of minimum and maximum, as follows:
@@ -1131,14 +1122,13 @@
         BigInteger maxOccursTotal = BigInteger.ZERO;
         BigInteger maxOccursInGroup = BigInteger.ZERO;
         SchemaParticle[] particleChildren = derivedModel.getParticleChildren();
-        for (int i = 0; i < particleChildren.length; i++) {
-            SchemaParticle particle = particleChildren[i];
+        for (SchemaParticle particle : particleChildren) {
             switch (particle.getParticleType()) {
                 case SchemaParticle.WILDCARD:
                 case SchemaParticle.ELEMENT:
                     // if unbounded then maxoccurs will be null
-                    if (particle.getMaxOccurs() == UNBOUNDED) {
-                        maxRange = UNBOUNDED;
+                    if (particle.getMaxOccurs() == null) {
+                        maxRange = null;
                     } else {
                         if (particle.getIntMaxOccurs() > 0) {
                             // show tht at least one non-zero particle is found for later test
@@ -1150,7 +1140,7 @@
                 case SchemaParticle.ALL:
                 case SchemaParticle.SEQUENCE:
                     maxRange = getEffectiveMaxRangeAllSeq(particle);
-                    if (maxRange != UNBOUNDED) {
+                    if (maxRange != null) {
                         // keep highest maxoccurs found
                         if (maxRange.compareTo(maxOccursInGroup) > 0) {
                             maxOccursInGroup = maxRange;
@@ -1159,7 +1149,7 @@
                     break;
                 case SchemaParticle.CHOICE:
                     maxRange = getEffectiveMaxRangeChoice(particle);
-                    if (maxRange != UNBOUNDED) {
+                    if (maxRange != null) {
                         // keep highest maxoccurs found
                         if (maxRange.compareTo(maxOccursInGroup) > 0) {
                             maxOccursInGroup = maxRange;
@@ -1168,7 +1158,7 @@
                     break;
             }
             // if an unbounded has been found then we are done
-            if (maxRange == UNBOUNDED) {
+            if (maxRange == null) {
                 break;
             }
         }
@@ -1176,10 +1166,10 @@
         // 1) unbounded if the {max occurs} of any wildcard or element declaration particle in the group's {particles} or
         // the maximum part of the effective total range of any of the group particles in the group's {particles} is
         // unbounded
-        if (maxRange != UNBOUNDED) {
+        if (maxRange != null) {
             // 2) if any of those is non-zero and the {max occurs} of the particle itself is unbounded
-            if (nonZeroParticleChildFound && derivedModel.getMaxOccurs() == UNBOUNDED) {
-                maxRange = UNBOUNDED;
+            if (nonZeroParticleChildFound && derivedModel.getMaxOccurs() == null) {
+                maxRange = null;
             } else {
                 // 3) the product of the particle's {max occurs} and the sum of the {max occurs} of every wildcard or element
                 // declaration particle in the group's {particles} and the maximum part of the effective total range of each of
@@ -1208,8 +1198,7 @@
         BigInteger minRange = null;
         // get the minimum of every wildcard or element
         // total up the effective total range for each group
-        for (int i = 0; i < particleChildren.length; i++) {
-            SchemaParticle particle = particleChildren[i];
+        for (SchemaParticle particle : particleChildren) {
             switch (particle.getParticleType()) {
                 case SchemaParticle.WILDCARD:
                 case SchemaParticle.ELEMENT:
@@ -1242,7 +1231,7 @@
     }
 
     private static BigInteger getEffectiveMinRangeAllSeq(SchemaParticle derivedModel) {
-        BigInteger minRange = BigInteger.ZERO;
+        BigInteger minRange;
         // Schema Component Constraint: Effective Total Range (all and sequence)
         // The effective total range of a particle whose {term} is a group whose {compositor} is all or sequence is a
         // pair of minimum and maximum, as follows:
@@ -1254,8 +1243,7 @@
         // of the group particles in the group's {particles} (or 0 if there are no {particles}).
         SchemaParticle[] particleChildren = derivedModel.getParticleChildren();
         BigInteger particleTotalMinOccurs = BigInteger.ZERO;
-        for (int i = 0; i < particleChildren.length; i++) {
-            SchemaParticle particle = particleChildren[i];
+        for (SchemaParticle particle : particleChildren) {
             switch (particle.getParticleType()) {
                 case SchemaParticle.WILDCARD:
                 case SchemaParticle.ELEMENT:
@@ -1280,7 +1268,7 @@
         // nsSubset is called when base: ANY, derived: ANY
         assert baseModel.getParticleType() == SchemaParticle.WILDCARD;
         assert derivedModel.getParticleType() == SchemaParticle.WILDCARD;
-        boolean nsSubset = false;
+        boolean nsSubset;
         // For a wildcard particle to be a �valid restriction� of another wildcard particle all of the following must be true:
         // 1 R's occurrence range must be a valid restriction of B's occurrence range as defined by Occurrence Range OK (�3.9.6).
         if (occurrenceRangeOK(baseModel, derivedModel, errors, context)) {
@@ -1306,7 +1294,7 @@
     private static boolean nsCompat(SchemaParticle baseModel, SchemaLocalElement derivedElement, Collection<XmlError> errors, XmlObject context) {
         // nsCompat is called when base: ANY, derived: ELEMENT
         assert baseModel.getParticleType() == SchemaParticle.WILDCARD;
-        boolean nsCompat = false;
+        boolean nsCompat;
         // For an element declaration particle to be a �valid restriction� of a wildcard particle all of the following must be true:
         // 1 The element declaration's {target namespace} is �valid� with respect to the wildcard's {namespace constraint}
         // as defined by Wildcard allows Namespace Name (�3.10.4).
@@ -1315,6 +1303,7 @@
             if (occurrenceRangeOK(baseModel, (SchemaParticle) derivedElement, errors, context)) {
                 nsCompat = true;
             } else {
+                nsCompat = false;
                 // error already produced by occurrenceRangeOK
                 //errors.add(XmlError.forObject(formatOccurenceRangeMinError(baseModel, (SchemaParticle) derivedElement), context));
             }
@@ -1374,12 +1363,7 @@
         }
 
         // 6 R's declaration's {disallowed substitutions} is a superset of B's declaration's {disallowed substitutions}.
-        if (!blockSetOK(baseElement, derivedElement, errors, context)) {
-            // error already produced
-            return false;
-        }
-
-        return true;
+        return blockSetOK(baseElement, derivedElement, errors, context);
     }
 
     private static boolean blockSetOK(SchemaLocalElement baseElement, SchemaLocalElement derivedElement, Collection<XmlError> errors, XmlObject context) {
@@ -1405,7 +1389,7 @@
     }
 
     private static boolean typeDerivationOK(SchemaType baseType, SchemaType derivedType, Collection<XmlError> errors, XmlObject context) {
-        boolean typeDerivationOK = false;
+        boolean typeDerivationOK;
         // 1 If B and D are not the same type definition, then the {derivation method} of D must not be in the subset.
         // 2 One of the following must be true:
         // 2.1 B and D must be the same type definition.
@@ -1435,9 +1419,9 @@
         SchemaType currentType = derivedType;
 
         // XMLBEANS-66: if baseType is a union, check restriction is of one of the constituant types
-        Set possibleTypes = null;
+        Set<SchemaType> possibleTypes = null;
         if (baseType.getSimpleVariety() == SchemaType.UNION) {
-            possibleTypes = new HashSet(Arrays.asList(baseType.getUnionConstituentTypes()));
+            possibleTypes = new HashSet<>(Arrays.asList(baseType.getUnionConstituentTypes()));
         }
 
         // run up the types hierarchy from derived Type to base Type and make sure that all are derived by
@@ -1463,8 +1447,7 @@
         SchemaIdentityConstraint[] baseConstraints = baseElement.getIdentityConstraints();
         SchemaIdentityConstraint[] derivedConstraints = derivedElement.getIdentityConstraints();
         // cycle thru derived's identity constraints and check each to assure they in the array of base constraints
-        for (int i = 0; i < derivedConstraints.length; i++) {
-            SchemaIdentityConstraint derivedConstraint = derivedConstraints[i];
+        for (SchemaIdentityConstraint derivedConstraint : derivedConstraints) {
             if (checkForIdentityConstraintExistence(baseConstraints, derivedConstraint)) {
                 identityConstraintsOK = false;
                 errors.add(XmlError.forObject(XmlErrorCodes.PARTICLE_RESTRICTION_NAME_AND_TYPE$IDENTITY_CONSTRAINTS,
@@ -1479,8 +1462,7 @@
     private static boolean checkForIdentityConstraintExistence(SchemaIdentityConstraint[] baseConstraints, SchemaIdentityConstraint derivedConstraint) {
         // spin thru the base identity constraints check to see if derived constraint exists
         boolean identityConstraintExists = false;
-        for (int i = 0; i < baseConstraints.length; i++) {
-            SchemaIdentityConstraint baseConstraint = baseConstraints[i];
+        for (SchemaIdentityConstraint baseConstraint : baseConstraints) {
             if (baseConstraint.getName().equals(derivedConstraint.getName())) {
                 identityConstraintExists = true;
                 break;
@@ -1493,7 +1475,7 @@
     private static boolean checkFixed(SchemaLocalElement baseModel, SchemaLocalElement derivedModel, Collection<XmlError> errors, XmlObject context) {
         // 4 either B's declaration's {value constraint} is absent, or is not fixed,
         // or R's declaration's {value constraint} is fixed with the same value.
-        boolean checkFixed = false;
+        boolean checkFixed;
         if (baseModel.isFixed()) {
             if (baseModel.getDefaultText().equals(derivedModel.getDefaultText())) {
                 //  R's declaration's {value constraint} is fixed with the same value.
@@ -1514,7 +1496,7 @@
     }
 
     private static boolean occurrenceRangeOK(SchemaParticle baseParticle, SchemaParticle derivedParticle, Collection<XmlError> errors, XmlObject context) {
-        boolean occurrenceRangeOK = false;
+        boolean occurrenceRangeOK;
         // Note: in the following comments (from the schema spec) other is the baseModel
         // 1 Its {min occurs} is greater than or equal to the other's {min occurs}.
         if (derivedParticle.getMinOccurs().compareTo(baseParticle.getMinOccurs()) >= 0) {
@@ -1545,8 +1527,8 @@
         return occurrenceRangeOK;
     }
 
-    private static String printParticles(List parts) {
-        return printParticles((SchemaParticle[]) parts.toArray(new SchemaParticle[parts.size()]));
+    private static String printParticles(List<SchemaParticle> parts) {
+        return printParticles(parts.toArray(new SchemaParticle[0]));
     }
 
     private static String printParticles(SchemaParticle[] parts) {
@@ -1602,8 +1584,7 @@
     private static void checkSubstitutionGroups(SchemaGlobalElement[] elts) {
         StscState state = StscState.get();
 
-        for (int i = 0; i < elts.length; i++) {
-            SchemaGlobalElement elt = elts[i];
+        for (SchemaGlobalElement elt : elts) {
             SchemaGlobalElement head = elt.substitutionGroup();
 
             if (head != null) {
diff --git a/src/main/java/org/apache/xmlbeans/impl/schema/StscImporter.java b/src/main/java/org/apache/xmlbeans/impl/schema/StscImporter.java
index c47ba67..84d1933 100644
--- a/src/main/java/org/apache/xmlbeans/impl/schema/StscImporter.java
+++ b/src/main/java/org/apache/xmlbeans/impl/schema/StscImporter.java
@@ -15,69 +15,46 @@
 
 package org.apache.xmlbeans.impl.schema;
 
-import org.apache.xmlbeans.impl.xb.xsdschema.RedefineDocument.Redefine;
-import org.apache.xmlbeans.impl.xb.xsdschema.SchemaDocument.Schema;
-import org.apache.xmlbeans.impl.xb.xsdschema.SchemaDocument;
-import org.apache.xmlbeans.impl.xb.xsdschema.ImportDocument.Import;
-import org.apache.xmlbeans.impl.xb.xsdschema.IncludeDocument.Include;
-
-import java.util.Map;
-import java.util.List;
-import java.util.LinkedList;
-import java.util.Set;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.ArrayList;
-import java.util.Iterator;
-import java.util.Arrays;
-import java.net.URI;
-import java.net.URISyntaxException;
-import java.net.URL;
-import java.net.MalformedURLException;
-import java.io.FileNotFoundException;
-import java.io.IOException;
-import java.io.Reader;
-import java.io.InputStream;
-import java.io.File;
-import java.io.FileOutputStream;
-import java.io.ByteArrayInputStream;
-import java.io.ByteArrayOutputStream;
-import java.io.CharArrayReader;
-import java.io.Writer;
-import java.io.CharArrayWriter;
-import java.io.OutputStreamWriter;
-
-import org.apache.xmlbeans.XmlObject;
-import org.apache.xmlbeans.XmlException;
-import org.apache.xmlbeans.XmlOptions;
-import org.apache.xmlbeans.SchemaTypeLoader;
-import org.apache.xmlbeans.XmlErrorCodes;
+import org.apache.xmlbeans.*;
 import org.apache.xmlbeans.impl.common.IOUtil;
 import org.apache.xmlbeans.impl.common.XmlEncodingSniffer;
+import org.apache.xmlbeans.impl.xb.xsdschema.ImportDocument.Import;
+import org.apache.xmlbeans.impl.xb.xsdschema.IncludeDocument.Include;
+import org.apache.xmlbeans.impl.xb.xsdschema.RedefineDocument.Redefine;
+import org.apache.xmlbeans.impl.xb.xsdschema.SchemaDocument;
+import org.apache.xmlbeans.impl.xb.xsdschema.SchemaDocument.Schema;
 import org.xml.sax.EntityResolver;
 import org.xml.sax.InputSource;
 import org.xml.sax.SAXException;
 
-public class StscImporter
-{
-    public static SchemaToProcess[] resolveImportsAndIncludes(Schema[] startWith, boolean forceSrcSave)
-    {
+import java.io.*;
+import java.net.MalformedURLException;
+import java.net.URI;
+import java.net.URISyntaxException;
+import java.net.URL;
+import java.util.*;
+
+public class StscImporter {
+    public static SchemaToProcess[] resolveImportsAndIncludes(Schema[] startWith, boolean forceSrcSave) {
         DownloadTable engine = new DownloadTable(startWith);
         return engine.resolveImportsAndIncludes(forceSrcSave);
     }
 
-    public static class SchemaToProcess
-    {
-        private Schema schema;
-        private String chameleonNamespace;
-        private List includes; // list of SchemaToProcess objects directly included by this
-        private List redefines; // list of SchemaToProcess objects directly redefined by this
-        private List redefineObjects; // list of Redefine objects associated to each redefinition
-        private Set indirectIncludes; // set of SchemaToProcess  objects directly/indirectly included by this
-        private Set indirectIncludedBy; // set of SchemaToProcess objects that include this directly/indirectly
+    public static class SchemaToProcess {
+        private final Schema schema;
+        private final String chameleonNamespace;
+        // list of SchemaToProcess objects directly included by this
+        private List<SchemaToProcess> includes;
+        // list of SchemaToProcess objects directly redefined by this
+        private List<SchemaToProcess> redefines;
+        // list of Redefine objects associated to each redefinition
+        private List<Redefine> redefineObjects;
+        // set of SchemaToProcess  objects directly/indirectly included by this
+        private Set<SchemaToProcess> indirectIncludes;
+        // set of SchemaToProcess objects that include this directly/indirectly
+        private Set<SchemaToProcess> indirectIncludedBy;
 
-        public SchemaToProcess(Schema schema, String chameleonNamespace)
-        {
+        public SchemaToProcess(Schema schema, String chameleonNamespace) {
             this.schema = schema;
             this.chameleonNamespace = chameleonNamespace;
         }
@@ -85,26 +62,23 @@
         /**
          * The schema to parse.
          */
-        public Schema getSchema()
-        {
+        public Schema getSchema() {
             return schema;
         }
 
         /**
          * The base URI for this stp
          */
-        public String getSourceName()
-        {
+        public String getSourceName() {
             return schema.documentProperties().getSourceName();
         }
-        
+
         /**
          * The chameleon namespace. Null if this schema is not being treated
          * as a chameleon. (The ordinary targetNamespace will just be extracted
          * from the syntax of the schema.)
          */
-        public String getChameleonNamespace()
-        {
+        public String getChameleonNamespace() {
             return chameleonNamespace;
         }
 
@@ -113,108 +87,99 @@
          * directed graph of includes/redefines. This is required in order
          * to establish identity component by component, as required in
          * xmlschema-1, chapter 4.2.2
-         * @return
          */
-        public List getRedefines()
-        {
+        public List<SchemaToProcess> getRedefines() {
             return redefines;
         }
 
-        public List getRedefineObjects()
-        {
+        public List<Redefine> getRedefineObjects() {
             return redefineObjects;
         }
 
-        private void addInclude(SchemaToProcess include)
-        {
-            if (includes == null)
-                includes = new ArrayList();
+        private void addInclude(SchemaToProcess include) {
+            if (includes == null) {
+                includes = new ArrayList<>();
+            }
             includes.add(include);
         }
 
-        private void addRedefine(SchemaToProcess redefine, Redefine object)
-        {
-            if (redefines == null || redefineObjects == null)
-            {
-                redefines = new ArrayList();
-                redefineObjects = new ArrayList();
+        private void addRedefine(SchemaToProcess redefine, Redefine object) {
+            if (redefines == null || redefineObjects == null) {
+                redefines = new ArrayList<>();
+                redefineObjects = new ArrayList<>();
             }
             redefines.add(redefine);
             redefineObjects.add(object);
         }
 
-        private void buildIndirectReferences()
-        {
-            if (includes != null)
-                for (int i = 0; i < includes.size(); i++)
-                {
-                    SchemaToProcess schemaToProcess = (SchemaToProcess) includes.get(i);
+        private void buildIndirectReferences() {
+            if (includes != null) {
+                for (SchemaToProcess schemaToProcess : includes) {
                     /* We have a this-schemaToProcess vertex
-                    * This means that all nodes accessible from schemaToProcess are
-                    * also accessible from this and all nodes that have access to
-                    * this also have access to schemaToProcess */
+                     * This means that all nodes accessible from schemaToProcess are
+                     * also accessible from this and all nodes that have access to
+                     * this also have access to schemaToProcess */
                     this.addIndirectIncludes(schemaToProcess);
                 }
+            }
             // Repeat the same algorithm for redefines, since redefines are also includes
-            if (redefines != null)
-                for (int i = 0; i < redefines.size(); i++)
-                {
-                    SchemaToProcess schemaToProcess = (SchemaToProcess) redefines.get(i);
+            if (redefines != null) {
+                for (SchemaToProcess schemaToProcess : redefines) {
                     this.addIndirectIncludes(schemaToProcess);
                 }
+            }
         }
 
-        private void addIndirectIncludes(SchemaToProcess schemaToProcess)
-        {
-            if (indirectIncludes == null)
-                indirectIncludes = new HashSet();
+        private void addIndirectIncludes(SchemaToProcess schemaToProcess) {
+            if (indirectIncludes == null) {
+                indirectIncludes = new HashSet<>();
+            }
             indirectIncludes.add(schemaToProcess);
-            if (schemaToProcess.indirectIncludedBy == null)
-                schemaToProcess.indirectIncludedBy = new HashSet();
+            if (schemaToProcess.indirectIncludedBy == null) {
+                schemaToProcess.indirectIncludedBy = new HashSet<>();
+            }
             schemaToProcess.indirectIncludedBy.add(this);
             addIndirectIncludesHelper(this, schemaToProcess);
-            if (indirectIncludedBy != null)
-                for (Iterator it = indirectIncludedBy.iterator(); it.hasNext();)
-                {
-                    SchemaToProcess stp = (SchemaToProcess) it.next();
+            if (indirectIncludedBy != null) {
+                for (SchemaToProcess stp : indirectIncludedBy) {
                     stp.indirectIncludes.add(schemaToProcess);
                     schemaToProcess.indirectIncludedBy.add(stp);
                     addIndirectIncludesHelper(stp, schemaToProcess);
                 }
+            }
         }
 
         private static void addIndirectIncludesHelper(SchemaToProcess including,
-            SchemaToProcess schemaToProcess)
-        {
-            if (schemaToProcess.indirectIncludes != null)
-                for (Iterator it = schemaToProcess.indirectIncludes.iterator(); it.hasNext();)
-                {
-                    SchemaToProcess stp = (SchemaToProcess) it.next();
+                                                      SchemaToProcess schemaToProcess) {
+            if (schemaToProcess.indirectIncludes != null) {
+                for (SchemaToProcess stp : schemaToProcess.indirectIncludes) {
                     including.indirectIncludes.add(stp);
                     stp.indirectIncludedBy.add(including);
                 }
+            }
         }
 
-        public boolean indirectIncludes(SchemaToProcess schemaToProcess)
-        {
+        public boolean indirectIncludes(SchemaToProcess schemaToProcess) {
             return indirectIncludes != null && indirectIncludes.contains(schemaToProcess);
         }
 
-        public boolean equals(Object o)
-        {
-            if (this == o) return true;
-            if (!(o instanceof SchemaToProcess)) return false;
+        public boolean equals(Object o) {
+            if (this == o) {
+                return true;
+            }
+            if (!(o instanceof SchemaToProcess)) {
+                return false;
+            }
 
             final SchemaToProcess schemaToProcess = (SchemaToProcess) o;
 
-            if (chameleonNamespace != null ? !chameleonNamespace.equals(schemaToProcess.chameleonNamespace) : schemaToProcess.chameleonNamespace != null) return false;
-            if (!(schema == schemaToProcess.schema)) return false;
-
-            return true;
+            if (!Objects.equals(chameleonNamespace, schemaToProcess.chameleonNamespace)) {
+                return false;
+            }
+            return schema == schemaToProcess.schema;
         }
 
-        public int hashCode()
-        {
+        public int hashCode() {
             int result;
             result = schema.hashCode();
             result = 29 * result + (chameleonNamespace != null ? chameleonNamespace.hashCode() : 0);
@@ -224,43 +189,41 @@
 
     private final static String PROJECT_URL_PREFIX = "project://local";
 
-    private static String baseURLForDoc(XmlObject obj)
-    {
+    private static String baseURLForDoc(XmlObject obj) {
         String path = obj.documentProperties().getSourceName();
 
-        if (path == null)
+        if (path == null) {
             return null;
+        }
 
-        if (path.startsWith("/"))
+        if (path.startsWith("/")) {
             return PROJECT_URL_PREFIX + path.replace('\\', '/');
+        }
 
         // looks like a URL?
         int colon = path.indexOf(':');
-        if (colon > 1 && path.substring(0, colon).matches("^\\w+$"))
+        if (colon > 1 && path.substring(0, colon).matches("^\\w+$")) {
             return path;
+        }
 
         return PROJECT_URL_PREFIX + "/" + path.replace('\\', '/');
     }
 
-    private static URI parseURI(String s)
-    {
-        if (s == null)
+    private static URI parseURI(String s) {
+        if (s == null) {
             return null;
-
-        try
-        {
-            return new URI(s);
         }
-        catch (URISyntaxException syntax)
-        {
-                return null;
+
+        try {
+            return new URI(s);
+        } catch (URISyntaxException syntax) {
+            return null;
         }
     }
 
     //workaround for Sun bug # 4723726
     public static URI resolve(URI base, String child)
-        throws URISyntaxException
-    {
+        throws URISyntaxException {
         URI childUri = new URI(child);
         URI ruri = base.resolve(childUri);
 
@@ -270,22 +233,19 @@
         // to this ourselves to make sure that the nested jar url gets
         // resolved correctly
         if (childUri.equals(ruri) && !childUri.isAbsolute() &&
-          (base.getScheme().equals("jar") || base.getScheme().equals("zip"))) {
+            (base.getScheme().equals("jar") || base.getScheme().equals("zip"))) {
             String r = base.toString();
             int lastslash = r.lastIndexOf('/');
-            r = r.substring(0,lastslash) + "/" + childUri;
+            r = r.substring(0, lastslash) + "/" + childUri;
             // Sun's implementation of URI doesn't support references to the
             // parent directory ("/..") in the part after "!/" so we have to
             // remove these ourselves
             int exclPointSlashIndex = r.lastIndexOf("!/");
-            if (exclPointSlashIndex > 0)
-            {
+            if (exclPointSlashIndex > 0) {
                 int slashDotDotIndex = r.indexOf("/..", exclPointSlashIndex);
-                while (slashDotDotIndex > 0)
-                {
+                while (slashDotDotIndex > 0) {
                     int prevSlashIndex = r.lastIndexOf("/", slashDotDotIndex - 1);
-                    if (prevSlashIndex >= exclPointSlashIndex)
-                    {
+                    if (prevSlashIndex >= exclPointSlashIndex) {
                         String temp = r.substring(slashDotDotIndex + 3);
                         r = r.substring(0, prevSlashIndex).concat(temp);
                     }
@@ -296,39 +256,32 @@
         }
 
         //fix up normalization bug
-        if ("file".equals(ruri.getScheme()) && ! child.equals(ruri))
-        {
-            if (base.getPath().startsWith("//") && !ruri.getPath().startsWith("//"))
-            {
+        if ("file".equals(ruri.getScheme()) && !child.equals(ruri.getPath())) {
+            if (base.getPath().startsWith("//") && !ruri.getPath().startsWith("//")) {
                 String path = "///".concat(ruri.getPath());
-                try
-                {
+                try {
                     ruri = new URI("file", null, path, ruri.getQuery(), ruri.getFragment());
+                } catch (URISyntaxException ignored) {
                 }
-                catch(URISyntaxException uris)
-                {}
             }
         }
         return ruri;
     }
 
-    public static class DownloadTable
-    {
+    public static class DownloadTable {
         /**
          * Namespace/schemaLocation pair.
-         *
+         * <p>
          * Downloaded schemas are indexed by namespace, schemaLocation, and both.
-         *
+         * <p>
          * A perfect match is preferred, but a match-by-namespace is accepted.
          * A match-by-schemaLocation is only accepted for includes (not imports).
          */
-        private static class NsLocPair
-        {
-            private String namespaceURI;
-            private String locationURL;
+        private static class NsLocPair {
+            private final String namespaceURI;
+            private final String locationURL;
 
-            public NsLocPair(String namespaceURI, String locationURL)
-            {
+            public NsLocPair(String namespaceURI, String locationURL) {
                 this.namespaceURI = namespaceURI;
                 this.locationURL = locationURL;
             }
@@ -336,31 +289,31 @@
             /**
              * Empty string for no-namespace, null for namespace-not-part-of-key
              */
-            public String getNamespaceURI()
-            {
+            public String getNamespaceURI() {
                 return namespaceURI;
             }
 
-            public String getLocationURL()
-            {
+            public String getLocationURL() {
                 return locationURL;
             }
 
-            public boolean equals(Object o)
-            {
-                if (this == o) return true;
-                if (!(o instanceof NsLocPair)) return false;
+            public boolean equals(Object o) {
+                if (this == o) {
+                    return true;
+                }
+                if (!(o instanceof NsLocPair)) {
+                    return false;
+                }
 
                 final NsLocPair nsLocPair = (NsLocPair) o;
 
-                if (locationURL != null ? !locationURL.equals(nsLocPair.locationURL) : nsLocPair.locationURL != null) return false;
-                if (namespaceURI != null ? !namespaceURI.equals(nsLocPair.namespaceURI) : nsLocPair.namespaceURI != null) return false;
-
-                return true;
+                if (!Objects.equals(locationURL, nsLocPair.locationURL)) {
+                    return false;
+                }
+                return Objects.equals(namespaceURI, nsLocPair.namespaceURI);
             }
 
-            public int hashCode()
-            {
+            public int hashCode() {
                 int result;
                 result = (namespaceURI != null ? namespaceURI.hashCode() : 0);
                 result = 29 * result + (locationURL != null ? locationURL.hashCode() : 0);
@@ -368,71 +321,69 @@
             }
         }
 
-        private static class DigestKey
-        {
+        private static class DigestKey {
             byte[] _digest;
             int _hashCode;
-            DigestKey(byte[] digest)
-            {
+
+            DigestKey(byte[] digest) {
                 _digest = digest;
-                for (int i = 0; i < 4 && i < digest.length; i++)
-                {
+                for (int i = 0; i < 4 && i < digest.length; i++) {
                     _hashCode = _hashCode << 8;
                     _hashCode = _hashCode + digest[i];
                 }
             }
 
-            public boolean equals(Object o)
-            {
-                if (this == o) return true;
-                if (!(o instanceof DigestKey)) return false;
-                return Arrays.equals(_digest, ((DigestKey)o)._digest);
+            public boolean equals(Object o) {
+                if (this == o) {
+                    return true;
+                }
+                if (!(o instanceof DigestKey)) {
+                    return false;
+                }
+                return Arrays.equals(_digest, ((DigestKey) o)._digest);
             }
 
-            public int hashCode()
-            {
+            public int hashCode() {
                 return _hashCode;
             }
         }
 
-        private Map schemaByNsLocPair = new HashMap();
-        private Map schemaByDigestKey = new HashMap();
-        private LinkedList scanNeeded = new LinkedList();
-        private Set emptyNamespaceSchemas = new HashSet();
-        private Map scannedAlready = new HashMap();
-        private Set failedDownloads = new HashSet();
+        private final Map<NsLocPair, Schema> schemaByNsLocPair = new HashMap<>();
+        private final Map<DigestKey, Schema> schemaByDigestKey = new HashMap<>();
+        private final LinkedList<SchemaToProcess> scanNeeded = new LinkedList<>();
+        private final Set<Schema> emptyNamespaceSchemas = new HashSet<>();
+        private final Map<SchemaToProcess, SchemaToProcess> scannedAlready = new HashMap<>();
+        private final Set<String> failedDownloads = new HashSet<>();
 
-        private Schema downloadSchema(XmlObject referencedBy, String targetNamespace, String locationURL)
-        {
+        private Schema downloadSchema(XmlObject referencedBy, String targetNamespace, String locationURL) {
             // no location URL provided?  Then nothing to do.
-            if (locationURL == null)
+            if (locationURL == null) {
                 return null;
-            
+            }
+
             StscState state = StscState.get();
-            
+
             // First resolve relative URLs with respect to base URL for doc
             URI baseURI = parseURI(baseURLForDoc(referencedBy));
-            String absoluteURL = null;
-            try
-            {
+            String absoluteURL;
+            try {
                 absoluteURL = baseURI == null ? locationURL : resolve(baseURI, locationURL).toString();
-            }
-            catch (URISyntaxException e)
-            {
+            } catch (URISyntaxException e) {
                 state.error("Could not find resource - invalid location URL: " + e.getMessage(), XmlErrorCodes.CANNOT_FIND_RESOURCE, referencedBy);
                 return null;
             }
 
             // probe 0: this url is already processed, from a previous compile
-            if (state.isFileProcessed(absoluteURL))
+            if (state.isFileProcessed(absoluteURL)) {
                 return null;
+            }
 
             // probe 1: ns+url - perfect match
-            if (absoluteURL != null && targetNamespace != null)
-            {
-                Schema result = (Schema)schemaByNsLocPair.get(new NsLocPair(targetNamespace, absoluteURL));
-                if (result != null)
+            if (absoluteURL != null && targetNamespace != null) {
+                Schema result = schemaByNsLocPair.get(new NsLocPair(targetNamespace, absoluteURL));
+                if (result != null) {
                     return result;
+                }
             }
 
             // probe 2: we have preexisting knowledge of this namespace,
@@ -444,80 +395,74 @@
             // (We never assume preexisting knowledge of the no-namespace,
             // even if we have some definitions, since it's likely that
             // more than one person is playing in the no-namespace at once.)
-            if (targetNamespace != null && !targetNamespace.equals(""))
-            {
+            if (targetNamespace != null && !targetNamespace.equals("")) {
                 // the URL is not one to download; should we assume we know about the namespace?
-                if (!state.shouldDownloadURI(absoluteURL))
-                {
+                if (!state.shouldDownloadURI(absoluteURL)) {
                     // If we already have a schema representing this namespace,
                     // then skip this URL silently without producing an error.
-                    Schema result = (Schema)schemaByNsLocPair.get(new NsLocPair(targetNamespace, null));
-                    if (result != null)
+                    Schema result = schemaByNsLocPair.get(new NsLocPair(targetNamespace, null));
+                    if (result != null) {
                         return result;
+                    }
                 }
 
                 // If the linker already knows about this namespace, skip
                 // this URL.
-                if (state.linkerDefinesNamespace(targetNamespace))
+                if (state.linkerDefinesNamespace(targetNamespace)) {
                     return null;
+                }
             }
 
             // probe 3: url only
-            if (absoluteURL != null)
-            {
-                Schema result = (Schema)schemaByNsLocPair.get(new NsLocPair(null, absoluteURL));
-                if (result != null)
+            if (absoluteURL != null) {
+                Schema result = schemaByNsLocPair.get(new NsLocPair(null, absoluteURL));
+                if (result != null) {
                     return result;
+                }
             }
 
             // no match: error if we can't or won't download.
-            if (absoluteURL == null)
-            {
+            if (absoluteURL == null) {
                 state.error("Could not find resource - no valid location URL.", XmlErrorCodes.CANNOT_FIND_RESOURCE, referencedBy);
                 return null;
             }
 
-            if (previouslyFailedToDownload(absoluteURL))
-            {
+            if (previouslyFailedToDownload(absoluteURL)) {
                 // an error message has already been produced.
                 return null;
             }
 
-            if (!state.shouldDownloadURI(absoluteURL))
-            {
+            if (!state.shouldDownloadURI(absoluteURL)) {
                 state.error("Could not load resource \"" + absoluteURL + "\" (network downloads disabled).", XmlErrorCodes.CANNOT_FIND_RESOURCE, referencedBy);
                 addFailedDownload(absoluteURL);
                 return null;
             }
 
             // try to download
-            download: try
-            {
+            download:
+            try {
                 XmlObject xdoc = downloadDocument(state.getS4SLoader(), targetNamespace, absoluteURL);
 
                 Schema result = findMatchByDigest(xdoc);
                 String shortname = state.relativize(absoluteURL);
-                if (result != null)
-                {
+                if (result != null) {
                     // if an exactly-the-same document has already been loaded, use the original and spew
                     String dupname = state.relativize(result.documentProperties().getSourceName());
-                    if (dupname != null)
+                    if (dupname != null) {
                         state.info(shortname + " is the same as " + dupname + " (ignoring the duplicate file)");
-                    else
+                    } else {
                         state.info(shortname + " is the same as another schema");
-                }
-                else
-                {
+                    }
+                } else {
                     // otherwise, it's a new document: validate it and grab the contents
                     XmlOptions voptions = new XmlOptions();
                     voptions.setErrorListener(state.getErrorListener());
-                    if (!(xdoc instanceof SchemaDocument) || !xdoc.validate(voptions))
-                    {
+                    if (!(xdoc instanceof SchemaDocument) || !xdoc.validate(voptions)) {
                         state.error("Referenced document is not a valid schema", XmlErrorCodes.CANNOT_FIND_RESOURCE, referencedBy);
                         break download;
                     }
 
-                    SchemaDocument sDoc = (SchemaDocument)xdoc;
+                    SchemaDocument sDoc = (SchemaDocument) xdoc;
 
                     result = sDoc.getSchema();
                     state.info("Loading referenced file " + shortname);
@@ -525,17 +470,11 @@
                 NsLocPair key = new NsLocPair(emptyStringIfNull(result.getTargetNamespace()), absoluteURL);
                 addSuccessfulDownload(key, result);
                 return result;
-            }
-            catch (MalformedURLException malformed)
-            {
+            } catch (MalformedURLException malformed) {
                 state.error("URL \"" + absoluteURL + "\" is not well-formed", XmlErrorCodes.CANNOT_FIND_RESOURCE, referencedBy);
-            }
-            catch (IOException connectionProblem)
-            {
+            } catch (IOException connectionProblem) {
                 state.error(connectionProblem.toString(), XmlErrorCodes.CANNOT_FIND_RESOURCE, referencedBy);
-            }
-            catch (XmlException e)
-            {
+            } catch (XmlException e) {
                 state.error("Problem parsing referenced XML resource - " + e.getMessage(), XmlErrorCodes.CANNOT_FIND_RESOURCE, referencedBy);
             }
 
@@ -543,59 +482,53 @@
             addFailedDownload(absoluteURL);
             return null;
         }
-        
+
         static XmlObject downloadDocument(SchemaTypeLoader loader, String namespace, String absoluteURL)
-                throws MalformedURLException, IOException, XmlException
-        {
+            throws IOException, XmlException {
             StscState state = StscState.get();
-            
+
             EntityResolver resolver = state.getEntityResolver();
-            if (resolver != null)
-            {
-                InputSource source = null;
-                try
-                {
+            if (resolver != null) {
+                InputSource source;
+                try {
                     source = resolver.resolveEntity(namespace, absoluteURL);
-                }
-                catch (SAXException e)
-                {
+                } catch (SAXException e) {
                     throw new XmlException(e);
                 }
 
-                if (source != null)
-                {
+                if (source != null) {
                     state.addSourceUri(absoluteURL, null);
 
                     // first preference for InputSource contract: character stream
                     Reader reader = source.getCharacterStream();
-                    if (reader != null)
-                    {
+                    if (reader != null) {
                         reader = copySchemaSource(absoluteURL, reader, state);
                         XmlOptions options = new XmlOptions();
                         options.setLoadLineNumbers();
                         options.setDocumentSourceName(absoluteURL);
                         return loader.parse(reader, null, options);
                     }
-                
-                    // second preference for InputSource contract: 
+
+                    // second preference for InputSource contract:
                     InputStream bytes = source.getByteStream();
-                    if (bytes != null)
-                    {
+                    if (bytes != null) {
                         bytes = copySchemaSource(absoluteURL, bytes, state);
                         String encoding = source.getEncoding();
                         XmlOptions options = new XmlOptions();
                         options.setLoadLineNumbers();
                         options.setLoadMessageDigest();
                         options.setDocumentSourceName(absoluteURL);
-                        if (encoding != null)
+                        if (encoding != null) {
                             options.setCharacterEncoding(encoding);
+                        }
                         return loader.parse(bytes, null, options);
                     }
-                
+
                     // third preference: use the (possibly redirected) url
                     String urlToLoad = source.getSystemId();
-                    if (urlToLoad == null)
+                    if (urlToLoad == null) {
                         throw new IOException("EntityResolver unable to resolve " + absoluteURL + " (for namespace " + namespace + ")");
+                    }
 
                     copySchemaSource(absoluteURL, state, false);
                     XmlOptions options = new XmlOptions();
@@ -619,18 +552,13 @@
             return loader.parse(urlDownload, null, options);
         }
 
-        private void addSuccessfulDownload(NsLocPair key, Schema schema)
-        {
+        private void addSuccessfulDownload(NsLocPair key, Schema schema) {
             byte[] digest = schema.documentProperties().getMessageDigest();
-            if (digest == null)
-            {
+            if (digest == null) {
                 StscState.get().addSchemaDigest(null);
-            }
-            else
-            {
+            } else {
                 DigestKey dk = new DigestKey(digest);
-                if (!schemaByDigestKey.containsKey(dk))
-                {
+                if (!schemaByDigestKey.containsKey(dk)) {
                     schemaByDigestKey.put(new DigestKey(digest), schema);
                     StscState.get().addSchemaDigest(digest);
                 }
@@ -638,77 +566,72 @@
 
             schemaByNsLocPair.put(key, schema);
             NsLocPair key1 = new NsLocPair(key.getNamespaceURI(), null);
-            if (!schemaByNsLocPair.containsKey(key1))
+            if (!schemaByNsLocPair.containsKey(key1)) {
                 schemaByNsLocPair.put(key1, schema);
+            }
             NsLocPair key2 = new NsLocPair(null, key.getLocationURL());
-            if (!schemaByNsLocPair.containsKey(key2))
+            if (!schemaByNsLocPair.containsKey(key2)) {
                 schemaByNsLocPair.put(key2, schema);
+            }
         }
 
-        private Schema findMatchByDigest(XmlObject original)
-        {
+        private Schema findMatchByDigest(XmlObject original) {
             byte[] digest = original.documentProperties().getMessageDigest();
-            if (digest == null)
+            if (digest == null) {
                 return null;
-            return (Schema)schemaByDigestKey.get(new DigestKey(digest));
+            }
+            return schemaByDigestKey.get(new DigestKey(digest));
         }
 
-        private void addFailedDownload(String locationURL)
-        {
+        private void addFailedDownload(String locationURL) {
             failedDownloads.add(locationURL);
         }
 
-        private boolean previouslyFailedToDownload(String locationURL)
-        {
+        private boolean previouslyFailedToDownload(String locationURL) {
             return failedDownloads.contains(locationURL);
         }
 
-        private static boolean nullableStringsMatch(String s1, String s2)
-        {
-            if (s1 == null && s2 == null)
+        private static boolean nullableStringsMatch(String s1, String s2) {
+            if (s1 == null && s2 == null) {
                 return true;
-            if (s1 == null || s2 == null)
+            }
+            if (s1 == null || s2 == null) {
                 return false;
+            }
             return (s1.equals(s2));
         }
 
-        private static String emptyStringIfNull(String s)
-        {
-            if (s == null)
+        private static String emptyStringIfNull(String s) {
+            if (s == null) {
                 return "";
+            }
             return s;
         }
 
-        private SchemaToProcess addScanNeeded(SchemaToProcess stp)
-        {
-            if (!scannedAlready.containsKey(stp))
-            {
+        private SchemaToProcess addScanNeeded(SchemaToProcess stp) {
+            if (!scannedAlready.containsKey(stp)) {
                 scannedAlready.put(stp, stp);
                 scanNeeded.add(stp);
                 return stp;
+            } else {
+                return scannedAlready.get(stp);
             }
-            else
-                return (SchemaToProcess) scannedAlready.get(stp);
         }
 
-        private void addEmptyNamespaceSchema(Schema s)
-        {
+        private void addEmptyNamespaceSchema(Schema s) {
             emptyNamespaceSchemas.add(s);
         }
 
-        private void usedEmptyNamespaceSchema(Schema s)
-        {
+        private void usedEmptyNamespaceSchema(Schema s) {
             emptyNamespaceSchemas.remove(s);
         }
 
-        private boolean fetchRemainingEmptyNamespaceSchemas()
-        {
-            if (emptyNamespaceSchemas.isEmpty())
+        private boolean fetchRemainingEmptyNamespaceSchemas() {
+            if (emptyNamespaceSchemas.isEmpty()) {
                 return false;
+            }
 
-            for (Iterator i = emptyNamespaceSchemas.iterator(); i.hasNext();)
-            {
-                Schema schema = (Schema)i.next();
+            for (Schema schema : emptyNamespaceSchemas) {
                 addScanNeeded(new SchemaToProcess(schema, null));
             }
 
@@ -716,35 +639,30 @@
             return true;
         }
 
-        private boolean hasNextToScan()
-        {
+        private boolean hasNextToScan() {
             return !scanNeeded.isEmpty();
         }
 
-        private SchemaToProcess nextToScan()
-        {
-            SchemaToProcess next = (SchemaToProcess)scanNeeded.removeFirst();
-            return next;
+        private SchemaToProcess nextToScan() {
+            return scanNeeded.removeFirst();
         }
 
-        public DownloadTable(Schema[] startWith)
-        {
-            for (int i = 0; i < startWith.length; i++)
-            {
-                String targetNamespace = startWith[i].getTargetNamespace();
-                NsLocPair key = new NsLocPair(targetNamespace, baseURLForDoc(startWith[i]));
-                addSuccessfulDownload(key, startWith[i]);
-                if (targetNamespace != null)
-                    addScanNeeded(new SchemaToProcess(startWith[i], null));
-                else
-                    addEmptyNamespaceSchema(startWith[i]);
+        public DownloadTable(Schema[] startWith) {
+            for (Schema schema : startWith) {
+                String targetNamespace = schema.getTargetNamespace();
+                NsLocPair key = new NsLocPair(targetNamespace, baseURLForDoc(schema));
+                addSuccessfulDownload(key, schema);
+                if (targetNamespace != null) {
+                    addScanNeeded(new SchemaToProcess(schema, null));
+                } else {
+                    addEmptyNamespaceSchema(schema);
+                }
             }
         }
 
-        public SchemaToProcess[] resolveImportsAndIncludes(boolean forceSave)
-        {
+        public SchemaToProcess[] resolveImportsAndIncludes(boolean forceSave) {
             StscState state = StscState.get();
-            List result = new ArrayList();
+            List<SchemaToProcess> result = new ArrayList<>();
             boolean hasRedefinitions = false;
 
             // algorithm is to scan through each schema document and
@@ -756,10 +674,8 @@
             // empty empty-namespace schemas that have NOT been chameleon-
             // included by other schemas and process them.
 
-            for (;;)
-            {
-                while (hasNextToScan())
-                {
+            do {
+                while (hasNextToScan()) {
                     SchemaToProcess stp = nextToScan();
                     String uri = stp.getSourceName();
                     state.addSourceUri(uri, null);
@@ -769,52 +685,45 @@
                     {
                         // handle imports
                         Import[] imports = stp.getSchema().getImportArray();
-                        for (int i = 0; i < imports.length; i++)
-                        {
-                            Schema imported = downloadSchema(imports[i], emptyStringIfNull(imports[i].getNamespace()), imports[i].getSchemaLocation());
+                        for (Import anImport : imports) {
+                            Schema imported = downloadSchema(anImport, emptyStringIfNull(anImport.getNamespace()), anImport.getSchemaLocation());
 
                             // if download fails, an error has already been reported.
-                            if (imported == null)
+                            if (imported == null) {
                                 continue;
-    
-                            if (!nullableStringsMatch(imported.getTargetNamespace(), imports[i].getNamespace()))
-                            {
-                                StscState.get().error("Imported schema has a target namespace \"" + imported.getTargetNamespace() + "\" that does not match the specified \"" + imports[i].getNamespace() + "\"", XmlErrorCodes.MISMATCHED_TARGET_NAMESPACE, imports[i]);
                             }
-                            else
-                            {
+
+                            if (!nullableStringsMatch(imported.getTargetNamespace(), anImport.getNamespace())) {
+                                StscState.get().error("Imported schema has a target namespace \"" + imported.getTargetNamespace() + "\" that does not match the specified \"" + anImport.getNamespace() + "\"", XmlErrorCodes.MISMATCHED_TARGET_NAMESPACE, anImport);
+                            } else {
                                 addScanNeeded(new SchemaToProcess(imported, null));
                             }
                         }
                     }
-                    
+
                     {
                         // handle includes
                         Include[] includes = stp.getSchema().getIncludeArray();
                         String sourceNamespace = stp.getChameleonNamespace();
-                        if (sourceNamespace == null)
+                        if (sourceNamespace == null) {
                             sourceNamespace = emptyStringIfNull(stp.getSchema().getTargetNamespace());
-    
-                        for (int i = 0; i < includes.length; i++)
-                        {
-                            Schema included = downloadSchema(includes[i], null, includes[i].getSchemaLocation());
+                        }
+
+                        for (Include include : includes) {
+                            Schema included = downloadSchema(include, null, include.getSchemaLocation());
                             // if download fails, an error has already been reported.
-                            if (included == null)
+                            if (included == null) {
                                 continue;
-    
-                            if (emptyStringIfNull(included.getTargetNamespace()).equals(sourceNamespace))
-                            {
+                            }
+
+                            if (emptyStringIfNull(included.getTargetNamespace()).equals(sourceNamespace)) {
                                 // non-chameleon case - just like an import
                                 SchemaToProcess s = addScanNeeded(new SchemaToProcess(included, null));
                                 stp.addInclude(s);
-                            }
-                            else if (included.getTargetNamespace() != null)
-                            {
+                            } else if (included.getTargetNamespace() != null) {
                                 // illegal include: included schema in wrong namespace.
-                                StscState.get().error("Included schema has a target namespace \"" + included.getTargetNamespace() + "\" that does not match the source namespace \"" + sourceNamespace + "\"", XmlErrorCodes.MISMATCHED_TARGET_NAMESPACE, includes[i]);
-                            }
-                            else
-                            {
+                                StscState.get().error("Included schema has a target namespace \"" + included.getTargetNamespace() + "\" that does not match the source namespace \"" + sourceNamespace + "\"", XmlErrorCodes.MISMATCHED_TARGET_NAMESPACE, include);
+                            } else {
                                 // chameleon include
                                 SchemaToProcess s = addScanNeeded(new SchemaToProcess(included, sourceNamespace));
                                 stp.addInclude(s);
@@ -822,37 +731,33 @@
                             }
                         }
                     }
-                    
+
                     {
                         // handle redefines
                         Redefine[] redefines = stp.getSchema().getRedefineArray();
                         String sourceNamespace = stp.getChameleonNamespace();
-                        if (sourceNamespace == null)
+                        if (sourceNamespace == null) {
                             sourceNamespace = emptyStringIfNull(stp.getSchema().getTargetNamespace());
-                        for (int i = 0; i < redefines.length; i++)
-                        {
-                            Schema redefined = downloadSchema(redefines[i], null, redefines[i].getSchemaLocation());
+                        }
+                        for (Redefine redefine : redefines) {
+                            Schema redefined = downloadSchema(redefine, null, redefine.getSchemaLocation());
                             // if download fails, an error has already been reported.
-                            if (redefined == null)
+                            if (redefined == null) {
                                 continue;
-    
-                            if (emptyStringIfNull(redefined.getTargetNamespace()).equals(sourceNamespace))
-                            {
+                            }
+
+                            if (emptyStringIfNull(redefined.getTargetNamespace()).equals(sourceNamespace)) {
                                 // non-chameleon case
                                 SchemaToProcess s = addScanNeeded(new SchemaToProcess(redefined, null));
-                                stp.addRedefine(s, redefines[i]);
+                                stp.addRedefine(s, redefine);
                                 hasRedefinitions = true;
-                            }
-                            else if (redefined.getTargetNamespace() != null)
-                            {
+                            } else if (redefined.getTargetNamespace() != null) {
                                 // illegal include: included schema in wrong namespace.
-                                StscState.get().error("Redefined schema has a target namespace \"" + redefined.getTargetNamespace() + "\" that does not match the source namespace \"" + sourceNamespace + "\"", XmlErrorCodes.MISMATCHED_TARGET_NAMESPACE, redefines[i]);
-                            }
-                            else
-                            {
+                                StscState.get().error("Redefined schema has a target namespace \"" + redefined.getTargetNamespace() + "\" that does not match the source namespace \"" + sourceNamespace + "\"", XmlErrorCodes.MISMATCHED_TARGET_NAMESPACE, redefine);
+                            } else {
                                 // chameleon redefine
                                 SchemaToProcess s = addScanNeeded(new SchemaToProcess(redefined, sourceNamespace));
-                                stp.addRedefine(s, redefines[i]);
+                                stp.addRedefine(s, redefine);
                                 usedEmptyNamespaceSchema(redefined);
                                 hasRedefinitions = true;
                             }
@@ -860,34 +765,31 @@
                     }
                 }
 
-                if (!fetchRemainingEmptyNamespaceSchemas())
-                    break;
-            }
+            } while (fetchRemainingEmptyNamespaceSchemas());
 
             // Build the lists of indirect references
             // Make all the effort only if there are redefinitions
-            if (hasRedefinitions)
-                for (int i = 0; i < result.size(); i++)
-                {
-                    SchemaToProcess schemaToProcess = (SchemaToProcess) result.get(i);
+            if (hasRedefinitions) {
+                for (SchemaToProcess schemaToProcess : result) {
                     schemaToProcess.buildIndirectReferences();
                 }
-            return (SchemaToProcess[])result.toArray(new SchemaToProcess[result.size()]);
+            }
+            return result.toArray(new SchemaToProcess[0]);
         }
 
-        private static Reader copySchemaSource(String url, Reader reader, StscState state)
-        {
+        private static Reader copySchemaSource(String url, Reader reader, StscState state) {
             //Copy the schema file if it wasn't already copied
-            if (state.getSchemasDir() == null)
+            if (state.getSchemasDir() == null) {
                 return reader;
+            }
 
             String schemalocation = state.sourceNameForUri(url);
             File targetFile = new File(state.getSchemasDir(), schemalocation);
-            if (targetFile.exists())
+            if (targetFile.exists()) {
                 return reader;
+            }
 
-            try
-            {
+            try {
                 File parentDir = new File(targetFile.getParent());
                 IOUtil.createDir(parentDir, null);
 
@@ -898,27 +800,25 @@
 
                 car.reset();
                 return car;
-            }
-            catch (IOException e)
-            {
+            } catch (IOException e) {
                 System.err.println("IO Error " + e);
                 return reader;
             }
         }
 
-        private static InputStream copySchemaSource(String url, InputStream bytes, StscState state)
-        {
+        private static InputStream copySchemaSource(String url, InputStream bytes, StscState state) {
             //Copy the schema file if it wasn't already copied
-            if (state.getSchemasDir() == null)
+            if (state.getSchemasDir() == null) {
                 return bytes;
+            }
 
             String schemalocation = state.sourceNameForUri(url);
             File targetFile = new File(state.getSchemasDir(), schemalocation);
-            if (targetFile.exists())
+            if (targetFile.exists()) {
                 return bytes;
+            }
 
-            try
-            {
+            try {
                 File parentDir = new File(targetFile.getParent());
                 IOUtil.createDir(parentDir, null);
 
@@ -929,51 +829,40 @@
 
                 bais.reset();
                 return bais;
-            }
-            catch (IOException e)
-            {
+            } catch (IOException e) {
                 System.err.println("IO Error " + e);
                 return bytes;
             }
         }
 
-        private static void copySchemaSource(String urlLoc, StscState state, boolean forceCopy)
-        {
+        private static void copySchemaSource(String urlLoc, StscState state, boolean forceCopy) {
             //Copy the schema file if it wasn't already copied
-            if (state.getSchemasDir()!=null)
-            {
+            if (state.getSchemasDir() != null) {
                 String schemalocation = state.sourceNameForUri(urlLoc);
 
                 File targetFile = new File(state.getSchemasDir(), schemalocation);
-                if (forceCopy || !targetFile.exists())
-                {
-                    try
-                    {
+                if (forceCopy || !targetFile.exists()) {
+                    try {
                         File parentDir = new File(targetFile.getParent());
                         IOUtil.createDir(parentDir, null);
 
                         InputStream in = null;
                         URL url = new URL(urlLoc);
                         // Copy the file from filepath to schema[METADATA_PACKAGE_GEN]/src/<schemaFile>
-                        try
-                        {
+                        try {
                             in = url.openStream();
-                        }
-                        catch (FileNotFoundException fnfe)
-                        {
-                            if (forceCopy && targetFile.exists())
+                        } catch (FileNotFoundException fnfe) {
+                            if (forceCopy && targetFile.exists()) {
                                 targetFile.delete();
-                            else
+                            } else {
                                 throw fnfe;
+                            }
                         }
-                        if (in != null)
-                        {
+                        if (in != null) {
                             FileOutputStream out = new FileOutputStream(targetFile);
                             IOUtil.copyCompletely(in, out);
                         }
-                    }
-                    catch (IOException e)
-                    {
+                    } catch (IOException e) {
                         System.err.println("IO Error " + e);
                         // failure = true; - not cause for failure
                     }
@@ -981,26 +870,26 @@
             }
         }
 
-        private static ByteArrayInputStream copy(InputStream is) throws IOException
-        {
-            byte [] buf = new byte[1024];
+        private static ByteArrayInputStream copy(InputStream is) throws IOException {
+            byte[] buf = new byte[1024];
             ByteArrayOutputStream baos = new ByteArrayOutputStream();
 
             int bytesRead;
-            while(( bytesRead = is.read(buf, 0, 1024)) > 0)
+            while ((bytesRead = is.read(buf, 0, 1024)) > 0) {
                 baos.write(buf, 0, bytesRead);
+            }
 
             return new ByteArrayInputStream(baos.toByteArray());
         }
 
-        private static CharArrayReader copy(Reader is) throws IOException
-        {
+        private static CharArrayReader copy(Reader is) throws IOException {
             char[] buf = new char[1024];
             CharArrayWriter baos = new CharArrayWriter();
 
             int bytesRead;
-            while(( bytesRead = is.read(buf, 0, 1024)) > 0)
+            while ((bytesRead = is.read(buf, 0, 1024)) > 0) {
                 baos.write(buf, 0, bytesRead);
+            }
 
             return new CharArrayReader(baos.toCharArray());
         }
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 247e353..8f53c58 100644
--- a/src/main/java/org/apache/xmlbeans/impl/schema/StscState.java
+++ b/src/main/java/org/apache/xmlbeans/impl/schema/StscState.java
@@ -82,9 +82,9 @@
     private final Map<String, SchemaContainer> _containers = new LinkedHashMap<>();
     private SchemaDependencies _dependencies;
 
-    private final Map<SchemaTypeImpl,SchemaTypeImpl> _redefinedGlobalTypes = new LinkedHashMap<>();
-    private final Map<SchemaModelGroupImpl,SchemaModelGroupImpl>  _redefinedModelGroups = new LinkedHashMap<>();
-    private final Map<SchemaAttributeGroupImpl,SchemaAttributeGroupImpl>  _redefinedAttributeGroups = new LinkedHashMap<>();
+    private final Map<SchemaTypeImpl, SchemaTypeImpl> _redefinedGlobalTypes = new LinkedHashMap<>();
+    private final Map<SchemaModelGroupImpl, SchemaModelGroupImpl> _redefinedModelGroups = new LinkedHashMap<>();
+    private final Map<SchemaAttributeGroupImpl, SchemaAttributeGroupImpl> _redefinedAttributeGroups = new LinkedHashMap<>();
 
     private final Map<QName, SchemaType> _globalTypes = new LinkedHashMap<>();
     private final Map<QName, SchemaGlobalElement> _globalElements = new LinkedHashMap<>();
@@ -450,16 +450,16 @@
 
         _allowPartial = options.hasOption("COMPILE_PARTIAL_TYPESYSTEM");
 
-        _compatMap = (Map) options.get(XmlOptions.COMPILE_SUBSTITUTE_NAMES);
-        _noUpa = options.hasOption(XmlOptions.COMPILE_NO_UPA_RULE) ? true :
-            !"true".equals(SystemProperties.getProperty("xmlbean.uniqueparticleattribution", "true"));
-        _noPvr = options.hasOption(XmlOptions.COMPILE_NO_PVR_RULE) ? true :
-            !"true".equals(SystemProperties.getProperty("xmlbean.particlerestriction", "true"));
-        _noAnn = options.hasOption(XmlOptions.COMPILE_NO_ANNOTATIONS) ? true :
-            !"true".equals(SystemProperties.getProperty("xmlbean.schemaannotations", "true"));
-        _doingDownloads = options.hasOption(XmlOptions.COMPILE_DOWNLOAD_URLS) ? true :
-            "true".equals(SystemProperties.getProperty("xmlbean.downloadurls", "false"));
-        _entityResolver = (EntityResolver) options.get(XmlOptions.ENTITY_RESOLVER);
+        _compatMap = options.getCompileSubstituteNames();
+        _noUpa = options.isCompileNoUpaRule() ||
+                 !"true".equals(SystemProperties.getProperty("xmlbean.uniqueparticleattribution", "true"));
+        _noPvr = options.isCompileNoPvrRule() ||
+                 !"true".equals(SystemProperties.getProperty("xmlbean.particlerestriction", "true"));
+        _noAnn = options.isCompileNoAnnotations() ||
+                 !"true".equals(SystemProperties.getProperty("xmlbean.schemaannotations", "true"));
+        _doingDownloads = options.isCompileDownloadUrls() ||
+                          "true".equals(SystemProperties.getProperty("xmlbean.downloadurls", "false"));
+        _entityResolver = options.getEntityResolver();
 
         if (_entityResolver == null) {
             _entityResolver = ResolverUtil.getGlobalEntityResolver();
@@ -469,8 +469,9 @@
             _doingDownloads = true;
         }
 
-        if (options.hasOption(XmlOptions.COMPILE_MDEF_NAMESPACES)) {
-            _mdefNamespaces.addAll((Collection) options.get(XmlOptions.COMPILE_MDEF_NAMESPACES));
+        Set<String> mdef = options.getCompileMdefNamespaces();
+        if (mdef != null) {
+            _mdefNamespaces.addAll(mdef);
 
             String local = "##local";
             String any = "##any";
@@ -720,7 +721,7 @@
     }
 
     SchemaType[] redefinedGlobalTypes() {
-        return (SchemaType[]) _redefinedGlobalTypes.values().toArray(new SchemaType[0]);
+        return _redefinedGlobalTypes.values().toArray(new SchemaType[0]);
     }
 
     /* DOCUMENT TYPES =================================================*/
diff --git a/src/main/java/org/apache/xmlbeans/impl/schema/StscTranslator.java b/src/main/java/org/apache/xmlbeans/impl/schema/StscTranslator.java
index ae275d5..2909fd8 100644
--- a/src/main/java/org/apache/xmlbeans/impl/schema/StscTranslator.java
+++ b/src/main/java/org/apache/xmlbeans/impl/schema/StscTranslator.java
@@ -15,413 +15,320 @@
 
 package org.apache.xmlbeans.impl.schema;
 
-import org.apache.xmlbeans.QNameSet;
-import org.apache.xmlbeans.QNameSetBuilder;
-import org.apache.xmlbeans.SchemaAttributeModel;
-import org.apache.xmlbeans.SchemaBookmark;
-import org.apache.xmlbeans.SchemaGlobalAttribute;
-import org.apache.xmlbeans.SchemaGlobalElement;
-import org.apache.xmlbeans.SchemaIdentityConstraint;
-import org.apache.xmlbeans.SchemaLocalAttribute;
-import org.apache.xmlbeans.SchemaParticle;
-import org.apache.xmlbeans.SchemaType;
-import org.apache.xmlbeans.XmlAnySimpleType;
-import org.apache.xmlbeans.XmlCursor;
-import org.apache.xmlbeans.XmlErrorCodes;
-import org.apache.xmlbeans.XmlNonNegativeInteger;
-import org.apache.xmlbeans.XmlObject;
-import org.apache.xmlbeans.XmlPositiveInteger;
+import org.apache.xmlbeans.*;
 import org.apache.xmlbeans.impl.common.QNameHelper;
 import org.apache.xmlbeans.impl.common.XMLChar;
 import org.apache.xmlbeans.impl.common.XPath;
+import org.apache.xmlbeans.impl.schema.StscImporter.SchemaToProcess;
 import org.apache.xmlbeans.impl.values.NamespaceContext;
 import org.apache.xmlbeans.impl.values.XmlNonNegativeIntegerImpl;
 import org.apache.xmlbeans.impl.values.XmlPositiveIntegerImpl;
 import org.apache.xmlbeans.impl.values.XmlValueOutOfRangeException;
-import org.apache.xmlbeans.impl.xb.xsdschema.Annotated;
-import org.apache.xmlbeans.impl.xb.xsdschema.AnnotationDocument;
-import org.apache.xmlbeans.impl.xb.xsdschema.Attribute;
-import org.apache.xmlbeans.impl.xb.xsdschema.AttributeGroup;
-import org.apache.xmlbeans.impl.xb.xsdschema.Element;
-import org.apache.xmlbeans.impl.xb.xsdschema.FieldDocument;
-import org.apache.xmlbeans.impl.xb.xsdschema.FormChoice;
-import org.apache.xmlbeans.impl.xb.xsdschema.Keybase;
-import org.apache.xmlbeans.impl.xb.xsdschema.KeyrefDocument;
-import org.apache.xmlbeans.impl.xb.xsdschema.LocalElement;
-import org.apache.xmlbeans.impl.xb.xsdschema.LocalSimpleType;
-import org.apache.xmlbeans.impl.xb.xsdschema.NamedAttributeGroup;
-import org.apache.xmlbeans.impl.xb.xsdschema.NamedGroup;
+import org.apache.xmlbeans.impl.xb.xsdschema.*;
 import org.apache.xmlbeans.impl.xb.xsdschema.RedefineDocument.Redefine;
 import org.apache.xmlbeans.impl.xb.xsdschema.SchemaDocument.Schema;
-import org.apache.xmlbeans.impl.xb.xsdschema.SimpleType;
-import org.apache.xmlbeans.impl.xb.xsdschema.TopLevelAttribute;
-import org.apache.xmlbeans.impl.xb.xsdschema.TopLevelComplexType;
-import org.apache.xmlbeans.impl.xb.xsdschema.TopLevelElement;
-import org.apache.xmlbeans.impl.xb.xsdschema.TopLevelSimpleType;
 import org.apache.xmlbeans.soap.SOAPArrayType;
 
 import javax.xml.namespace.QName;
 import java.math.BigInteger;
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.HashMap;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Map;
+import java.util.*;
 
-public class StscTranslator
-{
+public class StscTranslator {
     private static final QName WSDL_ARRAYTYPE_NAME =
         QNameHelper.forLNS("arrayType", "http://schemas.xmlsoap.org/wsdl/");
     private static final String FORM_QUALIFIED = "qualified";
 
-    public static void addAllDefinitions(StscImporter.SchemaToProcess[] schemasAndChameleons)
-    {
+    public static void addAllDefinitions(SchemaToProcess[] schemasAndChameleons) {
         // Build all redefine objects
-        List redefinitions = new ArrayList();
-        for (int i = 0; i < schemasAndChameleons.length; i++)
-        {
-            List redefines = schemasAndChameleons[i].getRedefines();
-            if (redefines != null)
-            {
-                List redefineObjects = schemasAndChameleons[i].getRedefineObjects();
-                Iterator it = redefines.iterator();
-                Iterator ito = redefineObjects.iterator();
-                for (; it.hasNext(); )
-                {
+        List<RedefinitionHolder> redefinitions = new ArrayList<>();
+        for (SchemaToProcess schemasAndChameleon : schemasAndChameleons) {
+            List<SchemaToProcess> redefines = schemasAndChameleon.getRedefines();
+            if (redefines != null) {
+                List<Redefine> redefineObjects = schemasAndChameleon.getRedefineObjects();
+                Iterator<SchemaToProcess> it = redefines.iterator();
+                Iterator<Redefine> ito = redefineObjects.iterator();
+                while (it.hasNext()) {
                     assert ito.hasNext() :
-                    "The array of redefines and redefine objects have to have the same length";
-                    redefinitions.add(new RedefinitionHolder(
-                            (StscImporter.SchemaToProcess) it.next(),
-                            (Redefine) ito.next()));
+                        "The array of redefines and redefine objects have to have the same length";
+                    redefinitions.add(new RedefinitionHolder(it.next(), ito.next()));
                 }
             }
         }
-        RedefinitionMaster globalRedefinitions = new RedefinitionMaster((RedefinitionHolder[])
-            redefinitions.toArray(new RedefinitionHolder[redefinitions.size()]));
+        RedefinitionMaster globalRedefinitions = new RedefinitionMaster(redefinitions.toArray(new RedefinitionHolder[0]));
 
         StscState state = StscState.get();
-        for (int j = 0; j < schemasAndChameleons.length; j++)
-        {
-            Schema schema = schemasAndChameleons[j].getSchema();
-            String givenTargetNamespace = schemasAndChameleons[j].getChameleonNamespace();
+        for (SchemaToProcess schemasAndChameleon : schemasAndChameleons) {
+            Schema schema = schemasAndChameleon.getSchema();
+            String givenTargetNamespace = schemasAndChameleon.getChameleonNamespace();
 
-        // quick check for a few unsupported features
+            // quick check for a few unsupported features
 
-        if (schema.sizeOfNotationArray() > 0)
-        {
-            state.warning("Schema <notation> is not yet supported for this release.", XmlErrorCodes.UNSUPPORTED_FEATURE, schema.getNotationArray(0));
-        }
+            if (schema.sizeOfNotationArray() > 0) {
+                state.warning("Schema <notation> is not yet supported for this release.", XmlErrorCodes.UNSUPPORTED_FEATURE, schema.getNotationArray(0));
+            }
 
-        // figure namespace (taking into account chameleons)
-        String targetNamespace = schema.getTargetNamespace();
-        boolean chameleon = false;
-        if (givenTargetNamespace != null && targetNamespace == null)
-        {
-            targetNamespace = givenTargetNamespace;
-            chameleon = true;
-        }
-        if (targetNamespace == null)
-            targetNamespace = "";
+            // figure namespace (taking into account chameleons)
+            String targetNamespace = schema.getTargetNamespace();
+            boolean chameleon = false;
+            if (givenTargetNamespace != null && targetNamespace == null) {
+                targetNamespace = givenTargetNamespace;
+                chameleon = true;
+            }
+            if (targetNamespace == null) {
+                targetNamespace = "";
+            }
 
-        //SchemaContainer container = null;
-        if (targetNamespace.length() > 0 || !isEmptySchema(schema))
-        {
-            state.registerContribution(targetNamespace, schema.documentProperties().getSourceName());
-            state.addNewContainer(targetNamespace);
-            //container = state.getContainer(targetNamespace);
-        }
+            //SchemaContainer container = null;
+            if (targetNamespace.length() > 0 || !isEmptySchema(schema)) {
+                state.registerContribution(targetNamespace, schema.documentProperties().getSourceName());
+                state.addNewContainer(targetNamespace);
+                //container = state.getContainer(targetNamespace);
+            }
 
-        List redefChain = new ArrayList();
-        TopLevelComplexType[] complexTypes = schema.getComplexTypeArray();
-        for (int i = 0; i < complexTypes.length; i++)
-        {
-            TopLevelComplexType type = complexTypes[i];
-            TopLevelComplexType redef;
-            // 1. Traverse the list of redefining Schemas putting all redefinitions
-            // of this type in a List
-            RedefinitionHolder[] rhArray = globalRedefinitions.getComplexTypeRedefinitions(
-                type.getName(), schemasAndChameleons[j]);
-            for (int k = 0; k < rhArray.length; k++)
-            {
-                // In error cases, some redefinitions were nulled out in the list
-                // which is why we need to perform this check
-                if (rhArray[k] != null)
-                {
-                    redef = rhArray[k].redefineComplexType(type.getName());
-                    assert redef != null; // This was already checked
-                    redefChain.add(type);
-                    type = redef;
+            List<Annotated> redefChain = new ArrayList<>();
+            TopLevelComplexType[] complexTypes = schema.getComplexTypeArray();
+            for (TopLevelComplexType complexType : complexTypes) {
+                TopLevelComplexType type = complexType;
+                TopLevelComplexType redef;
+                // 1. Traverse the list of redefining Schemas putting all redefinitions
+                // of this type in a List
+                RedefinitionHolder[] rhArray = globalRedefinitions.getComplexTypeRedefinitions(
+                    type.getName(), schemasAndChameleon);
+                for (RedefinitionHolder redefinitionHolder : rhArray) {
+                    // In error cases, some redefinitions were nulled out in the list
+                    // which is why we need to perform this check
+                    if (redefinitionHolder != null) {
+                        redef = redefinitionHolder.redefineComplexType(type.getName());
+                        assert redef != null; // This was already checked
+                        redefChain.add(type);
+                        type = redef;
+                    }
+                }
+
+                SchemaTypeImpl t = translateGlobalComplexType(type, targetNamespace, chameleon, redefChain.size() > 0);
+                state.addGlobalType(t, null);
+                SchemaTypeImpl r;
+                // 2. Traverse the List built in step 1 in reverse and add all the
+                // types in it to the list of redefined types
+                for (int k = redefChain.size() - 1; k >= 0; k--) {
+                    redef = (TopLevelComplexType) redefChain.remove(k);
+                    r = translateGlobalComplexType(redef, targetNamespace, chameleon, k > 0);
+                    state.addGlobalType(r, t);
+                    t = r;
                 }
             }
 
-            SchemaTypeImpl t = translateGlobalComplexType(type, targetNamespace, chameleon, redefChain.size() > 0);
-            state.addGlobalType(t, null);
-            SchemaTypeImpl r;
-            // 2. Traverse the List built in step 1 in reverse and add all the
-            // types in it to the list of redefined types
-            for (int k = redefChain.size() - 1; k >= 0; k--)
-            {
-                redef = (TopLevelComplexType) redefChain.remove(k);
-                r = translateGlobalComplexType(redef, targetNamespace, chameleon, k > 0);
-                state.addGlobalType(r, t);
-                t = r;
-            }
-        }
+            TopLevelSimpleType[] simpleTypes = schema.getSimpleTypeArray();
+            for (TopLevelSimpleType simpleType : simpleTypes) {
+                TopLevelSimpleType type = simpleType;
+                TopLevelSimpleType redef;
+                RedefinitionHolder[] rhArray = globalRedefinitions.getSimpleTypeRedefinitions(
+                    type.getName(), schemasAndChameleon);
+                for (RedefinitionHolder redefinitionHolder : rhArray) {
+                    // In error cases, some redefinitions were nulled out in the list
+                    // which is why we need to perform this check
+                    if (redefinitionHolder != null) {
+                        redef = redefinitionHolder.redefineSimpleType(type.getName());
+                        assert redef != null; // This was already checked
+                        redefChain.add(type);
+                        type = redef;
+                    }
+                }
 
-        TopLevelSimpleType[] simpleTypes = schema.getSimpleTypeArray();
-        for (int i = 0; i < simpleTypes.length; i++)
-        {
-            TopLevelSimpleType type = simpleTypes[i];
-            TopLevelSimpleType redef;
-            RedefinitionHolder[] rhArray = globalRedefinitions.getSimpleTypeRedefinitions(
-                type.getName(), schemasAndChameleons[j]);
-            for (int k = 0; k < rhArray.length; k++)
-            {
-                // In error cases, some redefinitions were nulled out in the list
-                // which is why we need to perform this check
-                if (rhArray[k] != null)
-                {
-                    redef = rhArray[k].redefineSimpleType(type.getName());
-                    assert redef != null; // This was already checked
-                    redefChain.add(type);
-                    type = redef;
+                SchemaTypeImpl t = translateGlobalSimpleType(type, targetNamespace, chameleon, redefChain.size() > 0);
+                state.addGlobalType(t, null);
+                SchemaTypeImpl r;
+                for (int k = redefChain.size() - 1; k >= 0; k--) {
+                    redef = (TopLevelSimpleType) redefChain.remove(k);
+                    r = translateGlobalSimpleType(redef, targetNamespace, chameleon, k > 0);
+                    state.addGlobalType(r, t);
+                    t = r;
                 }
             }
 
-            SchemaTypeImpl t = translateGlobalSimpleType(type, targetNamespace, chameleon,redefChain.size() > 0);
-            state.addGlobalType(t, null);
-            SchemaTypeImpl r;
-            for (int k = redefChain.size()-1; k >= 0; k--)
-            {
-                redef = (TopLevelSimpleType) redefChain.remove(k);
-                r = translateGlobalSimpleType(redef, targetNamespace, chameleon, k > 0);
-                state.addGlobalType(r, t);
-                t = r;
+            TopLevelElement[] elements = schema.getElementArray();
+            for (TopLevelElement element : elements) {
+                state.addDocumentType(translateDocumentType(element, targetNamespace, chameleon), QNameHelper.forLNS(element.getName(), targetNamespace));
             }
-        }
 
-        TopLevelElement[] elements = schema.getElementArray();
-        for (int i = 0; i < elements.length; i++)
-        {
-            TopLevelElement element = elements[i];
-            state.addDocumentType(translateDocumentType(element, targetNamespace, chameleon), QNameHelper.forLNS(element.getName(), targetNamespace));
-        }
+            TopLevelAttribute[] attributes = schema.getAttributeArray();
+            for (TopLevelAttribute attribute : attributes) {
+                state.addAttributeType(translateAttributeType(attribute, targetNamespace, chameleon), QNameHelper.forLNS(attribute.getName(), targetNamespace));
+            }
 
-        TopLevelAttribute[] attributes = schema.getAttributeArray();
-        for (int i = 0; i < attributes.length ; i++)
-        {
-            TopLevelAttribute attribute = attributes[i];
-            state.addAttributeType(translateAttributeType(attribute, targetNamespace, chameleon), QNameHelper.forLNS(attribute.getName(), targetNamespace));
-        }
+            NamedGroup[] modelgroups = schema.getGroupArray();
+            for (NamedGroup group : modelgroups) {
+                NamedGroup redef;
+                RedefinitionHolder[] rhArray = globalRedefinitions.getModelGroupRedefinitions(
+                    group.getName(), schemasAndChameleon);
+                for (RedefinitionHolder redefinitionHolder : rhArray) {
+                    // In error cases, some redefinitions were nulled out in the list
+                    // which is why we need to perform this check
+                    if (redefinitionHolder != null) {
+                        redef = redefinitionHolder.redefineModelGroup(group.getName());
+                        assert redef != null; // This was already checked
+                        redefChain.add(group);
+                        group = redef;
+                    }
+                }
 
-        NamedGroup[] modelgroups = schema.getGroupArray();
-        for (int i = 0; i < modelgroups.length; i++)
-        {
-            NamedGroup group = modelgroups[i];
-            NamedGroup redef;
-            RedefinitionHolder[] rhArray = globalRedefinitions.getModelGroupRedefinitions(
-                group.getName(), schemasAndChameleons[j]);
-            for (int k = 0; k < rhArray.length; k++)
-            {
-                // In error cases, some redefinitions were nulled out in the list
-                // which is why we need to perform this check
-                if (rhArray[k] != null)
-                {
-                    redef = rhArray[k].redefineModelGroup(group.getName());
-                    assert redef != null; // This was already checked
-                    redefChain.add(group);
-                    group = redef;
+                SchemaModelGroupImpl g = translateModelGroup(group, targetNamespace, chameleon, redefChain.size() > 0);
+                state.addModelGroup(g, null);
+                SchemaModelGroupImpl r;
+                for (int k = redefChain.size() - 1; k >= 0; k--) {
+                    redef = (NamedGroup) redefChain.remove(k);
+                    r = translateModelGroup(redef, targetNamespace, chameleon, k > 0);
+                    state.addModelGroup(r, g);
+                    g = r;
                 }
             }
 
-            SchemaModelGroupImpl g = translateModelGroup(group, targetNamespace, chameleon, redefChain.size() > 0);
-            state.addModelGroup(g, null);
-            SchemaModelGroupImpl r;
-            for (int k = redefChain.size()-1; k >= 0; k--)
-            {
-                redef = (NamedGroup) redefChain.remove(k);
-                r = translateModelGroup(redef, targetNamespace, chameleon, k > 0);
-                state.addModelGroup(r, g);
-                g = r;
-            }
-        }
+            NamedAttributeGroup[] attrgroups = schema.getAttributeGroupArray();
+            for (NamedAttributeGroup group : attrgroups) {
+                NamedAttributeGroup redef;
+                RedefinitionHolder[] rhArray = globalRedefinitions.getAttributeGroupRedefinitions(
+                    group.getName(), schemasAndChameleon);
+                for (RedefinitionHolder redefinitionHolder : rhArray) {
+                    // In error cases, some redefinitions were nulled out in the list
+                    // which is why we need to perform this check
+                    if (redefinitionHolder != null) {
+                        redef = redefinitionHolder.redefineAttributeGroup(group.getName());
+                        assert redef != null; // This was already checked
+                        redefChain.add(group);
+                        group = redef;
+                    }
+                }
 
-        NamedAttributeGroup[] attrgroups = schema.getAttributeGroupArray();
-        for (int i = 0; i < attrgroups.length; i++)
-        {
-            NamedAttributeGroup group = attrgroups[i];
-            NamedAttributeGroup redef;
-            RedefinitionHolder[] rhArray = globalRedefinitions.getAttributeGroupRedefinitions(
-                group.getName(), schemasAndChameleons[j]);
-            for (int k = 0; k < rhArray.length; k++)
-            {
-                // In error cases, some redefinitions were nulled out in the list
-                // which is why we need to perform this check
-                if (rhArray[k] != null)
-                {
-                    redef = rhArray[k].redefineAttributeGroup(group.getName());
-                    assert redef != null; // This was already checked
-                    redefChain.add(group);
-                    group = redef;
+                SchemaAttributeGroupImpl g = translateAttributeGroup(group, targetNamespace, chameleon, redefChain.size() > 0);
+                state.addAttributeGroup(g, null);
+                SchemaAttributeGroupImpl r;
+                for (int k = redefChain.size() - 1; k >= 0; k--) {
+                    redef = (NamedAttributeGroup) redefChain.remove(k);
+                    r = translateAttributeGroup(redef, targetNamespace, chameleon, k > 0);
+                    state.addAttributeGroup(r, g);
+                    g = r;
                 }
             }
 
-            SchemaAttributeGroupImpl g = translateAttributeGroup(group, targetNamespace, chameleon, redefChain.size() > 0);
-            state.addAttributeGroup(g, null);
-            SchemaAttributeGroupImpl r;
-            for (int k = redefChain.size()-1; k >= 0; k--)
-            {
-                redef = (NamedAttributeGroup) redefChain.remove(k);
-                r = translateAttributeGroup(redef, targetNamespace, chameleon, k > 0);
-                state.addAttributeGroup(r, g);
-                g = r;
+            AnnotationDocument.Annotation[] annotations = schema.getAnnotationArray();
+            for (AnnotationDocument.Annotation annotation : annotations) {
+                state.addAnnotation(SchemaAnnotationImpl.getAnnotation(state.getContainer(targetNamespace), schema, annotation), targetNamespace);
             }
         }
 
-        AnnotationDocument.Annotation[] annotations = schema.getAnnotationArray();
-        for (int i = 0; i < annotations.length; i++)
-            state.addAnnotation(SchemaAnnotationImpl.getAnnotation(state.getContainer(targetNamespace), schema, annotations[i]), targetNamespace);
+        for (Object redefinition : redefinitions) {
+            ((RedefinitionHolder) redefinition).complainAboutMissingDefinitions();
         }
-
-        for (int i = 0; i < redefinitions.size(); i++)
-            ((RedefinitionHolder) redefinitions.get(i)).complainAboutMissingDefinitions();
     }
 
-    private static class RedefinitionHolder
-    {
+    private static class RedefinitionHolder {
         // record redefinitions
-        private Map stRedefinitions = Collections.EMPTY_MAP;
-        private Map ctRedefinitions = Collections.EMPTY_MAP;
-        private Map agRedefinitions = Collections.EMPTY_MAP;
-        private Map mgRedefinitions = Collections.EMPTY_MAP;
+        private Map<String, TopLevelSimpleType> stRedefinitions = Collections.emptyMap();
+        private Map<String, TopLevelComplexType> ctRedefinitions = Collections.emptyMap();
+        private Map<String, NamedAttributeGroup> agRedefinitions = Collections.emptyMap();
+        private Map<String, NamedGroup> mgRedefinitions = Collections.emptyMap();
         private String schemaLocation = "";
-        private StscImporter.SchemaToProcess schemaRedefined;
+        private final SchemaToProcess schemaRedefined;
 
         // first build set of redefined components
-        RedefinitionHolder(StscImporter.SchemaToProcess schemaToProcess, Redefine redefine)
-        {
+        RedefinitionHolder(SchemaToProcess schemaToProcess, Redefine redefine) {
             schemaRedefined = schemaToProcess;
-            if (redefine != null)
-            {
+            if (redefine != null) {
                 StscState state = StscState.get();
 
-                stRedefinitions = new HashMap();
-                ctRedefinitions = new HashMap();
-                agRedefinitions = new HashMap();
-                mgRedefinitions = new HashMap();
-                if (redefine.getSchemaLocation() != null)
+                stRedefinitions = new HashMap<>();
+                ctRedefinitions = new HashMap<>();
+                agRedefinitions = new HashMap<>();
+                mgRedefinitions = new HashMap<>();
+                if (redefine.getSchemaLocation() != null) {
                     schemaLocation = redefine.getSchemaLocation();
+                }
 
                 TopLevelComplexType[] complexTypes = redefine.getComplexTypeArray();
-                for (int i = 0; i < complexTypes.length; i++)
-                {
-                    if (complexTypes[i].getName() != null)
-                    {
+                for (TopLevelComplexType complexType : complexTypes) {
+                    if (complexType.getName() != null) {
                         // KHK: which rule? sch-props-correct.2?
-                        if (ctRedefinitions.containsKey(complexTypes[i].getName()))
-                            state.error("Duplicate type redefinition: " + complexTypes[i].getName(), XmlErrorCodes.DUPLICATE_GLOBAL_TYPE, null);
-                        else
-                            ctRedefinitions.put(complexTypes[i].getName(), complexTypes[i]);
+                        if (ctRedefinitions.containsKey(complexType.getName())) {
+                            state.error("Duplicate type redefinition: " + complexType.getName(), XmlErrorCodes.DUPLICATE_GLOBAL_TYPE, null);
+                        } else {
+                            ctRedefinitions.put(complexType.getName(), complexType);
+                        }
                     }
                 }
 
                 TopLevelSimpleType[] simpleTypes = redefine.getSimpleTypeArray();
-                for (int i = 0; i < simpleTypes.length; i++)
-                {
-                    if (simpleTypes[i].getName() != null)
-                    {
-                        if (stRedefinitions.containsKey(simpleTypes[i].getName()))
-                            state.error("Duplicate type redefinition: " + simpleTypes[i].getName(), XmlErrorCodes.DUPLICATE_GLOBAL_TYPE, null);
-                        else
-                            stRedefinitions.put(simpleTypes[i].getName(), simpleTypes[i]);
+                for (TopLevelSimpleType simpleType : simpleTypes) {
+                    if (simpleType.getName() != null) {
+                        if (stRedefinitions.containsKey(simpleType.getName())) {
+                            state.error("Duplicate type redefinition: " + simpleType.getName(), XmlErrorCodes.DUPLICATE_GLOBAL_TYPE, null);
+                        } else {
+                            stRedefinitions.put(simpleType.getName(), simpleType);
+                        }
                     }
                 }
 
                 NamedGroup[] modelgroups = redefine.getGroupArray();
-                for (int i = 0; i < modelgroups.length; i++)
-                {
-                    if (modelgroups[i].getName() != null)
-                    {
-                        if (mgRedefinitions.containsKey(modelgroups[i].getName()))
-                            state.error("Duplicate type redefinition: " + modelgroups[i].getName(), XmlErrorCodes.DUPLICATE_GLOBAL_TYPE, null);
-                        else
-                            mgRedefinitions.put(modelgroups[i].getName(), modelgroups[i]);
+                for (NamedGroup modelgroup : modelgroups) {
+                    if (modelgroup.getName() != null) {
+                        if (mgRedefinitions.containsKey(modelgroup.getName())) {
+                            state.error("Duplicate type redefinition: " + modelgroup.getName(), XmlErrorCodes.DUPLICATE_GLOBAL_TYPE, null);
+                        } else {
+                            mgRedefinitions.put(modelgroup.getName(), modelgroup);
+                        }
                     }
                 }
 
                 NamedAttributeGroup[] attrgroups = redefine.getAttributeGroupArray();
-                for (int i = 0; i < attrgroups.length; i++)
-                {
-                    if (attrgroups[i].getName() != null)
-                    {
-                        if (agRedefinitions.containsKey(attrgroups[i].getName()))
-                            state.error("Duplicate type redefinition: " + attrgroups[i].getName(), XmlErrorCodes.DUPLICATE_GLOBAL_TYPE, null);
-                        else
-                            agRedefinitions.put(attrgroups[i].getName(), attrgroups[i]);
+                for (NamedAttributeGroup attrgroup : attrgroups) {
+                    if (attrgroup.getName() != null) {
+                        if (agRedefinitions.containsKey(attrgroup.getName())) {
+                            state.error("Duplicate type redefinition: " + attrgroup.getName(), XmlErrorCodes.DUPLICATE_GLOBAL_TYPE, null);
+                        } else {
+                            agRedefinitions.put(attrgroup.getName(), attrgroup);
+                        }
                     }
                 }
             }
         }
 
-        public TopLevelSimpleType redefineSimpleType(String name)
-        {
-            if (name == null || !stRedefinitions.containsKey(name))
-                return null;
-            return (TopLevelSimpleType)stRedefinitions.remove(name);
+        public TopLevelSimpleType redefineSimpleType(String name) {
+            return name == null || !stRedefinitions.containsKey(name) ? null : stRedefinitions.remove(name);
         }
 
-        public TopLevelComplexType redefineComplexType(String name)
-        {
-            if (name == null || !ctRedefinitions.containsKey(name))
-                return null;
-            return (TopLevelComplexType)ctRedefinitions.remove(name);
+        public TopLevelComplexType redefineComplexType(String name) {
+            return name == null || !ctRedefinitions.containsKey(name) ? null : ctRedefinitions.remove(name);
         }
 
-        public NamedGroup redefineModelGroup(String name)
-        {
-            if (name == null || !mgRedefinitions.containsKey(name))
-                return null;
-            return (NamedGroup)mgRedefinitions.remove(name);
+        public NamedGroup redefineModelGroup(String name) {
+            return name == null || !mgRedefinitions.containsKey(name) ? null : mgRedefinitions.remove(name);
         }
 
-        public NamedAttributeGroup redefineAttributeGroup(String name)
-        {
-            if (name == null || !agRedefinitions.containsKey(name))
-                return null;
-            return (NamedAttributeGroup)agRedefinitions.remove(name);
+        public NamedAttributeGroup redefineAttributeGroup(String name) {
+            return name == null || !agRedefinitions.containsKey(name) ? null : agRedefinitions.remove(name);
         }
 
-        public void complainAboutMissingDefinitions()
-        {
+        public void complainAboutMissingDefinitions() {
             if (stRedefinitions.isEmpty() && ctRedefinitions.isEmpty() &&
-                    agRedefinitions.isEmpty() && mgRedefinitions.isEmpty())
+                agRedefinitions.isEmpty() && mgRedefinitions.isEmpty()) {
                 return;
+            }
 
             StscState state = StscState.get();
 
-            for (Iterator i = stRedefinitions.keySet().iterator(); i.hasNext(); )
-            {
-                String name = (String)i.next();
-                state.error("Redefined simple type " + name + " not found in " + schemaLocation, XmlErrorCodes.GENERIC_ERROR, (XmlObject)stRedefinitions.get(name));
+            for (String name : stRedefinitions.keySet()) {
+                state.error("Redefined simple type " + name + " not found in " + schemaLocation, XmlErrorCodes.GENERIC_ERROR, stRedefinitions.get(name));
             }
 
-            for (Iterator i = ctRedefinitions.keySet().iterator(); i.hasNext(); )
-            {
-                String name = (String)i.next();
-                state.error("Redefined complex type " + name + " not found in " + schemaLocation, XmlErrorCodes.GENERIC_ERROR, (XmlObject)ctRedefinitions.get(name));
+            for (String name : ctRedefinitions.keySet()) {
+                state.error("Redefined complex type " + name + " not found in " + schemaLocation, XmlErrorCodes.GENERIC_ERROR, ctRedefinitions.get(name));
             }
 
-            for (Iterator i = agRedefinitions.keySet().iterator(); i.hasNext(); )
-            {
-                String name = (String)i.next();
-                state.error("Redefined attribute group " + name + " not found in " + schemaLocation, XmlErrorCodes.GENERIC_ERROR, (XmlObject)agRedefinitions.get(name));
+            for (String name : agRedefinitions.keySet()) {
+                state.error("Redefined attribute group " + name + " not found in " + schemaLocation, XmlErrorCodes.GENERIC_ERROR, agRedefinitions.get(name));
             }
 
-            for (Iterator i = mgRedefinitions.keySet().iterator(); i.hasNext(); )
-            {
-                String name = (String)i.next();
-                state.error("Redefined model group " + name + " not found in " + schemaLocation, XmlErrorCodes.GENERIC_ERROR, (XmlObject)mgRedefinitions.get(name));
+            for (String name : mgRedefinitions.keySet()) {
+                state.error("Redefined model group " + name + " not found in " + schemaLocation, XmlErrorCodes.GENERIC_ERROR, mgRedefinitions.get(name));
             }
         }
     }
@@ -435,130 +342,92 @@
      * and then topologically sorted based on the inclusion relationship to
      * ensure that redefinitions are applied in the right order.
      */
-    private static class RedefinitionMaster
-    {
+    private static class RedefinitionMaster {
+        private static final short SIMPLE_TYPE = 1;
+        private static final short COMPLEX_TYPE = 2;
+        private static final short MODEL_GROUP = 3;
+        private static final short ATTRIBUTE_GROUP = 4;
+
         // record redefinitions
-        private Map stRedefinitions = Collections.EMPTY_MAP;
-        private Map ctRedefinitions = Collections.EMPTY_MAP;
-        private Map agRedefinitions = Collections.EMPTY_MAP;
-        private Map mgRedefinitions = Collections.EMPTY_MAP;
+        private Map<String, List<RedefinitionHolder>> stRedefinitions = Collections.emptyMap();
+        private Map<String, List<RedefinitionHolder>> ctRedefinitions = Collections.emptyMap();
+        private Map<String, List<RedefinitionHolder>> agRedefinitions = Collections.emptyMap();
+        private Map<String, List<RedefinitionHolder>> mgRedefinitions = Collections.emptyMap();
         private static final RedefinitionHolder[] EMPTY_REDEFINTION_HOLDER_ARRAY =
             new RedefinitionHolder[0];
 
-        RedefinitionMaster(RedefinitionHolder[] redefHolders)
-        {
-            if (redefHolders.length > 0)
-            {
-                stRedefinitions = new HashMap();
-                ctRedefinitions = new HashMap();
-                agRedefinitions = new HashMap();
-                mgRedefinitions = new HashMap();
 
-                for (int i = 0; i < redefHolders.length; i++)
-                {
-                    RedefinitionHolder redefHolder = redefHolders[i];
-                    for (Iterator it = redefHolder.stRedefinitions.keySet().iterator(); it.hasNext();)
-                    {
-                        Object key = it.next();
-                        List redefinedIn = (List) stRedefinitions.get(key);
-                        if (redefinedIn == null)
-                        {
-                            redefinedIn = new ArrayList();
-                            stRedefinitions.put(key, redefinedIn);
-                        }
-                        redefinedIn.add(redefHolders[i]);
+        RedefinitionMaster(RedefinitionHolder[] redefHolders) {
+            if (redefHolders.length > 0) {
+                stRedefinitions = new HashMap<>();
+                ctRedefinitions = new HashMap<>();
+                agRedefinitions = new HashMap<>();
+                mgRedefinitions = new HashMap<>();
+
+                for (RedefinitionHolder redefHolder : redefHolders) {
+                    for (String key : redefHolder.stRedefinitions.keySet()) {
+                        stRedefinitions.computeIfAbsent(key, k -> new ArrayList<>()).add(redefHolder);
                     }
-                    for (Iterator it = redefHolder.ctRedefinitions.keySet().iterator(); it.hasNext();)
-                    {
-                        Object key = it.next();
-                        List redefinedIn = (List) ctRedefinitions.get(key);
-                        if (redefinedIn == null)
-                        {
-                            redefinedIn = new ArrayList();
-                            ctRedefinitions.put(key, redefinedIn);
-                        }
-                        redefinedIn.add(redefHolders[i]);
+                    for (String key : redefHolder.ctRedefinitions.keySet()) {
+                        ctRedefinitions.computeIfAbsent(key, k -> new ArrayList<>()).add(redefHolder);
                     }
-                    for (Iterator it = redefHolder.agRedefinitions.keySet().iterator(); it.hasNext();)
-                    {
-                        Object key = it.next();
-                        List redefinedIn = (List) agRedefinitions.get(key);
-                        if (redefinedIn == null)
-                        {
-                            redefinedIn = new ArrayList();
-                            agRedefinitions.put(key, redefinedIn);
-                        }
-                        redefinedIn.add(redefHolders[i]);
+                    for (String key : redefHolder.agRedefinitions.keySet()) {
+                        agRedefinitions.computeIfAbsent(key, k -> new ArrayList<>()).add(redefHolder);
                     }
-                    for (Iterator it = redefHolder.mgRedefinitions.keySet().iterator(); it.hasNext();)
-                    {
-                        Object key = it.next();
-                        List redefinedIn = (List) mgRedefinitions.get(key);
-                        if (redefinedIn == null)
-                        {
-                            redefinedIn = new ArrayList();
-                            mgRedefinitions.put(key, redefinedIn);
-                        }
-                        redefinedIn.add(redefHolders[i]);
+                    for (String key : redefHolder.mgRedefinitions.keySet()) {
+                        mgRedefinitions.computeIfAbsent(key, k -> new ArrayList<>()).add(redefHolder);
                     }
                 }
             }
         }
 
         RedefinitionHolder[] getSimpleTypeRedefinitions(String name,
-            StscImporter.SchemaToProcess schema)
-        {
-            List redefines = (List) stRedefinitions.get(name);
-            if (redefines == null)
+                                                        SchemaToProcess schema) {
+            List<RedefinitionHolder> redefines = stRedefinitions.get(name);
+            if (redefines == null) {
                 return EMPTY_REDEFINTION_HOLDER_ARRAY;
+            }
             return doTopologicalSort(redefines, schema, name, SIMPLE_TYPE);
         }
 
         RedefinitionHolder[] getComplexTypeRedefinitions(String name,
-            StscImporter.SchemaToProcess schema)
-        {
-            List redefines = (List) ctRedefinitions.get(name);
-            if (redefines == null)
+                                                         SchemaToProcess schema) {
+            List<RedefinitionHolder> redefines = ctRedefinitions.get(name);
+            if (redefines == null) {
                 return EMPTY_REDEFINTION_HOLDER_ARRAY;
+            }
             return doTopologicalSort(redefines, schema, name, COMPLEX_TYPE);
         }
 
         RedefinitionHolder[] getAttributeGroupRedefinitions(String name,
-            StscImporter.SchemaToProcess schema)
-        {
-            List redefines = (List) agRedefinitions.get(name);
-            if (redefines == null)
+                                                            SchemaToProcess schema) {
+            List<RedefinitionHolder> redefines = agRedefinitions.get(name);
+            if (redefines == null) {
                 return EMPTY_REDEFINTION_HOLDER_ARRAY;
+            }
             return doTopologicalSort(redefines, schema, name, ATTRIBUTE_GROUP);
         }
 
         RedefinitionHolder[] getModelGroupRedefinitions(String name,
-            StscImporter.SchemaToProcess schema)
-        {
-            List redefines = (List) mgRedefinitions.get(name);
-            if (redefines == null)
+                                                        SchemaToProcess schema) {
+            List<RedefinitionHolder> redefines = mgRedefinitions.get(name);
+            if (redefines == null) {
                 return EMPTY_REDEFINTION_HOLDER_ARRAY;
+            }
             return doTopologicalSort(redefines, schema, name, MODEL_GROUP);
         }
 
-        private final static short SIMPLE_TYPE = 1;
-        private final static short COMPLEX_TYPE = 2;
-        private final static short MODEL_GROUP = 3;
-        private final static short ATTRIBUTE_GROUP = 4;
-
-        private RedefinitionHolder[] doTopologicalSort(List genericRedefines,
-            StscImporter.SchemaToProcess schema, String name, short componentType)
-        {
+        private RedefinitionHolder[] doTopologicalSort(List<RedefinitionHolder> genericRedefines,
+                                                       SchemaToProcess schema, String name, short componentType) {
             // We have a list of files that redefine this name
             // Filter out the ones that don't redefine this file in particular
             RedefinitionHolder[] specificRedefines = new RedefinitionHolder[genericRedefines.size()];
             int n = 0;
-            for (int i = 0; i < genericRedefines.size(); i++)
-            {
-                RedefinitionHolder h = (RedefinitionHolder) genericRedefines.get(i);
+            for (RedefinitionHolder h : genericRedefines) {
                 if (h.schemaRedefined == schema ||
-                    h.schemaRedefined.indirectIncludes(schema))
+                    h.schemaRedefined.indirectIncludes(schema)) {
                     specificRedefines[n++] = h;
+                }
             }
             // Now we have the list of files that specifically redefine the
             // name in the file that we are looking for
@@ -567,71 +436,70 @@
             RedefinitionHolder[] sortedRedefines = new RedefinitionHolder[n];
             int[] numberOfIncludes = new int[n];
             // Just count the number of inclusions for each redefinition
-            for (int i = 0; i < n-1; i++)
-            {
+            for (int i = 0; i < n - 1; i++) {
                 RedefinitionHolder current = specificRedefines[i];
-                for (int j = i + 1; j < n; j++)
-                {
-                    if (current.schemaRedefined.indirectIncludes(specificRedefines[j].schemaRedefined))
+                for (int j = i + 1; j < n; j++) {
+                    if (current.schemaRedefined.indirectIncludes(specificRedefines[j].schemaRedefined)) {
                         numberOfIncludes[i]++;
-                    if (specificRedefines[j].schemaRedefined.indirectIncludes(current.schemaRedefined))
+                    }
+                    if (specificRedefines[j].schemaRedefined.indirectIncludes(current.schemaRedefined)) {
                         numberOfIncludes[j]++;
+                    }
                 }
             }
             // Eliminate members one by one, according to the number of schemas
             // that they include, to complete the sort
             int position = 0;
             boolean errorReported = false;
-            while (position < n)
-            {
+            while (position < n) {
                 int index = -1;
-                for (int i = 0; i < numberOfIncludes.length; i++)
-                    if (numberOfIncludes[i] == 0)
-                    {
-                        if (index < 0)
+                for (int i = 0; i < numberOfIncludes.length; i++) {
+                    if (numberOfIncludes[i] == 0) {
+                        if (index < 0) {
                             index = i;
+                        }
                     }
-                if (index < 0)
-                {
+                }
+                if (index < 0) {
                     // Error! Circular redefinition
-                    if (!errorReported)
-                    {
+                    if (!errorReported) {
                         StringBuilder fileNameList = new StringBuilder();
                         XmlObject location = null;
-                        for (int i = 0; i < n; i++)
-                            if (specificRedefines[i] != null)
-                            {
+                        for (int i = 0; i < n; i++) {
+                            if (specificRedefines[i] != null) {
                                 fileNameList.append(specificRedefines[i].schemaLocation).
                                     append(',').append(' ');
-                                if (location == null)
+                                if (location == null) {
                                     location = locationFromRedefinitionAndCode(
                                         specificRedefines[i], name, componentType);
+                                }
                             }
+                        }
                         StscState.get().error("Detected circular redefinition of " +
-                            componentNameFromCode(componentType) + " \"" + name +
-                            "\"; Files involved: " + fileNameList.toString(),
+                                              componentNameFromCode(componentType) + " \"" + name +
+                                              "\"; Files involved: " + fileNameList.toString(),
                             XmlErrorCodes.GENERIC_ERROR, location);
                         errorReported = true;
                     }
                     int min = n;
-                    for (int i = 0; i < n; i++)
-                        if (numberOfIncludes[i] > 0 && numberOfIncludes[i] < min)
-                        {
+                    for (int i = 0; i < n; i++) {
+                        if (numberOfIncludes[i] > 0 && numberOfIncludes[i] < min) {
                             min = numberOfIncludes[i];
                             index = i;
                         }
+                    }
                     numberOfIncludes[index]--;
-                }
-                else
-                {
+                } else {
                     assert specificRedefines[index] != null;
                     sortedRedefines[position++] = specificRedefines[index];
-                    for (int i = 0; i < n; i++)
+                    for (int i = 0; i < n; i++) {
                         if (specificRedefines[i] != null &&
                             specificRedefines[i].schemaRedefined.
                                 indirectIncludes(specificRedefines[index].
-                                    schemaRedefined))
+                                    schemaRedefined)) {
                             numberOfIncludes[i]--;
+                        }
+                    }
                     specificRedefines[index] = null;
                     numberOfIncludes[index]--;
                 }
@@ -640,36 +508,39 @@
             // Each one has to transitively redefine the one before, otherwise
             // it means we are attepting two different redefinitions for the same
             // component
-            for (int i = 1; i < n; i++)
-            {
+            for (int i = 1; i < n; i++) {
                 // Find the previous index with non-null Schema
                 // Since i is never 0, such index always exists
                 int j;
-                for (j = i-1; j >= 0; j--)
-                    if (sortedRedefines[j] != null)
+                for (j = i - 1; j >= 0; j--) {
+                    if (sortedRedefines[j] != null) {
                         break;
+                    }
+                }
 
                 if (!sortedRedefines[i].schemaRedefined.indirectIncludes(
-                        sortedRedefines[j].schemaRedefined))
-                {
+                    sortedRedefines[j].schemaRedefined)) {
                     StscState.get().error("Detected multiple redefinitions of " +
-                        componentNameFromCode(componentType) +
-                        " \"" + name + "\"; Files involved: " +
-                        sortedRedefines[j].schemaRedefined.getSourceName() + ", " +
-                        sortedRedefines[i].schemaRedefined.getSourceName(),
+                                          componentNameFromCode(componentType) +
+                                          " \"" + name + "\"; Files involved: " +
+                                          sortedRedefines[j].schemaRedefined.getSourceName() + ", " +
+                                          sortedRedefines[i].schemaRedefined.getSourceName(),
                         XmlErrorCodes.DUPLICATE_GLOBAL_TYPE,
                         locationFromRedefinitionAndCode(sortedRedefines[i], name, componentType));
                     // Ignore this redefinition
-                    switch (componentType)
-                    {
-                    case SIMPLE_TYPE:
-                        sortedRedefines[i].redefineSimpleType(name); break;
-                    case COMPLEX_TYPE:
-                        sortedRedefines[i].redefineComplexType(name); break;
-                    case ATTRIBUTE_GROUP:
-                        sortedRedefines[i].redefineAttributeGroup(name); break;
-                    case MODEL_GROUP:
-                        sortedRedefines[i].redefineModelGroup(name); break;
+                    switch (componentType) {
+                        case SIMPLE_TYPE:
+                            sortedRedefines[i].redefineSimpleType(name);
+                            break;
+                        case COMPLEX_TYPE:
+                            sortedRedefines[i].redefineComplexType(name);
+                            break;
+                        case ATTRIBUTE_GROUP:
+                            sortedRedefines[i].redefineAttributeGroup(name);
+                            break;
+                        case MODEL_GROUP:
+                            sortedRedefines[i].redefineModelGroup(name);
+                            break;
                     }
                     sortedRedefines[i] = null;
                 }
@@ -678,94 +549,92 @@
             return sortedRedefines;
         }
 
-        private String componentNameFromCode(short code)
-        {
+        private String componentNameFromCode(short code) {
             String componentName;
-            switch (code)
-            {
-            case SIMPLE_TYPE: componentName = "simple type"; break;
-            case COMPLEX_TYPE: componentName = "complex type"; break;
-            case MODEL_GROUP: componentName = "model group"; break;
-            case ATTRIBUTE_GROUP: componentName = "attribute group"; break;
-            default: componentName = "";
+            switch (code) {
+                case SIMPLE_TYPE:
+                    componentName = "simple type";
+                    break;
+                case COMPLEX_TYPE:
+                    componentName = "complex type";
+                    break;
+                case MODEL_GROUP:
+                    componentName = "model group";
+                    break;
+                case ATTRIBUTE_GROUP:
+                    componentName = "attribute group";
+                    break;
+                default:
+                    componentName = "";
             }
             return componentName;
         }
 
         private XmlObject locationFromRedefinitionAndCode(RedefinitionHolder redefinition,
-            String name, short code)
-        {
+                                                          String name, short code) {
             XmlObject location;
-            switch (code)
-            {
-            case SIMPLE_TYPE:
-                location = (XmlObject) redefinition.stRedefinitions.get(name);
-                break;
-            case COMPLEX_TYPE:
-                location = (XmlObject) redefinition.ctRedefinitions.get(name);
-                break;
-            case MODEL_GROUP:
-                location = (XmlObject) redefinition.mgRedefinitions.get(name);
-                break;
-            case ATTRIBUTE_GROUP:
-                location = (XmlObject) redefinition.agRedefinitions.get(name);
-                break;
-            default:
-                location = null;
+            switch (code) {
+                case SIMPLE_TYPE:
+                    location = redefinition.stRedefinitions.get(name);
+                    break;
+                case COMPLEX_TYPE:
+                    location = redefinition.ctRedefinitions.get(name);
+                    break;
+                case MODEL_GROUP:
+                    location = redefinition.mgRedefinitions.get(name);
+                    break;
+                case ATTRIBUTE_GROUP:
+                    location = redefinition.agRedefinitions.get(name);
+                    break;
+                default:
+                    location = null;
             }
             return location;
         }
     }
 
-    private static String findFilename(XmlObject xobj)
-    {
+    private static String findFilename(XmlObject xobj) {
         return StscState.get().sourceNameForUri(xobj.documentProperties().getSourceName());
     }
 
-    private static SchemaTypeImpl translateDocumentType ( TopLevelElement xsdType, String targetNamespace, boolean chameleon )
-    {
-        SchemaTypeImpl sType = new SchemaTypeImpl( StscState.get().getContainer(targetNamespace) );
+    private static SchemaTypeImpl translateDocumentType(TopLevelElement xsdType, String targetNamespace, boolean chameleon) {
+        SchemaTypeImpl sType = new SchemaTypeImpl(StscState.get().getContainer(targetNamespace));
 
         sType.setDocumentType(true);
-        sType.setParseContext( xsdType, targetNamespace, chameleon, null, null, false);
-        sType.setFilename( findFilename( xsdType ) );
+        sType.setParseContext(xsdType, targetNamespace, chameleon, null, null, false);
+        sType.setFilename(findFilename(xsdType));
 
         return sType;
     }
 
-    private static SchemaTypeImpl translateAttributeType ( TopLevelAttribute xsdType, String targetNamespace, boolean chameleon )
-    {
-        SchemaTypeImpl sType = new SchemaTypeImpl( StscState.get().getContainer(targetNamespace) );
+    private static SchemaTypeImpl translateAttributeType(TopLevelAttribute xsdType, String targetNamespace, boolean chameleon) {
+        SchemaTypeImpl sType = new SchemaTypeImpl(StscState.get().getContainer(targetNamespace));
 
         sType.setAttributeType(true);
-        sType.setParseContext( xsdType, targetNamespace, chameleon, null, null, false);
-        sType.setFilename( findFilename( xsdType ) );
+        sType.setParseContext(xsdType, targetNamespace, chameleon, null, null, false);
+        sType.setFilename(findFilename(xsdType));
 
         return sType;
     }
 
-    private static SchemaTypeImpl translateGlobalComplexType(TopLevelComplexType xsdType, String targetNamespace, boolean chameleon, boolean redefinition)
-    {
+    private static SchemaTypeImpl translateGlobalComplexType(TopLevelComplexType xsdType, String targetNamespace, boolean chameleon, boolean redefinition) {
         StscState state = StscState.get();
 
         String localname = xsdType.getName();
-        if (localname == null)
-        {
-            state.error(XmlErrorCodes.MISSING_NAME, new Object[] { "global type" }, xsdType);
+        if (localname == null) {
+            state.error(XmlErrorCodes.MISSING_NAME, new Object[]{"global type"}, xsdType);
             // recovery: ignore unnamed types.
             return null;
         }
-        if (!XMLChar.isValidNCName(localname))
-        {
-            state.error(XmlErrorCodes.INVALID_VALUE, new Object[] { localname, "name" }, xsdType.xgetName());
+        if (!XMLChar.isValidNCName(localname)) {
+            state.error(XmlErrorCodes.INVALID_VALUE, new Object[]{localname, "name"}, xsdType.xgetName());
             // recovery: let the name go through anyway.
         }
 
         QName name = QNameHelper.forLNS(localname, targetNamespace);
 
-        if (isReservedTypeName(name))
-        {
-            state.warning(XmlErrorCodes.RESERVED_TYPE_NAME, new Object[] { QNameHelper.pretty(name) }, xsdType);
+        if (isReservedTypeName(name)) {
+            state.warning(XmlErrorCodes.RESERVED_TYPE_NAME, new Object[]{QNameHelper.pretty(name)}, xsdType);
             return null;
         }
         // System.err.println("Recording type " + QNameHelper.pretty(name));
@@ -779,28 +648,24 @@
         return sType;
     }
 
-    private static SchemaTypeImpl translateGlobalSimpleType(TopLevelSimpleType xsdType, String targetNamespace, boolean chameleon, boolean redefinition)
-    {
+    private static SchemaTypeImpl translateGlobalSimpleType(TopLevelSimpleType xsdType, String targetNamespace, boolean chameleon, boolean redefinition) {
         StscState state = StscState.get();
 
         String localname = xsdType.getName();
-        if (localname == null)
-        {
-            state.error(XmlErrorCodes.MISSING_NAME, new Object[] { "global type" }, xsdType);
+        if (localname == null) {
+            state.error(XmlErrorCodes.MISSING_NAME, new Object[]{"global type"}, xsdType);
             // recovery: ignore unnamed types.
             return null;
         }
-        if (!XMLChar.isValidNCName(localname))
-        {
-            state.error(XmlErrorCodes.INVALID_VALUE, new Object[] { localname, "name" }, xsdType.xgetName());
+        if (!XMLChar.isValidNCName(localname)) {
+            state.error(XmlErrorCodes.INVALID_VALUE, new Object[]{localname, "name"}, xsdType.xgetName());
             // recovery: let the name go through anyway.
         }
 
         QName name = QNameHelper.forLNS(localname, targetNamespace);
 
-        if (isReservedTypeName(name))
-        {
-            state.warning(XmlErrorCodes.RESERVED_TYPE_NAME, new Object[] { QNameHelper.pretty(name) }, xsdType);
+        if (isReservedTypeName(name)) {
+            state.warning(XmlErrorCodes.RESERVED_TYPE_NAME, new Object[]{QNameHelper.pretty(name)}, xsdType);
             return null;
         }
         // System.err.println("Recording type " + QNameHelper.pretty(name));
@@ -815,10 +680,10 @@
         return sType;
     }
 
-    /*package*/ static SchemaTypeImpl translateAnonymousSimpleType(SimpleType typedef,
-        String targetNamespace, boolean chameleon, String elemFormDefault,
-        String attFormDefault, List anonymousTypes, SchemaType outerType)
-    {
+    /*package*/
+    static SchemaTypeImpl translateAnonymousSimpleType(SimpleType typedef,
+                                                       String targetNamespace, boolean chameleon, String elemFormDefault,
+                                                       String attFormDefault, List<SchemaType> anonymousTypes, SchemaType outerType) {
         StscState state = StscState.get();
         SchemaTypeImpl sType = new SchemaTypeImpl(state.getContainer(targetNamespace));
         sType.setSimpleType(true);
@@ -831,44 +696,44 @@
         return sType;
     }
 
-    static FormChoice findElementFormDefault(XmlObject obj)
-    {
+    static FormChoice findElementFormDefault(XmlObject obj) {
         XmlCursor cur = obj.newCursor();
-        while (cur.getObject().schemaType() != Schema.type)
-            if (!cur.toParent())
+        while (cur.getObject().schemaType() != Schema.type) {
+            if (!cur.toParent()) {
                 return null;
-        return ((Schema)cur.getObject()).xgetElementFormDefault();
+            }
+        }
+        return ((Schema) cur.getObject()).xgetElementFormDefault();
     }
 
-    public static boolean uriMatch(String s1, String s2)
-    {
-        if (s1 == null)
+    public static boolean uriMatch(String s1, String s2) {
+        if (s1 == null) {
             return s2 == null || s2.equals("");
-        if (s2 == null)
+        }
+        if (s2 == null) {
             return s1.equals("");
+        }
         return s1.equals(s2);
     }
 
-    public static void copyGlobalElementToLocalElement(SchemaGlobalElement referenced, SchemaLocalElementImpl target )
-    {
+    public static void copyGlobalElementToLocalElement(SchemaGlobalElement referenced, SchemaLocalElementImpl target) {
 
         target.setNameAndTypeRef(referenced.getName(), referenced.getType().getRef());
         target.setNillable(referenced.isNillable());
-        target.setDefault(referenced.getDefaultText(), referenced.isFixed(), ((SchemaGlobalElementImpl)referenced).getParseObject());
-        target.setIdentityConstraints(((SchemaLocalElementImpl)referenced).getIdentityConstraintRefs());
-        target.setBlock(referenced.blockExtension(),  referenced.blockRestriction(),  referenced.blockSubstitution());
+        target.setDefault(referenced.getDefaultText(), referenced.isFixed(), ((SchemaGlobalElementImpl) referenced).getParseObject());
+        target.setIdentityConstraints(((SchemaLocalElementImpl) referenced).getIdentityConstraintRefs());
+        target.setBlock(referenced.blockExtension(), referenced.blockRestriction(), referenced.blockSubstitution());
         target.setAbstract(referenced.isAbstract());
-        target.setTransitionRules(((SchemaParticle)referenced).acceptedStartNames(),
-            ((SchemaParticle)referenced).isSkippable());
+        target.setTransitionRules(((SchemaParticle) referenced).acceptedStartNames(),
+            ((SchemaParticle) referenced).isSkippable());
         target.setAnnotation(referenced.getAnnotation());
     }
 
-    public static void copyGlobalAttributeToLocalAttribute(SchemaGlobalAttributeImpl referenced, SchemaLocalAttributeImpl target )
-    {
+    public static void copyGlobalAttributeToLocalAttribute(SchemaGlobalAttributeImpl referenced, SchemaLocalAttributeImpl target) {
         target.init(
             referenced.getName(), referenced.getTypeRef(), referenced.getUse(),
             referenced.getDefaultText(),
-                referenced.getParseObject(), referenced._defaultValue,
+            referenced.getParseObject(), referenced._defaultValue,
             referenced.isFixed(),
             referenced.getWSDLArrayType(),
             referenced.getAnnotation(), null);
@@ -882,119 +747,102 @@
     public static SchemaLocalElementImpl translateElement(
         Element xsdElt, String targetNamespace, boolean chameleon,
         String elemFormDefault, String attFormDefault,
-        List anonymousTypes, SchemaType outerType)
-    {
+        List<SchemaType> anonymousTypes, SchemaType outerType) {
         StscState state = StscState.get();
 
         SchemaTypeImpl sgHead = null;
 
         // translate sg head
-        if (xsdElt.isSetSubstitutionGroup())
-        {
+        if (xsdElt.isSetSubstitutionGroup()) {
             sgHead = state.findDocumentType(xsdElt.getSubstitutionGroup(),
-                ((SchemaTypeImpl)outerType).getChameleonNamespace(), targetNamespace);
+                ((SchemaTypeImpl) outerType).getChameleonNamespace(), targetNamespace);
 
-            if (sgHead != null)
+            if (sgHead != null) {
                 StscResolver.resolveType(sgHead);
+            }
         }
 
         String name = xsdElt.getName();
         QName ref = xsdElt.getRef();
 
 
-        if (ref != null && name != null)
-        {
+        if (ref != null && name != null) {
             // if (name.equals(ref.getLocalPart()) && uriMatch(targetNamespace, ref.getNamespaceURI()))
             //     state.warning("Element " + name + " specifies both a ref and a name", XmlErrorCodes.ELEMENT_EXTRA_REF, xsdElt.xgetRef());
             // else
-                state.error(XmlErrorCodes.SCHEMA_ELEM$REF_OR_NAME_HAS_BOTH, new Object[] { name }, xsdElt.xgetRef());
+            state.error(XmlErrorCodes.SCHEMA_ELEM$REF_OR_NAME_HAS_BOTH, new Object[]{name}, xsdElt.xgetRef());
             // ignore name
             name = null;
         }
-        if (ref == null && name == null)
-        {
+        if (ref == null && name == null) {
             state.error(XmlErrorCodes.SCHEMA_ELEM$REF_OR_NAME_HAS_NEITHER, null, xsdElt);
             // recovery: ignore this element
             return null;
         }
-        if (name != null && !XMLChar.isValidNCName(name))
-        {
-            state.error(XmlErrorCodes.INVALID_VALUE, new Object[] { name, "name" }, xsdElt.xgetName());
+        if (name != null && !XMLChar.isValidNCName(name)) {
+            state.error(XmlErrorCodes.INVALID_VALUE, new Object[]{name, "name"}, xsdElt.xgetName());
             // recovery: let the name go through anyway.
         }
 
-        if (ref != null)
-        {
-            if (xsdElt.getType() != null)
-            {
-                state.error(XmlErrorCodes.SCHEMA_ELEM$REF_FEATURES, new Object[] { "type" }, xsdElt.xgetType());
+        if (ref != null) {
+            if (xsdElt.getType() != null) {
+                state.error(XmlErrorCodes.SCHEMA_ELEM$REF_FEATURES, new Object[]{"type"}, xsdElt.xgetType());
                 // recovery: let the name go through anyway.
             }
 
-            if (xsdElt.getSimpleType() != null)
-            {
-                state.error(XmlErrorCodes.SCHEMA_ELEM$REF_FEATURES, new Object[] { "<simpleType>" }, xsdElt.getSimpleType());
+            if (xsdElt.getSimpleType() != null) {
+                state.error(XmlErrorCodes.SCHEMA_ELEM$REF_FEATURES, new Object[]{"<simpleType>"}, xsdElt.getSimpleType());
                 // recovery: let the name go through anyway.
             }
 
-            if (xsdElt.getComplexType() != null)
-            {
-                state.error(XmlErrorCodes.SCHEMA_ELEM$REF_FEATURES, new Object[] { "<complexType>" }, xsdElt.getComplexType());
+            if (xsdElt.getComplexType() != null) {
+                state.error(XmlErrorCodes.SCHEMA_ELEM$REF_FEATURES, new Object[]{"<complexType>"}, xsdElt.getComplexType());
                 // recovery: let the name go through anyway.
             }
 
-            if (xsdElt.getForm() != null)
-            {
-                state.error(XmlErrorCodes.SCHEMA_ELEM$REF_FEATURES, new Object[] { "form" }, xsdElt.xgetForm());
+            if (xsdElt.getForm() != null) {
+                state.error(XmlErrorCodes.SCHEMA_ELEM$REF_FEATURES, new Object[]{"form"}, xsdElt.xgetForm());
                 // recovery: let the name go through anyway.
             }
 
-            if (xsdElt.sizeOfKeyArray() > 0)
-            {
-                state.warning(XmlErrorCodes.SCHEMA_ELEM$REF_FEATURES, new Object[] { "<key>" }, xsdElt);
+            if (xsdElt.sizeOfKeyArray() > 0) {
+                state.warning(XmlErrorCodes.SCHEMA_ELEM$REF_FEATURES, new Object[]{"<key>"}, xsdElt);
                 // recovery: ignore
             }
 
-            if (xsdElt.sizeOfKeyrefArray() > 0)
-            {
-                state.warning(XmlErrorCodes.SCHEMA_ELEM$REF_FEATURES, new Object[] { "<keyref>" }, xsdElt);
+            if (xsdElt.sizeOfKeyrefArray() > 0) {
+                state.warning(XmlErrorCodes.SCHEMA_ELEM$REF_FEATURES, new Object[]{"<keyref>"}, xsdElt);
                 // recovery: ignore
             }
 
-            if (xsdElt.sizeOfUniqueArray() > 0)
-            {
-                state.warning(XmlErrorCodes.SCHEMA_ELEM$REF_FEATURES, new Object[] { "<unique>" }, xsdElt);
+            if (xsdElt.sizeOfUniqueArray() > 0) {
+                state.warning(XmlErrorCodes.SCHEMA_ELEM$REF_FEATURES, new Object[]{"<unique>"}, xsdElt);
                 // recovery: ignore
             }
 
-            if (xsdElt.isSetDefault())
-            {
-                state.warning(XmlErrorCodes.SCHEMA_ELEM$REF_FEATURES, new Object[] { "default" }, xsdElt.xgetDefault());
+            if (xsdElt.isSetDefault()) {
+                state.warning(XmlErrorCodes.SCHEMA_ELEM$REF_FEATURES, new Object[]{"default"}, xsdElt.xgetDefault());
                 // recovery: ignore
             }
 
-            if (xsdElt.isSetFixed())
-            {
-                state.warning(XmlErrorCodes.SCHEMA_ELEM$REF_FEATURES, new Object[] { "fixed" }, xsdElt.xgetFixed());
+            if (xsdElt.isSetFixed()) {
+                state.warning(XmlErrorCodes.SCHEMA_ELEM$REF_FEATURES, new Object[]{"fixed"}, xsdElt.xgetFixed());
                 // recovery: ignore
             }
 
-            if (xsdElt.isSetBlock())
-            {
-                state.warning(XmlErrorCodes.SCHEMA_ELEM$REF_FEATURES, new Object[] { "block" }, xsdElt.xgetBlock());
+            if (xsdElt.isSetBlock()) {
+                state.warning(XmlErrorCodes.SCHEMA_ELEM$REF_FEATURES, new Object[]{"block"}, xsdElt.xgetBlock());
                 // recovery: ignore
             }
 
-            if (xsdElt.isSetNillable())
-            {
-                state.warning(XmlErrorCodes.SCHEMA_ELEM$REF_FEATURES, new Object[] { "nillable" }, xsdElt.xgetNillable());
+            if (xsdElt.isSetNillable()) {
+                state.warning(XmlErrorCodes.SCHEMA_ELEM$REF_FEATURES, new Object[]{"nillable"}, xsdElt.xgetNillable());
                 // recovery: ignore
             }
 
-            assert(xsdElt instanceof LocalElement);
+            assert (xsdElt instanceof LocalElement);
             SchemaGlobalElement referenced = state.findGlobalElement(ref, chameleon ? targetNamespace : null, targetNamespace);
-            if (referenced == null)
-            {
+            if (referenced == null) {
                 state.notFoundError(ref, SchemaType.ELEMENT, xsdElt.xgetRef(), true);
                 // recovery: ignore this element
                 return null;
@@ -1002,7 +850,7 @@
             SchemaLocalElementImpl target = new SchemaLocalElementImpl();
             target.setParticleType(SchemaParticle.ELEMENT);
             target.setUserData(getUserData(xsdElt));
-            copyGlobalElementToLocalElement( referenced, target );
+            copyGlobalElementToLocalElement(referenced, target);
             return target;
         }
 
@@ -1010,48 +858,43 @@
         SchemaLocalElementImpl impl;
         SchemaType sType = null;
 
-        if (xsdElt instanceof LocalElement)
-        {
+        if (xsdElt instanceof LocalElement) {
             impl = new SchemaLocalElementImpl();
-            boolean qualified = false; // default
+            boolean qualified;
             FormChoice form = xsdElt.xgetForm();
-            if (form != null)
+            if (form != null) {
                 qualified = form.getStringValue().equals(FORM_QUALIFIED);
-            else if (elemFormDefault != null)
+            } else if (elemFormDefault != null) {
                 qualified = elemFormDefault.equals(FORM_QUALIFIED);
-            else
-            {
+            } else {
                 form = findElementFormDefault(xsdElt);
                 qualified = form != null && form.getStringValue().equals(FORM_QUALIFIED);
             }
 
             qname = qualified ? QNameHelper.forLNS(name, targetNamespace) : QNameHelper.forLN(name);
-        }
-        else
-        {
+        } else {
             SchemaGlobalElementImpl gelt = new SchemaGlobalElementImpl(state.getContainer(targetNamespace));
             impl = gelt;
 
             // Set subst group head
-            if (sgHead != null)
-            {
+            if (sgHead != null) {
                 SchemaGlobalElementImpl head = state.findGlobalElement(xsdElt.getSubstitutionGroup(), chameleon ? targetNamespace : null, targetNamespace);
-                if (head != null)
+                if (head != null) {
                     gelt.setSubstitutionGroup(head.getRef());
+                }
             }
 
             // Set subst group members
             qname = QNameHelper.forLNS(name, targetNamespace);
-            SchemaTypeImpl docType = (SchemaTypeImpl)outerType;
+            SchemaTypeImpl docType = (SchemaTypeImpl) outerType;
 
             QName[] sgMembers = docType.getSubstitutionGroupMembers();
             QNameSetBuilder transitionRules = new QNameSetBuilder();
             transitionRules.add(qname);
 
-            for (int i = 0 ; i < sgMembers.length ; i++)
-            {
-                gelt.addSubstitutionGroupMember(sgMembers[i]);
-                transitionRules.add(sgMembers[i]);
+            for (QName sgMember : sgMembers) {
+                gelt.addSubstitutionGroupMember(sgMember);
+                transitionRules.add(sgMember);
             }
 
             impl.setTransitionRules(QNameSet.forSpecification(transitionRules), false);
@@ -1060,19 +903,18 @@
             boolean finalExt = false;
             boolean finalRest = false;
             Object ds = xsdElt.getFinal();
-            if (ds != null)
-            {
-                if (ds instanceof String && ds.equals("#all"))
-                {
+            if (ds != null) {
+                if (ds instanceof String && ds.equals("#all")) {
                     // #ALL value
                     finalExt = finalRest = true;
-                }
-                else if (ds instanceof List)
-                {
-                    if (((List)ds).contains("extension"))
+                } else if (ds instanceof List) {
+                    List<?> dsList = (List<?>) ds;
+                    if (dsList.contains("extension")) {
                         finalExt = true;
-                    if (((List)ds).contains("restriction"))
+                    }
+                    if (dsList.contains("restriction")) {
                         finalRest = true;
+                    }
                 }
             }
 
@@ -1085,94 +927,86 @@
         SchemaAnnotationImpl ann = SchemaAnnotationImpl.getAnnotation(state.getContainer(targetNamespace), xsdElt);
         impl.setAnnotation(ann);
         impl.setUserData(getUserData(xsdElt));
-        if (xsdElt.getType() != null)
-        {
-            sType = state.findGlobalType(xsdElt.getType(), chameleon ? targetNamespace : null, targetNamespace );
-            if (sType == null)
+        if (xsdElt.getType() != null) {
+            sType = state.findGlobalType(xsdElt.getType(), chameleon ? targetNamespace : null, targetNamespace);
+            if (sType == null) {
                 state.notFoundError(xsdElt.getType(), SchemaType.TYPE, xsdElt.xgetType(), true);
+            }
         }
 
         boolean simpleTypedef = false;
         Annotated typedef = xsdElt.getComplexType();
-        if (typedef == null)
-        {
+        if (typedef == null) {
             typedef = xsdElt.getSimpleType();
             simpleTypedef = true;
         }
 
-        if ((sType != null) && typedef != null)
-        {
+        if ((sType != null) && typedef != null) {
             state.error(XmlErrorCodes.SCHEMA_ELEM$TYPE_ATTR_OR_NESTED_TYPE, null, typedef);
             typedef = null;
         }
 
-        if (typedef != null)
-        {
+        if (typedef != null) {
             Object[] grps = state.getCurrentProcessing();
             QName[] context = new QName[grps.length];
-            for (int i = 0; i < context.length; i++)
-                if (grps[i] instanceof SchemaModelGroupImpl)
-                    context[i] = ((SchemaModelGroupImpl ) grps[i]).getName();
-            SchemaType repeat = checkRecursiveGroupReference(context, qname, (SchemaTypeImpl)outerType);
-            if (repeat != null)
+            for (int i = 0; i < context.length; i++) {
+                if (grps[i] instanceof SchemaModelGroupImpl) {
+                    context[i] = ((SchemaModelGroupImpl) grps[i]).getName();
+                }
+            }
+            SchemaType repeat = checkRecursiveGroupReference(context, qname, (SchemaTypeImpl) outerType);
+            if (repeat != null) {
                 sType = repeat;
-            else
-            {
-            SchemaTypeImpl sTypeImpl = new SchemaTypeImpl(state.getContainer(targetNamespace));
-            sType = sTypeImpl;
-            sTypeImpl.setContainerField(impl);
-            sTypeImpl.setOuterSchemaTypeRef(outerType == null ? null : outerType.getRef());
-            sTypeImpl.setGroupReferenceContext(context);
-            // leave the anonymous type unresolved: it will be resolved later.
-            anonymousTypes.add(sType);
-            sTypeImpl.setSimpleType(simpleTypedef);
-            sTypeImpl.setParseContext(typedef, targetNamespace, chameleon,
-                 elemFormDefault, attFormDefault, false);
-            sTypeImpl.setAnnotation(SchemaAnnotationImpl.getAnnotation(state.getContainer(targetNamespace), typedef));
-            sTypeImpl.setUserData(getUserData(typedef));
+            } else {
+                SchemaTypeImpl sTypeImpl = new SchemaTypeImpl(state.getContainer(targetNamespace));
+                sType = sTypeImpl;
+                sTypeImpl.setContainerField(impl);
+                sTypeImpl.setOuterSchemaTypeRef(outerType == null ? null : outerType.getRef());
+                sTypeImpl.setGroupReferenceContext(context);
+                // leave the anonymous type unresolved: it will be resolved later.
+                anonymousTypes.add(sType);
+                sTypeImpl.setSimpleType(simpleTypedef);
+                sTypeImpl.setParseContext(typedef, targetNamespace, chameleon,
+                    elemFormDefault, attFormDefault, false);
+                sTypeImpl.setAnnotation(SchemaAnnotationImpl.getAnnotation(state.getContainer(targetNamespace), typedef));
+                sTypeImpl.setUserData(getUserData(typedef));
             }
         }
 
-        if (sType == null)
-        {
+        if (sType == null) {
             // type may inherit from substitution group head
-            if (sgHead != null)
-            {
+            if (sgHead != null) {
                 SchemaGlobalElement head = state.findGlobalElement(xsdElt.getSubstitutionGroup(), chameleon ? targetNamespace : null, targetNamespace);
 
                 // Bug - Do I need to copy the type if it's anonymous?
                 // If element does not exist, error has already been reported
-                if (head != null)
+                if (head != null) {
                     sType = head.getType();
+                }
             }
 
         }
 
 
-
-        if (sType == null)
+        if (sType == null) {
             sType = BuiltinSchemaTypeSystem.ST_ANY_TYPE;
+        }
 
         SOAPArrayType wat = null;
         XmlCursor c = xsdElt.newCursor();
         String arrayType = c.getAttributeText(WSDL_ARRAYTYPE_NAME);
         c.dispose();
-        if (arrayType != null)
-        {
-            try
-            {
+        if (arrayType != null) {
+            try {
                 wat = new SOAPArrayType(arrayType, new NamespaceContext(xsdElt));
-            }
-            catch (XmlValueOutOfRangeException e)
-            {
-                state.error(XmlErrorCodes.SOAPARRAY, new Object[] {arrayType}, xsdElt);
+            } catch (XmlValueOutOfRangeException e) {
+                state.error(XmlErrorCodes.SOAPARRAY, new Object[]{arrayType}, xsdElt);
             }
         }
         impl.setWsdlArrayType(wat);
 
         boolean isFixed = xsdElt.isSetFixed();
-        if (xsdElt.isSetDefault() && isFixed)
-        {
+        if (xsdElt.isSetDefault() && isFixed) {
             state.error(XmlErrorCodes.SCHEMA_ELEM$DEFAULT_OR_FIXED, null, xsdElt.xgetFixed());
             // recovery: ignore fixed
             isFixed = false;
@@ -1187,21 +1021,21 @@
         boolean blockRest = false;
         boolean blockSubst = false;
 
-        if (block != null)
-        {
-            if (block instanceof String && block.equals("#all"))
-            {
+        if (block != null) {
+            if (block instanceof String && block.equals("#all")) {
                 // #ALL value
                 blockExt = blockRest = blockSubst = true;
-            }
-            else if (block instanceof List)
-            {
-                if (((List)block).contains("extension"))
+            } else if (block instanceof List) {
+                List<?> blockList = (List<?>) block;
+                if (blockList.contains("extension")) {
                     blockExt = true;
-                if (((List)block).contains("restriction"))
+                }
+                if (blockList.contains("restriction")) {
                     blockRest = true;
-                if (((List)block).contains("substitution"))
+                }
+                if (blockList.contains("substitution")) {
                     blockSubst = true;
+                }
             }
         }
 
@@ -1217,39 +1051,42 @@
 
         // Handle key constraints
         Keybase[] keys = xsdElt.getKeyArray();
-        for (int i = 0 ; i < keys.length ; i++, cur++) {
+        for (int i = 0; i < keys.length; i++, cur++) {
             constraints[cur] = translateIdentityConstraint(keys[i], targetNamespace, chameleon);
-            if (constraints[cur] != null)
+            if (constraints[cur] != null) {
                 constraints[cur].setConstraintCategory(SchemaIdentityConstraint.CC_KEY);
-            else
+            } else {
                 constraintFailed = true;
+            }
         }
 
         // Handle unique constraints
         Keybase[] uc = xsdElt.getUniqueArray();
-        for (int i = 0 ; i < uc.length ; i++, cur++) {
+        for (int i = 0; i < uc.length; i++, cur++) {
             constraints[cur] = translateIdentityConstraint(uc[i], targetNamespace, chameleon);
-            if (constraints[cur] != null)
+            if (constraints[cur] != null) {
                 constraints[cur].setConstraintCategory(SchemaIdentityConstraint.CC_UNIQUE);
-            else
+            } else {
                 constraintFailed = true;
+            }
         }
 
         // Handle keyref constraints
         KeyrefDocument.Keyref[] krs = xsdElt.getKeyrefArray();
-        for (int i = 0 ; i < krs.length ; i++, cur++) {
+        for (int i = 0; i < krs.length; i++, cur++) {
             constraints[cur] = translateIdentityConstraint(krs[i], targetNamespace, chameleon);
-            if (constraints[cur] != null)
+            if (constraints[cur] != null) {
                 constraints[cur].setConstraintCategory(SchemaIdentityConstraint.CC_KEYREF);
-            else
+            } else {
                 constraintFailed = true;
+            }
         }
 
-        if (!constraintFailed)
-        {
+        if (!constraintFailed) {
             SchemaIdentityConstraint.Ref[] refs = new SchemaIdentityConstraint.Ref[length];
-            for (int i = 0 ; i < refs.length ; i++)
+            for (int i = 0; i < refs.length; i++) {
                 refs[i] = constraints[i].getRef();
+            }
 
             impl.setIdentityConstraints(refs);
         }
@@ -1260,13 +1097,13 @@
     /**
      * We need to do this because of the following kind of Schemas:
      * <xs:group name="e">
-     *     <xs:sequence>
-     *         <xs:element name="error">
-     *             <xs:complexType>
-     *                 <xs:group ref="e"/>
-     *             </xs:complexType>
-     *         </xs:element>
-     *     </xs:sequence>
+     * <xs:sequence>
+     * <xs:element name="error">
+     * <xs:complexType>
+     * <xs:group ref="e"/>
+     * </xs:complexType>
+     * </xs:element>
+     * </xs:sequence>
      * </xs:group>
      * (see JIRA bug XMLBEANS-35)
      * Even though this should not be allowed because it produces an infinite
@@ -1280,32 +1117,31 @@
      * and if the same pattern is about to repeat, it means that we are in a
      * case similar to the above.
      */
-    private static SchemaType checkRecursiveGroupReference(QName[] context, QName containingElement, SchemaTypeImpl outerType)
-    {
-        if (context.length < 1)
+    private static SchemaType checkRecursiveGroupReference(QName[] context, QName containingElement, SchemaTypeImpl outerType) {
+        if (context.length < 1) {
             return null;
+        }
         SchemaTypeImpl type = outerType;
 
-        while (type != null)
-        {
-            if (type.getName() != null || type.isDocumentType())
+        while (type != null) {
+            if (type.getName() != null || type.isDocumentType()) {
                 return null; // not anonymous
-            if (containingElement.equals(type.getContainerField().getName()))
-            {
+            }
+            if (containingElement.equals(type.getContainerField().getName())) {
                 QName[] outerContext = type.getGroupReferenceContext();
-                if (outerContext != null && outerContext.length == context.length)
-                {
+                if (outerContext != null && outerContext.length == context.length) {
                     // Smells like trouble
                     boolean equal = true;
-                    for (int i = 0; i < context.length; i++)
+                    for (int i = 0; i < context.length; i++) {
                         if (!(context[i] == null && outerContext[i] == null ||
-                              context[i] != null && context[i].equals(outerContext[i])))
-                        {
+                              context[i] != null && context[i].equals(outerContext[i]))) {
                             equal = false;
                             break;
                         }
-                    if (equal)
+                    }
+                    if (equal) {
                         return type;
+                    }
                 }
             }
             type = (SchemaTypeImpl) type.getOuterType();
@@ -1313,14 +1149,13 @@
         return null;
     }
 
-    private static String removeWhitespace(String xpath)
-    {
+    private static String removeWhitespace(String xpath) {
         StringBuilder sb = new StringBuilder();
-        for (int i = 0; i < xpath.length(); i++)
-        {
+        for (int i = 0; i < xpath.length(); i++) {
             char ch = xpath.charAt(i);
-            if (XMLChar.isSpace(ch))
+            if (XMLChar.isSpace(ch)) {
                 continue;
+            }
             sb.append(ch);
         }
         return sb.toString();
@@ -1328,40 +1163,35 @@
 
     public static final org.apache.xmlbeans.impl.regex.RegularExpression XPATH_REGEXP = new org.apache.xmlbeans.impl.regex.RegularExpression("(\\.//)?((((child::)?((\\i\\c*:)?(\\i\\c*|\\*)))|\\.)/)*((((child::)?((\\i\\c*:)?(\\i\\c*|\\*)))|\\.)|((attribute::|@)((\\i\\c*:)?(\\i\\c*|\\*))))(\\|(\\.//)?((((child::)?((\\i\\c*:)?(\\i\\c*|\\*)))|\\.)/)*((((child::)?((\\i\\c*:)?(\\i\\c*|\\*)))|\\.)|((attribute::|@)((\\i\\c*:)?(\\i\\c*|\\*)))))*", "X");
 
-    private static boolean checkXPathSyntax(String xpath)
-    {
-        if (xpath == null)
+    private static boolean checkXPathSyntax(String xpath) {
+        if (xpath == null) {
             return false;
+        }
 
         // strip whitespace from xpath
         xpath = removeWhitespace(xpath);
 
         // apply regexp
-        synchronized (XPATH_REGEXP)
-        {
+        synchronized (XPATH_REGEXP) {
             return (XPATH_REGEXP.matches(xpath));
         }
     }
 
     private static SchemaIdentityConstraintImpl translateIdentityConstraint(Keybase parseIC,
-        String targetNamespace, boolean chameleon)
-    {
+                                                                            String targetNamespace, boolean chameleon) {
         StscState state = StscState.get();
 
         // first do some checking
         String selector = parseIC.getSelector() == null ? null : parseIC.getSelector().getXpath();
-        if (!checkXPathSyntax(selector))
-        {
-            state.error(XmlErrorCodes.SELECTOR_XPATH, new Object[] { selector }, parseIC.getSelector().xgetXpath());
+        if (!checkXPathSyntax(selector)) {
+            state.error(XmlErrorCodes.SELECTOR_XPATH, new Object[]{selector}, parseIC.getSelector().xgetXpath());
             return null;
         }
 
         FieldDocument.Field[] fieldElts = parseIC.getFieldArray();
-        for (int j = 0; j < fieldElts.length; j++)
-        {
-            if (!checkXPathSyntax(fieldElts[j].getXpath()))
-            {
-                state.error(XmlErrorCodes.FIELDS_XPATH, new Object[] { fieldElts[j].getXpath() }, fieldElts[j].xgetXpath());
+        for (FieldDocument.Field fieldElt : fieldElts) {
+            if (!checkXPathSyntax(fieldElt.getXpath())) {
+                state.error(XmlErrorCodes.FIELDS_XPATH, new Object[]{fieldElt.getXpath()}, fieldElt.xgetXpath());
                 return null;
             }
         }
@@ -1377,7 +1207,7 @@
 
         // Set the ns map
         XmlCursor c = parseIC.newCursor();
-        Map nsMap = new HashMap();
+        Map<String, String> nsMap = new HashMap<>();
 
         c.getAllNamespaces(nsMap);
         nsMap.remove(""); // Remove the default mapping. This cannot be used by the xpath expressions.
@@ -1385,15 +1215,15 @@
         c.dispose();
 
         String[] fields = new String[fieldElts.length];
-        for (int j = 0 ; j < fields.length ; j++)
+        for (int j = 0; j < fields.length; j++) {
             fields[j] = fieldElts[j].getXpath();
+        }
         ic.setFields(fields);
 
         try {
             ic.buildPaths();
-        }
-        catch (XPath.XPathCompileException e) {
-            state.error(XmlErrorCodes.INVALID_XPATH, new Object[] { e.getMessage() }, parseIC);
+        } catch (XPath.XPathCompileException e) {
+            state.error(XmlErrorCodes.INVALID_XPATH, new Object[]{e.getMessage()}, parseIC);
             return null;
         }
 
@@ -1404,12 +1234,10 @@
 
     }
 
-    public static SchemaModelGroupImpl translateModelGroup(NamedGroup namedGroup, String targetNamespace, boolean chameleon, boolean redefinition)
-    {
+    public static SchemaModelGroupImpl translateModelGroup(NamedGroup namedGroup, String targetNamespace, boolean chameleon, boolean redefinition) {
         String name = namedGroup.getName();
-        if (name == null)
-        {
-            StscState.get().error(XmlErrorCodes.MISSING_NAME, new Object[] { "model group" }, namedGroup);
+        if (name == null) {
+            StscState.get().error(XmlErrorCodes.MISSING_NAME, new Object[]{"model group"}, namedGroup);
             return null;
         }
         SchemaContainer c = StscState.get().getContainer(targetNamespace);
@@ -1425,12 +1253,10 @@
         return result;
     }
 
-    public static SchemaAttributeGroupImpl translateAttributeGroup(AttributeGroup attrGroup, String targetNamespace, boolean chameleon, boolean redefinition)
-    {
+    public static SchemaAttributeGroupImpl translateAttributeGroup(AttributeGroup attrGroup, String targetNamespace, boolean chameleon, boolean redefinition) {
         String name = attrGroup.getName();
-        if (name == null)
-        {
-            StscState.get().error(XmlErrorCodes.MISSING_NAME, new Object[] { "attribute group" }, attrGroup);
+        if (name == null) {
+            StscState.get().error(XmlErrorCodes.MISSING_NAME, new Object[]{"attribute group"}, attrGroup);
             return null;
         }
         SchemaContainer c = StscState.get().getContainer(targetNamespace);
@@ -1444,43 +1270,41 @@
         return result;
     }
 
-    static FormChoice findAttributeFormDefault(XmlObject obj)
-    {
+    static FormChoice findAttributeFormDefault(XmlObject obj) {
         XmlCursor cur = obj.newCursor();
-        while (cur.getObject().schemaType() != Schema.type)
-            if (!cur.toParent())
+        while (cur.getObject().schemaType() != Schema.type) {
+            if (!cur.toParent()) {
                 return null;
-        return ((Schema)cur.getObject()).xgetAttributeFormDefault();
+            }
+        }
+        return ((Schema) cur.getObject()).xgetAttributeFormDefault();
     }
 
     static SchemaLocalAttributeImpl translateAttribute(
         Attribute xsdAttr, String targetNamespace, String formDefault, boolean chameleon,
-        List anonymousTypes, SchemaType outerType, SchemaAttributeModel baseModel,
-        boolean local)
-    {
+        List<SchemaType> anonymousTypes, SchemaType outerType, SchemaAttributeModel baseModel,
+        boolean local) {
         StscState state = StscState.get();
 
         String name = xsdAttr.getName();
         QName ref = xsdAttr.getRef();
 
-        if (ref != null && name != null)
-        {
-            if (name.equals(ref.getLocalPart()) && uriMatch(targetNamespace, ref.getNamespaceURI()))
-                state.warning(XmlErrorCodes.SCHEMA_ATTR$REF_OR_NAME_HAS_BOTH, new Object[] { name }, xsdAttr.xgetRef());
-            else
-                state.error(XmlErrorCodes.SCHEMA_ATTR$REF_OR_NAME_HAS_BOTH, new Object[] { name }, xsdAttr.xgetRef());
+        if (ref != null && name != null) {
+            if (name.equals(ref.getLocalPart()) && uriMatch(targetNamespace, ref.getNamespaceURI())) {
+                state.warning(XmlErrorCodes.SCHEMA_ATTR$REF_OR_NAME_HAS_BOTH, new Object[]{name}, xsdAttr.xgetRef());
+            } else {
+                state.error(XmlErrorCodes.SCHEMA_ATTR$REF_OR_NAME_HAS_BOTH, new Object[]{name}, xsdAttr.xgetRef());
+            }
             // ignore name
             name = null;
         }
-        if (ref == null && name == null)
-        {
+        if (ref == null && name == null) {
             state.error(XmlErrorCodes.SCHEMA_ATTR$REF_OR_NAME_HAS_NEITHER, null, xsdAttr);
             // recovery: ignore this element
             return null;
         }
-        if (name != null && !XMLChar.isValidNCName(name))
-        {
-            state.error(XmlErrorCodes.INVALID_VALUE, new Object[] { name, "name" }, xsdAttr.xgetName());
+        if (name != null && !XMLChar.isValidNCName(name)) {
+            state.error(XmlErrorCodes.INVALID_VALUE, new Object[]{name, "name"}, xsdAttr.xgetName());
             // recovery: let the name go through anyway.
         }
 
@@ -1492,37 +1316,31 @@
         SchemaType sType = null;
         int use = SchemaLocalAttribute.OPTIONAL;
 
-        if (local)
+        if (local) {
             sAttr = new SchemaLocalAttributeImpl();
-        else
-        {
-            sAttr = new SchemaGlobalAttributeImpl(state.get().getContainer(targetNamespace));
-            ((SchemaGlobalAttributeImpl)sAttr).setParseContext(xsdAttr, targetNamespace, chameleon);
+        } else {
+            sAttr = new SchemaGlobalAttributeImpl(StscState.get().getContainer(targetNamespace));
+            ((SchemaGlobalAttributeImpl) sAttr).setParseContext(xsdAttr, targetNamespace, chameleon);
         }
 
-        if (ref != null)
-        {
-            if (xsdAttr.getType() != null)
-            {
-                state.error(XmlErrorCodes.SCHEMA_ATTR$REF_FEATURES, new Object[] { "type" }, xsdAttr.xgetType());
+        if (ref != null) {
+            if (xsdAttr.getType() != null) {
+                state.error(XmlErrorCodes.SCHEMA_ATTR$REF_FEATURES, new Object[]{"type"}, xsdAttr.xgetType());
                 // recovery: ignore type, simpleType
             }
 
-            if (xsdAttr.getSimpleType() != null)
-            {
-                state.error(XmlErrorCodes.SCHEMA_ATTR$REF_FEATURES, new Object[] { "<simpleType>" }, xsdAttr.getSimpleType());
+            if (xsdAttr.getSimpleType() != null) {
+                state.error(XmlErrorCodes.SCHEMA_ATTR$REF_FEATURES, new Object[]{"<simpleType>"}, xsdAttr.getSimpleType());
                 // recovery: ignore type, simpleType
             }
 
-            if (xsdAttr.getForm() != null)
-            {
-                state.error(XmlErrorCodes.SCHEMA_ATTR$REF_FEATURES, new Object[] { "form" }, xsdAttr.xgetForm());
+            if (xsdAttr.getForm() != null) {
+                state.error(XmlErrorCodes.SCHEMA_ATTR$REF_FEATURES, new Object[]{"form"}, xsdAttr.xgetForm());
                 // recovery: ignore form
             }
 
             SchemaGlobalAttribute referenced = state.findGlobalAttribute(ref, chameleon ? targetNamespace : null, targetNamespace);
-            if (referenced == null)
-            {
+            if (referenced == null) {
                 state.notFoundError(ref, SchemaType.ATTRIBUTE, xsdAttr.xgetRef(), true);
                 // recovery: ignore this element
                 return null;
@@ -1532,63 +1350,53 @@
             use = referenced.getUse();
             sType = referenced.getType();
             deftext = referenced.getDefaultText();
-            if (deftext != null)
-            {
+            if (deftext != null) {
                 isFixed = referenced.isFixed();
-                if (isFixed)
+                if (isFixed) {
                     fmrfixedtext = deftext;
+                }
             }
-        }
-        else
-        {
-            if (local)
-            {
-                boolean qualified = false; // default
+        } else {
+            if (local) {
+                boolean qualified;
                 FormChoice form = xsdAttr.xgetForm();
-                if (form != null)
+                if (form != null) {
                     qualified = form.getStringValue().equals(FORM_QUALIFIED);
-                else if (formDefault != null)
+                } else if (formDefault != null) {
                     qualified = formDefault.equals(FORM_QUALIFIED);
-                else
-                {
+                } else {
                     form = findAttributeFormDefault(xsdAttr);
                     qualified = form != null && form.getStringValue().equals(FORM_QUALIFIED);
                 }
 
                 qname = qualified ? QNameHelper.forLNS(name, targetNamespace) : QNameHelper.forLN(name);
-            }
-            else
-            {
+            } else {
                 qname = QNameHelper.forLNS(name, targetNamespace);
             }
 
-            if (xsdAttr.getType() != null)
-            {
-                sType = state.findGlobalType(xsdAttr.getType(), chameleon ? targetNamespace : null, targetNamespace );
-                if (sType == null)
+            if (xsdAttr.getType() != null) {
+                sType = state.findGlobalType(xsdAttr.getType(), chameleon ? targetNamespace : null, targetNamespace);
+                if (sType == null) {
                     state.notFoundError(xsdAttr.getType(), SchemaType.TYPE, xsdAttr.xgetType(), true);
+                }
             }
 
-            if (qname.getNamespaceURI().equals("http://www.w3.org/2001/XMLSchema-instance"))
-            {
-                state.error(XmlErrorCodes.NO_XSI, new Object[] { "http://www.w3.org/2001/XMLSchema-instance" }, xsdAttr.xgetName());
+            if (qname.getNamespaceURI().equals("http://www.w3.org/2001/XMLSchema-instance")) {
+                state.error(XmlErrorCodes.NO_XSI, new Object[]{"http://www.w3.org/2001/XMLSchema-instance"}, xsdAttr.xgetName());
             }
 
-            if (qname.getNamespaceURI().length() == 0 && qname.getLocalPart().equals("xmlns"))
-            {
+            if (qname.getNamespaceURI().length() == 0 && qname.getLocalPart().equals("xmlns")) {
                 state.error(XmlErrorCodes.NO_XMLNS, null, xsdAttr.xgetName());
             }
 
             LocalSimpleType typedef = xsdAttr.getSimpleType();
 
-            if ((sType != null) && typedef != null)
-            {
+            if ((sType != null) && typedef != null) {
                 state.error(XmlErrorCodes.SCHEMA_ATTR$TYPE_ATTR_OR_NESTED_TYPE, null, typedef);
                 typedef = null;
             }
 
-            if (typedef != null)
-            {
+            if (typedef != null) {
                 SchemaTypeImpl sTypeImpl = new SchemaTypeImpl(state.getContainer(targetNamespace));
                 sType = sTypeImpl;
                 sTypeImpl.setContainerField(sAttr);
@@ -1601,39 +1409,39 @@
                 sTypeImpl.setUserData(getUserData(typedef));
             }
 
-            if (sType == null && baseModel != null && baseModel.getAttribute(qname) != null)
+            if (sType == null && baseModel != null && baseModel.getAttribute(qname) != null) {
                 sType = baseModel.getAttribute(qname).getType();
+            }
         }
 
-        if (sType == null)
+        if (sType == null) {
             sType = BuiltinSchemaTypeSystem.ST_ANY_SIMPLE;
+        }
 
-        if (!sType.isSimpleType())
-        {
+        if (!sType.isSimpleType()) {
             // KHK: which rule? could use #a-simple_type_definition
             state.error("Attributes must have a simple type (not complex).", XmlErrorCodes.INVALID_SCHEMA, xsdAttr);
             // recovery: switch to the any-type
             sType = BuiltinSchemaTypeSystem.ST_ANY_SIMPLE;
         }
 
-        if (xsdAttr.isSetUse())
-        {
+        if (xsdAttr.isSetUse()) {
             use = translateUseCode(xsdAttr.xgetUse());
 
             // ignore referenced default if no longer optional
-            if (use != SchemaLocalAttribute.OPTIONAL && !isFixed)
+            if (use != SchemaLocalAttribute.OPTIONAL && !isFixed) {
                 deftext = null;
+            }
         }
 
-        if (xsdAttr.isSetDefault() || xsdAttr.isSetFixed())
-        {
-            if (isFixed && !xsdAttr.isSetFixed())
+        if (xsdAttr.isSetDefault() || xsdAttr.isSetFixed()) {
+            if (isFixed && !xsdAttr.isSetFixed()) {
                 state.error("A use of a fixed attribute definition must also be fixed", XmlErrorCodes.REDUNDANT_DEFAULT_FIXED, xsdAttr.xgetFixed());
+            }
 
             isFixed = xsdAttr.isSetFixed();
 
-            if (xsdAttr.isSetDefault() && isFixed)
-            {
+            if (xsdAttr.isSetDefault() && isFixed) {
                 state.error(XmlErrorCodes.SCHEMA_ATTR$DEFAULT_OR_FIXED, null, xsdAttr.xgetFixed());
                 // recovery: ignore fixed
                 isFixed = false;
@@ -1641,32 +1449,26 @@
             deftext = isFixed ? xsdAttr.getFixed() : xsdAttr.getDefault();
             // BUGBUG(radup) this is not good, since they should be compared by value
             // in StscChecker; but there we don't have yet access to the referred attr
-            if (fmrfixedtext != null && !fmrfixedtext.equals(deftext))
-            {
+            if (fmrfixedtext != null && !fmrfixedtext.equals(deftext)) {
                 state.error(XmlErrorCodes.SCHEMA_ATTR$FIXED_NOT_MATCH, null, xsdAttr.xgetFixed());
                 // recovery: reset fixed to the original value
                 deftext = fmrfixedtext;
             }
         }
 
-        if (!local)
-        {
-            ((SchemaGlobalAttributeImpl)sAttr).setFilename(findFilename(xsdAttr));
+        if (!local) {
+            ((SchemaGlobalAttributeImpl) sAttr).setFilename(findFilename(xsdAttr));
         }
 
         SOAPArrayType wat = null;
         XmlCursor c = xsdAttr.newCursor();
         String arrayType = c.getAttributeText(WSDL_ARRAYTYPE_NAME);
         c.dispose();
-        if (arrayType != null)
-        {
-            try
-            {
+        if (arrayType != null) {
+            try {
                 wat = new SOAPArrayType(arrayType, new NamespaceContext(xsdAttr));
-            }
-            catch (XmlValueOutOfRangeException e)
-            {
-                state.error(XmlErrorCodes.SOAPARRAY, new Object[] {arrayType}, xsdAttr);
+            } catch (XmlValueOutOfRangeException e) {
+                state.error(XmlErrorCodes.SOAPARRAY, new Object[]{arrayType}, xsdAttr);
             }
         }
 
@@ -1681,40 +1483,39 @@
         return sAttr;
     }
 
-    static int translateUseCode(Attribute.Use attruse)
-    {
-        if (attruse == null)
+    static int translateUseCode(Attribute.Use attruse) {
+        if (attruse == null) {
             return SchemaLocalAttribute.OPTIONAL;
+        }
 
         String val = attruse.getStringValue();
-        if (val.equals("optional"))
+        if (val.equals("optional")) {
             return SchemaLocalAttribute.OPTIONAL;
-        if (val.equals("required"))
+        }
+        if (val.equals("required")) {
             return SchemaLocalAttribute.REQUIRED;
-        if (val.equals("prohibited"))
+        }
+        if (val.equals("prohibited")) {
             return SchemaLocalAttribute.PROHIBITED;
+        }
         return SchemaLocalAttribute.OPTIONAL;
     }
 
-    static BigInteger buildBigInt(XmlAnySimpleType value)
-    {
-        if (value == null)
+    static BigInteger buildBigInt(XmlAnySimpleType value) {
+        if (value == null) {
             return null;
+        }
         String text = value.getStringValue();
         BigInteger bigInt;
-        try
-        {
+        try {
             bigInt = new BigInteger(text);
-        }
-        catch (NumberFormatException e)
-        {
-            StscState.get().error(XmlErrorCodes.INVALID_VALUE_DETAIL, new Object[] { text, "nonNegativeInteger", e.getMessage() }, value);
+        } catch (NumberFormatException e) {
+            StscState.get().error(XmlErrorCodes.INVALID_VALUE_DETAIL, new Object[]{text, "nonNegativeInteger", e.getMessage()}, value);
             return null;
         }
 
-        if (bigInt.signum() < 0)
-        {
-            StscState.get().error(XmlErrorCodes.INVALID_VALUE, new Object[] { text, "nonNegativeInteger" }, value);
+        if (bigInt.signum() < 0) {
+            StscState.get().error(XmlErrorCodes.INVALID_VALUE, new Object[]{text, "nonNegativeInteger"}, value);
             return null;
         }
 
@@ -1722,60 +1523,50 @@
     }
 
 
-    static XmlNonNegativeInteger buildNnInteger(XmlAnySimpleType value)
-    {
+    static XmlNonNegativeInteger buildNnInteger(XmlAnySimpleType value) {
         BigInteger bigInt = buildBigInt(value);
-        try
-        {
+        try {
             XmlNonNegativeIntegerImpl i = new XmlNonNegativeIntegerImpl();
-            i.set(bigInt);
+            i.setBigIntegerValue(bigInt);
             i.setImmutable();
             return i;
-        }
-        catch (XmlValueOutOfRangeException e)
-        {
+        } catch (XmlValueOutOfRangeException e) {
             StscState.get().error("Internal error processing number", XmlErrorCodes.MALFORMED_NUMBER, value);
             return null;
         }
     }
 
-    static XmlPositiveInteger buildPosInteger(XmlAnySimpleType value)
-    {
+    static XmlPositiveInteger buildPosInteger(XmlAnySimpleType value) {
         BigInteger bigInt = buildBigInt(value);
-        try
-        {
+        try {
             XmlPositiveIntegerImpl i = new XmlPositiveIntegerImpl();
-            i.set(bigInt);
+            i.setBigIntegerValue(bigInt);
             i.setImmutable();
             return i;
-        }
-        catch (XmlValueOutOfRangeException e)
-        {
+        } catch (XmlValueOutOfRangeException e) {
             StscState.get().error("Internal error processing number", XmlErrorCodes.MALFORMED_NUMBER, value);
             return null;
         }
     }
 
 
-    private static Object getUserData(XmlObject pos)
-    {
+    private static Object getUserData(XmlObject pos) {
         XmlCursor.XmlBookmark b = pos.newCursor().getBookmark(SchemaBookmark.class);
-        if (b != null && b instanceof SchemaBookmark)
+        if (b instanceof SchemaBookmark) {
             return ((SchemaBookmark) b).getValue();
-        else
+        } else {
             return null;
+        }
     }
 
-    private static boolean isEmptySchema(Schema schema)
-    {
+    private static boolean isEmptySchema(Schema schema) {
         XmlCursor cursor = schema.newCursor();
         boolean result = !cursor.toFirstChild();
         cursor.dispose();
         return result;
     }
 
-    private static boolean isReservedTypeName(QName name)
-    {
+    private static boolean isReservedTypeName(QName name) {
         return (BuiltinSchemaTypeSystem.get().findType(name) != null);
     }
 }
diff --git a/src/main/java/org/apache/xmlbeans/impl/store/Cur.java b/src/main/java/org/apache/xmlbeans/impl/store/Cur.java
index 5721fc8..66b3665 100755
--- a/src/main/java/org/apache/xmlbeans/impl/store/Cur.java
+++ b/src/main/java/org/apache/xmlbeans/impl/store/Cur.java
@@ -145,8 +145,9 @@
     boolean isContainerOrFinish() {
         assert isPositioned();
 
-        if (_pos != 0 && _pos != END_POS)
+        if (_pos != 0 && _pos != END_POS) {
             return false;
+        }
 
         int kind = _xobj.kind();
         return kind == ELEM || kind == -ELEM || kind == ROOT || kind == -ROOT;
@@ -248,36 +249,60 @@
     static Xobj createDomDocumentRootXobj(Locale l, boolean fragment) {
         Xobj xo;
 
-        if (l._saaj == null)
-            if (fragment)
+        if (l._saaj == null) {
+            if (fragment) {
                 xo = new DocumentFragXobj(l);
-            else
+            } else {
                 xo = new DocumentXobj(l);
-        else
+            }
+        } else {
             xo = new SoapPartDocXobj(l);
+        }
 
-        if (l._ownerDoc == null)
+        if (l._ownerDoc == null) {
             l._ownerDoc = xo.getDom();
+        }
 
         return xo;
     }
 
     static Xobj createElementXobj(Locale l, QName name, QName parentName) {
-        if (l._saaj == null)
+        if (l._saaj == null) {
             return new ElementXobj(l, name);
+        }
 
         Class c = l._saaj.identifyElement(name, parentName);
 
-        if (c == SOAPElement.class) return new SoapElementXobj(l, name);
-        if (c == SOAPBody.class) return new SoapBodyXobj(l, name);
-        if (c == SOAPBodyElement.class) return new SoapBodyElementXobj(l, name);
-        if (c == SOAPEnvelope.class) return new SoapEnvelopeXobj(l, name);
-        if (c == SOAPHeader.class) return new SoapHeaderXobj(l, name);
-        if (c == SOAPHeaderElement.class) return new SoapHeaderElementXobj(l, name);
-        if (c == SOAPFaultElement.class) return new SoapFaultElementXobj(l, name);
-        if (c == Detail.class) return new DetailXobj(l, name);
-        if (c == DetailEntry.class) return new DetailEntryXobj(l, name);
-        if (c == SOAPFault.class) return new SoapFaultXobj(l, name);
+        if (c == SOAPElement.class) {
+            return new SoapElementXobj(l, name);
+        }
+        if (c == SOAPBody.class) {
+            return new SoapBodyXobj(l, name);
+        }
+        if (c == SOAPBodyElement.class) {
+            return new SoapBodyElementXobj(l, name);
+        }
+        if (c == SOAPEnvelope.class) {
+            return new SoapEnvelopeXobj(l, name);
+        }
+        if (c == SOAPHeader.class) {
+            return new SoapHeaderXobj(l, name);
+        }
+        if (c == SOAPHeaderElement.class) {
+            return new SoapHeaderElementXobj(l, name);
+        }
+        if (c == SOAPFaultElement.class) {
+            return new SoapFaultElementXobj(l, name);
+        }
+        if (c == Detail.class) {
+            return new DetailXobj(l, name);
+        }
+        if (c == DetailEntry.class) {
+            return new DetailEntryXobj(l, name);
+        }
+        if (c == SOAPFault.class) {
+            return new SoapFaultXobj(l, name);
+        }
 
         throw new IllegalStateException("Unknown SAAJ element class: " + c);
     }
@@ -337,8 +362,9 @@
 
         // If in differnet locales, then can't comapre
 
-        if (_locale != that._locale)
+        if (_locale != that._locale) {
             return 2;
+        }
 
         // No need to denormalize, but I want positions which I can compare (no END_POS)
 
@@ -391,12 +417,12 @@
 
         while (dThis > dThat) {
             dThis--;
-            assert(xThis != null);
+            assert (xThis != null);
             xThis = xThis._parent;
         }
         while (dThat > dThis) {
             dThat--;
-            assert(xThat != null);
+            assert (xThat != null);
             xThat = xThat._parent;
         }
 
@@ -614,8 +640,9 @@
                 next[i] = before;
                 prev[before] = i;
 
-                if (head == before)
+                if (head == before) {
                     head = i;
+                }
             } else {
                 prev[i] = prev[head];
                 assert next[i] == NULL;
@@ -864,8 +891,9 @@
     boolean hasParent() {
         assert isPositioned();
 
-        if (_pos == END_POS || (_pos >= 1 && _pos < _xobj.posAfter()))
+        if (_pos == END_POS || (_pos >= 1 && _pos < _xobj.posAfter())) {
             return true;
+        }
 
         assert _pos == 0 || _xobj._parent != null;
 
@@ -875,13 +903,15 @@
     Xobj getParentNoRoot() {
         assert isPositioned();
 
-        if (_pos == END_POS || (_pos >= 1 && _pos < _xobj.posAfter()))
+        if (_pos == END_POS || (_pos >= 1 && _pos < _xobj.posAfter())) {
             return _xobj;
+        }
 
         assert _pos == 0 || _xobj._parent != null;
 
-        if (_xobj._parent != null)
+        if (_xobj._parent != null) {
             return _xobj._parent;
+        }
 
         return null;
     }
@@ -889,16 +919,19 @@
     Xobj getParent(boolean raw) {
         assert isPositioned();
 
-        if (_pos == END_POS || (_pos >= 1 && _pos < _xobj.posAfter()))
+        if (_pos == END_POS || (_pos >= 1 && _pos < _xobj.posAfter())) {
             return _xobj;
+        }
 
         assert _pos == 0 || _xobj._parent != null;
 
-        if (_xobj._parent != null)
+        if (_xobj._parent != null) {
             return _xobj._parent;
+        }
 
-        if (raw || _xobj.isRoot())
+        if (raw || _xobj.isRoot()) {
             return null;
+        }
 
         Cur r = _locale.tempCur();
 
@@ -916,8 +949,9 @@
     boolean toParent(boolean raw) {
         Xobj parent = getParent(raw);
 
-        if (parent == null)
+        if (parent == null) {
             return false;
+        }
 
         moveTo(parent);
 
@@ -967,8 +1001,9 @@
     boolean toFirstChild() {
         assert isNode();
 
-        if (!_xobj.hasChildren())
+        if (!_xobj.hasChildren()) {
             return false;
+        }
 
         for (Xobj x = _xobj._firstChild; ; x = x._nextSibling) {
             if (!x.isAttr()) {
@@ -981,8 +1016,9 @@
     protected boolean toLastChild() {
         assert isNode();
 
-        if (!_xobj.hasChildren())
+        if (!_xobj.hasChildren()) {
             return false;
+        }
 
         moveTo(_xobj._lastChild);
 
@@ -1015,8 +1051,9 @@
             prefixForNamespace(
                 ns, qname.getPrefix().length() > 0 ? qname.getPrefix() : null, true);
 
-        if (prefix.length() > 0)
+        if (prefix.length() > 0) {
             value = prefix + ":" + value;
+        }
 
         setValue(value);
     }
@@ -1042,10 +1079,11 @@
 
         if (toNextAttr()) {
             while (isAttr()) {
-                if (getName().equals(attrName))
+                if (getName().equals(attrName)) {
                     moveNode(null);
-                else if (!toNextAttr())
+                } else if (!toNextAttr()) {
                     break;
+                }
             }
         }
 
@@ -1103,8 +1141,9 @@
 
         Xobj a = _xobj.getAttr(name);
 
-        if (a == null)
+        if (a == null) {
             return false;
+        }
 
         moveTo(a);
 
@@ -1133,7 +1172,9 @@
         }
 
         //noinspection StatementWithEmptyBody
-        while (toNextAttr()) ;
+        while (toNextAttr()) {
+            ;
+        }
 
         return true;
     }
@@ -1198,16 +1239,19 @@
     boolean skip() {
         assert isNode();
 
-        if (_xobj.isRoot())
+        if (_xobj.isRoot()) {
             return false;
+        }
 
         if (_xobj.isAttr()) {
-            if (_xobj._nextSibling == null || !_xobj._nextSibling.isAttr())
+            if (_xobj._nextSibling == null || !_xobj._nextSibling.isAttr()) {
                 return false;
+            }
 
             moveTo(_xobj._nextSibling, 0);
-        } else
+        } else {
             moveTo(getNormal(_xobj, _xobj.posAfter()), _posTemp);
+        }
 
         return true;
     }
@@ -1408,13 +1452,15 @@
 
         int cchLeft = cchLeft();
 
-        if (cch < 0 || cch > cchLeft)
+        if (cch < 0 || cch > cchLeft) {
             cch = cchLeft;
+        }
 
         // Dang, I love this stmt :-)
 
-        if (cch != 0)
+        if (cch != 0) {
             moveTo(getNormal(getDenormal(), _posTemp - cch), _posTemp);
+        }
 
         return cch;
     }
@@ -1424,8 +1470,9 @@
 
         int cchRight = cchRight();
 
-        if (cchRight == 0)
+        if (cchRight == 0) {
             return 0;
+        }
 
         if (cch < 0 || cch >= cchRight) {
             // Use next to not skip over children
@@ -1447,13 +1494,15 @@
 
         assert !x.isRoot() || (p > 0 && p < x.posAfter());
 
-        if (p >= x.posAfter())
+        if (p >= x.posAfter()) {
             x._charNodesAfter = nodes;
-        else
+        } else {
             x._charNodesValue = nodes;
+        }
 
-        for (; nodes != null; nodes = nodes._next)
+        for (; nodes != null; nodes = nodes._next) {
             nodes.setDom((Dom) x);
+        }
 
         // No Need to notify text change or alter version, text nodes are
         // not part of the infoset
@@ -1554,8 +1603,9 @@
     }
 
     void insertString(String s) {
-        if (s != null)
+        if (s != null) {
             insertChars(s, 0, s.length());
+        }
     }
 
     void insertChars(Object src, int off, int cch) {
@@ -1564,8 +1614,9 @@
 
         // Check for nothing to insert
 
-        if (cch <= 0)
+        if (cch <= 0) {
             return;
+        }
 
         _locale.notifyChange();
 
@@ -1575,8 +1626,9 @@
         // insert in the value of the parent.  In the latter case, because the parent has a child,
         // it cannot be vacant.
 
-        if (_pos == END_POS)
+        if (_pos == END_POS) {
             _xobj.ensureOccupancy();
+        }
 
         // Get the denormailized Xobj and pos.  This is the Xobj which will actually receive
         // the new chars.  Note that a denormalized position can never be <= 0.
@@ -1609,8 +1661,9 @@
         assert cchMove <= 0 || cchMove <= cchRight();
         assert to == null || (to.isPositioned() && !to.isRoot());
 
-        if (cchMove < 0)
+        if (cchMove < 0) {
             cchMove = cchRight();
+        }
 
         // If we're instructed to move 0 characters, then return the null triple.
 
@@ -1689,10 +1742,11 @@
         //
         //if ( _xobj != null )
         {
-            if (to == null)
+            if (to == null) {
                 _xobj.removeCharsHelper(_pos, cchMove, null, NO_POS, false, true);
-            else
+            } else {
                 _xobj.removeCharsHelper(_pos, cchMove, to._xobj, to._pos, false, true);
+            }
         }
 
         // Need to update the position of this cursor even though it did not move anywhere.  This
@@ -1771,8 +1825,9 @@
             // a vacant node, I get it occupied.  I do not need to worry about the source being
             // vacant.
 
-            if (to._pos == END_POS)
+            if (to._pos == END_POS) {
                 to._xobj.ensureOccupancy();
+            }
 
             // See if the destination is on the edge of the node to be moved (a no-op).  It is
             // illegal to call this fcn when to is contained within the node to be moved.  Note
@@ -1804,14 +1859,16 @@
         // Node is going away.  Invalidate the parent (the text around the node is merging).
         // Also, this node may be an attribute -- invalidate special attrs ...
 
-        if (x.isAttr())
+        if (x.isAttr()) {
             x.invalidateSpecialAttr(to == null ? null : to.getParentRaw());
-        else {
-            if (x._parent != null)
+        } else {
+            if (x._parent != null) {
                 x._parent.invalidateUser();
+            }
 
-            if (to != null && to.hasParent())
+            if (to != null && to.hasParent()) {
                 to.getParent().invalidateUser();
+            }
         }
 
         // If there is any text after x, I move it to be before x.  This frees me to extract x
@@ -1870,16 +1927,18 @@
                 to.pop();
             }
 
-            if (append)
+            if (append) {
                 here.appendXobj(x);
-            else
+            } else {
                 here.insertXobj(x);
+            }
 
             // The only text I need to move is that to the right of "to".  Even considering all
             // the cases where an attribute is involed!
 
-            if (cchRight > 0)
+            if (cchRight > 0) {
                 transferChars(to._xobj, to._pos, x, x.posAfter(), cchRight);
+            }
 
             to.moveTo(x);
         }
@@ -1962,8 +2021,9 @@
 
             // TODO - shuffle interior curs?
 
-            if (isAtLeftEdge)
+            if (isAtLeftEdge) {
                 return;
+            }
 
             // Now, after dealing with the edge condition, I can assert that to is not inside x
 
@@ -1990,8 +2050,9 @@
             c.moveChars(to, -1);
             c.release();
 
-            if (to != null)
+            if (to != null) {
                 to.nextChars(valueMovedCch = c._cchSrc);
+            }
         }
 
         // Now, walk all the contents, invalidating special attrs, reportioning cursors,
@@ -2015,13 +2076,15 @@
                 y.invalidateSpecialAttr(to == null ? null : to.getParent());
             }
 
-            for (Cur c; (c = y._embedded) != null; )
+            for (Cur c; (c = y._embedded) != null; ) {
                 c.moveTo(x, END_POS);
+            }
 
             y.disconnectUser();
 
-            if (to != null)
+            if (to != null) {
                 y._locale = to._locale;
+            }
 
             sawBookmark = sawBookmark || y._bookmarks != null;
         }
@@ -2046,8 +2109,9 @@
         // invalidation needed.  If I've move text to "to" already, no need to invalidate
         // again.
 
-        if (!lastToMove.isAttr())
+        if (!lastToMove.isAttr()) {
             x.invalidateUser();
+        }
 
         x._locale._versionAll++;
         x._locale._versionSansText++;
@@ -2093,8 +2157,9 @@
             if (firstToMove.isAttr()) {
                 Xobj lastNewAttr = firstToMove;
 
-                while (lastNewAttr._nextSibling != null && lastNewAttr._nextSibling.isAttr())
+                while (lastNewAttr._nextSibling != null && lastNewAttr._nextSibling.isAttr()) {
                     lastNewAttr = lastNewAttr._nextSibling;
+                }
 
                 // Get to's parnet now before I potentially move him with the next transfer
 
@@ -2112,7 +2177,7 @@
                         cch = y._cchValue;
                     } else {
                         y = y.lastAttr();
-                        assert(y != null);
+                        assert (y != null);
                         p = y.posAfter();
                         cch = y._cchAfter;
                     }
@@ -2139,8 +2204,9 @@
 
         // If I consed up a to, release it here
 
-        if (surragateTo != null)
+        if (surragateTo != null) {
             surragateTo.release();
+        }
     }
 
     protected final Bookmark setBookmark(Object key, Object value) {
@@ -2154,9 +2220,11 @@
         assert isNormal();
         assert key != null;
 
-        for (Bookmark b = _xobj._bookmarks; b != null; b = b._next)
-            if (b._pos == _pos && b._key == key)
+        for (Bookmark b = _xobj._bookmarks; b != null; b = b._next) {
+            if (b._pos == _pos && b._key == key) {
                 return b._value;
+            }
+        }
 
         return null;
     }
@@ -2170,9 +2238,11 @@
         int d = -1;
 
         if (isText()) {
-            for (Bookmark b = _xobj._bookmarks; b != null; b = b._next)
-                if (b._key == key && inChars(b, cch, false))
+            for (Bookmark b = _xobj._bookmarks; b != null; b = b._next) {
+                if (b._key == key && inChars(b, cch, false)) {
                     d = (d == -1 || b._pos - _pos < d) ? b._pos - _pos : d;
+                }
+            }
         }
 
         return d;
@@ -2644,17 +2714,15 @@
             _lastXobj = _frontier;
             _lastPos = 0;
 
-            if (options.hasOption(XmlOptions.LOAD_REPLACE_DOCUMENT_ELEMENT)) {
-                _replaceDocElem = (QName) options.get(XmlOptions.LOAD_REPLACE_DOCUMENT_ELEMENT);
-                _discardDocElem = true;
-            }
+            _replaceDocElem = options.getLoadReplaceDocumentElement();
+            _discardDocElem = options.hasOption(XmlOptions.LOAD_REPLACE_DOCUMENT_ELEMENT);
 
-            _stripWhitespace = options.hasOption(XmlOptions.LOAD_STRIP_WHITESPACE);
-            _stripComments = options.hasOption(XmlOptions.LOAD_STRIP_COMMENTS);
-            _stripProcinsts = options.hasOption(XmlOptions.LOAD_STRIP_PROCINSTS);
+            _stripWhitespace = options.isSetLoadStripWhitespace();
+            _stripComments = options.isLoadStripComments();
+            _stripProcinsts = options.isLoadStripProcinsts();
 
-            _substituteNamespaces = (Map) options.get(XmlOptions.LOAD_SUBSTITUTE_NAMESPACES);
-            _additionalNamespaces = (Map) options.get(XmlOptions.LOAD_ADDITIONAL_NAMESPACES);
+            _substituteNamespaces = options.getLoadSubstituteNamespaces();
+            _additionalNamespaces = options.getLoadAdditionalNamespaces();
 
             _locale._versionAll++;
             _locale._versionSansText++;
@@ -2857,8 +2925,9 @@
         }
 
         protected void comment(String comment) {
-            if (!_stripComments)
+            if (!_stripComments) {
                 comment(comment, 0, comment.length());
+            }
             _stripLeft = true;
         }
 
@@ -2915,9 +2984,9 @@
         }
 
         protected void bookmarkLastNonAttr(XmlBookmark bm) {
-            if (_lastPos > 0 || !_lastXobj.isAttr())
+            if (_lastPos > 0 || !_lastXobj.isAttr()) {
                 _lastXobj.setBookmark(_lastPos, bm.getKey(), bm);
-            else {
+            } else {
                 assert _lastXobj._parent != null;
 
                 _lastXobj._parent.setBookmark(0, bm.getKey(), bm);
@@ -2955,8 +3024,9 @@
         protected Cur finish() {
             flushText();
 
-            if (_after)
+            if (_after) {
                 _frontier = _frontier._parent;
+            }
 
             assert _frontier != null && _frontier._parent == null && _frontier.isRoot();
 
@@ -2978,7 +3048,9 @@
                     // does not appear to have been the contents of the removed element.
 
                     //noinspection StatementWithEmptyBody
-                    while (c.toParent()) ;
+                    while (c.toParent()) {
+                        ;
+                    }
 
                     c.next();
 
@@ -3237,29 +3309,34 @@
     }
 
     private static void dumpXobj(PrintStream o, Xobj xo, int level, Object ref) {
-        if (xo == null)
+        if (xo == null) {
             return;
+        }
 
-        if (xo == ref)
+        if (xo == ref) {
             o.print("* ");
-        else
+        } else {
             o.print("  ");
+        }
 
-        for (int i = 0; i < level; i++)
+        for (int i = 0; i < level; i++) {
             o.print("  ");
+        }
 
         o.print(kindName(xo.kind()));
 
         if (xo._name != null) {
             o.print(" ");
 
-            if (xo._name.getPrefix().length() > 0)
+            if (xo._name.getPrefix().length() > 0) {
                 o.print(xo._name.getPrefix() + ":");
+            }
 
             o.print(xo._name.getLocalPart());
 
-            if (xo._name.getNamespaceURI().length() > 0)
+            if (xo._name.getNamespaceURI().length() > 0) {
                 o.print("@" + xo._name.getNamespaceURI());
+            }
         }
 
         if (xo._srcValue != null || xo._charNodesValue != null) {
@@ -3269,11 +3346,13 @@
             o.print(" )");
         }
 
-        if (xo._user != null)
+        if (xo._user != null) {
             o.print(" (USER)");
+        }
 
-        if (xo.isVacant())
+        if (xo.isVacant()) {
             o.print(" (VACANT)");
+        }
 
         if (xo._srcAfter != null || xo._charNodesAfter != null) {
             o.print(" After( ");
@@ -3294,8 +3373,9 @@
 
             i = className.lastIndexOf('$');
 
-            if (i > 0)
+            if (i > 0) {
                 className = className.substring(i + 1);
+            }
         }
 
         o.print(" (");
@@ -3304,8 +3384,9 @@
 
         o.println();
 
-        for (xo = xo._firstChild; xo != null; xo = xo._nextSibling)
+        for (xo = xo._firstChild; xo != null; xo = xo._nextSibling) {
             dumpXobj(o, xo, level + 1, ref);
+        }
     }
 
     void setId(String id) {
diff --git a/src/main/java/org/apache/xmlbeans/impl/store/Cursor.java b/src/main/java/org/apache/xmlbeans/impl/store/Cursor.java
index decbe7c..acdd4bb 100755
--- a/src/main/java/org/apache/xmlbeans/impl/store/Cursor.java
+++ b/src/main/java/org/apache/xmlbeans/impl/store/Cursor.java
@@ -68,8 +68,9 @@
             if (c.toParentRaw()) {
                 int pk = c.kind();
 
-                if (pk == COMMENT || pk == PROCINST || pk == ATTR)
+                if (pk == COMMENT || pk == PROCINST || pk == ATTR) {
                     return false;
+                }
             }
 
             c.pop();
@@ -95,35 +96,43 @@
     }
 
     static void validateLocalName(QName name) {
-        if (name == null)
+        if (name == null) {
             throw new IllegalArgumentException("QName is null");
+        }
 
         validateLocalName(name.getLocalPart());
     }
 
     static void validateLocalName(String name) {
-        if (name == null)
+        if (name == null) {
             throw new IllegalArgumentException("Name is null");
+        }
 
-        if (name.length() == 0)
+        if (name.length() == 0) {
             throw new IllegalArgumentException("Name is empty");
+        }
 
-        if (!XMLChar.isValidNCName(name))
+        if (!XMLChar.isValidNCName(name)) {
             throw new IllegalArgumentException("Name is not valid");
+        }
     }
 
     static void validatePrefix(String name) {
-        if (name == null)
+        if (name == null) {
             throw new IllegalArgumentException("Prefix is null");
+        }
 
-        if (name.length() == 0)
+        if (name.length() == 0) {
             throw new IllegalArgumentException("Prefix is empty");
+        }
 
-        if (Locale.beginsWithXml(name))
+        if (Locale.beginsWithXml(name)) {
             throw new IllegalArgumentException("Prefix begins with 'xml'");
+        }
 
-        if (!XMLChar.isValidNCName(name))
+        if (!XMLChar.isValidNCName(name)) {
             throw new IllegalArgumentException("Prefix is not valid");
+        }
     }
 
     private static void complain(String msg) {
@@ -133,16 +142,19 @@
     private void checkInsertionValidity(Cur that) {
         int thatKind = that.kind();
 
-        if (thatKind < 0)
+        if (thatKind < 0) {
             complain("Can't move/copy/insert an end token.");
+        }
 
-        if (thatKind == ROOT)
+        if (thatKind == ROOT) {
             complain("Can't move/copy/insert a whole document.");
+        }
 
         int thisKind = _cur.kind();
 
-        if (thisKind == ROOT)
+        if (thisKind == ROOT) {
             complain("Can't insert before the start of the document.");
+        }
 
         if (thatKind == ATTR) {
             _cur.push();
@@ -155,8 +167,9 @@
             }
         }
 
-        if (thisKind == ATTR && thatKind != ATTR)
+        if (thisKind == ATTR && thatKind != ATTR) {
             complain("Can only insert attributes before other attributes or after containers.");
+        }
     }
 
     private void insertNode(Cur that, String text) {
@@ -205,7 +218,7 @@
 
                 if (_cur.isXmlns()) {
                     return
-                            _cur._locale.makeQNameNoCheck(_cur.getXmlnsUri(), _cur.getXmlnsPrefix());
+                        _cur._locale.makeQNameNoCheck(_cur.getXmlnsUri(), _cur.getXmlnsPrefix());
                 }
 
                 // Fall thru
@@ -219,33 +232,34 @@
     }
 
     public void _setName(QName name) {
-        if (name == null)
+        if (name == null) {
             throw new IllegalArgumentException("Name is null");
+        }
 
         switch (_cur.kind()) {
             case ELEM:
-            case ATTR:
-                {
-                    validateLocalName(name.getLocalPart());
-                    break;
+            case ATTR: {
+                validateLocalName(name.getLocalPart());
+                break;
+            }
+
+            case PROCINST: {
+                validatePrefix(name.getLocalPart());
+
+                if (name.getNamespaceURI().length() > 0) {
+                    throw new IllegalArgumentException("Procinst name must have no URI");
                 }
 
-            case PROCINST:
-                {
-                    validatePrefix(name.getLocalPart());
-
-                    if (name.getNamespaceURI().length() > 0)
-                        throw new IllegalArgumentException("Procinst name must have no URI");
-
-                    if (name.getPrefix().length() > 0)
-                        throw new IllegalArgumentException("Procinst name must have no prefix");
-
-                    break;
+                if (name.getPrefix().length() > 0) {
+                    throw new IllegalArgumentException("Procinst name must have no prefix");
                 }
 
-            default :
+                break;
+            }
+
+            default:
                 throw
-                        new IllegalStateException("Can set name on element, atrtribute and procinst only");
+                    new IllegalStateException("Can set name on element, atrtribute and procinst only");
         }
 
         _cur.setName(name);
@@ -272,7 +286,7 @@
             case PROCINST:
                 return TokenType.PROCINST;
 
-            default :
+            default:
                 throw new IllegalStateException();
         }
     }
@@ -354,38 +368,36 @@
 
         switch (_cur.kind()) {
             case ROOT:
-            case ELEM:
-                {
-                    if (!_cur.toFirstAttr())
-                        _cur.next();
-
-                    break;
+            case ELEM: {
+                if (!_cur.toFirstAttr()) {
+                    _cur.next();
                 }
 
-            case ATTR:
-                {
-                    if (!_cur.toNextSibling()) {
-                        _cur.toParent();
-                        _cur.next();
-                    }
+                break;
+            }
 
-                    break;
+            case ATTR: {
+                if (!_cur.toNextSibling()) {
+                    _cur.toParent();
+                    _cur.next();
                 }
 
+                break;
+            }
+
             case COMMENT:
-            case PROCINST:
-                {
-                    _cur.skip();
-                    break;
+            case PROCINST: {
+                _cur.skip();
+                break;
+            }
+
+            default: {
+                if (!_cur.next()) {
+                    return TokenType.NONE;
                 }
 
-            default :
-                {
-                    if (!_cur.next())
-                        return TokenType.NONE;
-
-                    break;
-                }
+                break;
+            }
         }
 
         return _currentTokenType();
@@ -545,13 +557,14 @@
     }
 
     public void _save(ContentHandler ch, LexicalHandler lh, XmlOptions options)
-            throws SAXException {
+        throws SAXException {
         new Saver.SaxSaver(_cur, options, ch, lh);
     }
 
     public void _save(File file, XmlOptions options) throws IOException {
-        if (file == null)
+        if (file == null) {
             throw new IllegalArgumentException("Null file specified");
+        }
 
         try (OutputStream os = new FileOutputStream(file)) {
             _save(os, options);
@@ -559,33 +572,31 @@
     }
 
     public void _save(OutputStream os, XmlOptions options) throws IOException {
-        if (os == null)
+        if (os == null) {
             throw new IllegalArgumentException("Null OutputStream specified");
+        }
 
-        InputStream is = _newInputStream(options);
-
-        try {
+        try (InputStream is = _newInputStream(options)) {
             byte[] bytes = new byte[8192];
 
-            for (; ;) {
+            for (; ; ) {
                 int n = is.read(bytes);
 
-                if (n < 0)
+                if (n < 0) {
                     break;
+                }
 
                 os.write(bytes, 0, n);
             }
-        } finally {
-            is.close();
         }
     }
 
     public void _save(Writer w, XmlOptions options) throws IOException {
-        if (w == null)
+        if (w == null) {
             throw new IllegalArgumentException("Null Writer specified");
+        }
 
-        if (options != null && options.hasOption( XmlOptions.SAVE_OPTIMIZE_FOR_SPEED ))
-        {
+        if (options != null && options.isSaveOptimizeForSpeed()) {
             Saver.OptimizedForSpeedSaver.save(_cur, w); //ignore all other options
             return;
         }
@@ -593,7 +604,7 @@
         try (Reader r = _newReader(options)) {
             char[] chars = new char[8192];
 
-            for (;;) {
+            for (; ; ) {
                 int n = r.read(chars);
 
                 if (n < 0) {
@@ -610,8 +621,9 @@
     }
 
     private boolean isDomFragment() {
-        if (!isStartdoc())
+        if (!isStartdoc()) {
             return true;
+        }
 
         boolean seenElement = false;
 
@@ -619,18 +631,21 @@
         int token = c.toNextToken().intValue();
 
         try {
-            LOOP: for (; ;) {
+            LOOP:
+            for (; ; ) {
                 switch (token) {
                     case TokenType.INT_START:
-                        if (seenElement)
+                        if (seenElement) {
                             return true;
+                        }
                         seenElement = true;
                         token = c.toEndToken().intValue();
                         break;
 
                     case TokenType.INT_TEXT:
-                        if (!Locale.isWhiteSpace(c.getChars()))
+                        if (!Locale.isWhiteSpace(c.getChars())) {
                             return true;
+                        }
                         token = c.toNextToken().intValue();
                         break;
 
@@ -663,9 +678,9 @@
     public Node _newDomNode(XmlOptions options) {
         // Must ignore inner options for compat with v1.
 
-        if (XmlOptions.hasOption(options, XmlOptions.SAVE_INNER)) {
+        if (options != null && options.isSaveInner()) {
             options = new XmlOptions(options);
-            options.remove(XmlOptions.SAVE_INNER);
+            options.setSaveInner(false);
         }
 
         return new DomSaver(_cur, isDomFragment(), options).saveDom();
@@ -691,8 +706,9 @@
         // Force any path to get exausted, cursor may be disposed, but still be on the notification
         // list.
 
-        if (_cur != null)
+        if (_cur != null) {
             _getSelectionCount();
+        }
     }
 
     public void setNextChangeListener(ChangeListener listener) {
@@ -734,12 +750,14 @@
     }
 
     public boolean _toSelection(int i) {
-        if (i < 0)
+        if (i < 0) {
             return false;
+        }
 
         while (i >= _cur.selectionCount()) {
-            if (_pathEngine == null)
+            if (_pathEngine == null) {
                 return false;
+            }
 
             if (!_pathEngine.next(_cur)) {
                 _pathEngine.release();
@@ -779,15 +797,17 @@
     }
 
     public String _namespaceForPrefix(String prefix) {
-        if (!_cur.isContainer())
+        if (!_cur.isContainer()) {
             throw new IllegalStateException("Not on a container");
+        }
 
         return _cur.namespaceForPrefix(prefix, true);
     }
 
     public String _prefixForNamespace(String ns) {
-        if (ns == null || ns.length() == 0)
+        if (ns == null || ns.length() == 0) {
             throw new IllegalArgumentException("Must specify a namespace");
+        }
 
 // Note: I loosen this requirement in v2, can call this from anywhere
 //        if (!_cur.isContainer())
@@ -796,12 +816,14 @@
         return _cur.prefixForNamespace(ns, null, true);
     }
 
-    public void _getAllNamespaces(Map addToThis) {
-        if (!_cur.isContainer())
+    public void _getAllNamespaces(Map<String,String> addToThis) {
+        if (!_cur.isContainer()) {
             throw new IllegalStateException("Not on a container");
+        }
 
-        if (addToThis != null)
+        if (addToThis != null) {
             Locale.getAllNamespaces(_cur, addToThis);
+        }
     }
 
     public XmlObject _getObject() {
@@ -820,7 +842,7 @@
 
     public boolean _hasNextToken() {
         //return _cur.kind() != -ROOT;
-        return _cur._pos!=Cur.END_POS || _cur._xobj.kind()!=ROOT;
+        return _cur._pos != Cur.END_POS || _cur._xobj.kind() != ROOT;
     }
 
     public boolean _hasPrevToken() {
@@ -828,8 +850,9 @@
     }
 
     public TokenType _toFirstContentToken() {
-        if (!_cur.isContainer())
+        if (!_cur.isContainer()) {
             return TokenType.NONE;
+        }
 
         _cur.next();
 
@@ -837,8 +860,9 @@
     }
 
     public TokenType _toEndToken() {
-        if (!_cur.isContainer())
+        if (!_cur.isContainer()) {
             return TokenType.NONE;
+        }
 
         _cur.toEnd();
 
@@ -953,8 +977,9 @@
     }
 
     public String _getAttributeText(QName attrName) {
-        if (attrName == null)
+        if (attrName == null) {
             throw new IllegalArgumentException("Attr name is null");
+        }
 
         if (!_cur.isContainer()) {
             return null;
@@ -1167,7 +1192,7 @@
 
     public XmlCursor _execQuery(String query, XmlOptions options) {
         checkThisCursor();
-        return Query.cursorExecQuery(_cur,query,options);
+        return Query.cursorExecQuery(_cur, query, options);
     }
 
 
@@ -1196,7 +1221,7 @@
 
         _cur.push();
 
-        for (; ;) {
+        for (; ; ) {
             // Move a minimal amount.  If at text, move to a potential bookmark in the text.
 
             if ((cch = _cur.cchRight()) > 1) {
@@ -1222,14 +1247,15 @@
     }
 
     public XmlBookmark _toPrevBookmark(Object key) {
-        if (key == null)
+        if (key == null) {
             return null;
+        }
 
         int cch;
 
         _cur.push();
 
-        for (; ;) {
+        for (; ; ) {
             // Move a minimal amount.  If at text, move to a potential bookmark in the text.
 
             if ((cch = _cur.cchLeft()) > 1) {
@@ -1316,10 +1342,11 @@
 
         assert _cur.isText() || _cur.isNode();
 
-        if (_cur.isText())
+        if (_cur.isText()) {
             _cur.moveChars(null, -1);
-        else
+        } else {
             _cur.moveNode(null);
+        }
 
         return true;
     }
@@ -1482,11 +1509,13 @@
     public int _moveChars(int cch, Cursor to) {
         int cchRight = _cur.cchRight();
 
-        if (cchRight <= 0 || cch == 0)
+        if (cchRight <= 0 || cch == 0) {
             return 0;
+        }
 
-        if (cch < 0 || cch > cchRight)
+        if (cch < 0 || cch > cchRight) {
             cch = cchRight;
+        }
 
         to.checkInsertionValidity(_cur);
 
@@ -1500,11 +1529,13 @@
     public int _copyChars(int cch, Cursor to) {
         int cchRight = _cur.cchRight();
 
-        if (cchRight <= 0 || cch == 0)
+        if (cchRight <= 0 || cch == 0) {
             return 0;
+        }
 
-        if (cch < 0 || cch > cchRight)
+        if (cch < 0 || cch > cchRight) {
             cch = cchRight;
+        }
 
         to.checkInsertionValidity(_cur);
 
@@ -1521,7 +1552,7 @@
         if (l > 0) {
             if (_cur.isRoot() || _cur.isAttr()) {
                 throw
-                        new IllegalStateException("Can't insert before the document or an attribute.");
+                    new IllegalStateException("Can't insert before the document or an attribute.");
             }
 
             _cur.insertChars(text, 0, l);
@@ -1641,8 +1672,9 @@
     public void _insertProcInst(String target, String text) {
         validateLocalName(target);
 
-        if (Locale.beginsWithXml(target) && target.length() == 3)
+        if (Locale.beginsWithXml(target) && target.length() == 3) {
             throw new IllegalArgumentException("Target is 'xml'");
+        }
 
         Cur c = _cur._locale.tempCur();
 
@@ -1666,23 +1698,27 @@
     //
 
     private void checkThisCursor() {
-        if (_cur == null)
+        if (_cur == null) {
             throw new IllegalStateException("This cursor has been disposed");
+        }
     }
 
     private Cursor checkCursors(XmlCursor xOther) {
         checkThisCursor();
 
-        if (xOther == null)
+        if (xOther == null) {
             throw new IllegalArgumentException("Other cursor is <null>");
+        }
 
-        if (!(xOther instanceof Cursor))
+        if (!(xOther instanceof Cursor)) {
             throw new IllegalArgumentException("Incompatible cursors: " + xOther);
+        }
 
         Cursor other = (Cursor) xOther;
 
-        if (other._cur == null)
+        if (other._cur == null) {
             throw new IllegalStateException("Other cursor has been disposed");
+        }
 
         return other;
     }
@@ -1709,9 +1745,9 @@
         }
 
         if (locale.noSync()) {
-            if (otherLocale.noSync())
+            if (otherLocale.noSync()) {
                 return twoLocaleOp(other, op, arg);
-            else {
+            } else {
                 synchronized (otherLocale) {
                     return twoLocaleOp(other, op, arg);
                 }
@@ -1739,8 +1775,9 @@
         } catch (InterruptedException e) {
             throw new RuntimeException(e.getMessage(), e);
         } finally {
-            if (acquired)
+            if (acquired) {
                 GlobalLock.release();
+            }
         }
     }
 
@@ -1765,7 +1802,7 @@
                 case COPY_CHARS:
                     return _copyChars(arg, other);
 
-                default :
+                default:
                     throw new RuntimeException("Unknown operation: " + op);
             }
         } finally {
@@ -1863,12 +1900,14 @@
             } finally {
                 l.exit();
             }
-        } else synchronized (l) {
-            l.enter();
-            try {
-                return new Cursor(x, p);
-            } finally {
-                l.exit();
+        } else {
+            synchronized (l) {
+                l.enter();
+                try {
+                    return new Cursor(x, p);
+                } finally {
+                    l.exit();
+                }
             }
         }
     }
@@ -1901,7 +1940,7 @@
     }
 
     public XMLStreamReader newXMLStreamReader() {
-        return syncWrap((Supplier<XMLStreamReader>)this::_newXMLStreamReader);
+        return syncWrap((Supplier<XMLStreamReader>) this::_newXMLStreamReader);
     }
 
     public XMLStreamReader newXMLStreamReader(XmlOptions options) {
@@ -1912,23 +1951,23 @@
      * @deprecated XMLInputStream was deprecated by XMLStreamReader from STaX - jsr173 API.
      */
     public XMLInputStream newXMLInputStream() {
-        return syncWrap((Supplier<XMLInputStream>)this::_newXMLInputStream);
+        return syncWrap((Supplier<XMLInputStream>) this::_newXMLInputStream);
     }
 
     public String xmlText() {
-        return syncWrap((Supplier<String>)this::_xmlText);
+        return syncWrap((Supplier<String>) this::_xmlText);
     }
 
     public InputStream newInputStream() {
-        return syncWrap((Supplier<InputStream>)this::_newInputStream);
+        return syncWrap((Supplier<InputStream>) this::_newInputStream);
     }
 
     public Reader newReader() {
-        return syncWrap((Supplier<Reader>)this::_newReader);
+        return syncWrap((Supplier<Reader>) this::_newReader);
     }
 
     public Node newDomNode() {
-        return syncWrap((Supplier<Node>)this::_newDomNode);
+        return syncWrap((Supplier<Node>) this::_newDomNode);
     }
 
     public Node getDomNode() {
@@ -2058,7 +2097,7 @@
         return syncWrap(() -> _prefixForNamespace(namespaceURI));
     }
 
-    public void getAllNamespaces(Map addToThis) {
+    public void getAllNamespaces(Map<String,String> addToThis) {
         syncWrap(() -> _getAllNamespaces(addToThis));
     }
 
@@ -2166,7 +2205,7 @@
 
         Xobj parent = _cur.getParentNoRoot();
 
-        if (parent==null) {
+        if (parent == null) {
             _cur._locale.enter();
             try {
                 parent = _cur.getParent();
@@ -2259,7 +2298,7 @@
     }
 
     public String getTextValue() {
-        return syncWrap((Supplier<String>)this::_getTextValue);
+        return syncWrap((Supplier<String>) this::_getTextValue);
     }
 
     public int getTextValue(char[] chars, int offset, int cch) {
@@ -2275,7 +2314,7 @@
     }
 
     public String getChars() {
-        return syncWrap((Supplier<String>)this::_getChars);
+        return syncWrap((Supplier<String>) this::_getChars);
     }
 
     public int getChars(char[] chars, int offset, int cch) {
diff --git a/src/main/java/org/apache/xmlbeans/impl/store/DomSaver.java b/src/main/java/org/apache/xmlbeans/impl/store/DomSaver.java
index b3fd666..dcc2f89 100644
--- a/src/main/java/org/apache/xmlbeans/impl/store/DomSaver.java
+++ b/src/main/java/org/apache/xmlbeans/impl/store/DomSaver.java
@@ -22,7 +22,7 @@
 import org.w3c.dom.Node;
 
 import javax.xml.namespace.QName;
-import java.util.ArrayList;
+import java.util.List;
 
 final class DomSaver extends Saver {
     private Cur _nodeCur;
@@ -79,7 +79,8 @@
         }
     }
 
-    protected boolean emitElement(SaveCur c, ArrayList attrNames, ArrayList attrValues) {
+    @Override
+    protected boolean emitElement(SaveCur c, List<QName> attrNames, List<String> attrValues) {
         // If there was text or comments before the frag element, I will loose them -- oh well
         // Also, I will lose any attributes and namesapces on the fragment -- DOM can
         // have attrs in fragments
diff --git a/src/main/java/org/apache/xmlbeans/impl/store/Jsr173.java b/src/main/java/org/apache/xmlbeans/impl/store/Jsr173.java
index 049b733..6fec248 100755
--- a/src/main/java/org/apache/xmlbeans/impl/store/Jsr173.java
+++ b/src/main/java/org/apache/xmlbeans/impl/store/Jsr173.java
@@ -15,166 +15,156 @@
 
 package org.apache.xmlbeans.impl.store;
 
-import java.io.Reader;
-
-import java.util.HashMap;
-import java.util.Iterator;
-import java.util.ConcurrentModificationException;
+import org.apache.xmlbeans.XmlDocumentProperties;
+import org.apache.xmlbeans.XmlLineNumber;
+import org.apache.xmlbeans.XmlOptions;
+import org.w3c.dom.Node;
 
 import javax.xml.namespace.NamespaceContext;
 import javax.xml.namespace.QName;
-
-import javax.xml.stream.XMLStreamReader;
-import javax.xml.stream.XMLStreamException;
 import javax.xml.stream.Location;
+import javax.xml.stream.XMLStreamException;
+import javax.xml.stream.XMLStreamReader;
+import java.util.ConcurrentModificationException;
+import java.util.HashMap;
+import java.util.Iterator;
 
-import org.apache.xmlbeans.XmlOptions;
-import org.apache.xmlbeans.XmlLineNumber;
-import org.apache.xmlbeans.XmlDocumentProperties;
-
-import org.w3c.dom.Node;
-
-public class Jsr173
-{
-    public static Node nodeFromStream ( XMLStreamReader xs )
-    {
-        if (!(xs instanceof Jsr173GateWay))
+public class Jsr173 {
+    public static Node nodeFromStream(XMLStreamReader xs) {
+        if (!(xs instanceof Jsr173GateWay)) {
             return null;
+        }
 
         Jsr173GateWay gw = (Jsr173GateWay) xs;
 
         Locale l = gw._l;
 
-        if (l.noSync())         { l.enter(); try { return nodeFromStreamImpl( gw ); } finally { l.exit(); } }
-        else synchronized ( l ) { l.enter(); try { return nodeFromStreamImpl( gw ); } finally { l.exit(); } }
+        if (l.noSync()) {
+            l.enter();
+            try {
+                return nodeFromStreamImpl(gw);
+            } finally {
+                l.exit();
+            }
+        } else {
+            synchronized (l) {
+                l.enter();
+                try {
+                    return nodeFromStreamImpl(gw);
+                } finally {
+                    l.exit();
+                }
+            }
+        }
 
     }
 
-    public static Node nodeFromStreamImpl ( Jsr173GateWay gw )
-    {
+    public static Node nodeFromStreamImpl(Jsr173GateWay gw) {
         Cur c = gw._xs.getStreamCur();
 
         return c.isNode() ? (Node) c.getDom() : (Node) null;
     }
 
-    public static XMLStreamReader newXmlStreamReader ( Cur c, Object src, int off, int cch )
-    {
-        XMLStreamReaderBase xs = new XMLStreamReaderForString( c, src, off, cch );
+    public static XMLStreamReader newXmlStreamReader(Cur c, Object src, int off, int cch) {
+        XMLStreamReaderBase xs = new XMLStreamReaderForString(c, src, off, cch);
 
-        if (c._locale.noSync())
-            return new UnsyncedJsr173( c._locale, xs );
-        else
-            return new SyncedJsr173( c._locale, xs );
+        if (c._locale.noSync()) {
+            return new UnsyncedJsr173(c._locale, xs);
+        } else {
+            return new SyncedJsr173(c._locale, xs);
+        }
     }
 
-    public static XMLStreamReader newXmlStreamReader ( Cur c, XmlOptions options )
-    {
-        options = XmlOptions.maskNull( options );
+    public static XMLStreamReader newXmlStreamReader(Cur c, XmlOptions options) {
+        options = XmlOptions.maskNull(options);
 
-        boolean inner =
-            options.hasOption( XmlOptions.SAVE_INNER ) &&
-                !options.hasOption( XmlOptions.SAVE_OUTER );
+        boolean inner = options.isSaveInner() && !options.isSaveOuter();
 
         XMLStreamReaderBase xs;
 
         int k = c.kind();
 
-        if (k == Cur.TEXT || k < 0)
-        {
-            xs = new XMLStreamReaderForString( c, c.getChars( -1 ), c._offSrc, c._cchSrc );
-        }
-        else if (inner)
-        {
-            if (!c.hasAttrs() && !c.hasChildren())
-                xs = new XMLStreamReaderForString( c, c.getFirstChars(), c._offSrc, c._cchSrc );
-            else
-            {
+        if (k == Cur.TEXT || k < 0) {
+            xs = new XMLStreamReaderForString(c, c.getChars(-1), c._offSrc, c._cchSrc);
+        } else if (inner) {
+            if (!c.hasAttrs() && !c.hasChildren()) {
+                xs = new XMLStreamReaderForString(c, c.getFirstChars(), c._offSrc, c._cchSrc);
+            } else {
                 assert c.isContainer();
-                xs = new XMLStreamReaderForNode( c, true );
+                xs = new XMLStreamReaderForNode(c, true);
             }
+        } else {
+            xs = new XMLStreamReaderForNode(c, false);
         }
-        else
-            xs = new XMLStreamReaderForNode( c, false );
 
-        if (c._locale.noSync())
-            return new UnsyncedJsr173( c._locale, xs );
-        else
-            return new SyncedJsr173( c._locale, xs );
+        if (c._locale.noSync()) {
+            return new UnsyncedJsr173(c._locale, xs);
+        } else {
+            return new SyncedJsr173(c._locale, xs);
+        }
     }
 
     //
     //
     //
 
-    private static final class XMLStreamReaderForNode extends XMLStreamReaderBase
-    {
-        public XMLStreamReaderForNode ( Cur c, boolean inner )
-        {
-            super( c );
+    private static final class XMLStreamReaderForNode extends XMLStreamReaderBase {
+        public XMLStreamReaderForNode(Cur c, boolean inner) {
+            super(c);
 
             assert c.isContainer() || c.isComment() || c.isProcinst() || c.isAttr();
 
             // Iterate over everything *between* _cur and _end.  Do
             // not iterate the thing to the right of _end
 
-            if (inner)
-            {
+            if (inner) {
                 assert c.isContainer();
 
-                _cur = c.weakCur( this );
+                _cur = c.weakCur(this);
 
-                if (!_cur.toFirstAttr())
+                if (!_cur.toFirstAttr()) {
                     _cur.next();
+                }
 
-                _end = c.weakCur( this );
+                _end = c.weakCur(this);
                 _end.toEnd();
-            }
-            else
-            {
-                _cur = c.weakCur( this );
+            } else {
+                _cur = c.weakCur(this);
 
-                if (c.isRoot())
+                if (c.isRoot()) {
                     _wholeDoc = true;
-                else
-                {
-                    _end = c.weakCur( this );
+                } else {
+                    _end = c.weakCur(this);
 
-                    if (c.isAttr())
-                    {
-                        if (!_end.toNextAttr())
-                        {
+                    if (c.isAttr()) {
+                        if (!_end.toNextAttr()) {
                             _end.toParent();
                             _end.next();
                         }
-                    }
-                    else
+                    } else {
                         _end.skip();
+                    }
                 }
             }
 
-            if (!_wholeDoc)
-            {
+            if (!_wholeDoc) {
                 // Set the _done bit properly
 
                 _cur.push();
 
-                try
-                {
+                try {
                     next();
-                }
-                catch ( XMLStreamException e )
-                {
-                    throw new RuntimeException( e.getMessage(), e );
+                } catch (XMLStreamException e) {
+                    throw new RuntimeException(e.getMessage(), e);
                 }
 
                 _cur.pop();
             }
 
-            assert _wholeDoc || !_cur.isSamePos( _end );
+            assert _wholeDoc || !_cur.isSamePos(_end);
         }
 
-        protected Cur getStreamCur ( )
-        {
+        protected Cur getStreamCur() {
             return _cur;
         }
 
@@ -182,66 +172,66 @@
         //
         //
 
-        public boolean hasNext ( ) throws XMLStreamException
-        {
+        public boolean hasNext() throws XMLStreamException {
             checkChanged();
 
             return !_done;
         }
 
-        public int getEventType ( )
-        {
-            switch ( _cur.kind() )
-            {
-                case  Cur.ROOT     : return START_DOCUMENT;
-                case -Cur.ROOT     : return END_DOCUMENT;
-                case  Cur.ELEM     : return START_ELEMENT;
-                case -Cur.ELEM     : return END_ELEMENT;
-                case  Cur.ATTR     : return _cur.isXmlns() ? NAMESPACE : ATTRIBUTE;
-                case  Cur.TEXT     : return CHARACTERS;
-                case  Cur.COMMENT  : return COMMENT;
-                case  Cur.PROCINST : return PROCESSING_INSTRUCTION;
-                default            : throw new IllegalStateException();
+        public int getEventType() {
+            switch (_cur.kind()) {
+                case Cur.ROOT:
+                    return START_DOCUMENT;
+                case -Cur.ROOT:
+                    return END_DOCUMENT;
+                case Cur.ELEM:
+                    return START_ELEMENT;
+                case -Cur.ELEM:
+                    return END_ELEMENT;
+                case Cur.ATTR:
+                    return _cur.isXmlns() ? NAMESPACE : ATTRIBUTE;
+                case Cur.TEXT:
+                    return CHARACTERS;
+                case Cur.COMMENT:
+                    return COMMENT;
+                case Cur.PROCINST:
+                    return PROCESSING_INSTRUCTION;
+                default:
+                    throw new IllegalStateException();
             }
         }
 
-        public int next ( ) throws XMLStreamException
-        {
+        public int next() throws XMLStreamException {
             checkChanged();
 
-            if (!hasNext())
-                throw new IllegalStateException( "No next event in stream" );
+            if (!hasNext()) {
+                throw new IllegalStateException("No next event in stream");
+            }
 
             int kind = _cur.kind();
 
-            if (kind == -Cur.ROOT)
-            {
+            if (kind == -Cur.ROOT) {
                 assert _wholeDoc;
                 _done = true;
-            }
-            else
-            {
-                if (kind == Cur.ATTR)
-                {
-                    if (!_cur.toNextAttr())
-                    {
+            } else {
+                if (kind == Cur.ATTR) {
+                    if (!_cur.toNextAttr()) {
                         _cur.toParent();
                         _cur.next();
                     }
-                }
-                else if (kind == Cur.COMMENT || kind == Cur.PROCINST)
+                } else if (kind == Cur.COMMENT || kind == Cur.PROCINST) {
                     _cur.skip();
-                else if (kind == Cur.ROOT)
-                {
-                    if (!_cur.toFirstAttr())
+                } else if (kind == Cur.ROOT) {
+                    if (!_cur.toFirstAttr()) {
                         _cur.next();
-                }
-                else
+                    }
+                } else {
                     _cur.next();
+                }
 
                 assert _wholeDoc || _end != null;
 
-                _done = _wholeDoc ? _cur.kind() == -Cur.ROOT : _cur.isSamePos( _end );
+                _done = _wholeDoc ? _cur.kind() == -Cur.ROOT : _cur.isSamePos(_end);
             }
 
             _textFetched = false;
@@ -250,123 +240,117 @@
             return getEventType();
         }
 
-        public String getText ( )
-        {
+        public String getText() {
             checkChanged();
 
             int k = _cur.kind();
 
-            if (k == Cur.COMMENT)
+            if (k == Cur.COMMENT) {
                 return _cur.getValueAsString();
+            }
 
-            if (k == Cur.TEXT)
+            if (k == Cur.TEXT) {
                 return _cur.getCharsAsString();
+            }
 
             throw new IllegalStateException();
         }
 
-        public boolean isStartElement ( )
-        {
+        public boolean isStartElement() {
             return getEventType() == START_ELEMENT;
         }
 
-        public boolean isEndElement ( )
-        {
+        public boolean isEndElement() {
             return getEventType() == END_ELEMENT;
         }
 
-        public boolean isCharacters ( )
-        {
+        public boolean isCharacters() {
             return getEventType() == CHARACTERS;
         }
 
-        public String getElementText ( ) throws XMLStreamException
-        {
+        public String getElementText() throws XMLStreamException {
             checkChanged();
 
-            if (!isStartElement())
+            if (!isStartElement()) {
                 throw new IllegalStateException();
+            }
 
             StringBuilder sb = new StringBuilder();
 
-            for ( ; ; )
-            {
-                if (!hasNext())
+            for (; ; ) {
+                if (!hasNext()) {
                     throw new XMLStreamException();
+                }
 
                 int e = next();
 
-                if (e == END_ELEMENT)
+                if (e == END_ELEMENT) {
                     break;
-                else if (e == START_ELEMENT)
+                } else if (e == START_ELEMENT) {
                     throw new XMLStreamException();
-                else if (e != COMMENT && e != PROCESSING_INSTRUCTION)
-                    sb.append( getText() );
+                } else if (e != COMMENT && e != PROCESSING_INSTRUCTION) {
+                    sb.append(getText());
+                }
             }
 
             return sb.toString();
         }
 
-        public int nextTag ( ) throws XMLStreamException
-        {
+        public int nextTag() throws XMLStreamException {
             checkChanged();
 
-            for ( ; ; )
-            {
-                if (isStartElement() || isEndElement())
+            for (; ; ) {
+                if (isStartElement() || isEndElement()) {
                     return getEventType();
+                }
 
-                if (!isWhiteSpace())
+                if (!isWhiteSpace()) {
                     throw new XMLStreamException();
+                }
 
-                if (!hasNext())
+                if (!hasNext()) {
                     throw new XMLStreamException();
+                }
 
                 next();
             }
         }
 
-        private static boolean matchAttr ( Cur c, String uri, String local )
-        {
+        private static boolean matchAttr(Cur c, String uri, String local) {
             assert c.isNormalAttr();
 
             QName name = c.getName();
 
             return
-                name.getLocalPart().equals( local ) &&
-                    (uri == null || name.getNamespaceURI().equals( uri ));
+                name.getLocalPart().equals(local) &&
+                (uri == null || name.getNamespaceURI().equals(uri));
         }
 
-        private static Cur toAttr ( Cur c, String uri, String local )
-        {
-            if (uri == null || local == null || local.length() == 0)
+        private static Cur toAttr(Cur c, String uri, String local) {
+            if (uri == null || local == null || local.length() == 0) {
                 throw new IllegalArgumentException();
+            }
 
             Cur ca = c.tempCur();
             boolean match = false;
 
-            if (c.isElem())
-            {
-                if (ca.toFirstAttr())
-                {
-                    do
-                    {
-                        if (ca.isNormalAttr() && matchAttr( ca, uri, local ))
-                        {
+            if (c.isElem()) {
+                if (ca.toFirstAttr()) {
+                    do {
+                        if (ca.isNormalAttr() && matchAttr(ca, uri, local)) {
                             match = true;
                             break;
                         }
                     }
-                    while ( ca.toNextSibling() );
+                    while (ca.toNextSibling());
                 }
-            }
-            else if (c.isNormalAttr())
-                match = matchAttr( c, uri, local );
-            else
+            } else if (c.isNormalAttr()) {
+                match = matchAttr(c, uri, local);
+            } else {
                 throw new IllegalStateException();
+            }
 
-            if (!match)
-            {
+            if (!match) {
                 ca.release();
                 ca = null;
             }
@@ -374,14 +358,12 @@
             return ca;
         }
 
-        public String getAttributeValue ( String uri, String local )
-        {
-            Cur ca = toAttr( _cur, uri, local );
+        public String getAttributeValue(String uri, String local) {
+            Cur ca = toAttr(_cur, uri, local);
 
             String value = null;
 
-            if (ca != null)
-            {
+            if (ca != null) {
                 value = ca.getValueAsString();
                 ca.release();
             }
@@ -389,108 +371,93 @@
             return value;
         }
 
-        private static Cur toAttr ( Cur c, int i )
-        {
-            if (i < 0)
-                throw new IndexOutOfBoundsException( "Attribute index is negative" );
+        private static Cur toAttr(Cur c, int i) {
+            if (i < 0) {
+                throw new IndexOutOfBoundsException("Attribute index is negative");
+            }
 
             Cur ca = c.tempCur();
             boolean match = false;
 
-            if (c.isElem())
-            {
-                if (ca.toFirstAttr())
-                {
-                    do
-                    {
-                        if (ca.isNormalAttr() && i-- == 0)
-                        {
+            if (c.isElem()) {
+                if (ca.toFirstAttr()) {
+                    do {
+                        if (ca.isNormalAttr() && i-- == 0) {
                             match = true;
                             break;
                         }
                     }
-                    while ( ca.toNextSibling() );
+                    while (ca.toNextSibling());
                 }
-            }
-            else if (c.isNormalAttr())
+            } else if (c.isNormalAttr()) {
                 match = i == 0;
-            else
+            } else {
                 throw new IllegalStateException();
+            }
 
-            if (!match)
-            {
+            if (!match) {
                 ca.release();
-                throw new IndexOutOfBoundsException( "Attribute index is too large" );
+                throw new IndexOutOfBoundsException("Attribute index is too large");
             }
 
             return ca;
         }
 
-        public int getAttributeCount ( )
-        {
+        public int getAttributeCount() {
             int n = 0;
 
-            if (_cur.isElem())
-            {
+            if (_cur.isElem()) {
                 Cur ca = _cur.tempCur();
 
-                if (ca.toFirstAttr())
-                {
-                    do
-                    {
-                        if (ca.isNormalAttr())
+                if (ca.toFirstAttr()) {
+                    do {
+                        if (ca.isNormalAttr()) {
                             n++;
+                        }
                     }
-                    while ( ca.toNextSibling() );
+                    while (ca.toNextSibling());
                 }
 
                 ca.release();
-            }
-            else if (_cur.isNormalAttr())
+            } else if (_cur.isNormalAttr()) {
                 n++;
-            else
+            } else {
                 throw new IllegalStateException();
+            }
 
             return n;
         }
 
-        public QName getAttributeName ( int index )
-        {
-            Cur ca = toAttr( _cur, index );
+        public QName getAttributeName(int index) {
+            Cur ca = toAttr(_cur, index);
             QName name = ca.getName();
             ca.release();
             return name;
         }
 
-        public String getAttributeNamespace ( int index )
-        {
-            return getAttributeName( index ).getNamespaceURI();
+        public String getAttributeNamespace(int index) {
+            return getAttributeName(index).getNamespaceURI();
         }
 
-        public String getAttributeLocalName ( int index )
-        {
-            return getAttributeName( index ).getLocalPart();
+        public String getAttributeLocalName(int index) {
+            return getAttributeName(index).getLocalPart();
         }
 
-        public String getAttributePrefix ( int index )
-        {
-            return getAttributeName( index ).getPrefix();
+        public String getAttributePrefix(int index) {
+            return getAttributeName(index).getPrefix();
         }
 
-        public String getAttributeType ( int index )
-        {
-            toAttr( _cur, index ).release();
+        public String getAttributeType(int index) {
+            toAttr(_cur, index).release();
             return "CDATA";
         }
 
-        public String getAttributeValue ( int index )
-        {
-            Cur ca = toAttr( _cur, index );
+        public String getAttributeValue(int index) {
+            Cur ca = toAttr(_cur, index);
 
             String value = null;
 
-            if (ca != null)
-            {
+            if (ca != null) {
                 value = ca.getValueAsString();
                 ca.release();
             }
@@ -498,149 +465,136 @@
             return value;
         }
 
-        public boolean isAttributeSpecified ( int index )
-        {
+        public boolean isAttributeSpecified(int index) {
             // Go to attr to force index check
-            Cur ca = toAttr( _cur, index );
+            Cur ca = toAttr(_cur, index);
             ca.release();
 
             return false;
         }
 
-        public int getNamespaceCount ( )
-        {
+        public int getNamespaceCount() {
             int n = 0;
 
-            if (_cur.isElem() || _cur.kind() == -Cur.ELEM)
-            {
+            if (_cur.isElem() || _cur.kind() == -Cur.ELEM) {
                 Cur ca = _cur.tempCur();
 
-                if (_cur.kind() == -Cur.ELEM)
+                if (_cur.kind() == -Cur.ELEM) {
                     ca.toParent();
+                }
 
-                if (ca.toFirstAttr())
-                {
-                    do
-                    {
-                        if (ca.isXmlns())
+                if (ca.toFirstAttr()) {
+                    do {
+                        if (ca.isXmlns()) {
                             n++;
+                        }
                     }
-                    while ( ca.toNextSibling() );
+                    while (ca.toNextSibling());
                 }
 
                 ca.release();
-            }
-            else if (_cur.isXmlns())
+            } else if (_cur.isXmlns()) {
                 n++;
-            else
+            } else {
                 throw new IllegalStateException();
+            }
 
             return n;
         }
 
-        private static Cur toXmlns ( Cur c, int i )
-        {
-            if (i < 0)
-                throw new IndexOutOfBoundsException( "Namespace index is negative" );
+        private static Cur toXmlns(Cur c, int i) {
+            if (i < 0) {
+                throw new IndexOutOfBoundsException("Namespace index is negative");
+            }
 
             Cur ca = c.tempCur();
             boolean match = false;
 
-            if (c.isElem() || c.kind() == -Cur.ELEM)
-            {
-                if (c.kind() == -Cur.ELEM)
+            if (c.isElem() || c.kind() == -Cur.ELEM) {
+                if (c.kind() == -Cur.ELEM) {
                     ca.toParent();
+                }
 
-                if (ca.toFirstAttr())
-                {
-                    do
-                    {
-                        if (ca.isXmlns() && i-- == 0)
-                        {
+                if (ca.toFirstAttr()) {
+                    do {
+                        if (ca.isXmlns() && i-- == 0) {
                             match = true;
                             break;
                         }
                     }
-                    while ( ca.toNextSibling() );
+                    while (ca.toNextSibling());
                 }
-            }
-            else if (c.isXmlns())
+            } else if (c.isXmlns()) {
                 match = i == 0;
-            else
+            } else {
                 throw new IllegalStateException();
+            }
 
-            if (!match)
-            {
+            if (!match) {
                 ca.release();
-                throw new IndexOutOfBoundsException( "Namespace index is too large" );
+                throw new IndexOutOfBoundsException("Namespace index is too large");
             }
 
             return ca;
         }
 
-        public String getNamespacePrefix ( int index )
-        {
-            Cur ca = toXmlns( _cur, index );
+        public String getNamespacePrefix(int index) {
+            Cur ca = toXmlns(_cur, index);
             String prefix = ca.getXmlnsPrefix();
             ca.release();
             return prefix;
         }
 
-        public String getNamespaceURI ( int index )
-        {
-            Cur ca = toXmlns( _cur, index );
+        public String getNamespaceURI(int index) {
+            Cur ca = toXmlns(_cur, index);
             String uri = ca.getXmlnsUri();
             ca.release();
             return uri;
         }
 
-        private void fetchChars ( )
-        {
-            if (!_textFetched)
-            {
+        private void fetchChars() {
+            if (!_textFetched) {
                 int k = _cur.kind();
 
                 Cur cText = null;
 
-                if (k == Cur.COMMENT)
-                {
+                if (k == Cur.COMMENT) {
                     cText = _cur.tempCur();
                     cText.next();
-                }
-                else if (k == Cur.TEXT)
+                } else if (k == Cur.TEXT) {
                     cText = _cur;
-                else
+                } else {
                     throw new IllegalStateException();
+                }
 
-                Object src = cText.getChars( -1 );
+                Object src = cText.getChars(-1);
 
-                ensureCharBufLen( cText._cchSrc );
+                ensureCharBufLen(cText._cchSrc);
 
                 CharUtil.getChars(
-                    _chars, _offChars = 0, src, cText._offSrc, _cchChars = cText._cchSrc );
+                    _chars, _offChars = 0, src, cText._offSrc, _cchChars = cText._cchSrc);
 
-                if (cText != _cur)
+                if (cText != _cur) {
                     cText.release();
+                }
 
                 _textFetched = true;
             }
         }
 
-        private void ensureCharBufLen ( int cch )
-        {
-            if (_chars == null || _chars.length < cch)
-            {
+        private void ensureCharBufLen(int cch) {
+            if (_chars == null || _chars.length < cch) {
                 int l = 256;
 
-                while ( l < cch )
+                while (l < cch) {
                     l *= 2;
+                }
 
-                _chars = new char [ l ];
+                _chars = new char[l];
             }
         }
 
-        public char[] getTextCharacters ( )
-        {
+        public char[] getTextCharacters() {
             checkChanged();
 
             fetchChars();
@@ -648,8 +602,7 @@
             return _chars;
         }
 
-        public int getTextStart ( )
-        {
+        public int getTextStart() {
             checkChanged();
 
             fetchChars();
@@ -657,8 +610,7 @@
             return _offChars;
         }
 
-        public int getTextLength ( )
-        {
+        public int getTextLength() {
             checkChanged();
 
             fetchChars();
@@ -666,99 +618,95 @@
             return _cchChars;
         }
 
-        public int getTextCharacters (
-            int sourceStart, char[] target, int targetStart, int length )
-                throws XMLStreamException
-        {
-            if (length < 0)
+        public int getTextCharacters(
+            int sourceStart, char[] target, int targetStart, int length)
+            throws XMLStreamException {
+            if (length < 0) {
                 throw new IndexOutOfBoundsException();
+            }
 
-            if (targetStart < 0 || targetStart >= target.length)
+            if (targetStart < 0 || targetStart >= target.length) {
                 throw new IndexOutOfBoundsException();
+            }
 
-            if (targetStart + length > target.length)
+            if (targetStart + length > target.length) {
                 throw new IndexOutOfBoundsException();
+            }
 
-            if (!_srcFetched)
-            {
+            if (!_srcFetched) {
                 int k = _cur.kind();
 
                 Cur cText = null;
 
-                if (k == Cur.COMMENT)
-                {
+                if (k == Cur.COMMENT) {
                     cText = _cur.tempCur();
                     cText.next();
-                }
-                else if (k == Cur.TEXT)
+                } else if (k == Cur.TEXT) {
                     cText = _cur;
-                else
+                } else {
                     throw new IllegalStateException();
+                }
 
-                _src = cText.getChars( -1 );
+                _src = cText.getChars(-1);
                 _offSrc = cText._offSrc;
                 _cchSrc = cText._cchSrc;
 
-                if (cText != _cur)
+                if (cText != _cur) {
                     cText.release();
+                }
 
                 _srcFetched = true;
             }
 
-            if (sourceStart > _cchSrc)
+            if (sourceStart > _cchSrc) {
                 throw new IndexOutOfBoundsException();
+            }
 
-            if (sourceStart + length > _cchSrc)
+            if (sourceStart + length > _cchSrc) {
                 length = _cchSrc - sourceStart;
+            }
 
-            CharUtil.getChars( target, targetStart, _src, _offSrc, length );
+            CharUtil.getChars(target, targetStart, _src, _offSrc, length);
 
             return length;
         }
 
-        public boolean hasText ( )
-        {
+        public boolean hasText() {
             int k = _cur.kind();
 
             return k == Cur.COMMENT || k == Cur.TEXT;
         }
 
-        public boolean hasName ( )
-        {
+        public boolean hasName() {
             int k = _cur.kind();
             return k == Cur.ELEM || k == -Cur.ELEM;
         }
 
-        public QName getName ( )
-        {
-            if (!hasName())
+        public QName getName() {
+            if (!hasName()) {
                 throw new IllegalStateException();
+            }
 
             return _cur.getName();
         }
 
-        public String getNamespaceURI ( )
-        {
+        public String getNamespaceURI() {
             return getName().getNamespaceURI();
         }
 
-        public String getLocalName ( )
-        {
+        public String getLocalName() {
             return getName().getLocalPart();
         }
 
-        public String getPrefix ( )
-        {
+        public String getPrefix() {
             return getName().getPrefix();
         }
 
-        public String getPITarget ( )
-        {
+        public String getPITarget() {
             return _cur.kind() == Cur.PROCINST ? _cur.getName().getLocalPart() : null;
         }
 
-        public String getPIData ( )
-        {
+        public String getPIData() {
             return _cur.kind() == Cur.PROCINST ? _cur.getValueAsString() : null;
         }
 
@@ -773,14 +721,14 @@
         private Cur _end;
 
         private boolean _srcFetched;
-        private Object  _src;
-        private int     _offSrc;
-        private int     _cchSrc;
+        private Object _src;
+        private int _offSrc;
+        private int _cchSrc;
 
         private boolean _textFetched;
-        private char[]  _chars;
-        private int     _offChars;
-        private int     _cchChars;
+        private char[] _chars;
+        private int _offChars;
+        private int _cchChars;
     }
 
     //
@@ -788,58 +736,50 @@
     //
 
     private static abstract class XMLStreamReaderBase
-        implements XMLStreamReader, NamespaceContext, Location
-    {
-        XMLStreamReaderBase ( Cur c )
-        {
+        implements XMLStreamReader, NamespaceContext, Location {
+        XMLStreamReaderBase(Cur c) {
             _locale = c._locale;
             _version = _locale.version();
         }
 
-        protected final void checkChanged ( )
-        {
-            if (_version != _locale.version())
-                throw new ConcurrentModificationException( "Document changed while streaming" );
+        protected final void checkChanged() {
+            if (_version != _locale.version()) {
+                throw new ConcurrentModificationException("Document changed while streaming");
+            }
         }
 
         //
         // XMLStreamReader methods
         //
 
-        public void close ( ) throws XMLStreamException
-        {
+        public void close() throws XMLStreamException {
             checkChanged();
         }
 
-        public boolean isWhiteSpace ( )
-        {
+        public boolean isWhiteSpace() {
             checkChanged();
 
             // TODO - avoid creating a string here
             String s = getText();