fix spotbugs issues - reduce complexity of org.apache.xmlbeans.impl.common.XPath by extracting inner classes

git-svn-id: https://svn.apache.org/repos/asf/xmlbeans/trunk@1881037 13f79535-47bb-0310-9956-ffa450edef68
diff --git a/src/main/java/org/apache/xmlbeans/CDataBookmark.java b/src/main/java/org/apache/xmlbeans/CDataBookmark.java
index 7f3cd2a..57f9766 100644
--- a/src/main/java/org/apache/xmlbeans/CDataBookmark.java
+++ b/src/main/java/org/apache/xmlbeans/CDataBookmark.java
@@ -16,19 +16,19 @@
 

 /**

  * Represents a CDATA bookmark.<p>

- *

+ * <p>

  * When XmlOption UseCDataBookmarks is setted on parse methods,

  * the loader will set these CDataBookmarks in the store on the respective

  * TEXT fields that were represented as CDATA.<p>

- *

+ * <p>

  * Users can modify the 'look' of TEXT fields, by annotating them with

  * this bookmark, or remove the bookmark.<p>

- *

+ * <p>

  * Additionaly if setted on save methods, the output will look for these

  * bookmarks and will output the text as CDATA.

  * Note: The SaveCDataEntityCountThreshold and SaveCDataLengthThreshold

  * options and their default values still apply.<p>

- *

+ * <p>

  * Note: Due to the store representation, a CDATA will not be recognized

  * if it is imediately after non CDATA text and all text following it will

  * be considered CDATA.<br>

@@ -42,17 +42,14 @@
  * @see XmlOptions#setUseCDataBookmarks()

  * @see org.apache.xmlbeans.XmlObject.Factory#parse(String, XmlOptions)

  * @see org.apache.xmlbeans.XmlObject#save(java.io.OutputStream, XmlOptions)

- * @see XmlOptions#setSaveCDataEntityCountThreshold(int) 

+ * @see XmlOptions#setSaveCDataEntityCountThreshold(int)

  * @see XmlOptions#setSaveCDataLengthThreshold(int)

- * @author Cezar Andrei  (cezar dot andrei at gmail dot com)

  */

-public class CDataBookmark

-   extends XmlCursor.XmlBookmark

-{

+public class CDataBookmark extends XmlCursor.XmlBookmark {

     /**

      * The actual bookmark object representing CData.<br>

      * Users must use this bookmark in addition to UseCDataBookmarks

      * option to make use of CDATA representation in XML text.

      */

-    public static CDataBookmark CDATA_BOOKMARK = new CDataBookmark();

+    public static final CDataBookmark CDATA_BOOKMARK = new CDataBookmark();

 }
\ No newline at end of file
diff --git a/src/main/java/org/apache/xmlbeans/impl/common/IdentityConstraint.java b/src/main/java/org/apache/xmlbeans/impl/common/IdentityConstraint.java
index f959be2..b39300e 100644
--- a/src/main/java/org/apache/xmlbeans/impl/common/IdentityConstraint.java
+++ b/src/main/java/org/apache/xmlbeans/impl/common/IdentityConstraint.java
@@ -15,11 +15,11 @@
 
 package org.apache.xmlbeans.impl.common;
 
+import org.apache.xmlbeans.*;
 import org.apache.xmlbeans.impl.common.ValidatorListener.Event;
+
 import javax.xml.namespace.QName;
 import javax.xml.stream.Location;
-
-import org.apache.xmlbeans.*;
 import java.util.*;
 
 /**
@@ -34,7 +34,7 @@
     private boolean _invalid;
     private boolean _trackIdrefs; // We only track idrefs if validating from the root element
 
-    public IdentityConstraint(Collection  errorListener, boolean trackIdrefs) {
+    public IdentityConstraint(Collection errorListener, boolean trackIdrefs) {
         _errorListener = errorListener;
         _trackIdrefs = trackIdrefs;
     }
@@ -45,21 +45,23 @@
         newState();
 
         // First dispatch this element event
-        for (ConstraintState cs = _constraintStack ; cs != null ; cs = cs._next)
+        for (ConstraintState cs = _constraintStack; cs != null; cs = cs._next) {
             cs.element(e, st);
+        }
 
         // Create a new SelectorState for each new Identity Constraint
 
-        for (int i = 0 ; ics != null && i < ics.length ; i++)
+        for (int i = 0; ics != null && i < ics.length; i++) {
             newConstraintState(ics[i], e, st);
+        }
     }
 
     public void endElement(Event e) {
         // Pop the element state stack and any constraints at this depth
-        if (_elementStack._hasConstraints)
-        {
-            for (ConstraintState cs = _constraintStack ; cs != null && cs != _elementStack._savePoint ; cs = cs._next)
-                cs.remove( e );
+        if (_elementStack._hasConstraints) {
+            for (ConstraintState cs = _constraintStack; cs != null && cs != _elementStack._savePoint; cs = cs._next) {
+                cs.remove(e);
+            }
 
             _constraintStack = _elementStack._savePoint;
         }
@@ -67,39 +69,42 @@
         _elementStack = _elementStack._next;
 
         // Dispatch the event
-        for (ConstraintState cs = _constraintStack ; cs != null ; cs = cs._next)
+        for (ConstraintState cs = _constraintStack; cs != null; cs = cs._next) {
             cs.endElement(e);
+        }
 
     }
 
     public void attr(Event e, QName name, SchemaType st, String value) {
-        for (ConstraintState cs = _constraintStack ; cs != null ; cs = cs._next)
+        for (ConstraintState cs = _constraintStack; cs != null; cs = cs._next) {
             cs.attr(e, name, st, value);
+        }
     }
 
     public void text(Event e, SchemaType st, String value, boolean emptyContent) {
-        for (ConstraintState cs = _constraintStack ; cs != null ; cs = cs._next)
+        for (ConstraintState cs = _constraintStack; cs != null; cs = cs._next) {
             cs.text(e, st, value, emptyContent);
+        }
     }
 
     public boolean isValid() {
         return !_invalid;
     }
 
-    private void newConstraintState(SchemaIdentityConstraint ic, Event e, SchemaType st)
-    {
-        if (ic.getConstraintCategory() == SchemaIdentityConstraint.CC_KEYREF)
+    private void newConstraintState(SchemaIdentityConstraint ic, Event e, SchemaType st) {
+        if (ic.getConstraintCategory() == SchemaIdentityConstraint.CC_KEYREF) {
             new KeyrefState(ic, e, st);
-        else
+        } else {
             new SelectorState(ic, e, st);
+        }
     }
 
-    private void buildIdStates()
-    {
+    private void buildIdStates() {
         // Construct states to hold the values for IDs and IDRefs
         IdState ids = new IdState();
-        if (_trackIdrefs)
+        if (_trackIdrefs) {
             new IdRefState(ids);
+        }
     }
 
     private void newState() {
@@ -109,96 +114,81 @@
         st._next = _elementStack;
         _elementStack = st;
 
-        if (firstTime)
+        if (firstTime) {
             buildIdStates();
+        }
     }
 
-    private void emitError ( Event event, String code, Object[] args )
-    {
+    private void emitError(Event event, String code, Object[] args) {
         _invalid = true;
 
-        if (_errorListener != null)
-        {
+        if (_errorListener != null) {
             assert event != null;
-            
+
             _errorListener.add(errorForEvent(code, args, XmlError.SEVERITY_ERROR, event));
         }
     }
 
-    public static XmlError errorForEvent(String code, Object[] args, int severity, Event event)
-    {
+    public static XmlError errorForEvent(String code, Object[] args, int severity, Event event) {
         XmlCursor loc = event.getLocationAsCursor();
         XmlError error;
-        if (loc!=null)
+        if (loc != null) {
             error = XmlError.forCursor(code, args, severity, loc);
-        else
-        {
+        } else {
             Location location = event.getLocation();
-            if (location!=null)
-            {
+            if (location != null) {
                 error = XmlError.forLocation(code, args, severity,
                     location.getSystemId(), location.getLineNumber(),
                     location.getColumnNumber(), location.getCharacterOffset());
-            }
-            else
-            {
+            } else {
                 error = XmlError.forMessage(code, args, severity);
             }
         }
         return error;
     }
 
-    private void emitError ( Event event, String msg )
-    {
+    private void emitError(Event event, String msg) {
         _invalid = true;
 
-        if (_errorListener != null)
-        {
+        if (_errorListener != null) {
             assert event != null;
-            
+
             _errorListener.add(errorForEvent(msg, XmlError.SEVERITY_ERROR, event));
         }
     }
 
-    public static XmlError errorForEvent(String msg, int severity, Event event)
-    {
+    public static XmlError errorForEvent(String msg, int severity, Event event) {
         XmlCursor loc = event.getLocationAsCursor();
         XmlError error;
-        if (loc!=null)
+        if (loc != null) {
             error = XmlError.forCursor(msg, severity, loc);
-        else
-        {
+        } else {
             Location location = event.getLocation();
-            if (location!=null)
-            {
+            if (location != null) {
                 error = XmlError.forLocation(msg, severity,
                     location.getSystemId(), location.getLineNumber(),
                     location.getColumnNumber(), location.getCharacterOffset());
-            }
-            else
-            {
+            } else {
                 error = XmlError.forMessage(msg, severity);
             }
         }
         return error;
     }
 
-    private void setSavePoint( ConstraintState cs )
-    {
-        if (! _elementStack._hasConstraints)
+    private void setSavePoint(ConstraintState cs) {
+        if (!_elementStack._hasConstraints) {
             _elementStack._savePoint = cs;
+        }
 
         _elementStack._hasConstraints = true;
     }
 
-    private static XmlObject newValue(SchemaType st, String value)
-    {
+    private static XmlObject newValue(SchemaType st, String value) {
         try {
             return st.newValue(value);
-        }
-        catch (IllegalArgumentException e) {
-            // This is a bit hacky. newValue throws XmlValueOutOfRangeException which is 
-            // unchecked and declared in typeimpl. I can only catch its parent class, 
+        } catch (IllegalArgumentException e) {
+            // This is a bit hacky. newValue throws XmlValueOutOfRangeException which is
+            // unchecked and declared in typeimpl. I can only catch its parent class,
             // typeimpl is built after common.
 
             // Ignore these exceptions. Assume that validation will catch them.
@@ -211,36 +201,38 @@
      * simple, just return it. If it is a complex type with simple content,
      * return the simple type it extends.
      */
-    static SchemaType getSimpleType(SchemaType st) 
-    {
-        assert st.isSimpleType() || st.getContentType() == SchemaType.SIMPLE_CONTENT : 
+    static SchemaType getSimpleType(SchemaType st) {
+        assert st.isSimpleType() || st.getContentType() == SchemaType.SIMPLE_CONTENT :
             st + " does not have simple content.";
 
-        while (! st.isSimpleType() )
+        while (!st.isSimpleType()) {
             st = st.getBaseType();
+        }
 
         return st;
     }
 
-    static boolean hasSimpleContent(SchemaType st)
-    {
+    static boolean hasSimpleContent(SchemaType st) {
         return st.isSimpleType() || st.getContentType() == SchemaType.SIMPLE_CONTENT;
     }
 
     public abstract class ConstraintState {
         ConstraintState _next;
 
-        ConstraintState()
-        {
+        ConstraintState() {
             setSavePoint(_constraintStack);
             _next = _constraintStack;
             _constraintStack = this;
         }
 
         abstract void element(Event e, SchemaType st);
+
         abstract void endElement(Event e);
+
         abstract void attr(Event e, QName name, SchemaType st, String value);
+
         abstract void text(Event e, SchemaType st, String value, boolean emptyContent);
+
         abstract void remove(Event e);
 
     }
@@ -248,42 +240,41 @@
     public class SelectorState extends ConstraintState {
         SchemaIdentityConstraint _constraint;
         Set _values = new LinkedHashSet();
-        XPath.ExecutionContext _context;
+        XPathExecutionContext _context;
 
         SelectorState(SchemaIdentityConstraint constraint, Event e, SchemaType st) {
             _constraint = constraint;
-            _context = new XPath.ExecutionContext();
-            _context.init((XPath)_constraint.getSelectorPath());
+            _context = new XPathExecutionContext();
+            _context.init((XPath) _constraint.getSelectorPath());
 
-            if ( ( _context.start() & XPath.ExecutionContext.HIT ) != 0 )
+            if ((_context.start() & XPathExecutionContext.HIT) != 0) {
                 createFieldState(e, st);
-        }
-
-        void addFields(XmlObjectList fields, Event e) 
-        {
-            if (_constraint.getConstraintCategory() == SchemaIdentityConstraint.CC_KEYREF)
-                _values.add(fields);
-            else if (_values.contains(fields))
-            {
-                if (_constraint.getConstraintCategory() == SchemaIdentityConstraint.CC_UNIQUE)
-                    emitError(e, XmlErrorCodes.IDENTITY_CONSTRAINT_VALID$DUPLICATE_UNIQUE,
-                        new Object[] { fields, QNameHelper.pretty(_constraint.getName()) });
-                else
-                    emitError(e, XmlErrorCodes.IDENTITY_CONSTRAINT_VALID$DUPLICATE_KEY,
-                        new Object[] { fields, QNameHelper.pretty(_constraint.getName()) });
             }
-            else
+        }
+
+        void addFields(XmlObjectList fields, Event e) {
+            if (_constraint.getConstraintCategory() == SchemaIdentityConstraint.CC_KEYREF) {
                 _values.add(fields);
+            } else if (_values.contains(fields)) {
+                if (_constraint.getConstraintCategory() == SchemaIdentityConstraint.CC_UNIQUE) {
+                    emitError(e, XmlErrorCodes.IDENTITY_CONSTRAINT_VALID$DUPLICATE_UNIQUE,
+                        new Object[]{fields, QNameHelper.pretty(_constraint.getName())});
+                } else {
+                    emitError(e, XmlErrorCodes.IDENTITY_CONSTRAINT_VALID$DUPLICATE_KEY,
+                        new Object[]{fields, QNameHelper.pretty(_constraint.getName())});
+                }
+            } else {
+                _values.add(fields);
+            }
         }
 
-        void element(Event e, SchemaType st) 
-        {
-            if ( ( _context.element(e.getName()) & XPath.ExecutionContext.HIT) != 0 )
+        void element(Event e, SchemaType st) {
+            if ((_context.element(e.getName()) & XPathExecutionContext.HIT) != 0) {
                 createFieldState(e, st);
+            }
         }
 
-        void endElement(Event e) 
-        {
+        void endElement(Event e) {
             _context.end();
         }
 
@@ -293,19 +284,21 @@
 
         void remove(Event e) {
             // Bubble up key, unique values to keyrefs
-            for (ConstraintState cs = _next ; cs != null ; cs = cs._next )
-            {
-                if (cs instanceof KeyrefState)
-                {
-                    KeyrefState kr = (KeyrefState)cs;
-                    if (kr._constraint.getReferencedKey() == this._constraint)
+            for (ConstraintState cs = _next; cs != null; cs = cs._next) {
+                if (cs instanceof KeyrefState) {
+                    KeyrefState kr = (KeyrefState) cs;
+                    if (kr._constraint.getReferencedKey() == this._constraint) {
                         kr.addKeyValues(_values, true);
+                    }
                 }
             }
         }
 
-        void attr(Event e, QName name, SchemaType st, String value) {}
-        void text(Event e, SchemaType st, String value, boolean emptyContent) {}
+        void attr(Event e, QName name, SchemaType st, String value) {
+        }
+
+        void text(Event e, SchemaType st, String value, boolean emptyContent) {
+        }
     }
 
     public class KeyrefState extends SelectorState {
@@ -318,35 +311,31 @@
             super(constraint, e, st);
         }
 
-        void addKeyValues(final Set values, boolean child)
-        {
+        void addKeyValues(final Set values, boolean child) {
             /** If the key values are added by children, then if two or
              more children add the same value, the value dissapears from the map
              but if is added by the element in question directly then it will
              be present in the map regardless of what children contained */
-            for (Iterator it = values.iterator(); it.hasNext();)
-            {
+            for (Iterator it = values.iterator(); it.hasNext(); ) {
                 Object key = it.next();
                 Object value = _keyValues.get(key);
-                if (value == null)
+                if (value == null) {
                     _keyValues.put(key, child ? CHILD_ADDED : SELF_ADDED);
-                else if (value == CHILD_ADDED)
-                {
-                    if (child)
+                } else if (value == CHILD_ADDED) {
+                    if (child) {
                         _keyValues.put(key, CHILD_REMOVED);
-                    else
+                    } else {
                         _keyValues.put(key, SELF_ADDED);
-                }
-                else if (value == CHILD_REMOVED)
-                {
-                    if (!child)
+                    }
+                } else if (value == CHILD_REMOVED) {
+                    if (!child) {
                         _keyValues.put(key, SELF_ADDED);
+                    }
                 }
             }
         }
 
-        private boolean hasKeyValue(Object key)
-        {
+        private boolean hasKeyValue(Object key) {
             Object value = _keyValues.get(key);
             return value != null && value != CHILD_REMOVED;
         }
@@ -354,27 +343,24 @@
         void remove(Event e) {
             // First check if there are any keys at the same stack level as this
             // that may contribute key values to me
-            for (ConstraintState cs = _next ; cs != null && cs != _elementStack._savePoint ; cs = cs._next)
-            {
-                if (cs instanceof SelectorState)
-                {
-                    SelectorState sel = (SelectorState)cs;
-                    if (sel._constraint == _constraint.getReferencedKey())
+            for (ConstraintState cs = _next; cs != null && cs != _elementStack._savePoint; cs = cs._next) {
+                if (cs instanceof SelectorState) {
+                    SelectorState sel = (SelectorState) cs;
+                    if (sel._constraint == _constraint.getReferencedKey()) {
                         addKeyValues(sel._values, false);
+                    }
                 }
             }
 
 
             // validate all values have been seen
-            for (Iterator it = _values.iterator() ; it.hasNext() ; )
-            {
+            for (Iterator it = _values.iterator(); it.hasNext(); ) {
 
-                XmlObjectList fields = (XmlObjectList)it.next();
-                if (fields.unfilled() < 0 && ! hasKeyValue(fields))
-                {
+                XmlObjectList fields = (XmlObjectList) it.next();
+                if (fields.unfilled() < 0 && !hasKeyValue(fields)) {
                     // KHK: cvc-identity-constraint.4.3 ?
-                	emitError(e, XmlErrorCodes.IDENTITY_CONSTRAINT_VALID$KEYREF_KEY_NOT_FOUND,
-                	    new Object[] {fields, QNameHelper.pretty(_constraint.getName())});
+                    emitError(e, XmlErrorCodes.IDENTITY_CONSTRAINT_VALID$KEYREF_KEY_NOT_FOUND,
+                        new Object[]{fields, QNameHelper.pretty(_constraint.getName())});
                     return;
                 }
             }
@@ -383,7 +369,7 @@
 
     public class FieldState extends ConstraintState {
         SelectorState _selector;
-        XPath.ExecutionContext[] _contexts;
+        XPathExecutionContext[] _contexts;
         boolean[] _needsValue;
         XmlObjectList _value;
 
@@ -395,47 +381,45 @@
             SchemaIdentityConstraint ic = selector._constraint;
 
             int fieldCount = ic.getFields().length;
-            _contexts = new XPath.ExecutionContext[fieldCount];
+            _contexts = new XPathExecutionContext[fieldCount];
             _needsValue = new boolean[fieldCount];
             _value = new XmlObjectList(fieldCount);
 
-            for (int i = 0 ; i < fieldCount ; i++)
-            {
-                _contexts[i] = new XPath.ExecutionContext();
-                _contexts[i].init((XPath)ic.getFieldPath(i));
-                if ( ( _contexts[i].start() & XPath.ExecutionContext.HIT ) != 0 )
-                {
+            for (int i = 0; i < fieldCount; i++) {
+                _contexts[i] = new XPathExecutionContext();
+                _contexts[i].init((XPath) ic.getFieldPath(i));
+                if ((_contexts[i].start() & XPathExecutionContext.HIT) != 0) {
                     // System.out.println("hit for element: " + e.getName());
 
                     if (!hasSimpleContent(st))
-                        // KHK: cvc-identity-constraint.3
+                    // KHK: cvc-identity-constraint.3
+                    {
                         emitError(e, "Identity constraint field must have simple content");
-                    else
+                    } else {
                         _needsValue[i] = true;
+                    }
                 }
             }
 
         }
 
-        void element(Event e, SchemaType st)
-        {
-            for (int i = 0 ; i < _contexts.length ; i++) {
-                if (_needsValue[i])
-                {
+        void element(Event e, SchemaType st) {
+            for (int i = 0; i < _contexts.length; i++) {
+                if (_needsValue[i]) {
                     // KHK: cvc-identity-constraint.3
                     emitError(e, "Identity constraint field must have simple content");
                     _needsValue[i] = false;
                 }
             }
 
-            for (int i = 0 ; i < _contexts.length ; i++) {
-                if ( ( _contexts[i].element(e.getName()) & XPath.ExecutionContext.HIT) != 0 )
-                {
-                    if (! hasSimpleContent(st))
+            for (int i = 0; i < _contexts.length; i++) {
+                if ((_contexts[i].element(e.getName()) & XPathExecutionContext.HIT) != 0) {
+                    if (!hasSimpleContent(st)) {
                         // KHK: cvc-identity-constraint.3
                         emitError(e, "Identity constraint field must have simple content");
-                    else
+                    } else {
                         _needsValue[i] = true;
+                    }
                 }
             }
         }
@@ -443,21 +427,26 @@
         void attr(Event e, QName name, SchemaType st, String value) {
 
             // Null value indicates previously reported validation problem
-            if (value == null) return;
+            if (value == null) {
+                return;
+            }
 
-            for (int i = 0 ; i < _contexts.length ; i++) {
-                if ( _contexts[i].attr(name) ) {
+            for (int i = 0; i < _contexts.length; i++) {
+                if (_contexts[i].attr(name)) {
                     XmlObject o = newValue(st, value);
 
                     // Ignore invalid values. Assume that validation catches these
-                    if (o == null) return;
+                    if (o == null) {
+                        return;
+                    }
 
                     boolean set = _value.set(o, i);
 
                     // KHK: ?
-                    if (! set)
-                        emitError(e, "Multiple instances of field with xpath: '" 
-                            + _selector._constraint.getFields()[i] + "' for a selector");
+                    if (!set) {
+                        emitError(e, "Multiple instances of field with xpath: '"
+                                     + _selector._constraint.getFields()[i] + "' for a selector");
+                    }
                 }
 
             }
@@ -467,13 +456,14 @@
         void text(Event e, SchemaType st, String value, boolean emptyContent) {
 
             // Null value indicates previously reported validation problem
-            if (value == null && !emptyContent) return;
+            if (value == null && !emptyContent) {
+                return;
+            }
 
-            for (int i = 0 ; i < _contexts.length ; i++) {
-                if ( _needsValue[i] ) {
+            for (int i = 0; i < _contexts.length; i++) {
+                if (_needsValue[i]) {
 
-                    if (emptyContent || !hasSimpleContent(st))
-                    {
+                    if (emptyContent || !hasSimpleContent(st)) {
                         // KHK: cvc-identity-constraint.3
                         emitError(e, "Identity constraint field must have simple content");
                         return;
@@ -483,42 +473,40 @@
                     XmlObject o = newValue(simpleType, value);
 
                     // Ignore invalid values. Assume that validation catches these
-                    if (o == null) return;
+                    if (o == null) {
+                        return;
+                    }
 
                     boolean set = _value.set(o, i);
 
                     // KHK: ?
-                    if (! set)
-                        emitError(e, "Multiple instances of field with xpath: '" 
-                            + _selector._constraint.getFields()[i] + "' for a selector");
+                    if (!set) {
+                        emitError(e, "Multiple instances of field with xpath: '"
+                                     + _selector._constraint.getFields()[i] + "' for a selector");
+                    }
                 }
             }
         }
 
         void endElement(Event e) {
-            // reset any  _needsValue flags 
+            // reset any  _needsValue flags
             // assume that if we didn't see the text, it was because of another validation
             // error, so don't emit another one.
-            for (int i = 0 ; i < _needsValue.length ; i++)
-            {
+            for (int i = 0; i < _needsValue.length; i++) {
                 _contexts[i].end();
                 _needsValue[i] = false;
             }
 
         }
 
-        void remove(Event e) 
-        {
+        void remove(Event e) {
 
             if (_selector._constraint.getConstraintCategory() == SchemaIdentityConstraint.CC_KEY &&
-                _value.unfilled() >= 0 )
-            {
+                _value.unfilled() >= 0) {
                 // KHK: cvc-identity-constraint.4.2.1 ?
                 // keys must have all values supplied
                 emitError(e, "Key " + QNameHelper.pretty(_selector._constraint.getName()) + " is missing field with xpath: '" + _selector._constraint.getFields()[_value.unfilled()] + "'");
-            }
-            else
-            {
+            } else {
                 // Finished. Add these fields to the selector state
                 _selector.addFields(_value, e);
             }
@@ -526,138 +514,144 @@
 
     }
 
-    public class IdState extends ConstraintState
-    {
+    public class IdState extends ConstraintState {
         Set _values = new LinkedHashSet();
 
-        IdState() { }
+        IdState() {
+        }
 
-        void attr(Event e, QName name, SchemaType st, String value)
-        {
+        void attr(Event e, QName name, SchemaType st, String value) {
             handleValue(e, st, value);
         }
 
-        void text(Event e, SchemaType st, String value, boolean emptyContent)
-        {
-            if (emptyContent)
+        void text(Event e, SchemaType st, String value, boolean emptyContent) {
+            if (emptyContent) {
                 return;
+            }
 
             handleValue(e, st, value);
         }
 
-        private void handleValue(Event e, SchemaType st, String value)
-        {
+        private void handleValue(Event e, SchemaType st, String value) {
 
             // Null value indicates previously reported validation problem
-            if (value == null) return;
+            if (value == null) {
+                return;
+            }
 
-            if (st == null || st.isNoType())
-            {
+            if (st == null || st.isNoType()) {
                 // ignore invalid values. Assume that validation catches these
                 return;
             }
 
-            if (XmlID.type.isAssignableFrom(st))
-            {
+            if (XmlID.type.isAssignableFrom(st)) {
                 XmlObjectList xmlValue = new XmlObjectList(1);
                 XmlObject o = newValue(XmlID.type, value);
 
                 // Ignore invalid values. Assume that validation catches these
-                if (o == null) return;
+                if (o == null) {
+                    return;
+                }
 
                 xmlValue.set(o, 0);
 
-                if (_values.contains(xmlValue))
-                    emitError(e, XmlErrorCodes.ID_VALID$DUPLICATE, new Object[] { value });
-                else
+                if (_values.contains(xmlValue)) {
+                    emitError(e, XmlErrorCodes.ID_VALID$DUPLICATE, new Object[]{value});
+                } else {
                     _values.add(xmlValue);
+                }
             }
         }
 
-        void element(Event e, SchemaType st) {}
-        void endElement(Event e){}
-        void remove(Event e){}
+        void element(Event e, SchemaType st) {
+        }
+
+        void endElement(Event e) {
+        }
+
+        void remove(Event e) {
+        }
 
     }
 
-    public class IdRefState extends ConstraintState
-    {
+    public class IdRefState extends ConstraintState {
         IdState _ids;
         List _values;
 
-        IdRefState(IdState ids)
-        {
+        IdRefState(IdState ids) {
             _ids = ids;
             _values = new ArrayList();
         }
 
-        private void handleValue(Event e, SchemaType st, String value)
-        {
+        private void handleValue(Event e, SchemaType st, String value) {
             // Null value indicates previously reported validation problem
-            if (value == null) return;
+            if (value == null) {
+                return;
+            }
 
-            if (st == null || st.isNoType())
-            {
+            if (st == null || st.isNoType()) {
                 // ignore invalid values. Assume that validation catches these
                 return;
             }
-            if (XmlIDREFS.type.isAssignableFrom(st))
-            {
-                XmlIDREFS lv = (XmlIDREFS)newValue(XmlIDREFS.type, value);
+            if (XmlIDREFS.type.isAssignableFrom(st)) {
+                XmlIDREFS lv = (XmlIDREFS) newValue(XmlIDREFS.type, value);
 
                 // Ignore invalid values. Assume that validation catches these
-                if (lv == null) return;
+                if (lv == null) {
+                    return;
+                }
 
                 List l = lv.xgetListValue();
 
                 // Add one value for each idref in the list
-                for (int i = 0 ; i < l.size() ; i++)
-                {
+                for (int i = 0; i < l.size(); i++) {
                     XmlObjectList xmlValue = new XmlObjectList(1);
-                    XmlIDREF idref = (XmlIDREF)l.get(i);
+                    XmlIDREF idref = (XmlIDREF) l.get(i);
                     xmlValue.set(idref, 0);
                     _values.add(xmlValue);
                 }
-            }
-            else if (XmlIDREF.type.isAssignableFrom(st))
-            {
+            } else if (XmlIDREF.type.isAssignableFrom(st)) {
                 XmlObjectList xmlValue = new XmlObjectList(1);
-                XmlIDREF idref = (XmlIDREF)st.newValue(value);
+                XmlIDREF idref = (XmlIDREF) st.newValue(value);
 
                 // Ignore invalid values. Assume that validation catches these
-                if (idref == null) return;
+                if (idref == null) {
+                    return;
+                }
 
                 xmlValue.set(idref, 0);
                 _values.add(xmlValue);
             }
         }
 
-        void attr(Event e, QName name, SchemaType st, String value) 
-        {
+        void attr(Event e, QName name, SchemaType st, String value) {
             handleValue(e, st, value);
         }
-        void text(Event e, SchemaType st, String value, boolean emptyContent) 
-        {
-            if (emptyContent)
+
+        void text(Event e, SchemaType st, String value, boolean emptyContent) {
+            if (emptyContent) {
                 return;
+            }
 
             handleValue(e, st, value);
         }
-        void remove(Event e) 
-        { 
+
+        void remove(Event e) {
             // Validate each ref has a corresponding ID
-            for (Iterator it = _values.iterator() ; it.hasNext() ; )
-            {
+            for (Iterator it = _values.iterator(); it.hasNext(); ) {
                 Object o = it.next();
-                if (! _ids._values.contains(o))
-                {
+                if (!_ids._values.contains(o)) {
                     // KHK: cvc-id.1
                     emitError(e, "ID not found for IDRef value '" + o + "'");
                 }
             }
         }
-        void element(Event e, SchemaType st) { }
-        void endElement(Event e) { }
+
+        void element(Event e, SchemaType st) {
+        }
+
+        void endElement(Event e) {
+        }
     }
 
     private static class ElementState {
diff --git a/src/main/java/org/apache/xmlbeans/impl/common/NameUtil.java b/src/main/java/org/apache/xmlbeans/impl/common/NameUtil.java
index 85ac33f..da71017 100644
--- a/src/main/java/org/apache/xmlbeans/impl/common/NameUtil.java
+++ b/src/main/java/org/apache/xmlbeans/impl/common/NameUtil.java
@@ -16,91 +16,89 @@
 package org.apache.xmlbeans.impl.common;
 
 import javax.xml.namespace.QName;
-
 import java.util.*;
 
-public class NameUtil
-{
+public class NameUtil {
     // punctuation characters
     public final static char HYPHEN = '\u002D';
     public final static char PERIOD = '\u002E';
-    public final static char COLON  = '\u003A';
+    public final static char COLON = '\u003A';
     public final static char USCORE = '\u005F';
-    public final static char DOT    = '\u00B7';
+    public final static char DOT = '\u00B7';
     public final static char TELEIA = '\u0387';
-    public final static char AYAH   = '\u06DD';
+    public final static char AYAH = '\u06DD';
     public final static char ELHIZB = '\u06DE';
 
     private final static boolean DEBUG = false;
 
     private final static Set javaWords = new HashSet(Arrays.asList(
         new String[]
-        {
-              "assert",
-              "abstract",
-              "boolean",
-              "break",
-              "byte",
-              "case",
-              "catch",
-              "char",
-              "class",
-              "const",
-              "continue",
-              "default",
-              "do",
-              "double",
-              "else",
-              "enum", // since JDK1.5
-              "extends",
-              "false", // not a keyword
-              "final",
-              "finally",
-              "float",
-              "for",
-              "goto",
-              "if",
-              "implements",
-              "import",
-              "instanceof",
-              "int",
-              "interface",
-              "long",
-              "native",
-              "new",
-              "null", // not a keyword
-              "package",
-              "private",
-              "protected",
-              "public",
-              "return",
-              "short",
-              "static",
-              "strictfp",
-              "super",
-              "switch",
-              "synchronized",
-              "this",
-              "threadsafe",
-              "throw",
-              "throws",
-              "transient",
-              "true", // not a keyword
-              "try",
-              "void",
-              "volatile",
-              "while",
-        }
+            {
+                "assert",
+                "abstract",
+                "boolean",
+                "break",
+                "byte",
+                "case",
+                "catch",
+                "char",
+                "class",
+                "const",
+                "continue",
+                "default",
+                "do",
+                "double",
+                "else",
+                "enum", // since JDK1.5
+                "extends",
+                "false", // not a keyword
+                "final",
+                "finally",
+                "float",
+                "for",
+                "goto",
+                "if",
+                "implements",
+                "import",
+                "instanceof",
+                "int",
+                "interface",
+                "long",
+                "native",
+                "new",
+                "null", // not a keyword
+                "package",
+                "private",
+                "protected",
+                "public",
+                "return",
+                "short",
+                "static",
+                "strictfp",
+                "super",
+                "switch",
+                "synchronized",
+                "this",
+                "threadsafe",
+                "throw",
+                "throws",
+                "transient",
+                "true", // not a keyword
+                "try",
+                "void",
+                "volatile",
+                "while",
+            }
     ));
 
     private final static Set extraWords = new HashSet(Arrays.asList(
         new String[]
-        {
-              "i",          // used for indexes
-              "target",     // used for parameter
-              "org",        // used for package names
-              "com",        // used for package names
-        }
+            {
+                "i",          // used for indexes
+                "target",     // used for parameter
+                "org",        // used for package names
+                "com",        // used for package names
+            }
     ));
 
     /*
@@ -196,141 +194,142 @@
 
     private final static Set javaNames = new HashSet(Arrays.asList(
         new String[]
-        {
-            // 1. all the Java.lang classes [1.4.1 JDK].
-            "CharSequence",
-            "Cloneable",
-            "Comparable",
-            "Runnable",
+            {
+                // 1. all the Java.lang classes [1.4.1 JDK].
+                "CharSequence",
+                "Cloneable",
+                "Comparable",
+                "Runnable",
 
-            "Boolean",
-            "Byte",
-            "Character",
-            "Class",
-            "ClassLoader",
-            "Compiler",
-            "Double",
-            "Float",
-            "InheritableThreadLocal",
-            "Integer",
-            "Long",
-            "Math",
-            "Number",
-            "Object",
-            "Package",
-            "Process",
-            "Runtime",
-            "RuntimePermission",
-            "SecurityManager",
-            "Short",
-            "StackTraceElement",
-            "StrictMath",
-            "String",
-            "StringBuffer",
-            "System",
-            "Thread",
-            "ThreadGroup",
-            "ThreadLocal",
-            "Throwable",
-            "Void",
+                "Boolean",
+                "Byte",
+                "Character",
+                "Class",
+                "ClassLoader",
+                "Compiler",
+                "Double",
+                "Float",
+                "InheritableThreadLocal",
+                "Integer",
+                "Long",
+                "Math",
+                "Number",
+                "Object",
+                "Package",
+                "Process",
+                "Runtime",
+                "RuntimePermission",
+                "SecurityManager",
+                "Short",
+                "StackTraceElement",
+                "StrictMath",
+                "String",
+                "StringBuffer",
+                "System",
+                "Thread",
+                "ThreadGroup",
+                "ThreadLocal",
+                "Throwable",
+                "Void",
 
-            "ArithmeticException",
-            "ArrayIndexOutOfBoundsException",
-            "ArrayStoreException",
-            "ClassCastException",
-            "ClassNotFoundException",
-            "CloneNotSupportedException",
-            "Exception",
-            "IllegalAccessException",
-            "IllegalArgumentException",
-            "IllegalMonitorStateException",
-            "IllegalStateException",
-            "IllegalThreadStateException",
-            "IndexOutOfBoundsException",
-            "InstantiationException",
-            "InterruptedException",
-            "NegativeArraySizeException",
-            "NoSuchFieldException",
-            "NoSuchMethodException",
-            "NullPointerException",
-            "NumberFormatException",
-            "RuntimeException",
-            "SecurityException",
-            "StringIndexOutOfBoundsException",
-            "UnsupportedOperationException",
+                "ArithmeticException",
+                "ArrayIndexOutOfBoundsException",
+                "ArrayStoreException",
+                "ClassCastException",
+                "ClassNotFoundException",
+                "CloneNotSupportedException",
+                "Exception",
+                "IllegalAccessException",
+                "IllegalArgumentException",
+                "IllegalMonitorStateException",
+                "IllegalStateException",
+                "IllegalThreadStateException",
+                "IndexOutOfBoundsException",
+                "InstantiationException",
+                "InterruptedException",
+                "NegativeArraySizeException",
+                "NoSuchFieldException",
+                "NoSuchMethodException",
+                "NullPointerException",
+                "NumberFormatException",
+                "RuntimeException",
+                "SecurityException",
+                "StringIndexOutOfBoundsException",
+                "UnsupportedOperationException",
 
-            "AbstractMethodError",
-            "AssertionError",
-            "ClassCircularityError",
-            "ClassFormatError",
-            "Error",
-            "ExceptionInInitializerError",
-            "IllegalAccessError",
-            "IncompatibleClassChangeError",
-            "InstantiationError",
-            "InternalError",
-            "LinkageError",
-            "NoClassDefFoundError",
-            "NoSuchFieldError",
-            "NoSuchMethodError",
-            "OutOfMemoryError",
-            "StackOverflowError",
-            "ThreadDeath",
-            "UnknownError",
-            "UnsatisfiedLinkError",
-            "UnsupportedClassVersionError",
-            "VerifyError",
-            "VirtualMachineError",
+                "AbstractMethodError",
+                "AssertionError",
+                "ClassCircularityError",
+                "ClassFormatError",
+                "Error",
+                "ExceptionInInitializerError",
+                "IllegalAccessError",
+                "IncompatibleClassChangeError",
+                "InstantiationError",
+                "InternalError",
+                "LinkageError",
+                "NoClassDefFoundError",
+                "NoSuchFieldError",
+                "NoSuchMethodError",
+                "OutOfMemoryError",
+                "StackOverflowError",
+                "ThreadDeath",
+                "UnknownError",
+                "UnsatisfiedLinkError",
+                "UnsupportedClassVersionError",
+                "VerifyError",
+                "VirtualMachineError",
 
-            // 2. other classes used as primitive types by xml beans
-            "BigInteger",
-            "BigDecimal",
-            "Enum",
-            "Date",
-            "GDate",
-            "GDuration",
-            "QName",
-            "List",
+                // 2. other classes used as primitive types by xml beans
+                "BigInteger",
+                "BigDecimal",
+                "Enum",
+                "Date",
+                "GDate",
+                "GDuration",
+                "QName",
+                "List",
 
-            // 3. the top few org.apache.xmlbeans names
-            "XmlObject",
-            "XmlCursor",
-            "XmlBeans",
-            "SchemaType",
-        }
+                // 3. the top few org.apache.xmlbeans names
+                "XmlObject",
+                "XmlCursor",
+                "XmlBeans",
+                "SchemaType",
+            }
     ));
 
-    public static boolean isValidJavaIdentifier(String id)
-    {
-        if (id == null)
+    public static boolean isValidJavaIdentifier(String id) {
+        if (id == null) {
             throw new IllegalArgumentException("id cannot be null");
+        }
 
         int len = id.length();
-        if (len == 0)
+        if (len == 0) {
             return false;
+        }
 
-        if (javaWords.contains(id))
+        if (javaWords.contains(id)) {
             return false;
+        }
 
-        if (!Character.isJavaIdentifierStart(id.charAt(0)))
+        if (!Character.isJavaIdentifierStart(id.charAt(0))) {
             return false;
+        }
 
-        for (int i = 1; i < len; i++)
-        {
-            if (!Character.isJavaIdentifierPart(id.charAt(i)))
+        for (int i = 1; i < len; i++) {
+            if (!Character.isJavaIdentifierPart(id.charAt(i))) {
                 return false;
+            }
         }
 
         return true;
     }
 
-    public static String getClassNameFromQName(QName qname)
-    {
+    public static String getClassNameFromQName(QName qname) {
         return getClassNameFromQName(qname, false);
     }
 
-    public static String getClassNameFromQName(QName qname, boolean useJaxRpcRules)
-    {
+    public static String getClassNameFromQName(QName qname, boolean useJaxRpcRules) {
         String java_type = upperCamelCase(qname.getLocalPart(), useJaxRpcRules);
 
         String uri = qname.getNamespaceURI();
@@ -338,21 +337,22 @@
 
         java_pkg = getPackageFromNamespace(uri, useJaxRpcRules);
 
-        if (java_pkg != null)
+        if (java_pkg != null) {
             return java_pkg + "." + java_type;
-        else
+        } else {
             return java_type;
+        }
     }
 
-    private static final String JAVA_NS_PREFIX="java:";
+    private static final String JAVA_NS_PREFIX = "java:";
     private static final String LANG_PREFIX = "java.";
 
-    public static String getNamespaceFromPackage(final Class clazz)
-    {
+    public static String getNamespaceFromPackage(final Class clazz) {
         Class curr_clazz = clazz;
 
-        while (curr_clazz.isArray())
+        while (curr_clazz.isArray()) {
             curr_clazz = curr_clazz.getComponentType();
+        }
 
         String fullname = clazz.getName();
         int lastdot = fullname.lastIndexOf('.');
@@ -373,62 +373,67 @@
         return JAVA_NS_PREFIX + pkg_name;
     }
 
-    private static boolean isUriSchemeChar(char ch)
-    {
-        return (ch >= 'a' && ch <='z' ||
-            ch >= 'A' && ch <='Z' ||
-            ch >= '0' && ch <='9' ||
-            ch == '-' || ch == '.' || ch == '+');
+    private static boolean isUriSchemeChar(char ch) {
+        return (ch >= 'a' && ch <= 'z' ||
+                ch >= 'A' && ch <= 'Z' ||
+                ch >= '0' && ch <= '9' ||
+                ch == '-' || ch == '.' || ch == '+');
     }
 
-    private static boolean isUriAlphaChar(char ch)
-    {
-        return (ch >= 'a' && ch <='z' || ch >= 'A' && ch <= 'Z');
+    private static boolean isUriAlphaChar(char ch) {
+        return (ch >= 'a' && ch <= 'z' || ch >= 'A' && ch <= 'Z');
     }
 
-    private static int findSchemeColon(String uri)
-    {
+    private static int findSchemeColon(String uri) {
         int len = uri.length();
-        if (len == 0)
+        if (len == 0) {
             return -1;
-        if (!isUriAlphaChar(uri.charAt(0)))
+        }
+        if (!isUriAlphaChar(uri.charAt(0))) {
             return -1;
+        }
         int i;
-        for (i = 1; i < len; i++)
-            if (!isUriSchemeChar(uri.charAt(i)))
+        for (i = 1; i < len; i++) {
+            if (!isUriSchemeChar(uri.charAt(i))) {
                 break;
-        if (i == len)
+            }
+        }
+        if (i == len) {
             return -1;
-        if (uri.charAt(i) != ':')
+        }
+        if (uri.charAt(i) != ':') {
             return -1;
+        }
         // consume consecutive colons
-        for (; i < len; i++)
-            if (uri.charAt(i) != ':')
+        for (; i < len; i++) {
+            if (uri.charAt(i) != ':') {
                 break;
+            }
+        }
         // for the "scheme:::" case, return len-1
-        return i-1;
+        return i - 1;
     }
 
-    private static String jls77String(String name)
-    {
+    private static String jls77String(String name) {
         StringBuilder buf = new StringBuilder(name);
-        for (int i = 0; i < name.length(); i++)
-        {
+        for (int i = 0; i < name.length(); i++) {
             // We need to also make sure that our package names don't contain the
             // "$" character in them, which, although a valid Java identifier part,
             // would create confusion when trying to generate fully-qualified names
-            if (!Character.isJavaIdentifierPart(buf.charAt(i)) || '$' == buf.charAt(i))
+            if (!Character.isJavaIdentifierPart(buf.charAt(i)) || '$' == buf.charAt(i)) {
                 buf.setCharAt(i, '_');
+            }
         }
-        if (buf.length() == 0 || !Character.isJavaIdentifierStart(buf.charAt(0)))
+        if (buf.length() == 0 || !Character.isJavaIdentifierStart(buf.charAt(0))) {
             buf.insert(0, '_');
-        if (isJavaReservedWord(name))
+        }
+        if (isJavaReservedWord(name)) {
             buf.append('_');
+        }
         return buf.toString();
     }
 
-    private static List splitDNS(String dns)
-    {
+    private static List splitDNS(String dns) {
         // JAXB says: only split+reverse DNS if TLD matches known TLDs or ISO 3166
         // We are ignoring this now (TH)
 
@@ -436,8 +441,7 @@
 
         int end = dns.length();
         int begin = dns.lastIndexOf('.');
-        for ( ; begin != -1 ; begin--)
-        {
+        for (; begin != -1; begin--) {
             if (dns.charAt(begin) == '.') {
                 result.add(jls77String(dns.substring(begin + 1, end)));
                 end = begin;
@@ -447,98 +451,98 @@
 
         // JAXB draft example implies removal of www
         if (result.size() >= 3 &&
-                ((String)result.get(result.size() - 1)).toLowerCase().equals("www"))
+            ((String) result.get(result.size() - 1)).toLowerCase().equals("www")) {
             result.remove(result.size() - 1);
+        }
 
         return result;
     }
 
-    private static String processFilename(String filename)
-    {
+    private static String processFilename(String filename) {
         // JAXB says: strip 2 or 3 letter extension or ".html"
 
         int i = filename.lastIndexOf('.');
         if (i > 0 && (
-                i + 1 + 2 == filename.length() ||
-                i + 1 + 3 == filename.length() ||
-                filename.substring(i + 1).toLowerCase() == "html"))
-        {
+            i + 1 + 2 == filename.length() ||
+            i + 1 + 3 == filename.length() ||
+            "html".equals(filename.substring(i + 1).toLowerCase()))) {
             return filename.substring(0, i);
         }
 
         return filename;
     }
 
-    public static String getPackageFromNamespace(String uri)
-    {
+    public static String getPackageFromNamespace(String uri) {
         return getPackageFromNamespace(uri, false);
     }
 
-    public static String getPackageFromNamespace(String uri, boolean useJaxRpcRules)
-    {
+    public static String getPackageFromNamespace(String uri, boolean useJaxRpcRules) {
         // special case: no namespace -> package "noNamespace"
-        if (uri == null || uri.length() == 0)
+        if (uri == null || uri.length() == 0) {
             return "noNamespace";
+        }
 
         // apply draft JAXB rules
         int len = uri.length();
         int i = findSchemeColon(uri);
         List result = null;
 
-        if (i == len-1)
-        {
+        if (i == len - 1) {
             // XMLBEANS-57: colon is at end so just use scheme as the package name
             result = new ArrayList();
             result.add(uri.substring(0, i));
-        }
-        else if (i >= 0 && uri.substring(0, i).equals("java"))
-        {
-            result =  Arrays.asList(uri.substring(i + 1).split("\\."));
-        }
-        else {
+        } else if (i >= 0 && uri.substring(0, i).equals("java")) {
+            result = Arrays.asList(uri.substring(i + 1).split("\\."));
+        } else {
             result = new ArrayList();
-            outer: for (i = i + 1; i < len; )
-            {
-                while (uri.charAt(i) == '/')
-                    if (++i >= len) break outer;
+            outer:
+            for (i = i + 1; i < len; ) {
+                while (uri.charAt(i) == '/') {
+                    if (++i >= len) {
+                        break outer;
+                    }
+                }
                 int start = i;
-                while (uri.charAt(i) != '/')
-                    if (++i >= len) break;
+                while (uri.charAt(i) != '/') {
+                    if (++i >= len) {
+                        break;
+                    }
+                }
                 int end = i;
                 result.add(uri.substring(start, end));
             }
-            if (result.size() > 1)
-                result.set(result.size() - 1, processFilename((String)result.get(result.size() - 1)));
+            if (result.size() > 1) {
+                result.set(result.size() - 1, processFilename((String) result.get(result.size() - 1)));
+            }
 
-            if (result.size() > 0)
-            {
-                List splitdns = splitDNS((String)result.get(0));
+            if (result.size() > 0) {
+                List splitdns = splitDNS((String) result.get(0));
                 result.remove(0);
                 result.addAll(0, splitdns);
             }
         }
 
         StringBuilder buf = new StringBuilder();
-        for (Iterator it = result.iterator(); it.hasNext(); )
-        {
-            String part = nonJavaKeyword(lowerCamelCase((String)it.next(), useJaxRpcRules, true));
-            if (part.length() > 0)
-            {
+        for (Iterator it = result.iterator(); it.hasNext(); ) {
+            String part = nonJavaKeyword(lowerCamelCase((String) it.next(), useJaxRpcRules, true));
+            if (part.length() > 0) {
                 buf.append(part);
                 buf.append('.');
             }
         }
-        if (buf.length() == 0)
+        if (buf.length() == 0) {
             return "noNamespace";
-        if (useJaxRpcRules)
+        }
+        if (useJaxRpcRules) {
             return buf.substring(0, buf.length() - 1).toLowerCase();
+        }
         return buf.substring(0, buf.length() - 1); // chop off extra dot
     }
 
-    public static void main(String[] args)
-    {
-        for (int i = 0; i < args.length; i++)
+    public static void main(String[] args) {
+        for (int i = 0; i < args.length; i++) {
             System.out.println(upperCaseUnderbar(args[i]));
+        }
     }
 
     /**
@@ -547,30 +551,27 @@
      * java identifier start. (If JAXB rules don't produce
      * one, then "X_" is prepended.)
      */
-    public static String upperCaseUnderbar(String xml_name)
-    {
+    public static String upperCaseUnderbar(String xml_name) {
         StringBuilder buf = new StringBuilder();
         List words = splitWords(xml_name, false);
 
         final int sz = words.size() - 1;
-        if (sz >= 0 && !Character.isJavaIdentifierStart(((String)words.get(0)).charAt(0)))
+        if (sz >= 0 && !Character.isJavaIdentifierStart(((String) words.get(0)).charAt(0))) {
             buf.append("X_");
+        }
 
-        for(int i = 0 ; i < sz ; i++)
-        {
-            buf.append((String)words.get(i));
+        for (int i = 0; i < sz; i++) {
+            buf.append((String) words.get(i));
             buf.append(USCORE);
         }
 
-        if (sz >= 0)
-        {
-            buf.append((String)words.get(sz));
+        if (sz >= 0) {
+            buf.append((String) words.get(sz));
         }
 
         //upcase entire buffer
         final int len = buf.length();
-        for(int j = 0 ; j < len ; j++)
-        {
+        for (int j = 0; j < len; j++) {
             char c = buf.charAt(j);
             buf.setCharAt(j, Character.toUpperCase(c));
         }
@@ -584,8 +585,7 @@
      * java identifier start. (If JAXB rules don't produce
      * one, then "X" is prepended.)
      */
-    public static String upperCamelCase(String xml_name)
-    {
+    public static String upperCamelCase(String xml_name) {
         return upperCamelCase(xml_name, false);
     }
 
@@ -593,19 +593,19 @@
      * Returns a camel-cased string, but either JAXB or JAX-RPC rules
      * are used
      */
-    public static String upperCamelCase(String xml_name, boolean useJaxRpcRules)
-    {
+    public static String upperCamelCase(String xml_name, boolean useJaxRpcRules) {
         StringBuilder buf = new StringBuilder();
         List words = splitWords(xml_name, useJaxRpcRules);
 
-        if (words.size() > 0)
-        {
-            if (!Character.isJavaIdentifierStart(((String)words.get(0)).charAt(0)))
+        if (words.size() > 0) {
+            if (!Character.isJavaIdentifierStart(((String) words.get(0)).charAt(0))) {
                 buf.append("X");
+            }
 
             Iterator itr = words.iterator();
-            while(itr.hasNext())
-                buf.append((String)itr.next());
+            while (itr.hasNext()) {
+                buf.append((String) itr.next());
+            }
         }
         return buf.toString();
     }
@@ -619,8 +619,7 @@
      * java identifier start. (If JAXB rules don't produce
      * one, then "x" is prepended.)
      */
-    public static String lowerCamelCase(String xml_name)
-    {
+    public static String lowerCamelCase(String xml_name) {
         return lowerCamelCase(xml_name, false, true);
     }
 
@@ -628,31 +627,31 @@
      * Returns a camel-cased string using the JAXB or JAX-RPC rules
      */
     public static String lowerCamelCase(String xml_name, boolean useJaxRpcRules,
-                                        boolean fixGeneratedName)
-    {
+                                        boolean fixGeneratedName) {
         StringBuilder buf = new StringBuilder();
         List words = splitWords(xml_name, useJaxRpcRules);
 
-        if (words.size() > 0)
-        {
-            String first = ((String)words.get(0)).toLowerCase();
+        if (words.size() > 0) {
+            String first = ((String) words.get(0)).toLowerCase();
             char f = first.charAt(0);
-            if (!Character.isJavaIdentifierStart(f) && fixGeneratedName)
+            if (!Character.isJavaIdentifierStart(f) && fixGeneratedName) {
                 buf.append("x");
+            }
             buf.append(first);
 
             Iterator itr = words.iterator();
             itr.next(); // skip already-lowercased word
-            while(itr.hasNext())
-                buf.append((String)itr.next());
+            while (itr.hasNext()) {
+                buf.append((String) itr.next());
+            }
         }
         return buf.toString();
     }
 
-    public static String upperCaseFirstLetter(String s)
-    {
-        if (s.length() == 0 || Character.isUpperCase(s.charAt(0)))
+    public static String upperCaseFirstLetter(String s) {
+        if (s.length() == 0 || Character.isUpperCase(s.charAt(0))) {
             return s;
+        }
 
         StringBuilder buf = new StringBuilder(s);
         buf.setCharAt(0, Character.toUpperCase(buf.charAt(0)));
@@ -661,42 +660,38 @@
 
 
     /**
-       split an xml name into words via JAXB approach, upcasing first
-       letter of each word as needed, if upcase is true
-
-       ncname is xml ncname (i.e. no colons).
-    */
-    private static void addCapped(List list, String str)
-    {
-        if (str.length() > 0)
+     * split an xml name into words via JAXB approach, upcasing first
+     * letter of each word as needed, if upcase is true
+     * <p>
+     * ncname is xml ncname (i.e. no colons).
+     */
+    private static void addCapped(List list, String str) {
+        if (str.length() > 0) {
             list.add(upperCaseFirstLetter(str));
+        }
     }
 
-    public static List splitWords(String name, boolean useJaxRpcRules)
-    {
+    public static List splitWords(String name, boolean useJaxRpcRules) {
         List list = new ArrayList();
         int len = name.length();
         int start = 0;
         int prefix = START;
-        for (int i = 0; i < len; i++)
-        {
+        for (int i = 0; i < len; i++) {
             int current = getCharClass(name.charAt(i), useJaxRpcRules);
-            if (prefix != PUNCT && current == PUNCT)
-            {
+            if (prefix != PUNCT && current == PUNCT) {
                 addCapped(list, name.substring(start, i));
-                while ((current = getCharClass(name.charAt(i), useJaxRpcRules)) == PUNCT)
-                    if (++i >= len) return list;
+                while ((current = getCharClass(name.charAt(i), useJaxRpcRules)) == PUNCT) {
+                    if (++i >= len) {
+                        return list;
+                    }
+                }
                 start = i;
-            }
-            else if ((prefix == DIGIT) != (current == DIGIT) ||
-                     (prefix == LOWER && current != LOWER) ||
-                     (isLetter(prefix) != isLetter(current)))
-            {
+            } else if ((prefix == DIGIT) != (current == DIGIT) ||
+                       (prefix == LOWER && current != LOWER) ||
+                       (isLetter(prefix) != isLetter(current))) {
                 addCapped(list, name.substring(start, i));
                 start = i;
-            }
-            else if (prefix == UPPER && current == LOWER && i > start + 1)
-            {
+            } else if (prefix == UPPER && current == LOWER && i > start + 1) {
                 addCapped(list, name.substring(start, i - 1));
                 start = i - 1;
             }
@@ -712,45 +707,43 @@
     private final static int DIGIT = 2;
     private final static int MARK = 3;
     private final static int UPPER = 4;
-    private final static int LOWER= 5;
-    private final static int NOCASE= 6;
+    private final static int LOWER = 5;
+    private final static int NOCASE = 6;
 
-    public static int getCharClass(char c, boolean useJaxRpcRules)
-    {
+    public static int getCharClass(char c, boolean useJaxRpcRules) {
         //ordering is important here.
-        if (isPunctuation(c, useJaxRpcRules))
+        if (isPunctuation(c, useJaxRpcRules)) {
             return PUNCT;
-        else if (Character.isDigit(c))
+        } else if (Character.isDigit(c)) {
             return DIGIT;
-        else if (Character.isUpperCase(c))
+        } else if (Character.isUpperCase(c)) {
             return UPPER;
-        else if (Character.isLowerCase(c))
+        } else if (Character.isLowerCase(c)) {
             return LOWER;
-        else if (Character.isLetter(c))
+        } else if (Character.isLetter(c)) {
             return NOCASE;
-        else if (Character.isJavaIdentifierPart(c))
+        } else if (Character.isJavaIdentifierPart(c)) {
             return MARK;
-        else
+        } else {
             return PUNCT; // not covered by JAXB: treat it as punctuation
+        }
     }
 
-    private static boolean isLetter(int state)
-    {
-        return (state==UPPER
-              || state==LOWER
-              || state==NOCASE);
+    private static boolean isLetter(int state) {
+        return (state == UPPER
+                || state == LOWER
+                || state == NOCASE);
     }
 
-    public static boolean isPunctuation(char c, boolean useJaxRpcRules)
-    {
+    public static boolean isPunctuation(char c, boolean useJaxRpcRules) {
         return (c == HYPHEN
-              || c == PERIOD
-              || c == COLON
-              || c == DOT
-              || (c == USCORE && !useJaxRpcRules)
-              || c == TELEIA
-              || c == AYAH
-              || c == ELHIZB);
+                || c == PERIOD
+                || c == COLON
+                || c == DOT
+                || (c == USCORE && !useJaxRpcRules)
+                || c == TELEIA
+                || c == AYAH
+                || c == ELHIZB);
     }
 
     /**
@@ -758,10 +751,10 @@
      * may collide with a Java keyword.  If it does collide, this
      * prepends the letter "x".
      */
-    public static String nonJavaKeyword(String word)
-    {
-        if (isJavaReservedWord(word))
+    public static String nonJavaKeyword(String word) {
+        if (isJavaReservedWord(word)) {
             return 'x' + word;
+        }
         return word;
     }
 
@@ -770,10 +763,10 @@
      * may collide with a Java keyword.  If it does collide, this
      * prepends the letter "x".
      */
-    public static String nonExtraKeyword(String word)
-    {
-        if (isExtraReservedWord(word, true))
+    public static String nonExtraKeyword(String word) {
+        if (isExtraReservedWord(word, true)) {
             return word + "Value";
+        }
         return word;
     }
 
@@ -782,34 +775,32 @@
      * may collide with a java.lang.* classname.  If it does collide, this
      * prepends the letter "X".
      */
-    public static String nonJavaCommonClassName(String name)
-    {
-        if (isJavaCommonClassName(name))
+    public static String nonJavaCommonClassName(String name) {
+        if (isJavaCommonClassName(name)) {
             return "X" + name;
+        }
         return name;
     }
 
-    private static boolean isJavaReservedWord(String word)
-    {
+    private static boolean isJavaReservedWord(String word) {
         return isJavaReservedWord(word, true);
     }
 
-    private static boolean isJavaReservedWord(String word, boolean ignore_case)
-    {
-        if (ignore_case)
+    private static boolean isJavaReservedWord(String word, boolean ignore_case) {
+        if (ignore_case) {
             word = word.toLowerCase();
+        }
         return javaWords.contains(word);
     }
 
-    private static boolean isExtraReservedWord(String word, boolean ignore_case)
-    {
-        if (ignore_case)
+    private static boolean isExtraReservedWord(String word, boolean ignore_case) {
+        if (ignore_case) {
             word = word.toLowerCase();
+        }
         return extraWords.contains(word);
     }
 
-    public static boolean isJavaCommonClassName(String word)
-    {
+    public static boolean isJavaCommonClassName(String word) {
         return javaNames.contains(word);
     }
 }
diff --git a/src/main/java/org/apache/xmlbeans/impl/common/SniffedXmlInputStream.java b/src/main/java/org/apache/xmlbeans/impl/common/SniffedXmlInputStream.java
index 611af92..6f2a4eb 100644
--- a/src/main/java/org/apache/xmlbeans/impl/common/SniffedXmlInputStream.java
+++ b/src/main/java/org/apache/xmlbeans/impl/common/SniffedXmlInputStream.java
@@ -15,43 +15,34 @@
 
 package org.apache.xmlbeans.impl.common;
 
-import java.io.InputStream;
-import java.io.BufferedInputStream;
-import java.io.IOException;
-import java.io.ByteArrayInputStream;
-import java.io.InputStreamReader;
-import java.io.Reader;
+import java.io.*;
 import java.nio.charset.Charset;
 
-public class SniffedXmlInputStream extends BufferedInputStream
-{
+public class SniffedXmlInputStream extends BufferedInputStream {
     // We don't sniff more than 192 bytes.
-    public static int MAX_SNIFFED_BYTES = 192;
+    public static final int MAX_SNIFFED_BYTES = 192;
 
-    public SniffedXmlInputStream(InputStream stream) throws IOException
-    {
+    public SniffedXmlInputStream(InputStream stream) throws IOException {
         super(stream);
 
         // read byte order marks and detect EBCDIC etc
         _encoding = sniffFourBytes();
 
-        if (_encoding != null && _encoding.equals("IBM037"))
-        {
+        if (_encoding != null && _encoding.equals("IBM037")) {
             // First four bytes suggest EBCDIC with <?xm at start
             String encoding = sniffForXmlDecl(_encoding);
-            if (encoding != null)
+            if (encoding != null) {
                 _encoding = encoding;
+            }
         }
 
-        if (_encoding == null)
-        {
+        if (_encoding == null) {
             // Haven't yet determined encoding: sniff for <?xml encoding="..."?>
             // assuming we can read it as UTF-8.
             _encoding = sniffForXmlDecl("UTF-8");
         }
 
-        if (_encoding == null)
-        {
+        if (_encoding == null) {
             // The XML spec says these two things:
 
             // (1) "In the absence of external character encoding information
@@ -81,56 +72,54 @@
         }
     }
 
-    private int readAsMuchAsPossible(byte[] buf, int startAt, int len) throws IOException
-    {
+    private int readAsMuchAsPossible(byte[] buf, int startAt, int len) throws IOException {
         int total = 0;
-        while (total < len)
-        {
+        while (total < len) {
             int count = read(buf, startAt + total, len - total);
-            if (count < 0)
+            if (count < 0) {
                 break;
+            }
             total += count;
         }
         return total;
     }
 
-    private String sniffFourBytes() throws IOException
-    {
+    private String sniffFourBytes() throws IOException {
         mark(4);
         int skip = 0;
-        try
-        {
+        try {
             byte[] buf = new byte[4];
-            if (readAsMuchAsPossible(buf, 0, 4) < 4)
+            if (readAsMuchAsPossible(buf, 0, 4) < 4) {
                 return null;
+            }
             long result = 0xFF000000 & (buf[0] << 24) | 0x00FF0000 & (buf[1] << 16) | 0x0000FF00 & (buf[2] << 8) | 0x000000FF & buf[3];
 
-            if (result == 0x0000FEFF)
+            if (result == 0x0000FEFF) {
                 return "UCS-4";
-            else if (result == 0xFFFE0000)
+            } else if (result == 0xFFFE0000) {
                 return "UCS-4";
-            else if (result == 0x0000003C)
+            } else if (result == 0x0000003C) {
                 return "UCS-4BE";
-            else if (result == 0x3C000000)
+            } else if (result == 0x3C000000) {
                 return "UCS-4LE";
-            else if (result == 0x003C003F)
+            } else if (result == 0x003C003F) {
                 return "UTF-16BE";
-            else if (result == 0x3C003F00)
+            } else if (result == 0x3C003F00) {
                 return "UTF-16LE";
-            else if (result == 0x3C3F786D)
+            } else if (result == 0x3C3F786D) {
                 return null; // looks like US-ASCII with <?xml: sniff
-            else if (result == 0x4C6FA794)
+            } else if (result == 0x4C6FA794) {
                 return "IBM037"; // Sniff for ebdic codepage
-            else if ((result & 0xFFFF0000) == 0xFEFF0000)
+            } else if ((result & 0xFFFF0000) == 0xFEFF0000) {
                 return "UTF-16";
-            else if ((result & 0xFFFF0000) == 0xFFFE0000)
+            } else if ((result & 0xFFFF0000) == 0xFFFE0000) {
                 return "UTF-16";
-            else if ((result & 0xFFFFFF00) == 0xEFBBBF00)
+            } else if ((result & 0xFFFFFF00) == 0xEFBBBF00) {
                 return "UTF-8";
-            else return null;
-        }
-        finally
-        {
+            } else {
+                return null;
+            }
+        } finally {
             reset();
         }
     }
@@ -147,11 +136,9 @@
     private static Charset dummy7 = Charset.forName("Cp1252");
 
 
-    private String sniffForXmlDecl(String encoding) throws IOException
-    {
+    private String sniffForXmlDecl(String encoding) throws IOException {
         mark(MAX_SNIFFED_BYTES);
-        try
-        {
+        try {
             byte[] bytebuf = new byte[MAX_SNIFFED_BYTES];
             int bytelimit = readAsMuchAsPossible(bytebuf, 0, MAX_SNIFFED_BYTES);
 
@@ -160,63 +147,56 @@
             Reader reader = new InputStreamReader(new ByteArrayInputStream(bytebuf, 0, bytelimit), charset);
             char[] buf = new char[bytelimit];
             int limit = 0;
-            while (limit < bytelimit)
-            {
+            while (limit < bytelimit) {
                 int count = reader.read(buf, limit, bytelimit - limit);
-                if (count < 0)
+                if (count < 0) {
                     break;
+                }
                 limit += count;
             }
 
             return extractXmlDeclEncoding(buf, 0, limit);
-        }
-        finally
-        {
+        } finally {
             reset();
         }
     }
 
     private String _encoding;
 
-    public String getXmlEncoding()
-    {
+    public String getXmlEncoding() {
         return _encoding;
     }
 
-    /* package */ static String extractXmlDeclEncoding(char[] buf, int offset, int size)
-    {
+    /* package */
+    static String extractXmlDeclEncoding(char[] buf, int offset, int size) {
         int limit = offset + size;
         int xmlpi = firstIndexOf("<?xml", buf, offset, limit);
-        if (xmlpi >= 0)
-        {
+        if (xmlpi >= 0) {
             int i = xmlpi + 5;
             ScannedAttribute attr = new ScannedAttribute();
-            while (i < limit)
-            {
+            while (i < limit) {
                 i = scanAttribute(buf, i, limit, attr);
-                if (i < 0)
+                if (i < 0) {
                     return null;
-                if (attr.name.equals("encoding"))
+                }
+                if (attr.name.equals("encoding")) {
                     return attr.value;
+                }
             }
         }
         return null;
     }
 
-    private static int firstIndexOf(String s, char[] buf, int startAt, int limit)
-    {
-        assert(s.length() > 0);
+    private static int firstIndexOf(String s, char[] buf, int startAt, int limit) {
+        assert (s.length() > 0);
         char[] lookFor = s.toCharArray();
 
         char firstchar = lookFor[0];
-        searching: for (limit -= lookFor.length; startAt < limit; startAt++)
-        {
-            if (buf[startAt] == firstchar)
-            {
-                for (int i = 1; i < lookFor.length; i++)
-                {
-                    if (buf[startAt + i] != lookFor[i])
-                    {
+        searching:
+        for (limit -= lookFor.length; startAt < limit; startAt++) {
+            if (buf[startAt] == firstchar) {
+                for (int i = 1; i < lookFor.length; i++) {
+                    if (buf[startAt + i] != lookFor[i]) {
                         continue searching;
                     }
                 }
@@ -227,68 +207,75 @@
         return -1;
     }
 
-    private static int nextNonmatchingByte(char[] lookFor, char[] buf, int startAt, int limit)
-    {
-        searching: for (; startAt < limit; startAt++)
-        {
+    private static int nextNonmatchingByte(char[] lookFor, char[] buf, int startAt, int limit) {
+        searching:
+        for (; startAt < limit; startAt++) {
             int thischar = buf[startAt];
-            for (int i = 0; i < lookFor.length; i++)
-                if (thischar == lookFor[i])
+            for (int i = 0; i < lookFor.length; i++) {
+                if (thischar == lookFor[i]) {
                     continue searching;
+                }
+            }
             return startAt;
         }
         return -1;
     }
 
-    private static int nextMatchingByte(char[] lookFor, char[] buf, int startAt, int limit)
-    {
-        searching: for (; startAt < limit; startAt++)
-        {
+    private static int nextMatchingByte(char[] lookFor, char[] buf, int startAt, int limit) {
+        searching:
+        for (; startAt < limit; startAt++) {
             int thischar = buf[startAt];
-            for (int i = 0; i < lookFor.length; i++)
-                if (thischar == lookFor[i])
+            for (int i = 0; i < lookFor.length; i++) {
+                if (thischar == lookFor[i]) {
                     return startAt;
+                }
+            }
         }
         return -1;
     }
 
-    private static int nextMatchingByte(char lookFor, char[] buf, int startAt, int limit)
-    {
-        searching: for (; startAt < limit; startAt++)
-        {
-            if (buf[startAt] == lookFor)
+    private static int nextMatchingByte(char lookFor, char[] buf, int startAt, int limit) {
+        searching:
+        for (; startAt < limit; startAt++) {
+            if (buf[startAt] == lookFor) {
                 return startAt;
+            }
         }
         return -1;
     }
-    private static char[] WHITESPACE = new char[] { ' ', '\r', '\t', '\n' };
-    private static char[] NOTNAME = new char[] { '=', ' ', '\r', '\t', '\n', '?', '>', '<', '\'', '\"' };
 
-    private static class ScannedAttribute
-    {
+    private static char[] WHITESPACE = new char[]{' ', '\r', '\t', '\n'};
+    private static char[] NOTNAME = new char[]{'=', ' ', '\r', '\t', '\n', '?', '>', '<', '\'', '\"'};
+
+    private static class ScannedAttribute {
         public String name;
         public String value;
     }
 
-    private static int scanAttribute(char[] buf, int startAt, int limit, ScannedAttribute attr)
-    {
+    private static int scanAttribute(char[] buf, int startAt, int limit, ScannedAttribute attr) {
         int nameStart = nextNonmatchingByte(WHITESPACE, buf, startAt, limit);
-        if (nameStart < 0)
+        if (nameStart < 0) {
             return -1;
+        }
         int nameEnd = nextMatchingByte(NOTNAME, buf, nameStart, limit);
-        if (nameEnd < 0)
+        if (nameEnd < 0) {
             return -1;
+        }
         int equals = nextNonmatchingByte(WHITESPACE, buf, nameEnd, limit);
-        if (equals < 0)
+        if (equals < 0) {
             return -1;
-        if (buf[equals] != '=')
+        }
+        if (buf[equals] != '=') {
             return -1;
+        }
         int valQuote = nextNonmatchingByte(WHITESPACE, buf, equals + 1, limit);
-        if (buf[valQuote] != '\'' && buf[valQuote] != '\"')
+        if (buf[valQuote] != '\'' && buf[valQuote] != '\"') {
             return -1;
+        }
         int valEndquote = nextMatchingByte(buf[valQuote], buf, valQuote + 1, limit);
-        if (valEndquote < 0)
+        if (valEndquote < 0) {
             return -1;
+        }
         attr.name = new String(buf, nameStart, nameEnd - nameStart);
         attr.value = new String(buf, valQuote + 1, valEndquote - valQuote - 1);
         return valEndquote + 1;
diff --git a/src/main/java/org/apache/xmlbeans/impl/common/SniffedXmlReader.java b/src/main/java/org/apache/xmlbeans/impl/common/SniffedXmlReader.java
index b497814..214ec4d 100644
--- a/src/main/java/org/apache/xmlbeans/impl/common/SniffedXmlReader.java
+++ b/src/main/java/org/apache/xmlbeans/impl/common/SniffedXmlReader.java
@@ -15,30 +15,27 @@
 
 package org.apache.xmlbeans.impl.common;
 
+import java.io.BufferedReader;
 import java.io.IOException;
 import java.io.Reader;
-import java.io.BufferedReader;
 import java.nio.charset.Charset;
 
-public class SniffedXmlReader extends BufferedReader
-{
+public class SniffedXmlReader extends BufferedReader {
     // We don't sniff more than 192 bytes.
-    public static int MAX_SNIFFED_CHARS = 192;
+    public static final int MAX_SNIFFED_CHARS = 192;
 
-    public SniffedXmlReader(Reader reader) throws IOException
-    {
+    public SniffedXmlReader(Reader reader) throws IOException {
         super(reader);
         _encoding = sniffForXmlDecl();
     }
 
-    private int readAsMuchAsPossible(char[] buf, int startAt, int len) throws IOException
-    {
+    private int readAsMuchAsPossible(char[] buf, int startAt, int len) throws IOException {
         int total = 0;
-        while (total < len)
-        {
+        while (total < len) {
             int count = read(buf, startAt + total, len - total);
-            if (count < 0)
+            if (count < 0) {
                 break;
+            }
             total += count;
         }
         return total;
@@ -56,25 +53,20 @@
     private static Charset dummy7 = Charset.forName("Cp1252");
 
 
-    private String sniffForXmlDecl() throws IOException
-    {
+    private String sniffForXmlDecl() throws IOException {
         mark(MAX_SNIFFED_CHARS);
-        try
-        {
+        try {
             char[] buf = new char[MAX_SNIFFED_CHARS];
             int limit = readAsMuchAsPossible(buf, 0, MAX_SNIFFED_CHARS);
             return SniffedXmlInputStream.extractXmlDeclEncoding(buf, 0, limit);
-        }
-        finally
-        {
+        } finally {
             reset();
         }
     }
 
     private String _encoding;
 
-    public String getXmlEncoding()
-    {
+    public String getXmlEncoding() {
         return _encoding;
     }
 }
diff --git a/src/main/java/org/apache/xmlbeans/impl/common/XBeanDebug.java b/src/main/java/org/apache/xmlbeans/impl/common/XBeanDebug.java
index 19f2c4a..b2b62af 100644
--- a/src/main/java/org/apache/xmlbeans/impl/common/XBeanDebug.java
+++ b/src/main/java/org/apache/xmlbeans/impl/common/XBeanDebug.java
@@ -18,102 +18,83 @@
 import org.apache.xmlbeans.SystemProperties;
 
 import java.io.File;
-import java.io.PrintStream;
-import java.io.FileOutputStream;
 import java.io.IOException;
+import java.io.PrintStream;
 
-public class XBeanDebug
-{
+public class XBeanDebug {
     public static final int TRACE_SCHEMA_LOADING = 0x0001;
     public static final String traceProp = "org.apache.xmlbeans.impl.debug";
     public static final String defaultProp = ""; // "TRACE_SCHEMA_LOADING";
 
     private static int _enabled = initializeBitsFromProperty();
     private static int _indent = 0;
-    private static String _indentspace = "                                                                                ";
 
-    private static int initializeBitsFromProperty()
-    {
-        int bits = 0;
+    private static int initializeBitsFromProperty() {
         String prop = SystemProperties.getProperty(traceProp, defaultProp);
-        if (prop.indexOf("TRACE_SCHEMA_LOADING") >= 0)
-            bits |= TRACE_SCHEMA_LOADING;
-        return bits;
+        return (prop.contains("TRACE_SCHEMA_LOADING")) ? TRACE_SCHEMA_LOADING : 0;
     }
-    public static void enable(int bits)
-    {
+
+    public static void enable(int bits) {
         _enabled = _enabled | bits;
     }
 
-    public static void disable(int bits)
-    {
+    public static void disable(int bits) {
         _enabled = _enabled & ~bits;
     }
 
-    public static void trace(int bits, String message, int indent)
-    {
-        if (test(bits))
-        {
-            synchronized (XBeanDebug.class)
-            {
-                if (indent < 0)
+    public static void trace(int bits, String message, int indent) {
+        if (test(bits)) {
+            synchronized (XBeanDebug.class) {
+                if (indent < 0) {
                     _indent += indent;
+                }
 
+                String _indentspace = "                                                                                ";
                 String spaces = _indent < 0 ? "" : _indent > _indentspace.length() ? _indentspace : _indentspace.substring(0, _indent);
                 String logmessage = Thread.currentThread().getName() + ": " + spaces + message + "\n";
                 System.err.print(logmessage);
 
-                if (indent > 0)
+                if (indent > 0) {
                     _indent += indent;
+                }
             }
         }
     }
 
-    public static boolean test(int bits)
-    {
+    public static boolean test(int bits) {
         return (_enabled & bits) != 0;
     }
-    
+
     static PrintStream _err;
-    
-    public static String log(String message)
-    {
+
+    public static String log(String message) {
         log(message, null);
         return message;
     }
-    
-    public static String logStackTrace(String message)
-    {
+
+    public static String logStackTrace(String message) {
         log(message, new Throwable());
         return message;
     }
-    
-    private synchronized static String log(String message, Throwable stackTrace)
-    {
-        if (_err == null)
-        {
-            try
-            {
+
+    private synchronized static String log(String message, Throwable stackTrace) {
+        if (_err == null) {
+            try {
                 File diagnosticFile = File.createTempFile("xmlbeandebug", ".log");
-                _err = new PrintStream(new FileOutputStream(diagnosticFile));
+                _err = new PrintStream(diagnosticFile, "UTF-8");
                 System.err.println("Diagnostic XML Bean debug log file created: " + diagnosticFile);
-            }
-            catch (IOException e)
-            {
+            } catch (IOException e) {
                 _err = System.err;
             }
         }
         _err.println(message);
-        if (stackTrace != null)
-        {
+        if (stackTrace != null) {
             stackTrace.printStackTrace(_err);
         }
         return message;
     }
-    
-    public static Throwable logException(Throwable t)
-    {
+
+    public static void logException(Throwable t) {
         log(t.getMessage(), t);
-        return t;
     }
 }
diff --git a/src/main/java/org/apache/xmlbeans/impl/common/XPath.java b/src/main/java/org/apache/xmlbeans/impl/common/XPath.java
index fe8a2ff..4ba2f68 100644
--- a/src/main/java/org/apache/xmlbeans/impl/common/XPath.java
+++ b/src/main/java/org/apache/xmlbeans/impl/common/XPath.java
@@ -15,1105 +15,65 @@
 
 package org.apache.xmlbeans.impl.common;
 
-import javax.xml.namespace.QName;
-
-import java.util.ArrayList;
-import java.util.List;
-import java.util.Map;
-import java.util.HashMap;
 import org.apache.xmlbeans.XmlError;
 import org.apache.xmlbeans.XmlException;
-import org.apache.xmlbeans.impl.common.XMLChar;
+
+import java.util.Map;
 
 
-public class XPath
-{
-    public static class XPathCompileException extends XmlException
-    {
-        XPathCompileException ( XmlError err )
-        {
-            super( err.toString(), null, err );
+public class XPath {
+    public static final String _NS_BOUNDARY = "$xmlbeans!ns_boundary";
+    public static final String _DEFAULT_ELT_NS = "$xmlbeans!default_uri";
+    final Selector _selector;
+    private final boolean _sawDeepDot;
+
+    public static class XPathCompileException extends XmlException {
+        XPathCompileException(XmlError err) {
+            super(err.toString(), null, err);
         }
     }
 
-    //
-    //
-    //
-
-    public static class ExecutionContext
-    {
-        public ExecutionContext ( )
-        {
-            _stack = new ArrayList();
-        }
-
-        public static final int HIT     = 0x1;
-        public static final int DESCEND = 0x2;
-        public static final int ATTRS   = 0x4;
-        
-        public final void init ( XPath xpath )
-        {
-            if (_xpath != xpath)
-            {
-                _xpath = xpath;
-                
-                _paths = new PathContext [ xpath._selector._paths.length ];
-                
-                for ( int i = 0 ; i < _paths.length ; i++ )
-                    _paths[ i ] = new PathContext();
-            }
-
-            _stack.clear();
-
-            for ( int i = 0 ; i < _paths.length ; i++ )
-                _paths[ i ].init( xpath._selector._paths[ i ] );
-        }
-
-        public final int start ( )
-        {
-            int result = 0;
-            
-            for ( int i = 0 ; i < _paths.length ; i++ )
-                result |= _paths[ i ].start();
-
-            return result;
-        }
-        
-        public final int element ( QName name )
-        {
-            assert name != null;
-            
-            _stack.add( name );
-            
-            int result = 0;
-            
-            for ( int i = 0 ; i < _paths.length ; i++ )
-                result |= _paths[ i ].element( name );
-
-            return result;
-        }
-        
-        public final boolean attr ( QName name )
-        {
-            boolean hit = false;
-            
-            for ( int i = 0 ; i < _paths.length ; i++ )
-                hit = hit | _paths[ i ].attr( name );
-
-            return hit;
-        }
-
-        public final void end ( )
-        {
-            _stack.remove( _stack.size() - 1 );
-            
-            for ( int i = 0 ; i < _paths.length ; i++ )
-                _paths[ i ].end();
-        }
-        
-        private final class PathContext
-        {
-            PathContext ( )
-            {
-                _prev = new ArrayList();
-            }
-            
-            void init ( Step steps )
-            {
-                _curr = steps;
-                _prev.clear();
-            }
-
-            private QName top ( int i )
-            {
-                return (QName) ExecutionContext.this._stack.get( _stack.size() - 1 - i );
-            }
-
-            // goes back to the begining of the sequence since last // wildcard
-            private void backtrack ( )
-            {
-                assert _curr != null;
-                
-                if (_curr._hasBacktrack)
-                {   // _backtrack seems to be a pointer to the step that follows a // wildcard
-                    // ex: for .//b/c/d steps c and d should backtrack to b in case there isn't a match 
-                    _curr = _curr._backtrack;
-                    return;
-                }
-
-                assert !_curr._deep;
-
-                _curr = _curr._prev;
-
-                search: for ( ; !_curr._deep ; _curr = _curr._prev )
-                {
-                    int t = 0;
-                    
-                    for ( Step s = _curr ; !s._deep ; s = s._prev )
-                    {
-                        if (!s.match( top( t++ )))
-                            continue search;
-                    }
-
-                    break;
-                }
-            }
-            
-            int start ( )
-            {
-                assert _curr != null;
-                assert _curr._prev == null;
-
-                if (_curr._name != null)
-                    return _curr._flags;
-
-                // If the steps consist on only a terminator, then the path can
-                // only be '.'.  In this case, we get a hit, but there is
-                // nothing else to match.  No need to backtrack.
-
-                _curr = null;
-
-                return HIT;
-            }
-            
-            int element ( QName name )
-            {
-                //System.out.println("  Path.element: " + name);
-                _prev.add( _curr );
-
-                if (_curr == null)
-                    return 0;
-
-                assert _curr._name != null;
-
-                if (!_curr._attr && _curr.match( name ))
-                {
-                    if ((_curr = _curr._next)._name != null)
-                        return _curr._flags;
-                    
-                    backtrack();
-                    
-                    //System.out.println("    element - HIT " + _curr._flags);
-                    return _curr == null ? HIT : HIT | _curr._flags;
-                }
-
-                for ( ; ; )
-                {
-                    backtrack();
-
-                    if (_curr == null)
-                        return 0;
-
-                    if (_curr.match( name ))
-                    {
-                        _curr = _curr._next;
-                        break;
-                    }
-
-                    if (_curr._deep)
-                        break;
-                }
-                
-                return _curr._flags;
-            }
-            
-            boolean attr ( QName name )
-            {
-                return _curr != null && _curr._attr && _curr.match( name );
-            }
-
-            void end ( )
-            {
-                //System.out.println("  Path.end ");
-                _curr = (Step) _prev.remove( _prev.size() - 1 );
-            }
-            
-            private Step _curr;
-            private List _prev;
-        }
-
-        private XPath         _xpath;
-        private ArrayList     _stack;
-        private PathContext[] _paths;
+    public static XPath compileXPath(String xpath) throws XPathCompileException {
+        return compileXPath(xpath, "$this", null);
     }
 
-    //
-    //
-    //
-
-    public static XPath compileXPath ( String xpath )
-        throws XPathCompileException
-    {
-        return compileXPath( xpath, "$this", null );
-    }
-    
-    public static XPath compileXPath ( String xpath, String currentNodeVar )
-        throws XPathCompileException
-    {
-        return compileXPath( xpath, currentNodeVar, null );
+    public static XPath compileXPath(String xpath, String currentNodeVar)
+        throws XPathCompileException {
+        return compileXPath(xpath, currentNodeVar, null);
     }
 
-    public static XPath compileXPath ( String xpath, Map namespaces )
-            throws XPathCompileException
-    {
-        return compileXPath( xpath, "$this", namespaces );
+    public static XPath compileXPath(String xpath, Map<String, String> namespaces)
+        throws XPathCompileException {
+        return compileXPath(xpath, "$this", namespaces);
     }
-    
-    public static XPath compileXPath (
-        String xpath, String currentNodeVar, Map namespaces )
-            throws XPathCompileException
-    {
+
+    public static XPath compileXPath(
+        String xpath, String currentNodeVar, Map<String, String> namespaces)
+        throws XPathCompileException {
         return
-            new CompilationContext( namespaces, currentNodeVar ).
-                compile( xpath );
+            new XPathCompilationContext(namespaces, currentNodeVar).
+                compile(xpath);
     }
 
-    private static class CompilationContext
-    {
-        CompilationContext ( Map namespaces, String currentNodeVar )
-        {
-            assert
-                _currentNodeVar == null ||
-                _currentNodeVar.startsWith( "$" );
-
-            if (currentNodeVar == null)
-                _currentNodeVar = "$this";
-            else
-                _currentNodeVar = currentNodeVar;
-
-            _namespaces = new HashMap();
-            
-            _externalNamespaces =
-                namespaces == null ? new HashMap() : namespaces;
-        }
-
-        XPath compile ( String expr ) throws XPathCompileException
-        {
-            _offset = 0;
-            _line = 1;
-            _column = 1;
-            _expr = expr;
-
-            return tokenizeXPath();
-        }
-        
-        int currChar ( )
-        {
-            return currChar( 0 );
-        }
-        
-        int currChar ( int offset )
-        {
-            return
-                _offset + offset >= _expr.length()
-                    ? -1
-                    : _expr.charAt( _offset + offset );
-        }
-        
-        void advance ( )
-        {
-            if (_offset < _expr.length())
-            {
-                char ch = _expr.charAt( _offset );
-                
-                _offset++;
-                _column++;
-
-                if (ch == '\r' || ch == '\n')
-                {
-                    _line++;
-                    _column = 1;
-
-                    if (_offset + 1 < _expr.length())
-                    {
-                        char nextCh = _expr.charAt( _offset + 1 );
-
-                        if ((nextCh == '\r' || nextCh == '\n') && ch != nextCh)
-                            _offset++;
-                    }
-                }
-            }
-        }
-
-        void advance ( int count )
-        {
-            assert count >= 0;
-            
-            while ( count-- > 0 )
-                advance();
-        }
-                
-        boolean isWhitespace ( )
-        {
-            return isWhitespace( 0 );
-        }
-        
-        boolean isWhitespace ( int offset )
-        {
-            int ch = currChar( offset );
-            return ch == ' ' || ch == '\t' || ch == '\n' || ch == '\r';
-        }
-
-        boolean isNCNameStart ( )
-        {
-            return
-                currChar() == -1
-                    ? false :
-                    XMLChar.isNCNameStart( currChar() );
-        }
-        
-        boolean isNCName ( )
-        {
-            return
-                currChar() == -1
-                    ? false :
-                    XMLChar.isNCName( currChar() );
-        }
-        
-        boolean startsWith ( String s )
-        {
-            return startsWith( s, 0 );
-        }
-        
-        boolean startsWith ( String s, int offset )
-        {
-            if (_offset + offset >= _expr.length())
-                return false;
-            
-            return _expr.startsWith( s, _offset + offset );
-        }
-
-        private XPathCompileException newError ( String msg )
-        {
-            XmlError err =
-                XmlError.forLocation(
-                    msg, XmlError.SEVERITY_ERROR, null,
-                    _line, _column, _offset );
-                                     
-            return new XPathCompileException( err );
-        }
-
-        String lookupPrefix ( String prefix ) throws XPathCompileException
-        {
-            if (_namespaces.containsKey( prefix ))
-                return (String) _namespaces.get( prefix );
-            
-            if (_externalNamespaces.containsKey( prefix ))
-                return (String) _externalNamespaces.get( prefix );
-
-            if (prefix.equals( "xml" ))
-                  return "http://www.w3.org/XML/1998/namespace";
-            
-            if (prefix.equals( "xs" ))
-                  return "http://www.w3.org/2001/XMLSchema";
-            
-            if (prefix.equals( "xsi" ))
-                  return "http://www.w3.org/2001/XMLSchema-instance";
-            
-            if (prefix.equals( "fn" ))
-                  return "http://www.w3.org/2002/11/xquery-functions";
-
-            if (prefix.equals( "xdt" ))
-                  return "http://www.w3.org/2003/11/xpath-datatypes";
-
-            if (prefix.equals( "local" ))
-                  return "http://www.w3.org/2003/11/xquery-local-functions";
-
-            throw newError( "Undefined prefix: " + prefix );
-        }
-
-        private boolean parseWhitespace ( ) throws XPathCompileException
-        {
-            boolean sawSpace = false;
-            
-            while ( isWhitespace() )
-            {
-                advance();
-                sawSpace = true;
-            }
-
-            return sawSpace;
-        }
-        
-        //
-        // Tokenizing will consume whitespace followed by the tokens, separated
-        // by whitespace.  The whitespace following the last token is not
-        // consumed.
-        //
-        
-        private boolean tokenize ( String s )
-        {
-            assert s.length() > 0;
-            
-            int offset = 0;
-
-            while ( isWhitespace( offset ) )
-                offset++;
-            
-            if (!startsWith( s, offset ))
-                return false;
-
-            offset += s.length();
-
-            advance( offset );
-
-            return true;
-        }
-
-        private boolean tokenize ( String s1, String s2 )
-        {
-            assert s1.length() > 0;
-            assert s2.length() > 0;
-            
-            int offset = 0;
-
-            while ( isWhitespace( offset ) )
-                offset++;
-            
-            if (!startsWith( s1, offset ))
-                return false;
-
-            offset += s1.length();
-
-            while ( isWhitespace( offset ) )
-                offset++;
-            
-            if (!startsWith( s2, offset ))
-                return false;
-                
-            offset += s2.length();
-
-            advance( offset );
-
-            return true;
-        }
-
-        private boolean tokenize ( String s1, String s2, String s3)
-        {
-            assert s1.length() > 0;
-            assert s2.length() > 0;
-            assert s3.length() > 0;
-
-            int offset = 0;
-
-            while ( isWhitespace( offset ) )
-                offset++;
-            
-            if (!startsWith( s1, offset ))
-                return false;
-
-            offset += s1.length();
-
-            while ( isWhitespace( offset ) )
-                offset++;
-            
-            if (!startsWith( s2, offset ))
-                return false;
-                
-            offset += s2.length();
-
-            while ( isWhitespace( offset ) )
-                offset++;
-            
-            if (!startsWith( s3, offset ))
-                return false;
-            
-            offset += s3.length();
-
-             while ( isWhitespace( offset ) )
-                offset++;
-
-            advance( offset );
-
-            return true;
-        }
-        private boolean tokenize ( String s1, String s2, String s3,String s4) {
-            assert s1.length() > 0;
-            assert s2.length() > 0;
-            assert s3.length() > 0;
-            assert s4.length() > 0;
-
-            int offset = 0;
-
-            while ( isWhitespace( offset ) )
-                offset++;
-
-            if (!startsWith( s1, offset ))
-                return false;
-
-            offset += s1.length();
-
-            while ( isWhitespace( offset ) )
-                offset++;
-
-            if (!startsWith( s2, offset ))
-                return false;
-
-            offset += s2.length();
-
-            while ( isWhitespace( offset ) )
-                offset++;
-
-            if (!startsWith( s3, offset ))
-                return false;
-
-            offset += s3.length();
-
-             while ( isWhitespace( offset ) )
-                offset++;
-
-            if (!startsWith( s4, offset ))
-                return false;
-
-            offset += s4.length();
-
-            advance( offset );
-
-            return true;
-        }
-
-
-        private String tokenizeNCName ( ) throws XPathCompileException
-        {
-            parseWhitespace();
-            
-            if (!isNCNameStart())
-                throw newError( "Expected non-colonized name" );
-
-            StringBuilder sb = new StringBuilder();
-
-            sb.append( (char) currChar() );
-
-            for ( advance() ; isNCName() ; advance() )
-                sb.append( (char) currChar() );
-
-            return sb.toString();
-        }
-
-        private QName getAnyQName ( )
-        {
-            return new QName( "", "" );
-        }
-        
-        private QName tokenizeQName ( ) throws XPathCompileException
-        {
-            if (tokenize( "*" ))
-                return getAnyQName();
-            
-            String ncName = tokenizeNCName();
-
-            if (!tokenize( ":" ))
-                return new QName( lookupPrefix( "" ), ncName );
-            
-            return
-                new QName(
-                    lookupPrefix( ncName ),
-                    tokenize( "*" ) ? "" : tokenizeNCName() );
-        }
-        
-        private String tokenizeQuotedUri ( ) throws XPathCompileException
-        {
-            char quote;
-            
-            if (tokenize( "\"" ))
-                quote = '"';
-            else  if (tokenize( "'" ))
-                quote = '\'';
-            else
-                throw newError( "Expected quote (\" or ')" );
-
-            StringBuilder sb = new StringBuilder();
-
-            for ( ; ; )
-            {
-                if (currChar() == -1)
-                    throw newError( "Path terminated in URI literal" );
-                
-                if (currChar() == quote)
-                {
-                    advance();
-                    
-                    if (currChar() != quote)
-                        break;
-                }
-                
-                sb.append( (char) currChar() );
-                
-                advance();
-            }
-
-            return sb.toString();
-        }
-
-        private Step addStep ( boolean deep, boolean attr, QName name, Step steps )
-        {
-            Step step = new Step( deep, attr, name );
-
-            if (steps == null)
-                return step;
-
-            Step s = steps;
-            
-            while ( steps._next != null )
-                steps = steps._next;
-
-            steps._next = step;
-            step._prev = steps;
-
-            return s;
-        }
-
-        private Step tokenizeSteps ( ) throws XPathCompileException
-        {
-            if (tokenize( "/" ))
-                throw newError( "Absolute paths unsupported" );
-
-            boolean deep;
-
-            if (tokenize( "$", _currentNodeVar, "//" ) || tokenize( ".", "//" ))
-                deep = true;
-            else if (tokenize( "$", _currentNodeVar, "/" ) || tokenize( ".", "/" ))
-                deep = false;
-            else if (tokenize( "$", _currentNodeVar ) || tokenize( "." ))
-                return addStep( false, false, null, null );
-            else
-                deep = false;
-
-            Step steps = null;
-
-            // Compile the steps removing /. and mergind //. with the next step
-
-            boolean deepDot = false;
-
-            for ( ; ; )
-            {
-                if (tokenize( "attribute", "::" ) || tokenize( "@" ))
-                {
-                    steps = addStep( deep, true, tokenizeQName(), steps );
-                    break;
-                }
-
-                QName name;
-                
-                if (tokenize( "." ))
-                    deepDot = deepDot || deep;
-                else
-                {
-                    tokenize( "child", "::" );
-                    if ((name = tokenizeQName()) != null)
-                    {
-                        steps = addStep( deep, false, name, steps );
-                        deep = false; // only this step needs to be deep
-                        // other folowing steps will be deep only if they are preceded by // wildcard
-                    }
-                }
-
-                if (tokenize( "//" ))
-                {
-                    deep = true;
-                    deepDot = false;
-                }
-                else if (tokenize( "/" ))
-                {
-                    if (deepDot)
-                        deep = true;
-                }
-                else
-                    break;
-            }
-
-            // If there was a //. at the end of th path, then we need to make
-            // two paths, one with * at the end and another with @* at the end.
-
-            if ((_lastDeepDot = deepDot))
-            {
-                _lastDeepDot = true;
-                steps = addStep( true, false, getAnyQName(), steps );
-            }
-
-            // Add sentinal step (_name == null)
-            
-            return addStep( false, false, null, steps );
-        }
-
-        private void computeBacktrack ( Step steps )
-            throws XPathCompileException
-        {
-            //
-            // Compute static backtrack information
-            //
-            // Note that I use the fact that _hasBacktrack is initialized to
-            // false and _backtrack to null in the following code.
-            //
-
-            Step s, t;
-            
-            for ( s = steps ; s != null ; s = t )
-            {
-                // Compute the segment from [ s, t )
-                
-                for ( t = s._next ; t != null && !t._deep ; )
-                    t = t._next;
-
-                // If the segment is NOT rooted at //, then the backtrack is
-                // null for the entire segment, including possible attr and/or
-                // sentinal
-
-                if (!s._deep)
-                {
-                    for ( Step u = s ; u != t ; u = u._next )
-                        u._hasBacktrack = true;
-
-                    continue;
-                }
-
-                // Compute the sequence [ s, u ) of length n which contain no
-                // wild steps.
-
-                int n = 0;
-                Step u = s;
-
-                while ( u != t && u._name != null && !u.isWild() && !u._attr )
-                {
-                    n++;
-                    u = u._next;
-                }
-
-                // Now, apply KMP to [ s, u ) for fast backtracking
-
-                QName [] pattern = new QName [ n + 1 ];
-                int [] kmp = new int [ n + 1 ];
-
-                Step v = s;
-                
-                for ( int i = 0 ; i < n ; i++ )
-                {
-                    pattern[ i ] = v._name;
-                    v = v._next;
-                }
-
-                pattern[ n ] = getAnyQName();
-
-                int i = 0;
-                int j = kmp[ 0 ] = -1;
-
-                while ( i < n )
-                {
-                    while ( j > -1 && !pattern[ i ].equals( pattern[ j ] ) )
-                        j = kmp[ j ];
-
-                    if (pattern[ ++i ].equals( pattern[ ++j ] ))
-                        kmp[ i ] = kmp[ j ];
-                    else
-                        kmp[ i ] = j;
-                }
-
-                i = 0;
-                
-                for ( v = s ; v != u ; v = v._next )
-                {
-                    v._hasBacktrack = true;
-                    v._backtrack = s;
-                    
-                    for ( j = kmp[ i ] ; j > 0 ; j-- )
-                        v._backtrack = v._backtrack._next;
-                    
-                    i++;
-                }
-
-                // Compute the success backtrack and stuff it into an attr and
-                // sentinal if they exist for this segment
-                
-                v = s;
-
-                if (n > 1)
-                {
-                    for ( j = kmp[ n - 1 ] ; j > 0 ; j-- )
-                        v = v._next;
-                }
-
-                if (u != t && u._attr)
-                {
-                    u._hasBacktrack = true;
-                    u._backtrack = v;
-                    u = u._next;
-                }
-
-                if (u != t && u._name == null)
-                {
-                    u._hasBacktrack = true;
-                    u._backtrack = v;
-                }
-
-                // The first part of a deep segment always backtracks to itself
-                
-                assert s._deep;
-
-                s._hasBacktrack = true;
-                s._backtrack = s;
-            }
-        }
-
-        private void tokenizePath ( ArrayList paths )
-            throws XPathCompileException
-        {
-            _lastDeepDot = false;
-            
-            Step steps = tokenizeSteps();
-            
-            computeBacktrack( steps );
-
-            paths.add( steps );
-
-            // If the last path ended in //., that path will match all
-            // elements, here I make a path which matches all attributes.
-
-            if (_lastDeepDot)
-            {
-                _sawDeepDot = true;
-                
-                Step s = null;
-
-                for ( Step t = steps ; t != null ; t = t._next )
-                {
-                    if (t._next != null && t._next._next == null)
-                        s = addStep( t._deep, true, t._name, s );
-                    else
-                        s = addStep( t._deep, t._attr, t._name, s );
-                }
-
-                computeBacktrack( s );
-
-                paths.add( s );
-            }
-        }
-        
-        private Selector tokenizeSelector ( ) throws XPathCompileException
-        {
-            ArrayList paths = new ArrayList();
-
-            tokenizePath( paths );
-
-            while ( tokenize( "|" ) )
-                tokenizePath( paths );
-
-            return new Selector( (Step[]) paths.toArray( new Step [ 0 ] ) );
-        }
-
-        private XPath tokenizeXPath ( ) throws XPathCompileException
-        {
-            for ( ; ; )
-            {
-                if (tokenize( "declare", "namespace" ))
-                {
-                    if (!parseWhitespace())
-                        throw newError( "Expected prefix after 'declare namespace'" );
-
-                    String prefix = tokenizeNCName();
-
-                    if (!tokenize( "=" ))
-                        throw newError( "Expected '='" );
-
-                    String uri = tokenizeQuotedUri();
-                    
-                    if (_namespaces.containsKey( prefix ))
-                    {
-                        throw newError(
-                            "Redefinition of namespace prefix: " + prefix );
-                    }
-
-                    _namespaces.put( prefix, uri );
-
-                    //return these to saxon:? Is it an error to pass external NS
-                    //that conflicts? or should we just override it?
-                    if (_externalNamespaces.containsKey( prefix ))
-                    {
-                        throw newError(
-                            "Redefinition of namespace prefix: " + prefix );
-                    }
-                    _externalNamespaces.put( prefix, uri );
-
-                    if (! tokenize( ";" ))
-                    {
-//			            throw newError(
-//                            "Namespace declaration must end with ;" );
-			        }
-
-                    _externalNamespaces.put(_NS_BOUNDARY,new Integer(_offset));
-
-                    continue;
-                }
-                
-                if (tokenize( "declare","default", "element", "namespace" ))
-                {
-                    String uri = tokenizeQuotedUri();
-                    
-                    if (_namespaces.containsKey( "" ))
-                    {
-                        throw newError(
-                            "Redefinition of default element namespace" );
-                    }
-
-                    _namespaces.put( "", uri );
-
-                    //return these to saxon:? Is it an error to pass external NS
-                    //that conflicts? or should we just override it?
-                    if (_externalNamespaces.containsKey( XPath._DEFAULT_ELT_NS ))
-                    {
-                         throw newError("Redefinition of default element namespace : ");
-                    }
-                    _externalNamespaces.put( XPath._DEFAULT_ELT_NS, uri );
-
-                    if (! tokenize( ";" ))
-                        throw newError("Default Namespace declaration must end with ;" );
-                    //the boundary is the last ; in the prolog...
-                    _externalNamespaces.put(_NS_BOUNDARY,new Integer(_offset));
-
-                    continue;
-                }
-                
-                break;
-            }
-
-            // Add the default prefix mapping if it has not been redefined
-            
-            if (!_namespaces.containsKey( "" ))
-                _namespaces.put( "", "" );
-
-            Selector selector = tokenizeSelector();
-
-            parseWhitespace();
-            
-            if (currChar() != -1)
-            {
-                throw newError(
-                    "Unexpected char '" + (char) currChar() + "'" );
-            }
-
-            return new XPath( selector, _sawDeepDot );
-        }
-
-        //split of prolog decls that are not standard XPath syntax
-        //but work in v1
-        private void processNonXpathDecls(){
-
-        }
-
-        private String _expr;
-
-        private boolean _sawDeepDot;  // Saw one overall
-        private boolean _lastDeepDot;
-
-        private String _currentNodeVar;
-        
-       // private Map _namespaces;
-        protected Map _namespaces;
-        private Map _externalNamespaces;
-        
-        private int _offset;
-        private int _line;
-        private int _column;
-    }
-
-    private static final class Step
-    {
-        Step ( boolean deep, boolean attr, QName name )
-        {
-            _name = name;
-
-            _deep = deep;
-            _attr = attr;
-
-            int flags = 0;
-
-            if (_deep || !_attr)
-                flags |= ExecutionContext.DESCEND;
-
-            if (_attr)
-                flags |= ExecutionContext.ATTRS;
-
-            _flags = flags;
-        }
-
-        boolean isWild ( )
-        {
-            return _name.getLocalPart().length() == 0;
-        }
-
-        boolean match ( QName name )
-        {
-            String local = _name.getLocalPart();
-            String nameLocal = name.getLocalPart();
-            String uri;
-            String nameUri;
-
-            int localLength = local.length();
-            int uriLength;
-
-            // match any name to _name when _name is empty ""@""
-            if (localLength==0)
-            {
-                uri = _name.getNamespaceURI();
-                uriLength = uri.length();
-
-                if (uriLength==0)
-                    return true;
-
-                return uri.equals(name.getNamespaceURI());
-            }
-
-            if (localLength!=nameLocal.length())
-                return false;
-
-            uri = _name.getNamespaceURI();
-            nameUri = name.getNamespaceURI();
-
-            if (uri.length()!=nameUri.length())
-                return false;
-
-            return local.equals(nameLocal) && uri.equals(nameUri);
-        }
-
-        final boolean _attr;
-        final boolean _deep;
-
-        int _flags;
-        
-        final QName _name;
-
-        Step _next, _prev;
-
-        boolean _hasBacktrack;
-        Step    _backtrack;
-    }
-
-    private static final class Selector
-    {
-        Selector ( Step[] paths )
-        {
+    static final class Selector {
+        Selector(XPathStep[] paths) {
             _paths = paths;
         }
 
-        final Step[] _paths;
+        final XPathStep[] _paths;
     }
 
     //
     //
     //
-    
-    private XPath ( Selector selector, boolean sawDeepDot )
-    {
+
+    XPath(Selector selector, boolean sawDeepDot) {
         _selector = selector;
         _sawDeepDot = sawDeepDot;
     }
 
-    public boolean sawDeepDot ( )
-    {
+    public boolean sawDeepDot() {
         return _sawDeepDot;
     }
 
-    public static final String _NS_BOUNDARY = "$xmlbeans!ns_boundary";
-    public static final String _DEFAULT_ELT_NS = "$xmlbeans!default_uri";
-    private final Selector _selector;
-    private final boolean  _sawDeepDot;
 }
\ No newline at end of file
diff --git a/src/main/java/org/apache/xmlbeans/impl/common/XPathCompilationContext.java b/src/main/java/org/apache/xmlbeans/impl/common/XPathCompilationContext.java
new file mode 100644
index 0000000..0e03a5d
--- /dev/null
+++ b/src/main/java/org/apache/xmlbeans/impl/common/XPathCompilationContext.java
@@ -0,0 +1,606 @@
+/*   Copyright 2004 The Apache Software Foundation
+ *
+ *   Licensed under the Apache License, Version 2.0 (the "License");
+ *   you may not use this file except in compliance with the License.
+ *   You may obtain a copy of the License at
+ *
+ *       http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *   Unless required by applicable law or agreed to in writing, software
+ *   distributed under the License is distributed on an "AS IS" BASIS,
+ *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *   See the License for the specific language governing permissions and
+ *  limitations under the License.
+ */
+
+package org.apache.xmlbeans.impl.common;
+
+import org.apache.xmlbeans.XmlError;
+
+import javax.xml.namespace.QName;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.Map;
+
+import static org.apache.xmlbeans.impl.common.XPath._NS_BOUNDARY;
+
+class XPathCompilationContext {
+    private String _expr;
+
+    private boolean _sawDeepDot;  // Saw one overall
+    private boolean _lastDeepDot;
+
+    private final String _currentNodeVar;
+
+    // private Map _namespaces;
+    protected final Map<String, String> _namespaces = new HashMap<>();
+    private final Map<String, String> _externalNamespaces;
+
+    private int _offset;
+    private int _line;
+    private int _column;
+
+    XPathCompilationContext(Map<String, String> namespaces, String currentNodeVar) {
+        // TODO: checkme
+//        assert (_currentNodeVar == null || _currentNodeVar.startsWith("$"));
+
+        _currentNodeVar = (currentNodeVar == null) ? "$this" : currentNodeVar;
+
+        _externalNamespaces = (namespaces == null) ? new HashMap<>() : namespaces;
+    }
+
+    XPath compile(String expr) throws XPath.XPathCompileException {
+        _offset = 0;
+        _line = 1;
+        _column = 1;
+        _expr = expr;
+
+        return tokenizeXPath();
+    }
+
+    int currChar() {
+        return currChar(0);
+    }
+
+    int currChar(int offset) {
+        return
+            _offset + offset >= _expr.length()
+                ? -1
+                : _expr.charAt(_offset + offset);
+    }
+
+    void advance() {
+        if (_offset < _expr.length()) {
+            char ch = _expr.charAt(_offset);
+
+            _offset++;
+            _column++;
+
+            if (ch == '\r' || ch == '\n') {
+                _line++;
+                _column = 1;
+
+                if (_offset + 1 < _expr.length()) {
+                    char nextCh = _expr.charAt(_offset + 1);
+
+                    if ((nextCh == '\r' || nextCh == '\n') && ch != nextCh) {
+                        _offset++;
+                    }
+                }
+            }
+        }
+    }
+
+    void advance(int count) {
+        assert count >= 0;
+
+        while (count-- > 0) {
+            advance();
+        }
+    }
+
+    boolean isWhitespace() {
+        return isWhitespace(0);
+    }
+
+    boolean isWhitespace(int offset) {
+        int ch = currChar(offset);
+        return ch == ' ' || ch == '\t' || ch == '\n' || ch == '\r';
+    }
+
+    boolean isNCNameStart() {
+        return currChar() != -1 && XMLChar.isNCNameStart(currChar());
+    }
+
+    boolean isNCName() {
+        return currChar() != -1 && XMLChar.isNCName(currChar());
+    }
+
+    boolean startsWith(String s, int offset) {
+        if (_offset + offset >= _expr.length()) {
+            return false;
+        }
+
+        return _expr.startsWith(s, _offset + offset);
+    }
+
+    private XPath.XPathCompileException newError(String msg) {
+        XmlError err =
+            XmlError.forLocation(
+                msg, XmlError.SEVERITY_ERROR, null,
+                _line, _column, _offset);
+
+        return new XPath.XPathCompileException(err);
+    }
+
+    String lookupPrefix(String prefix) throws XPath.XPathCompileException {
+        if (_namespaces.containsKey(prefix)) {
+            return _namespaces.get(prefix);
+        }
+
+        if (_externalNamespaces.containsKey(prefix)) {
+            return _externalNamespaces.get(prefix);
+        }
+
+        switch (prefix != null ? prefix : "") {
+            case "xml":
+            return "http://www.w3.org/XML/1998/namespace";
+
+            case "xs":
+            return "http://www.w3.org/2001/XMLSchema";
+
+            case "xsi":
+            return "http://www.w3.org/2001/XMLSchema-instance";
+
+            case "fn":
+            return "http://www.w3.org/2002/11/xquery-functions";
+
+            case "xdt":
+            return "http://www.w3.org/2003/11/xpath-datatypes";
+
+            case "local":
+            return "http://www.w3.org/2003/11/xquery-local-functions";
+        }
+
+        throw newError("Undefined prefix: " + prefix);
+    }
+
+    private boolean parseWhitespace() {
+        boolean sawSpace = false;
+
+        while (isWhitespace()) {
+            advance();
+            sawSpace = true;
+        }
+
+        return sawSpace;
+    }
+
+    //
+    // Tokenizing will consume whitespace followed by the tokens, separated
+    // by whitespace.  The whitespace following the last token is not
+    // consumed.
+    //
+    private boolean tokenize(String... tokens) {
+        int offset = 0;
+
+        for (String s : tokens) {
+            assert (s != null && !s.isEmpty());
+
+        while (isWhitespace(offset)) {
+            offset++;
+        }
+
+        if (!startsWith(s, offset)) {
+            return false;
+        }
+
+        offset += s.length();
+        }
+
+        advance(offset);
+
+        return true;
+    }
+
+
+    private String tokenizeNCName() throws XPath.XPathCompileException {
+        parseWhitespace();
+
+        if (!isNCNameStart()) {
+            throw newError("Expected non-colonized name");
+        }
+
+        StringBuilder sb = new StringBuilder();
+
+        sb.append((char) currChar());
+
+        for (advance(); isNCName(); advance()) {
+            sb.append((char) currChar());
+        }
+
+        return sb.toString();
+    }
+
+    private QName getAnyQName() {
+        return new QName("", "");
+    }
+
+    private QName tokenizeQName() throws XPath.XPathCompileException {
+        if (tokenize("*")) {
+            return getAnyQName();
+        }
+
+        String ncName = tokenizeNCName();
+
+        if (!tokenize(":")) {
+            return new QName(lookupPrefix(""), ncName);
+        }
+
+        return
+            new QName(
+                lookupPrefix(ncName),
+                tokenize("*") ? "" : tokenizeNCName());
+    }
+
+    private String tokenizeQuotedUri() throws XPath.XPathCompileException {
+        char quote;
+
+        if (tokenize("\"")) {
+            quote = '"';
+        } else if (tokenize("'")) {
+            quote = '\'';
+        } else {
+            throw newError("Expected quote (\" or ')");
+        }
+
+        StringBuilder sb = new StringBuilder();
+
+        for (; ; ) {
+            if (currChar() == -1) {
+                throw newError("Path terminated in URI literal");
+            }
+
+            if (currChar() == quote) {
+                advance();
+
+                if (currChar() != quote) {
+                    break;
+                }
+            }
+
+            sb.append((char) currChar());
+
+            advance();
+        }
+
+        return sb.toString();
+    }
+
+    private XPathStep addStep(boolean deep, boolean attr, QName name, XPathStep steps) {
+        XPathStep step = new XPathStep(deep, attr, name);
+
+        if (steps == null) {
+            return step;
+        }
+
+        XPathStep s = steps;
+
+        while (steps._next != null) {
+            steps = steps._next;
+        }
+
+        steps._next = step;
+        step._prev = steps;
+
+        return s;
+    }
+
+    private XPathStep tokenizeSteps() throws XPath.XPathCompileException {
+        if (tokenize("/")) {
+            throw newError("Absolute paths unsupported");
+        }
+
+        boolean deep;
+
+        if (tokenize("$", _currentNodeVar, "//") || tokenize(".", "//")) {
+            deep = true;
+        } else if (tokenize("$", _currentNodeVar, "/") || tokenize(".", "/")) {
+            deep = false;
+        } else if (tokenize("$", _currentNodeVar) || tokenize(".")) {
+            return addStep(false, false, null, null);
+        } else {
+            deep = false;
+        }
+
+        XPathStep steps = null;
+
+        // Compile the steps removing /. and mergind //. with the next step
+
+        boolean deepDot = false;
+
+        for (; ; ) {
+            if (tokenize("attribute", "::") || tokenize("@")) {
+                steps = addStep(deep, true, tokenizeQName(), steps);
+                break;
+            }
+
+            QName name;
+
+            if (tokenize(".")) {
+                deepDot = deepDot || deep;
+            } else {
+                tokenize("child", "::");
+                name = tokenizeQName();
+                    steps = addStep(deep, false, name, steps);
+                    deep = false; // only this step needs to be deep
+                    // other folowing steps will be deep only if they are preceded by // wildcard
+                }
+
+            if (tokenize("//")) {
+                deep = true;
+                deepDot = false;
+            } else if (tokenize("/")) {
+                if (deepDot) {
+                    deep = true;
+                }
+            } else {
+                break;
+            }
+        }
+
+        // If there was a //. at the end of th path, then we need to make
+        // two paths, one with * at the end and another with @* at the end.
+
+        if ((_lastDeepDot = deepDot)) {
+            _lastDeepDot = true;
+            steps = addStep(true, false, getAnyQName(), steps);
+        }
+
+        // Add sentinal step (_name == null)
+
+        return addStep(false, false, null, steps);
+    }
+
+    private void computeBacktrack(XPathStep steps) {
+        //
+        // Compute static backtrack information
+        //
+        // Note that I use the fact that _hasBacktrack is initialized to
+        // false and _backtrack to null in the following code.
+        //
+
+        XPathStep s, t;
+
+        for (s = steps; s != null; s = t) {
+            // Compute the segment from [ s, t )
+
+            for (t = s._next; t != null && !t._deep; ) {
+                t = t._next;
+            }
+
+            // If the segment is NOT rooted at //, then the backtrack is
+            // null for the entire segment, including possible attr and/or
+            // sentinal
+
+            if (!s._deep) {
+                for (XPathStep u = s; u != t; u = u._next) {
+                    u._hasBacktrack = true;
+                }
+
+                continue;
+            }
+
+            // Compute the sequence [ s, u ) of length n which contain no
+            // wild steps.
+
+            int n = 0;
+            XPathStep u = s;
+
+            while (u != t && u._name != null && !u.isWild() && !u._attr) {
+                n++;
+                u = u._next;
+            }
+
+            // Now, apply KMP to [ s, u ) for fast backtracking
+
+            QName[] pattern = new QName[n + 1];
+            int[] kmp = new int[n + 1];
+
+            XPathStep v = s;
+
+            for (int i = 0; i < n; i++) {
+                pattern[i] = v._name;
+                v = v._next;
+            }
+
+            pattern[n] = getAnyQName();
+
+            int i = 0;
+            int j = kmp[0] = -1;
+
+            while (i < n) {
+                while (j > -1 && !pattern[i].equals(pattern[j])) {
+                    j = kmp[j];
+                }
+
+                i++;
+                j++;
+                kmp[i] = (pattern[i].equals(pattern[j])) ? kmp[j] : j;
+            }
+
+            i = 0;
+
+            for (v = s; v != u; v = v._next) {
+                v._hasBacktrack = true;
+                v._backtrack = s;
+
+                for (j = kmp[i]; j > 0; j--) {
+                    v._backtrack = v._backtrack._next;
+                }
+
+                i++;
+            }
+
+            // Compute the success backtrack and stuff it into an attr and
+            // sentinal if they exist for this segment
+
+            v = s;
+
+            if (n > 1) {
+                for (j = kmp[n - 1]; j > 0; j--) {
+                    v = v._next;
+                }
+            }
+
+            if (u != t && u._attr) {
+                u._hasBacktrack = true;
+                u._backtrack = v;
+                u = u._next;
+            }
+
+            if (u != t && u._name == null) {
+                u._hasBacktrack = true;
+                u._backtrack = v;
+            }
+
+            // The first part of a deep segment always backtracks to itself
+
+            assert s._deep;
+
+            s._hasBacktrack = true;
+            s._backtrack = s;
+        }
+    }
+
+    private void tokenizePath(ArrayList<XPathStep> paths)
+        throws XPath.XPathCompileException {
+        _lastDeepDot = false;
+
+        XPathStep steps = tokenizeSteps();
+
+        computeBacktrack(steps);
+
+        paths.add(steps);
+
+        // If the last path ended in //., that path will match all
+        // elements, here I make a path which matches all attributes.
+
+        if (_lastDeepDot) {
+            _sawDeepDot = true;
+
+            XPathStep s = null;
+
+            for (XPathStep t = steps; t != null; t = t._next) {
+                boolean attr = (t._next != null && t._next._next == null) || t._attr;
+                s = addStep(t._deep, attr, t._name, s);
+            }
+
+            computeBacktrack(s);
+
+            paths.add(s);
+        }
+    }
+
+    private XPath.Selector tokenizeSelector() throws XPath.XPathCompileException {
+        ArrayList<XPathStep> paths = new ArrayList<>();
+
+        tokenizePath(paths);
+
+        while (tokenize("|")) {
+            tokenizePath(paths);
+        }
+
+        return new XPath.Selector(paths.toArray(new XPathStep[0]));
+    }
+
+    private XPath tokenizeXPath() throws XPath.XPathCompileException {
+        for (; ; ) {
+            if (tokenize("declare", "namespace")) {
+                if (!parseWhitespace()) {
+                    throw newError("Expected prefix after 'declare namespace'");
+                }
+
+                String prefix = tokenizeNCName();
+
+                if (!tokenize("=")) {
+                    throw newError("Expected '='");
+                }
+
+                String uri = tokenizeQuotedUri();
+
+                if (_namespaces.containsKey(prefix)) {
+                    throw newError("Redefinition of namespace prefix: " + prefix);
+                }
+
+                _namespaces.put(prefix, uri);
+
+                //return these to saxon:? Is it an error to pass external NS
+                //that conflicts? or should we just override it?
+                if (_externalNamespaces.containsKey(prefix)) {
+                    throw newError("Redefinition of namespace prefix: " + prefix);
+                }
+                _externalNamespaces.put(prefix, uri);
+
+                if (!tokenize(";")) {
+//			            throw newError( "Namespace declaration must end with ;" );
+                }
+
+                _externalNamespaces.put(_NS_BOUNDARY, Integer.toString(_offset));
+
+                continue;
+            }
+
+            if (tokenize("declare", "default", "element", "namespace")) {
+                String uri = tokenizeQuotedUri();
+
+                if (_namespaces.containsKey("")) {
+                    throw newError("Redefinition of default element namespace");
+                }
+
+                _namespaces.put("", uri);
+
+                //return these to saxon:? Is it an error to pass external NS
+                //that conflicts? or should we just override it?
+                if (_externalNamespaces.containsKey(XPath._DEFAULT_ELT_NS)) {
+                    throw newError("Redefinition of default element namespace : ");
+                }
+                _externalNamespaces.put(XPath._DEFAULT_ELT_NS, uri);
+
+                if (!tokenize(";")) {
+                    throw newError("Default Namespace declaration must end with ;");
+                }
+                //the boundary is the last ; in the prolog...
+                _externalNamespaces.put(_NS_BOUNDARY, Integer.toString(_offset));
+
+                continue;
+            }
+
+            break;
+        }
+
+        // Add the default prefix mapping if it has not been redefined
+
+        if (!_namespaces.containsKey("")) {
+            _namespaces.put("", "");
+        }
+
+        XPath.Selector selector = tokenizeSelector();
+
+        parseWhitespace();
+
+        if (currChar() != -1) {
+            throw newError("Unexpected char '" + (char) currChar() + "'");
+        }
+
+        return new XPath(selector, _sawDeepDot);
+    }
+
+    //split of prolog decls that are not standard XPath syntax
+    //but work in v1
+    private void processNonXpathDecls() {
+
+    }
+
+}
+
diff --git a/src/main/java/org/apache/xmlbeans/impl/common/XPathExecutionContext.java b/src/main/java/org/apache/xmlbeans/impl/common/XPathExecutionContext.java
new file mode 100644
index 0000000..b5b38f7
--- /dev/null
+++ b/src/main/java/org/apache/xmlbeans/impl/common/XPathExecutionContext.java
@@ -0,0 +1,204 @@
+/*   Copyright 2004 The Apache Software Foundation
+ *
+ *   Licensed under the Apache License, Version 2.0 (the "License");
+ *   you may not use this file except in compliance with the License.
+ *   You may obtain a copy of the License at
+ *
+ *       http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *   Unless required by applicable law or agreed to in writing, software
+ *   distributed under the License is distributed on an "AS IS" BASIS,
+ *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *   See the License for the specific language governing permissions and
+ *  limitations under the License.
+ */
+
+package org.apache.xmlbeans.impl.common;
+
+import javax.xml.namespace.QName;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.List;
+
+public class XPathExecutionContext {
+
+    private XPath _xpath;
+    private final ArrayList<QName> _stack;
+    private PathContext[] _paths;
+
+    public XPathExecutionContext() {
+        _stack = new ArrayList<>();
+    }
+
+    public static final int HIT = 0x1;
+    public static final int DESCEND = 0x2;
+    public static final int ATTRS = 0x4;
+
+    public final void init(XPath xpath) {
+        if (_xpath != xpath) {
+            _xpath = xpath;
+
+            _paths = new PathContext[xpath._selector._paths.length];
+
+            Arrays.setAll(_paths, i -> new PathContext());
+        }
+
+        _stack.clear();
+
+        for (int i = 0; i < _paths.length; i++) {
+            _paths[i].init(xpath._selector._paths[i]);
+        }
+    }
+
+    public final int start() {
+        int result = 0;
+
+        for (PathContext path : _paths) {
+            result |= path.start();
+        }
+
+        return result;
+    }
+
+    public final int element(QName name) {
+        assert name != null;
+
+        _stack.add(name);
+
+        int result = 0;
+
+        for (PathContext path : _paths) {
+            result |= path.element(name);
+        }
+
+        return result;
+    }
+
+    public final boolean attr(QName name) {
+        boolean hit = false;
+
+        for (PathContext path : _paths) {
+            hit = hit | path.attr(name);
+        }
+
+        return hit;
+    }
+
+    public final void end() {
+        _stack.remove(_stack.size() - 1);
+
+        for (PathContext path : _paths) {
+            path.end();
+        }
+    }
+
+    private final class PathContext {
+
+        private XPathStep _curr;
+        private final List<XPathStep> _prev = new ArrayList<>();
+
+        void init(XPathStep steps) {
+            _curr = steps;
+            _prev.clear();
+        }
+
+        private QName top(int i) {
+            return XPathExecutionContext.this._stack.get(_stack.size() - 1 - i);
+        }
+
+        // goes back to the begining of the sequence since last // wildcard
+        private void backtrack() {
+            assert _curr != null;
+
+            if (_curr._hasBacktrack) {   // _backtrack seems to be a pointer to the step that follows a // wildcard
+                // ex: for .//b/c/d steps c and d should backtrack to b in case there isn't a match
+                _curr = _curr._backtrack;
+                return;
+            }
+
+            assert !_curr._deep;
+
+            _curr = _curr._prev;
+
+            search:
+            for (; !_curr._deep; _curr = _curr._prev) {
+                int t = 0;
+
+                for (XPathStep s = _curr; !s._deep; s = s._prev) {
+                    if (!s.match(top(t++))) {
+                        continue search;
+                    }
+                }
+
+                break;
+            }
+        }
+
+        int start() {
+            assert _curr != null;
+            assert _curr._prev == null;
+
+            if (_curr._name != null) {
+                return _curr._flags;
+            }
+
+            // If the steps consist on only a terminator, then the path can
+            // only be '.'.  In this case, we get a hit, but there is
+            // nothing else to match.  No need to backtrack.
+
+            _curr = null;
+
+            return HIT;
+        }
+
+        int element(QName name) {
+            //System.out.println("  Path.element: " + name);
+            _prev.add(_curr);
+
+            if (_curr == null) {
+                return 0;
+            }
+
+            assert _curr._name != null;
+
+            if (!_curr._attr && _curr.match(name)) {
+                if ((_curr = _curr._next)._name != null) {
+                    return _curr._flags;
+                }
+
+                backtrack();
+
+                //System.out.println("    element - HIT " + _curr._flags);
+                return _curr == null ? HIT : HIT | _curr._flags;
+            }
+
+            for (; ; ) {
+                backtrack();
+
+                if (_curr == null) {
+                    return 0;
+                }
+
+                if (_curr.match(name)) {
+                    _curr = _curr._next;
+                    break;
+                }
+
+                if (_curr._deep) {
+                    break;
+                }
+            }
+
+            return _curr._flags;
+        }
+
+        boolean attr(QName name) {
+            return _curr != null && _curr._attr && _curr.match(name);
+        }
+
+        void end() {
+            //System.out.println("  Path.end ");
+            _curr = (XPathStep) _prev.remove(_prev.size() - 1);
+        }
+    }
+}
diff --git a/src/main/java/org/apache/xmlbeans/impl/common/XPathStep.java b/src/main/java/org/apache/xmlbeans/impl/common/XPathStep.java
new file mode 100644
index 0000000..4426f3f
--- /dev/null
+++ b/src/main/java/org/apache/xmlbeans/impl/common/XPathStep.java
@@ -0,0 +1,83 @@
+/*   Copyright 2004 The Apache Software Foundation
+ *
+ *   Licensed under the Apache License, Version 2.0 (the "License");
+ *   you may not use this file except in compliance with the License.
+ *   You may obtain a copy of the License at
+ *
+ *       http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *   Unless required by applicable law or agreed to in writing, software
+ *   distributed under the License is distributed on an "AS IS" BASIS,
+ *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *   See the License for the specific language governing permissions and
+ *  limitations under the License.
+ */
+
+package org.apache.xmlbeans.impl.common;
+
+import javax.xml.namespace.QName;
+
+class XPathStep {
+
+    final boolean _attr;
+    final boolean _deep;
+
+    int _flags;
+
+    final QName _name;
+
+    XPathStep _next, _prev;
+
+    boolean _hasBacktrack;
+    XPathStep _backtrack;
+
+    XPathStep(boolean deep, boolean attr, QName name) {
+        _name = name;
+
+        _deep = deep;
+        _attr = attr;
+
+        int flags = 0;
+
+        if (_deep || !_attr) {
+            flags |= XPathExecutionContext.DESCEND;
+        }
+
+        if (_attr) {
+            flags |= XPathExecutionContext.ATTRS;
+        }
+
+        _flags = flags;
+    }
+
+    boolean isWild() {
+        return _name.getLocalPart().length() == 0;
+    }
+
+    boolean match(QName name) {
+        String local = _name.getLocalPart();
+        String nameLocal = name.getLocalPart();
+
+        int localLength = local.length();
+
+        // match any name to _name when _name is empty ""@""
+        if (localLength == 0) {
+            String uri = _name.getNamespaceURI();
+            return uri.isEmpty() || uri.equals(name.getNamespaceURI());
+        }
+
+        if (localLength != nameLocal.length()) {
+            return false;
+        }
+
+        String uri = _name.getNamespaceURI();
+        String nameUri = name.getNamespaceURI();
+
+        if (uri.length() != nameUri.length()) {
+            return false;
+        }
+
+        return local.equals(nameLocal) && uri.equals(nameUri);
+    }
+}
+
diff --git a/src/main/java/org/apache/xmlbeans/impl/config/NameSet.java b/src/main/java/org/apache/xmlbeans/impl/config/NameSet.java
index 2b0b8d0..4bf7b32 100644
--- a/src/main/java/org/apache/xmlbeans/impl/config/NameSet.java
+++ b/src/main/java/org/apache/xmlbeans/impl/config/NameSet.java
@@ -18,63 +18,60 @@
  */
 package org.apache.xmlbeans.impl.config;
 
-import java.util.Set;
 import java.util.Collections;
 import java.util.HashSet;
+import java.util.Set;
 
 /**
- * Reprezents a non finite set of names.
+ * Represents a non finite set of names.
+ *
  * @see NameSetBuilder
  */
-public class NameSet
-{
+public class NameSet {
     /**
      * An empty NameSet, it doesn't contain any name
      */
-    public static NameSet EMPTY = new NameSet(true, Collections.EMPTY_SET);
+    public static final NameSet EMPTY = new NameSet(true, Collections.EMPTY_SET);
     /**
      * The NameSet that contains any name
      */
-    public static NameSet EVERYTHING = new NameSet(false, Collections.EMPTY_SET);
+    public static final NameSet EVERYTHING = new NameSet(false, Collections.EMPTY_SET);
 
     /*
     There are two big cases:
-    1) - it reprezents "*", ie all except a finite set of names: _isFinite==false
-    2) - if reprezents only a finite set of names: _isFinite==true
+    1) - it represents "*", ie all except a finite set of names: _isFinite==false
+    2) - if represents only a finite set of names: _isFinite==true
     */
     private boolean _isFinite;
-    private Set _finiteSet;
+    private Set<String> _finiteSet;
 
-    private NameSet(boolean isFinite, Set finiteSet)
-    {
+    private NameSet(boolean isFinite, Set<String> finiteSet) {
         _isFinite = isFinite;
         _finiteSet = finiteSet;
     }
 
-    static NameSet newInstance(boolean isFinite, Set finiteSet)
-    {
-        if ( finiteSet.size()==0 )
-            if ( isFinite )
+    static NameSet newInstance(boolean isFinite, Set<String> finiteSet) {
+        if (finiteSet.size() == 0) {
+            if (isFinite) {
                 return NameSet.EMPTY;
-            else
+            } else {
                 return NameSet.EVERYTHING;
-        else
-        {
-            Set fs = new HashSet();
+            }
+        } else {
+            Set<String> fs = new HashSet<>();
             fs.addAll(finiteSet);
             return new NameSet(isFinite, fs);
         }
     }
 
-    private static Set intersectFiniteSets(Set a, Set b)
-    {
-        Set intersection = new HashSet();
+    private static Set<String> intersectFiniteSets(Set<String> a, Set<String> b) {
+        Set<String> intersection = new HashSet<>();
         //compute the intersection of _finiteSet with withSet
-        while (a.iterator().hasNext())
-        {
+        while (a.iterator().hasNext()) {
             String name = (String) a.iterator().next();
-            if (b.contains(name))
+            if (b.contains(name)) {
                 intersection.add(name);
+            }
         }
         return intersection;
     }
@@ -82,36 +79,26 @@
     /**
      * Returns the union of this NameSet with the 'with' NameSet.
      */
-    public NameSet union(NameSet with)
-    {
-        if (_isFinite)
-        {
-            if (with._isFinite)
-            {
-                Set union = new HashSet();
+    public NameSet union(NameSet with) {
+        if (_isFinite) {
+            if (with._isFinite) {
+                Set<String> union = new HashSet<>();
                 union.addAll(_finiteSet);
                 union.addAll(with._finiteSet);
                 return newInstance(true, union);
-            }
-            else
-            {
-                Set subst = new HashSet();
+            } else {
+                Set<String> subst = new HashSet<>();
                 subst.addAll(with._finiteSet);
                 subst.removeAll(_finiteSet);
                 return newInstance(false, subst);
             }
-        }
-        else
-        {
-            if (with._isFinite)
-            {
-                Set subst = new HashSet();
+        } else {
+            if (with._isFinite) {
+                Set<String> subst = new HashSet<>();
                 subst.addAll(_finiteSet);
                 subst.removeAll(with._finiteSet);
                 return newInstance(false, subst);
-            }
-            else
-            {
+            } else {
                 return newInstance(false, intersectFiniteSets(_finiteSet, with._finiteSet));
             }
         }
@@ -120,34 +107,24 @@
     /**
      * Returns the intersection of this NameSet with the 'with' NameSet
      */
-    public NameSet intersect(NameSet with)
-    {
-        if (_isFinite)
-        {
-            if (with._isFinite)
-            {
+    public NameSet intersect(NameSet with) {
+        if (_isFinite) {
+            if (with._isFinite) {
                 return newInstance(true, intersectFiniteSets(_finiteSet, with._finiteSet));
-            }
-            else
-            {
-                Set subst = new HashSet();
+            } else {
+                Set<String> subst = new HashSet<>();
                 subst.addAll(_finiteSet);
                 subst.removeAll(with._finiteSet);
                 return newInstance(false, subst);
             }
-        }
-        else
-        {
-            if (with._isFinite)
-            {
-                Set subst = new HashSet();
+        } else {
+            if (with._isFinite) {
+                Set<String> subst = new HashSet<>();
                 subst.addAll(with._finiteSet);
                 subst.removeAll(_finiteSet);
                 return newInstance(true, subst);
-            }
-            else
-            {
-                Set union = new HashSet();
+            } else {
+                Set<String> union = new HashSet<>();
                 union.addAll(_finiteSet);
                 union.addAll(with._finiteSet);
                 return newInstance(false, union);
@@ -157,48 +134,39 @@
 
     /**
      * Returns the result of substracting this NameSet from 'from' NameSet
+     *
      * @see NameSet#substract
      */
-    public NameSet substractFrom(NameSet from)
-    {
+    public NameSet substractFrom(NameSet from) {
         return from.substract(this);
     }
 
     /**
      * Returns the result of substracting 'what' NameSet from this NameSet
+     *
      * @see NameSet#substractFrom
      */
-    public NameSet substract(NameSet what)
-    {
-        if (_isFinite)
-        {
-            if ( what._isFinite )
-            {
+    public NameSet substract(NameSet what) {
+        if (_isFinite) {
+            if (what._isFinite) {
                 // it's the subst of _finiteSet with what._finiteSet
-                Set subst = new HashSet();
+                Set<String> subst = new HashSet<>();
                 subst.addAll(_finiteSet);
                 subst.removeAll(what._finiteSet);
                 return newInstance(true, subst);
-            }
-            else
-            {
+            } else {
                 return newInstance(true, intersectFiniteSets(_finiteSet, what._finiteSet));
             }
-        }
-        else
-        {
-            if ( what._isFinite )
-            {
+        } else {
+            if (what._isFinite) {
                 // it's the union of _finiteSet with what._finiteSet
-                Set union = new HashSet();
+                Set<String> union = new HashSet<>();
                 union.addAll(_finiteSet);
                 union.addAll(what._finiteSet);
                 return newInstance(false, union);
-            }
-            else
-            {
+            } else {
                 // what's in thisSet and it's not in whatSet
-                Set subst = new HashSet();
+                Set<String> subst = new HashSet<>();
                 subst.addAll(what._finiteSet);
                 subst.removeAll(_finiteSet);
                 return newInstance(true, subst);
@@ -209,16 +177,15 @@
     /**
      * Returns an inversion of this NameSet
      */
-    public NameSet invert()
-    {
+    public NameSet invert() {
         return newInstance(!_isFinite, _finiteSet);
     }
 
-    public boolean contains(String name)
-    {
-        if (_isFinite)
+    public boolean contains(String name) {
+        if (_isFinite) {
             return _finiteSet.contains(name);
-        else
+        } else {
             return !_finiteSet.contains(name);
+        }
     }
 }
diff --git a/src/main/java/org/apache/xmlbeans/impl/config/NameSetBuilder.java b/src/main/java/org/apache/xmlbeans/impl/config/NameSetBuilder.java
index da61a08..582b19f 100644
--- a/src/main/java/org/apache/xmlbeans/impl/config/NameSetBuilder.java
+++ b/src/main/java/org/apache/xmlbeans/impl/config/NameSetBuilder.java
@@ -18,25 +18,16 @@
  */
 package org.apache.xmlbeans.impl.config;
 
-import java.util.Set;
 import java.util.HashSet;
+import java.util.Set;
 
 /**
  * Used to build {@link NameSet NameSets}.
  */
 public class NameSetBuilder
 {
-    private boolean _isFinite;
-    private Set _finiteSet;
-
-    /**
-     * Creates an empty builder for a NameSet.
-     */
-    public NameSetBuilder()
-    {
-        _isFinite = true;
-        _finiteSet = new HashSet();
-    }
+    private boolean _isFinite = true;
+    private final Set<String> _finiteSet = new HashSet<>();
 
     /**
      * Inverts the representing NameSet
@@ -50,26 +41,28 @@
      * Adds a name to the representing NameSet
      * @param name
      */
-    public void add(String name)
-    {
-        if (_isFinite )
+    public void add(String name) {
+        if (_isFinite) {
             _finiteSet.add(name);
-        else
+        } else {
             _finiteSet.remove(name);
+        }
     }
 
     /**
      * Creates a new NameSet with the current state.
+     *
      * @return created NameSet
      */
-    public NameSet toNameSet()
-    {
-        if ( _finiteSet.size()==0 )
-            if ( _isFinite )
+    public NameSet toNameSet() {
+        if (_finiteSet.size() == 0) {
+            if (_isFinite) {
                 return NameSet.EMPTY;
-            else
+            } else {
                 return NameSet.EVERYTHING;
-        else
+            }
+        } else {
             return NameSet.newInstance(_isFinite, _finiteSet);
+        }
     }
 }
\ No newline at end of file
diff --git a/src/main/java/org/apache/xmlbeans/impl/regex/RangeToken.java b/src/main/java/org/apache/xmlbeans/impl/regex/RangeToken.java
index 537fdc4..b78ab46 100644
--- a/src/main/java/org/apache/xmlbeans/impl/regex/RangeToken.java
+++ b/src/main/java/org/apache/xmlbeans/impl/regex/RangeToken.java
@@ -32,7 +32,7 @@
         this.setSorted(false);
     }
 
-                                                // for RANGE or NRANGE
+    // for RANGE or NRANGE
     protected void addRange(int start, int end) {
         this.icaseCache = null;
         //System.err.println("Token#addRange(): "+start+" "+end);
@@ -45,65 +45,73 @@
             r2 = start;
         }
 
-        int pos = 0;
         if (this.ranges == null) {
             this.ranges = new int[2];
             this.ranges[0] = r1;
             this.ranges[1] = r2;
             this.setSorted(true);
         } else {
-            pos = this.ranges.length;
-            if (this.ranges[pos-1]+1 == r1) {
-                this.ranges[pos-1] = r2;
+            int pos = this.ranges.length;
+            if (this.ranges[pos - 1] + 1 == r1) {
+                this.ranges[pos - 1] = r2;
                 return;
             }
-            int[] temp = new int[pos+2];
+            int[] temp = new int[pos + 2];
             System.arraycopy(this.ranges, 0, temp, 0, pos);
             this.ranges = temp;
-            if (this.ranges[pos-1] >= r1)
+            if (this.ranges[pos - 1] >= r1) {
                 this.setSorted(false);
+            }
             this.ranges[pos++] = r1;
             this.ranges[pos] = r2;
-            if (!this.sorted)
+            if (!this.sorted) {
                 this.sortRanges();
+            }
         }
     }
 
-    private final boolean isSorted() {
+    private boolean isSorted() {
         return this.sorted;
     }
-    private final void setSorted(boolean sort) {
+
+    private void setSorted(boolean sort) {
         this.sorted = sort;
-        if (!sort)  this.compacted = false;
+        if (!sort) {
+            this.compacted = false;
+        }
     }
-    private final boolean isCompacted() {
+
+    private boolean isCompacted() {
         return this.compacted;
     }
-    private final void setCompacted() {
+
+    private void setCompacted() {
         this.compacted = true;
     }
 
     protected void sortRanges() {
-        if (this.isSorted())
+        if (this.isSorted()) {
             return;
-        if (this.ranges == null)
+        }
+        if (this.ranges == null) {
             return;
+        }
         //System.err.println("Do sorting: "+this.ranges.length);
 
-                                                // Bubble sort
-                                                // Why? -- In many cases,
-                                                //         this.ranges has few elements.
-        for (int i = this.ranges.length-4;  i >= 0;  i -= 2) {
-            for (int j = 0;  j <= i;  j += 2) {
-                if (this.ranges[j] > this.ranges[j+2]
-                    || this.ranges[j] == this.ranges[j+2] && this.ranges[j+1] > this.ranges[j+3]) {
+        // Bubble sort
+        // Why? -- In many cases,
+        //         this.ranges has few elements.
+        for (int i = this.ranges.length - 4; i >= 0; i -= 2) {
+            for (int j = 0; j <= i; j += 2) {
+                if (this.ranges[j] > this.ranges[j + 2]
+                    || this.ranges[j] == this.ranges[j + 2] && this.ranges[j + 1] > this.ranges[j + 3]) {
                     int tmp;
-                    tmp = this.ranges[j+2];
-                    this.ranges[j+2] = this.ranges[j];
+                    tmp = this.ranges[j + 2];
+                    this.ranges[j + 2] = this.ranges[j];
                     this.ranges[j] = tmp;
-                    tmp = this.ranges[j+3];
-                    this.ranges[j+3] = this.ranges[j+1];
-                    this.ranges[j+1] = tmp;
+                    tmp = this.ranges[j + 3];
+                    this.ranges[j + 3] = this.ranges[j + 1];
+                    this.ranges[j + 1] = tmp;
                 }
             }
         }
@@ -115,63 +123,70 @@
      */
     protected void compactRanges() {
         boolean DEBUG = false;
-        if (this.ranges == null || this.ranges.length <= 2)
+        if (this.ranges == null || this.ranges.length <= 2) {
             return;
-        if (this.isCompacted())
+        }
+        if (this.isCompacted()) {
             return;
+        }
         int base = 0;                           // Index of writing point
         int target = 0;                         // Index of processing point
 
         while (target < this.ranges.length) {
             if (base != target) {
                 this.ranges[base] = this.ranges[target++];
-                this.ranges[base+1] = this.ranges[target++];
-            } else
+                this.ranges[base + 1] = this.ranges[target++];
+            } else {
                 target += 2;
-            int baseend = this.ranges[base+1];
+            }
+            int baseend = this.ranges[base + 1];
             while (target < this.ranges.length) {
-                if (baseend+1 < this.ranges[target])
+                if (baseend + 1 < this.ranges[target]) {
                     break;
-                if (baseend+1 == this.ranges[target]) {
-                    if (DEBUG)
-                        System.err.println("Token#compactRanges(): Compaction: ["+this.ranges[base]
-                                           +", "+this.ranges[base+1]
-                                           +"], ["+this.ranges[target]
-                                           +", "+this.ranges[target+1]
-                                           +"] -> ["+this.ranges[base]
-                                           +", "+this.ranges[target+1]
-                                           +"]");
-                    this.ranges[base+1] = this.ranges[target+1];
-                    baseend = this.ranges[base+1];
+                }
+                if (baseend + 1 == this.ranges[target]) {
+                    if (DEBUG) {
+                        System.err.println("Token#compactRanges(): Compaction: [" + this.ranges[base]
+                                           + ", " + this.ranges[base + 1]
+                                           + "], [" + this.ranges[target]
+                                           + ", " + this.ranges[target + 1]
+                                           + "] -> [" + this.ranges[base]
+                                           + ", " + this.ranges[target + 1]
+                                           + "]");
+                    }
+                    this.ranges[base + 1] = this.ranges[target + 1];
+                    baseend = this.ranges[base + 1];
                     target += 2;
-                } else if (baseend >= this.ranges[target+1]) {
-                    if (DEBUG)
-                        System.err.println("Token#compactRanges(): Compaction: ["+this.ranges[base]
-                                           +", "+this.ranges[base+1]
-                                           +"], ["+this.ranges[target]
-                                           +", "+this.ranges[target+1]
-                                           +"] -> ["+this.ranges[base]
-                                           +", "+this.ranges[base+1]
-                                           +"]");
+                } else if (baseend >= this.ranges[target + 1]) {
+                    if (DEBUG) {
+                        System.err.println("Token#compactRanges(): Compaction: [" + this.ranges[base]
+                                           + ", " + this.ranges[base + 1]
+                                           + "], [" + this.ranges[target]
+                                           + ", " + this.ranges[target + 1]
+                                           + "] -> [" + this.ranges[base]
+                                           + ", " + this.ranges[base + 1]
+                                           + "]");
+                    }
                     target += 2;
-                } else if (baseend < this.ranges[target+1]) {
-                    if (DEBUG)
-                        System.err.println("Token#compactRanges(): Compaction: ["+this.ranges[base]
-                                           +", "+this.ranges[base+1]
-                                           +"], ["+this.ranges[target]
-                                           +", "+this.ranges[target+1]
-                                           +"] -> ["+this.ranges[base]
-                                           +", "+this.ranges[target+1]
-                                           +"]");
-                    this.ranges[base+1] = this.ranges[target+1];
-                    baseend = this.ranges[base+1];
+                } else if (baseend < this.ranges[target + 1]) {
+                    if (DEBUG) {
+                        System.err.println("Token#compactRanges(): Compaction: [" + this.ranges[base]
+                                           + ", " + this.ranges[base + 1]
+                                           + "], [" + this.ranges[target]
+                                           + ", " + this.ranges[target + 1]
+                                           + "] -> [" + this.ranges[base]
+                                           + ", " + this.ranges[target + 1]
+                                           + "]");
+                    }
+                    this.ranges[base + 1] = this.ranges[target + 1];
+                    baseend = this.ranges[base + 1];
                     target += 2;
                 } else {
                     throw new RuntimeException("Token#compactRanges(): Internel Error: ["
-                                               +this.ranges[base]
-                                               +","+this.ranges[base+1]
-                                               +"] ["+this.ranges[target]
-                                               +","+this.ranges[target+1]+"]");
+                                               + this.ranges[base]
+                                               + "," + this.ranges[base + 1]
+                                               + "] [" + this.ranges[target]
+                                               + "," + this.ranges[target + 1] + "]");
                 }
             } // while
             base += 2;
@@ -186,11 +201,12 @@
     }
 
     protected void mergeRanges(Token token) {
-        RangeToken tok = (RangeToken)token;
+        RangeToken tok = (RangeToken) token;
         this.sortRanges();
         tok.sortRanges();
-        if (tok.ranges == null)
+        if (tok.ranges == null) {
             return;
+        }
         this.icaseCache = null;
         this.setSorted(true);
         if (this.ranges == null) {
@@ -198,8 +214,8 @@
             System.arraycopy(tok.ranges, 0, this.ranges, 0, tok.ranges.length);
             return;
         }
-        int[] result = new int[this.ranges.length+tok.ranges.length];
-        for (int i = 0, j = 0, k = 0;  i < this.ranges.length || j < tok.ranges.length;) {
+        int[] result = new int[this.ranges.length + tok.ranges.length];
+        for (int i = 0, j = 0, k = 0; i < this.ranges.length || j < tok.ranges.length; ) {
             if (i >= this.ranges.length) {
                 result[k++] = tok.ranges[j++];
                 result[k++] = tok.ranges[j++];
@@ -207,7 +223,7 @@
                 result[k++] = this.ranges[i++];
                 result[k++] = this.ranges[i++];
             } else if (tok.ranges[j] < this.ranges[i]
-                       || tok.ranges[j] == this.ranges[i] && tok.ranges[j+1] < this.ranges[i+1]) {
+                       || tok.ranges[j] == this.ranges[i] && tok.ranges[j + 1] < this.ranges[i + 1]) {
                 result[k++] = tok.ranges[j++];
                 result[k++] = tok.ranges[j++];
             } else {
@@ -223,9 +239,10 @@
             this.intersectRanges(token);
             return;
         }
-        RangeToken tok = (RangeToken)token;
-        if (tok.ranges == null || this.ranges == null)
+        RangeToken tok = (RangeToken) token;
+        if (tok.ranges == null || this.ranges == null) {
             return;
+        }
         this.icaseCache = null;
         this.sortRanges();
         this.compactRanges();
@@ -234,69 +251,69 @@
 
         //System.err.println("Token#substractRanges(): Entry: "+this.ranges.length+", "+tok.ranges.length);
 
-        int[] result = new int[this.ranges.length+tok.ranges.length];
+        int[] result = new int[this.ranges.length + tok.ranges.length];
         int wp = 0, src = 0, sub = 0;
         while (src < this.ranges.length && sub < tok.ranges.length) {
             int srcbegin = this.ranges[src];
-            int srcend = this.ranges[src+1];
+            int srcend = this.ranges[src + 1];
             int subbegin = tok.ranges[sub];
-            int subend = tok.ranges[sub+1];
+            int subend = tok.ranges[sub + 1];
             if (srcend < subbegin) {            // Not overlapped
-                                                // src: o-----o
-                                                // sub:         o-----o
-                                                // res: o-----o
-                                                // Reuse sub
+                // src: o-----o
+                // sub:         o-----o
+                // res: o-----o
+                // Reuse sub
                 result[wp++] = this.ranges[src++];
                 result[wp++] = this.ranges[src++];
             } else if (srcend >= subbegin
                        && srcbegin <= subend) { // Overlapped
-                                                // src:    o--------o
-                                                // sub:  o----o
-                                                // sub:      o----o
-                                                // sub:          o----o
-                                                // sub:  o------------o
+                // src:    o--------o
+                // sub:  o----o
+                // sub:      o----o
+                // sub:          o----o
+                // sub:  o------------o
                 if (subbegin <= srcbegin && srcend <= subend) {
-                                                // src:    o--------o
-                                                // sub:  o------------o
-                                                // res: empty
-                                                // Reuse sub
+                    // src:    o--------o
+                    // sub:  o------------o
+                    // res: empty
+                    // Reuse sub
                     src += 2;
                 } else if (subbegin <= srcbegin) {
-                                                // src:    o--------o
-                                                // sub:  o----o
-                                                // res:       o-----o
-                                                // Reuse src(=res)
-                    this.ranges[src] = subend+1;
+                    // src:    o--------o
+                    // sub:  o----o
+                    // res:       o-----o
+                    // Reuse src(=res)
+                    this.ranges[src] = subend + 1;
                     sub += 2;
                 } else if (srcend <= subend) {
-                                                // src:    o--------o
-                                                // sub:          o----o
-                                                // res:    o-----o
-                                                // Reuse sub
+                    // src:    o--------o
+                    // sub:          o----o
+                    // res:    o-----o
+                    // Reuse sub
                     result[wp++] = srcbegin;
-                    result[wp++] = subbegin-1;
+                    result[wp++] = subbegin - 1;
                     src += 2;
                 } else {
-                                                // src:    o--------o
-                                                // sub:      o----o
-                                                // res:    o-o    o-o
-                                                // Reuse src(=right res)
+                    // src:    o--------o
+                    // sub:      o----o
+                    // res:    o-o    o-o
+                    // Reuse src(=right res)
                     result[wp++] = srcbegin;
-                    result[wp++] = subbegin-1;
-                    this.ranges[src] = subend+1;
+                    result[wp++] = subbegin - 1;
+                    this.ranges[src] = subend + 1;
                     sub += 2;
                 }
             } else if (subend < srcbegin) {
-                                                // Not overlapped
-                                                // src:          o-----o
-                                                // sub: o----o
+                // Not overlapped
+                // src:          o-----o
+                // sub: o----o
                 sub += 2;
             } else {
-                throw new RuntimeException("Token#subtractRanges(): Internal Error: ["+this.ranges[src]
-                                           +","+this.ranges[src+1]
-                                           +"] - ["+tok.ranges[sub]
-                                           +","+tok.ranges[sub+1]
-                                           +"]");
+                throw new RuntimeException("Token#subtractRanges(): Internal Error: [" + this.ranges[src]
+                                           + "," + this.ranges[src + 1]
+                                           + "] - [" + tok.ranges[sub]
+                                           + "," + tok.ranges[sub + 1]
+                                           + "]");
             }
         }
         while (src < this.ranges.length) {
@@ -305,88 +322,89 @@
         }
         this.ranges = new int[wp];
         System.arraycopy(result, 0, this.ranges, 0, wp);
-                                                // this.ranges is sorted and compacted.
+        // this.ranges is sorted and compacted.
     }
 
     /**
-     * @param tok Ignore whether it is NRANGE or not.
+     * @param token Ignore whether it is NRANGE or not.
      */
     protected void intersectRanges(Token token) {
-        RangeToken tok = (RangeToken)token;
-        if (tok.ranges == null || this.ranges == null)
+        RangeToken tok = (RangeToken) token;
+        if (tok.ranges == null || this.ranges == null) {
             return;
+        }
         this.icaseCache = null;
         this.sortRanges();
         this.compactRanges();
         tok.sortRanges();
         tok.compactRanges();
 
-        int[] result = new int[this.ranges.length+tok.ranges.length];
+        int[] result = new int[this.ranges.length + tok.ranges.length];
         int wp = 0, src1 = 0, src2 = 0;
         while (src1 < this.ranges.length && src2 < tok.ranges.length) {
             int src1begin = this.ranges[src1];
-            int src1end = this.ranges[src1+1];
+            int src1end = this.ranges[src1 + 1];
             int src2begin = tok.ranges[src2];
-            int src2end = tok.ranges[src2+1];
+            int src2end = tok.ranges[src2 + 1];
             if (src1end < src2begin) {          // Not overlapped
-                                                // src1: o-----o
-                                                // src2:         o-----o
-                                                // res:  empty
-                                                // Reuse src2
+                // src1: o-----o
+                // src2:         o-----o
+                // res:  empty
+                // Reuse src2
                 src1 += 2;
             } else if (src1end >= src2begin
                        && src1begin <= src2end) { // Overlapped
-                                                // src1:    o--------o
-                                                // src2:  o----o
-                                                // src2:      o----o
-                                                // src2:          o----o
-                                                // src2:  o------------o
-                if (src2begin <= src2begin && src1end <= src2end) {
-                                                // src1:    o--------o
-                                                // src2:  o------------o
-                                                // res:     o--------o
-                                                // Reuse src2
+                // src1:    o--------o
+                // src2:  o----o
+                // src2:      o----o
+                // src2:          o----o
+                // src2:  o------------o
+                if (src2begin <= src1begin && src1end <= src2end) {
+                    // src1:    o--------o
+                    // src2:  o------------o
+                    // res:     o--------o
+                    // Reuse src2
                     result[wp++] = src1begin;
                     result[wp++] = src1end;
                     src1 += 2;
                 } else if (src2begin <= src1begin) {
-                                                // src1:    o--------o
-                                                // src2:  o----o
-                                                // res:     o--o
-                                                // Reuse the rest of src1
+                    // src1:    o--------o
+                    // src2:  o----o
+                    // res:     o--o
+                    // Reuse the rest of src1
                     result[wp++] = src1begin;
                     result[wp++] = src2end;
-                    this.ranges[src1] = src2end+1;
+                    this.ranges[src1] = src2end + 1;
                     src2 += 2;
                 } else if (src1end <= src2end) {
-                                                // src1:    o--------o
-                                                // src2:          o----o
-                                                // res:           o--o
-                                                // Reuse src2
+                    // src1:    o--------o
+                    // src2:          o----o
+                    // res:           o--o
+                    // Reuse src2
                     result[wp++] = src2begin;
                     result[wp++] = src1end;
                     src1 += 2;
                 } else {
-                                                // src1:    o--------o
-                                                // src2:      o----o
-                                                // res:       o----o
-                                                // Reuse the rest of src1
+                    // src1:    o--------o
+                    // src2:      o----o
+                    // res:       o----o
+                    // Reuse the rest of src1
                     result[wp++] = src2begin;
                     result[wp++] = src2end;
-                    this.ranges[src1] = src2end+1;
+                    this.ranges[src1] = src2end + 1;
                 }
             } else if (src2end < src1begin) {
-                                                // Not overlapped
-                                                // src1:          o-----o
-                                                // src2: o----o
+                // Not overlapped
+                // src1:          o-----o
+                // src2: o----o
                 src2 += 2;
             } else {
                 throw new RuntimeException("Token#intersectRanges(): Internal Error: ["
-                                           +this.ranges[src1]
-                                           +","+this.ranges[src1+1]
-                                           +"] & ["+tok.ranges[src2]
-                                           +","+tok.ranges[src2+1]
-                                           +"]");
+                                           + this.ranges[src1]
+                                           + "," + this.ranges[src1 + 1]
+                                           + "] & [" + tok.ranges[src2]
+                                           + "," + tok.ranges[src2 + 1]
+                                           + "]");
             }
         }
         while (src1 < this.ranges.length) {
@@ -395,7 +413,7 @@
         }
         this.ranges = new int[wp];
         System.arraycopy(result, 0, this.ranges, 0, wp);
-                                                // this.ranges is sorted and compacted.
+        // this.ranges is sorted and compacted.
     }
 
     /**
@@ -403,30 +421,33 @@
      * for NRANGE: Creates the same meaning RANGE.
      */
     static Token complementRanges(Token token) {
-        if (token.type != RANGE && token.type != NRANGE)
-            throw new IllegalArgumentException("Token#complementRanges(): must be RANGE: "+token.type);
-        RangeToken tok = (RangeToken)token;
+        if (token.type != RANGE && token.type != NRANGE) {
+            throw new IllegalArgumentException("Token#complementRanges(): must be RANGE: " + token.type);
+        }
+        RangeToken tok = (RangeToken) token;
         tok.sortRanges();
         tok.compactRanges();
-        int len = tok.ranges.length+2;
-        if (tok.ranges[0] == 0)
+        int len = tok.ranges.length + 2;
+        if (tok.ranges[0] == 0) {
             len -= 2;
-        int last = tok.ranges[tok.ranges.length-1];
-        if (last == UTF16_MAX)
+        }
+        int last = tok.ranges[tok.ranges.length - 1];
+        if (last == UTF16_MAX) {
             len -= 2;
+        }
         RangeToken ret = Token.createRange();
         ret.ranges = new int[len];
         int wp = 0;
         if (tok.ranges[0] > 0) {
             ret.ranges[wp++] = 0;
-            ret.ranges[wp++] = tok.ranges[0]-1;
+            ret.ranges[wp++] = tok.ranges[0] - 1;
         }
-        for (int i = 1;  i < tok.ranges.length-2;  i += 2) {
-            ret.ranges[wp++] = tok.ranges[i]+1;
-            ret.ranges[wp++] = tok.ranges[i+1]-1;
+        for (int i = 1; i < tok.ranges.length - 2; i += 2) {
+            ret.ranges[wp++] = tok.ranges[i] + 1;
+            ret.ranges[wp++] = tok.ranges[i + 1] - 1;
         }
         if (last != UTF16_MAX) {
-            ret.ranges[wp++] = last+1;
+            ret.ranges[wp++] = last + 1;
             ret.ranges[wp] = UTF16_MAX;
         }
         ret.setCompacted();
@@ -434,27 +455,28 @@
     }
 
     synchronized RangeToken getCaseInsensitiveToken() {
-        if (this.icaseCache != null)
+        if (this.icaseCache != null) {
             return this.icaseCache;
-            
+        }
+
         RangeToken uppers = this.type == Token.RANGE ? Token.createRange() : Token.createNRange();
-        for (int i = 0;  i < this.ranges.length;  i += 2) {
-            for (int ch = this.ranges[i];  ch <= this.ranges[i+1];  ch ++) {
-                if (ch > 0xffff)
+        for (int i = 0; i < this.ranges.length; i += 2) {
+            for (int ch = this.ranges[i]; ch <= this.ranges[i + 1]; ch++) {
+                if (ch > 0xffff) {
                     uppers.addRange(ch, ch);
-                else {
-                    char uch = Character.toUpperCase((char)ch);
+                } else {
+                    char uch = Character.toUpperCase((char) ch);
                     uppers.addRange(uch, uch);
                 }
             }
         }
         RangeToken lowers = this.type == Token.RANGE ? Token.createRange() : Token.createNRange();
-        for (int i = 0;  i < uppers.ranges.length;  i += 2) {
-            for (int ch = uppers.ranges[i];  ch <= uppers.ranges[i+1];  ch ++) {
-                if (ch > 0xffff)
+        for (int i = 0; i < uppers.ranges.length; i += 2) {
+            for (int ch = uppers.ranges[i]; ch <= uppers.ranges[i + 1]; ch++) {
+                if (ch > 0xffff) {
                     lowers.addRange(ch, ch);
-                else {
-                    char uch = Character.toUpperCase((char)ch);
+                } else {
+                    char uch = Character.toUpperCase((char) ch);
                     lowers.addRange(uch, uch);
                 }
             }
@@ -469,40 +491,48 @@
 
     void dumpRanges() {
         System.err.print("RANGE: ");
-        if (this.ranges == null)
+        if (this.ranges == null) {
             System.err.println(" NULL");
-        for (int i = 0;  i < this.ranges.length;  i += 2) {
-            System.err.print("["+this.ranges[i]+","+this.ranges[i+1]+"] ");
         }
-        System.err.println("");
+        for (int i = 0; i < this.ranges.length; i += 2) {
+            System.err.print("[" + this.ranges[i] + "," + this.ranges[i + 1] + "] ");
+        }
+        System.err.println();
     }
 
     boolean match(int ch) {
-        if (this.map == null)  this.createMap();
+        if (this.map == null) {
+            this.createMap();
+        }
         boolean ret;
         if (this.type == RANGE) {
-            if (ch < MAPSIZE)
-                return (this.map[ch/32] & (1<<(ch&0x1f))) != 0;
+            if (ch < MAPSIZE) {
+                return (this.map[ch / 32] & (1 << (ch & 0x1f))) != 0;
+            }
             ret = false;
-            for (int i = this.nonMapIndex;  i < this.ranges.length;  i += 2) {
-                if (this.ranges[i] <= ch && ch <= this.ranges[i+1])
+            for (int i = this.nonMapIndex; i < this.ranges.length; i += 2) {
+                if (this.ranges[i] <= ch && ch <= this.ranges[i + 1]) {
                     return true;
+                }
             }
         } else {
-            if (ch < MAPSIZE)
-                return (this.map[ch/32] & (1<<(ch&0x1f))) == 0;
+            if (ch < MAPSIZE) {
+                return (this.map[ch / 32] & (1 << (ch & 0x1f))) == 0;
+            }
             ret = true;
-            for (int i = this.nonMapIndex;  i < this.ranges.length;  i += 2) {
-                if (this.ranges[i] <= ch && ch <= this.ranges[i+1])
+            for (int i = this.nonMapIndex; i < this.ranges.length; i += 2) {
+                if (this.ranges[i] <= ch && ch <= this.ranges[i + 1]) {
                     return false;
+                }
             }
         }
         return ret;
     }
 
     private static final int MAPSIZE = 256;
+
     private void createMap() {
-        int asize = MAPSIZE/32;                 // 32 is the number of bits in `int'.
+        int asize = MAPSIZE / 32;                 // 32 is the number of bits in `int'.
         // CHANGE(radup) we need a new map, since this is not synchronized
         // and if we init the instance map with 0's it's going to be trouble
         // -this.map = new int[asize];
@@ -510,13 +540,16 @@
         // -for (int i = 0; i < asize; i++) this.map[i] = 0;
         int[] localmap = new int[asize]; // +
         int localnonMapIndex = this.ranges.length; // +
-        for (int i = 0;  i < asize;  i ++)  localmap[i] = 0; // + redundant
-        for (int i = 0;  i < this.ranges.length;  i += 2) {
+        for (int i = 0; i < asize; i++) {
+            localmap[i] = 0; // + redundant
+        }
+        for (int i = 0; i < this.ranges.length; i += 2) {
             int s = this.ranges[i];
-            int e = this.ranges[i+1];
+            int e = this.ranges[i + 1];
             if (s < MAPSIZE) {
-                for (int j = s;  j <= e && j < MAPSIZE;  j ++)
-                    localmap[j/32] |= 1<<(j&0x1f); // s&0x1f : 0-31
+                for (int j = s; j <= e && j < MAPSIZE; j++) {
+                    localmap[j / 32] |= 1 << (j & 0x1f); // s&0x1f : 0-31
+                }
             } else {
                 localnonMapIndex = i;
                 break;
@@ -534,48 +567,52 @@
     public String toString(int options) {
         String ret;
         if (this.type == RANGE) {
-            if (this == Token.token_dot)
+            if (this == Token.token_dot) {
                 ret = ".";
-            else if (this == Token.token_0to9)
+            } else if (this == Token.token_0to9) {
                 ret = "\\d";
-            else if (this == Token.token_wordchars)
+            } else if (this == Token.token_wordchars) {
                 ret = "\\w";
-            else if (this == Token.token_spaces)
+            } else if (this == Token.token_spaces) {
                 ret = "\\s";
-            else {
+            } else {
                 StringBuilder sb = new StringBuilder();
                 sb.append("[");
-                for (int i = 0;  i < this.ranges.length;  i += 2) {
-                    if ((options & RegularExpression.SPECIAL_COMMA) != 0 && i > 0)  sb.append(",");
-                    if (this.ranges[i] == this.ranges[i+1]) {
+                for (int i = 0; i < this.ranges.length; i += 2) {
+                    if ((options & RegularExpression.SPECIAL_COMMA) != 0 && i > 0) {
+                        sb.append(",");
+                    }
+                    if (this.ranges[i] == this.ranges[i + 1]) {
                         sb.append(escapeCharInCharClass(this.ranges[i]));
                     } else {
                         sb.append(escapeCharInCharClass(this.ranges[i]));
-                        sb.append((char)'-');
-                        sb.append(escapeCharInCharClass(this.ranges[i+1]));
+                        sb.append((char) '-');
+                        sb.append(escapeCharInCharClass(this.ranges[i + 1]));
                     }
                 }
                 sb.append("]");
                 ret = sb.toString();
             }
         } else {
-            if (this == Token.token_not_0to9)
+            if (this == Token.token_not_0to9) {
                 ret = "\\D";
-            else if (this == Token.token_not_wordchars)
+            } else if (this == Token.token_not_wordchars) {
                 ret = "\\W";
-            else if (this == Token.token_not_spaces)
+            } else if (this == Token.token_not_spaces) {
                 ret = "\\S";
-            else {
+            } else {
                 StringBuilder sb = new StringBuilder();
                 sb.append("[^");
-                for (int i = 0;  i < this.ranges.length;  i += 2) {
-                    if ((options & RegularExpression.SPECIAL_COMMA) != 0 && i > 0)  sb.append(",");
-                    if (this.ranges[i] == this.ranges[i+1]) {
+                for (int i = 0; i < this.ranges.length; i += 2) {
+                    if ((options & RegularExpression.SPECIAL_COMMA) != 0 && i > 0) {
+                        sb.append(",");
+                    }
+                    if (this.ranges[i] == this.ranges[i + 1]) {
                         sb.append(escapeCharInCharClass(this.ranges[i]));
                     } else {
                         sb.append(escapeCharInCharClass(this.ranges[i]));
                         sb.append('-');
-                        sb.append(escapeCharInCharClass(this.ranges[i+1]));
+                        sb.append(escapeCharInCharClass(this.ranges[i + 1]));
                     }
                 }
                 sb.append("]");
@@ -588,25 +625,40 @@
     private static String escapeCharInCharClass(int ch) {
         String ret;
         switch (ch) {
-          case '[':  case ']':  case '-':  case '^':
-          case ',':  case '\\':
-            ret = "\\"+(char)ch;
-            break;
-          case '\f':  ret = "\\f";  break;
-          case '\n':  ret = "\\n";  break;
-          case '\r':  ret = "\\r";  break;
-          case '\t':  ret = "\\t";  break;
-          case 0x1b:  ret = "\\e";  break;
-          //case 0x0b:  ret = "\\v";  break;
-          default:
-            if (ch < 0x20) {
-                String pre = "0"+Integer.toHexString(ch);
-                ret = "\\x"+pre.substring(pre.length()-2, pre.length());
-            } else if (ch >= 0x10000) {
-                String pre = "0"+Integer.toHexString(ch);
-                ret = "\\v"+pre.substring(pre.length()-6, pre.length());
-            } else
-                ret = ""+(char)ch;
+            case '[':
+            case ']':
+            case '-':
+            case '^':
+            case ',':
+            case '\\':
+                ret = "\\" + (char) ch;
+                break;
+            case '\f':
+                ret = "\\f";
+                break;
+            case '\n':
+                ret = "\\n";
+                break;
+            case '\r':
+                ret = "\\r";
+                break;
+            case '\t':
+                ret = "\\t";
+                break;
+            case 0x1b:
+                ret = "\\e";
+                break;
+            //case 0x0b:  ret = "\\v";  break;
+            default:
+                if (ch < 0x20) {
+                    String pre = "0" + Integer.toHexString(ch);
+                    ret = "\\x" + pre.substring(pre.length() - 2);
+                } else if (ch >= 0x10000) {
+                    String pre = "0" + Integer.toHexString(ch);
+                    ret = "\\v" + pre.substring(pre.length() - 6);
+                } else {
+                    ret = "" + (char) ch;
+                }
         }
         return ret;
     }
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 1d00a0d..f548cf0 100644
--- a/src/main/java/org/apache/xmlbeans/impl/schema/SchemaTypeCodePrinter.java
+++ b/src/main/java/org/apache/xmlbeans/impl/schema/SchemaTypeCodePrinter.java
@@ -15,38 +15,23 @@
 
 package org.apache.xmlbeans.impl.schema;
 
-import java.io.Writer;
+import org.apache.xmlbeans.*;
+import org.apache.xmlbeans.impl.common.NameUtil;
+
+import javax.xml.namespace.QName;
 import java.io.IOException;
+import java.io.Writer;
 import java.nio.charset.CharacterCodingException;
 import java.nio.charset.Charset;
 import java.nio.charset.CharsetEncoder;
-import java.util.ArrayList;
-import java.util.Map;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.LinkedHashMap;
-import java.util.List;
-
-import javax.xml.namespace.QName;
-import org.apache.xmlbeans.impl.common.NameUtil;
-import org.apache.xmlbeans.PrePostExtension;
-import org.apache.xmlbeans.InterfaceExtension;
-import org.apache.xmlbeans.SchemaType;
-import org.apache.xmlbeans.SchemaTypeSystem;
-import org.apache.xmlbeans.SchemaProperty;
-import org.apache.xmlbeans.SchemaStringEnumEntry;
-import org.apache.xmlbeans.SystemProperties;
-import org.apache.xmlbeans.XmlObject;
-import org.apache.xmlbeans.XmlOptions;
-import org.apache.xmlbeans.SchemaCodePrinter;
+import java.util.*;
 
 /**
  * Prints the java code for a single schema type
  */
-public final class SchemaTypeCodePrinter implements SchemaCodePrinter
-{
+public final class SchemaTypeCodePrinter implements SchemaCodePrinter {
     Writer _writer;
-    int    _indent;
+    int _indent;
     boolean _useJava15;
 
 
@@ -60,125 +45,108 @@
 
     public static final String INDEX_CLASSNAME = "TypeSystemHolder";
 
-    public static void printTypeImpl ( Writer writer, SchemaType sType,
-                                       XmlOptions opt )
-        throws IOException
-    {
-        getPrinter(opt).printTypeImpl( writer, sType );
+    public static void printTypeImpl(Writer writer, SchemaType sType,
+                                     XmlOptions opt)
+        throws IOException {
+        getPrinter(opt).printTypeImpl(writer, sType);
     }
 
-    public static void printType ( Writer writer, SchemaType sType,
-                                   XmlOptions opt )
-        throws IOException
-    {
-        getPrinter(opt).printType( writer, sType );
+    public static void printType(Writer writer, SchemaType sType,
+                                 XmlOptions opt)
+        throws IOException {
+        getPrinter(opt).printType(writer, sType);
     }
 
-    /** @deprecated */
-    public static void printLoader ( Writer writer, SchemaTypeSystem system,
-                                     XmlOptions opt )
-        throws IOException
-    {
-        getPrinter(opt).printLoader( writer, system );
+    /**
+     * @deprecated
+     */
+    public static void printLoader(Writer writer, SchemaTypeSystem system,
+                                   XmlOptions opt)
+        throws IOException {
+        getPrinter(opt).printLoader(writer, system);
     }
 
-    private static SchemaCodePrinter getPrinter(XmlOptions opt)
-    {
+    private static SchemaCodePrinter getPrinter(XmlOptions opt) {
         Object printer = XmlOptions.safeGet
             (opt, XmlOptions.SCHEMA_CODE_PRINTER);
-        if (printer == null || !(printer instanceof SchemaCodePrinter))
-        {
+        if (printer == null || !(printer instanceof SchemaCodePrinter)) {
             printer = new SchemaTypeCodePrinter(opt);
         }
         return (SchemaCodePrinter) printer;
     }
 
-    public SchemaTypeCodePrinter (XmlOptions opt)
-    {
+    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);
+        if (opt != null && XmlOptions.hasOption(opt, XmlOptions.GENERATE_JAVA_VERSION)) {
+            genversion = (String) opt.get(XmlOptions.GENERATE_JAVA_VERSION);
+        }
 
-        if (genversion == null)
+        if (genversion == null) {
             genversion = XmlOptions.GENERATE_JAVA_14;
+        }
 
         _useJava15 = XmlOptions.GENERATE_JAVA_15.equals(genversion);
     }
 
-    void indent()
-    {
+    void indent() {
         _indent += INDENT_INCREMENT;
     }
 
-    void outdent()
-    {
+    void outdent() {
         _indent -= INDENT_INCREMENT;
     }
 
-    String encodeString ( String s )
-    {
+    String encodeString(String s) {
         StringBuilder sb = new StringBuilder();
 
-        sb.append( '"' );
+        sb.append('"');
 
-        for ( int i = 0 ; i < s.length() ; i++ )
-        {
-            char ch = s.charAt( i );
+        for (int i = 0; i < s.length(); i++) {
+            char ch = s.charAt(i);
 
-            if (ch == '"')
-            {
-                sb.append( '\\' );
-                sb.append( '\"' );
+            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);
             }
-            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( '"' );
+        sb.append('"');
 
         return sb.toString();
     }
 
-    void emit(String s) throws IOException
-    {
+    void emit(String s) throws IOException {
         int indent = _indent;
 
-        if (indent > MAX_SPACES.length() / 2)
+        if (indent > MAX_SPACES.length() / 2) {
             indent = MAX_SPACES.length() / 4 + indent / 2;
+        }
 
-        if (indent > MAX_SPACES.length())
+        if (indent > MAX_SPACES.length()) {
             indent = MAX_SPACES.length();
+        }
 
         _writer.write(MAX_SPACES.substring(0, indent));
-        try
-        {
+        try {
             _writer.write(s);
-        }
-        catch (CharacterCodingException cce)
-        {
+        } catch (CharacterCodingException cce) {
             _writer.write(makeSafe(s));
         }
         _writer.write(LINE_SEPARATOR);
@@ -187,48 +155,48 @@
         // System.out.println(s);
     }
 
-    private static String makeSafe(String s)
-    {
+    private static String makeSafe(String s) {
         Charset charset = Charset.forName(System.getProperty("file.encoding"));
-        if (charset == null)
+        if (charset == null) {
             throw new IllegalStateException("Default character set is null!");
+        }
         CharsetEncoder cEncoder = charset.newEncoder();
         StringBuilder result = new StringBuilder();
         int i;
-        for (i = 0; i < s.length(); i++)
-        {
+        for (i = 0; i < s.length(); i++) {
             char c = s.charAt(i);
-            if (!cEncoder.canEncode(c))
+            if (!cEncoder.canEncode(c)) {
                 break;
+            }
         }
-        for (; i < s.length(); i++)
-        {
+        for (; i < s.length(); i++) {
             char c = s.charAt(i);
-            if (cEncoder.canEncode(c))
+            if (cEncoder.canEncode(c)) {
                 result.append(c);
-            else
-            {
+            } else {
                 String hexValue = Integer.toHexString((int) c);
-                switch (hexValue.length())
-                {
-                case 1:
-                    result.append("\\u000").append(hexValue); break;
-                case 2:
-                    result.append("\\u00").append(hexValue); break;
-                case 3:
-                    result.append("\\u0").append(hexValue); break;
-                case 4:
-                    result.append("\\u").append(hexValue); break;
-                default:
-                    throw new IllegalStateException();
+                switch (hexValue.length()) {
+                    case 1:
+                        result.append("\\u000").append(hexValue);
+                        break;
+                    case 2:
+                        result.append("\\u00").append(hexValue);
+                        break;
+                    case 3:
+                        result.append("\\u0").append(hexValue);
+                        break;
+                    case 4:
+                        result.append("\\u").append(hexValue);
+                        break;
+                    default:
+                        throw new IllegalStateException();
                 }
             }
         }
         return result.toString();
     }
 
-    public void printType(Writer writer, SchemaType sType) throws IOException
-    {
+    public void printType(Writer writer, SchemaType sType) throws IOException {
         _writer = writer;
         printTopComment(sType);
         printPackage(sType, true);
@@ -238,8 +206,7 @@
     }
 
     public void printTypeImpl(Writer writer, SchemaType sType)
-        throws IOException
-    {
+        throws IOException {
         _writer = writer;
         printTopComment(sType);
         printPackage(sType, false);
@@ -250,47 +217,46 @@
      * Since not all schema types have java types, this skips
      * over any that don't and gives you the nearest java base type.
      */
-    String findJavaType ( SchemaType sType )
-    {
-        while ( sType.getFullJavaName() == null )
+    String findJavaType(SchemaType sType) {
+        while (sType.getFullJavaName() == null) {
             sType = sType.getBaseType();
+        }
 
         return sType.getFullJavaName();
     }
 
-    static String prettyQName(QName qname)
-    {
+    static String prettyQName(QName qname) {
         String result = qname.getLocalPart();
-        if (qname.getNamespaceURI() != null)
+        if (qname.getNamespaceURI() != null) {
             result += "(@" + qname.getNamespaceURI() + ")";
+        }
         return result;
     }
 
-    void printInnerTypeJavaDoc(SchemaType sType) throws IOException
-    {
+    void printInnerTypeJavaDoc(SchemaType sType) throws IOException {
         QName name = sType.getName();
-        if (name == null)
-        {
-            if (sType.isDocumentType())
+        if (name == null) {
+            if (sType.isDocumentType()) {
                 name = sType.getDocumentElementName();
-            else if (sType.isAttributeType())
+            } else if (sType.isAttributeType()) {
                 name = sType.getAttributeTypeAttributeName();
-            else if (sType.getContainerField() != null)
+            } else if (sType.getContainerField() != null) {
                 name = sType.getContainerField().getName();
+            }
         }
 
         emit("/**");
-        if (sType.isDocumentType())
+        if (sType.isDocumentType()) {
             emit(" * A document containing one " + prettyQName(name) + " element.");
-        else if (sType.isAttributeType())
+        } else if (sType.isAttributeType()) {
             emit(" * A document containing one " + prettyQName(name) + " attribute.");
-        else if (name != null)
+        } else if (name != null) {
             emit(" * An XML " + prettyQName(name) + ".");
-        else
+        } else {
             emit(" * An anonymous inner XML type.");
+        }
         emit(" *");
-        switch (sType.getSimpleVariety())
-        {
+        switch (sType.getSimpleVariety()) {
             case SchemaType.NOT_SIMPLE:
                 emit(" * This is a complex type.");
                 break;
@@ -303,71 +269,68 @@
             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++)
+                for (int i = 0; i < members.length; i++) {
                     emit(" *     " + members[i].getFullJavaName());
+                }
                 break;
         }
         emit(" */");
     }
 
-    private String getFullJavaName(SchemaType sType)
-    {
+    private String getFullJavaName(SchemaType sType) {
 
         SchemaTypeImpl sTypeI = (SchemaTypeImpl) sType;
         String ret = sTypeI.getFullJavaName();
 
-        while (sTypeI.isRedefinition())
-        {
+        while (sTypeI.isRedefinition()) {
             ret = sTypeI.getFullJavaName();
             sTypeI = (SchemaTypeImpl) sTypeI.getBaseType();
         }
         return ret;
     }
 
-    private String getUserTypeStaticHandlerMethod(boolean encode, SchemaTypeImpl stype)
-    {
+    private String getUserTypeStaticHandlerMethod(boolean encode, SchemaTypeImpl stype) {
         String unqualifiedName = stype.getName().getLocalPart();
-        if (unqualifiedName.length() < 2)
+        if (unqualifiedName.length() < 2) {
             unqualifiedName = unqualifiedName.toUpperCase();
-        else
+        } else {
             unqualifiedName = unqualifiedName.substring(0, 1).toUpperCase() + unqualifiedName.substring(1);
+        }
 
-        if (encode)
+        if (encode) {
             return stype.getUserTypeHandlerName() + ".encode" + unqualifiedName;
-        else
+        } else {
             return stype.getUserTypeHandlerName() + ".decode" + unqualifiedName;
+        }
     }
 
 
-    public static String indexClassForSystem(SchemaTypeSystem system)
-    {
+    public static String indexClassForSystem(SchemaTypeSystem system) {
         String name = system.getName();
         return name + "." + INDEX_CLASSNAME;
     }
 
-    static String shortIndexClassForSystem(SchemaTypeSystem system)
-    {
+    static String shortIndexClassForSystem(SchemaTypeSystem system) {
         return INDEX_CLASSNAME;
     }
 
-    void printStaticTypeDeclaration(SchemaType sType, SchemaTypeSystem system) throws IOException
-    {
+    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) + "\");");
+        emit("Factory.getTypeLoader().resolveHandle(\"" + ((SchemaTypeSystemImpl) system).handleForType(sType) + "\");");
         outdent();
     }
 
-    /** @deprecated */
+    /**
+     * @deprecated
+     */
     public void printLoader(Writer writer, SchemaTypeSystem system)
-        throws IOException
-    {
+        throws IOException {
         // deprecated
     }
 
-    void printInnerType(SchemaType sType, SchemaTypeSystem system) throws IOException
-    {
+    void printInnerType(SchemaType sType, SchemaTypeSystem system) throws IOException {
         emit("");
 
         printInnerTypeJavaDoc(sType);
@@ -376,20 +339,18 @@
 
         printStaticTypeDeclaration(sType, system);
 
-        if (sType.isSimpleType())
-        {
-            if (sType.hasStringEnumValues())
+        if (sType.isSimpleType()) {
+            if (sType.hasStringEnumValues()) {
                 printStringEnumeration(sType);
-        }
-        else
-        {
-            if (sType.getContentType() == SchemaType.SIMPLE_CONTENT && sType.hasStringEnumValues())
+            }
+        } else {
+            if (sType.getContentType() == SchemaType.SIMPLE_CONTENT && sType.hasStringEnumValues()) {
                 printStringEnumeration(sType);
+            }
 
             SchemaProperty[] props = getDerivedProperties(sType);
 
-            for (int i = 0; i < props.length; i++)
-            {
+            for (int i = 0; i < props.length; i++) {
                 SchemaProperty prop = props[i];
 
                 printPropertyGetters(
@@ -405,8 +366,7 @@
                     prop.extendsJavaSingleton()
                 );
 
-                if (!prop.isReadOnly())
-                {
+                if (!prop.isReadOnly()) {
                     printPropertySetters(
                         prop.getName(),
                         prop.isAttribute(),
@@ -431,12 +391,12 @@
         endBlock();
     }
 
-    void printFactory(SchemaType sType) throws IOException
-    {
+    void printFactory(SchemaType sType) throws IOException {
         // Only need full factories for top-level types
         boolean fullFactory = true;
-        if (sType.isAnonymousType() && ! sType.isDocumentType() && !sType.isAttributeType())
+        if (sType.isAnonymousType() && !sType.isDocumentType() && !sType.isAttributeType()) {
             fullFactory = false;
+        }
 
         String fullName = sType.getFullJavaName().replace('$', '.');
 
@@ -457,8 +417,7 @@
         emit("}");
         emit("");
 
-        if (sType.isSimpleType())
-        {
+        if (sType.isSimpleType()) {
             emit("public static " + fullName + " newValue(java.lang.Object obj) {");
             emit("  return (" + fullName + ") type.newValue( obj ); }");
             emit("");
@@ -467,8 +426,9 @@
         // Only need newInstance() for non-abstract types
         if (sType.isAbstract()) {
             emit("/** @deprecated No need to be able to create instances of abstract types */");
-            if (_useJava15)
+            if (_useJava15) {
                 emit("@Deprecated");
+            }
         }
         emit("public static " + fullName + " newInstance() {");
         emit("  return (" + fullName + ") getTypeLoader().newInstance( type, null ); }");
@@ -477,15 +437,15 @@
         // Only need newInstance() for non-abstract types
         if (sType.isAbstract()) {
             emit("/** @deprecated No need to be able to create instances of abstract types */");
-            if (_useJava15)
+            if (_useJava15) {
                 emit("@Deprecated");
+            }
         }
         emit("public static " + fullName + " newInstance(org.apache.xmlbeans.XmlOptions options) {");
         emit("  return (" + fullName + ") getTypeLoader().newInstance( type, options ); }");
         emit("");
 
-        if (fullFactory)
-        {
+        if (fullFactory) {
             emit("/** @param xmlAsString the string value to parse */");
             emit("public static " + fullName + " parse(java.lang.String xmlAsString) throws org.apache.xmlbeans.XmlException {");
             emit("  return (" + fullName + ") getTypeLoader().parse( xmlAsString, type, null ); }");
@@ -545,31 +505,35 @@
             emit("");
 
             emit("/** @deprecated {@link org.apache.xmlbeans.xml.stream.XMLInputStream} */");
-            if (_useJava15)
+            if (_useJava15) {
                 emit("@Deprecated");
+            }
             emit("public static " + fullName + " parse(org.apache.xmlbeans.xml.stream.XMLInputStream xis) throws org.apache.xmlbeans.XmlException, org.apache.xmlbeans.xml.stream.XMLStreamException {");
             emit("  return (" + fullName + ") getTypeLoader().parse( xis, type, null ); }");
             emit("");
 
             emit("/** @deprecated {@link org.apache.xmlbeans.xml.stream.XMLInputStream} */");
-            if (_useJava15)
+            if (_useJava15) {
                 emit("@Deprecated");
+            }
             emit("public static " + fullName + " parse(org.apache.xmlbeans.xml.stream.XMLInputStream xis, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, org.apache.xmlbeans.xml.stream.XMLStreamException {");
             emit("  return (" + fullName + ") getTypeLoader().parse( xis, type, options ); }");
             emit("");
 
             // Don't have XMLInputStream anymore
             emit("/** @deprecated {@link org.apache.xmlbeans.xml.stream.XMLInputStream} */");
-            if (_useJava15)
+            if (_useJava15) {
                 emit("@Deprecated");
+            }
             emit("public static org.apache.xmlbeans.xml.stream.XMLInputStream newValidatingXMLInputStream(org.apache.xmlbeans.xml.stream.XMLInputStream xis) throws org.apache.xmlbeans.XmlException, org.apache.xmlbeans.xml.stream.XMLStreamException {");
             emit("  return getTypeLoader().newValidatingXMLInputStream( xis, type, null ); }");
             emit("");
 
             // Don't have XMLInputStream anymore
             emit("/** @deprecated {@link org.apache.xmlbeans.xml.stream.XMLInputStream} */");
-            if (_useJava15)
+            if (_useJava15) {
                 emit("@Deprecated");
+            }
             emit("public static org.apache.xmlbeans.xml.stream.XMLInputStream newValidatingXMLInputStream(org.apache.xmlbeans.xml.stream.XMLInputStream xis, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, org.apache.xmlbeans.xml.stream.XMLStreamException {");
             emit("  return getTypeLoader().newValidatingXMLInputStream( xis, type, options ); }");
             emit("");
@@ -580,55 +544,47 @@
         emit("}");
     }
 
-    void printNestedInnerTypes(SchemaType sType, SchemaTypeSystem system) throws IOException
-    {
+    void printNestedInnerTypes(SchemaType sType, SchemaTypeSystem system) throws IOException {
         boolean redefinition = sType.getName() != null &&
-            sType.getName().equals(sType.getBaseType().getName());
-        while (sType != null)
-        {
+                               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())
+            for (int i = 0; i < anonTypes.length; i++) {
+                if (anonTypes[i].isSkippedAnonymousType()) {
                     printNestedInnerTypes(anonTypes[i], system);
-                else
+                } else {
                     printInnerType(anonTypes[i], system);
+                }
             }
             // For redefinition other than by extension for complex types, go ahead and print
             // the anonymous types in the base
             if (!redefinition ||
-                (sType.getDerivationType() != SchemaType.DT_EXTENSION && !sType.isSimpleType()))
+                (sType.getDerivationType() != SchemaType.DT_EXTENSION && !sType.isSimpleType())) {
                 break;
+            }
             sType = sType.getBaseType();
         }
     }
 
-    void printTopComment(SchemaType sType) throws IOException
-    {
+    void printTopComment(SchemaType sType) throws IOException {
         emit("/*");
-        if (sType.getName() != null)
-        {
+        if (sType.getName() != null) {
             emit(" * XML Type:  " + sType.getName().getLocalPart());
             emit(" * Namespace: " + sType.getName().getNamespaceURI());
-        }
-        else
-        {
+        } else {
             QName thename = null;
 
-            if (sType.isDocumentType())
-            {
+            if (sType.isDocumentType()) {
                 thename = sType.getDocumentElementName();
                 emit(" * An XML document type.");
-            }
-            else if (sType.isAttributeType())
-            {
+            } else if (sType.isAttributeType()) {
                 thename = sType.getAttributeTypeAttributeName();
                 emit(" * An XML attribute type.");
-            }
-            else
+            } else {
                 assert false;
+            }
 
-            assert( thename != null );
+            assert (thename != null);
 
             emit(" * Localname: " + thename.getLocalPart());
             emit(" * Namespace: " + thename.getNamespaceURI());
@@ -639,23 +595,23 @@
         emit(" */");
     }
 
-    void printPackage(SchemaType sType, boolean intf) throws IOException
-    {
+    void printPackage(SchemaType sType, boolean intf) throws IOException {
         String fqjn;
-        if (intf)
+        if (intf) {
             fqjn = sType.getFullJavaName();
-        else
+        } else {
             fqjn = sType.getFullJavaImplName();
+        }
 
         int lastdot = fqjn.lastIndexOf('.');
-        if (lastdot < 0)
+        if (lastdot < 0) {
             return;
+        }
         String pkg = fqjn.substring(0, lastdot);
         emit("package " + pkg + ";");
     }
 
-    void startInterface(SchemaType sType) throws IOException
-    {
+    void startInterface(SchemaType sType) throws IOException {
         String shortName = sType.getShortJavaName();
 
         String baseInterface = findJavaType(sType.getBaseType());
@@ -692,176 +648,176 @@
         emitSpecializedAccessors(sType);
     }
 
-    private static String getExtensionInterfaces(SchemaType sType)
-    {
+    private static String getExtensionInterfaces(SchemaType sType) {
         SchemaTypeImpl sImpl = getImpl(sType);
-        if (sImpl == null)
+        if (sImpl == null) {
             return "";
+        }
 
         StringBuilder sb = new StringBuilder();
 
         InterfaceExtension[] exts = sImpl.getInterfaceExtensions();
-        if (exts != null) for (int i = 0; i < exts.length; i++)
-            sb.append(", " + exts[i].getInterface());
+        if (exts != null) {
+            for (int i = 0; i < exts.length; i++) {
+                sb.append(", " + exts[i].getInterface());
+            }
+        }
 
         return sb.toString();
     }
 
-    private static SchemaTypeImpl getImpl(SchemaType sType)
-    {
-        if (sType instanceof SchemaTypeImpl)
+    private static SchemaTypeImpl getImpl(SchemaType sType) {
+        if (sType instanceof SchemaTypeImpl) {
             return (SchemaTypeImpl) sType;
-        else
+        } else {
             return null;
+        }
     }
 
-    private void emitSpecializedAccessors(SchemaType sType) throws IOException
-    {
+    private void emitSpecializedAccessors(SchemaType sType) throws IOException {
         if (sType.getSimpleVariety() == SchemaType.ATOMIC &&
-            sType.getPrimitiveType().getBuiltinTypeCode() == SchemaType.BTC_DECIMAL)
-        {
+            sType.getPrimitiveType().getBuiltinTypeCode() == SchemaType.BTC_DECIMAL) {
             int bits = sType.getDecimalSize();
             int parentBits = sType.getBaseType().getDecimalSize();
-            if (bits != parentBits || sType.getBaseType().getFullJavaName() == null)
-            {
-                if (bits == SchemaType.SIZE_BIG_INTEGER)
-                {
+            if (bits != parentBits || sType.getBaseType().getFullJavaName() == null) {
+                if (bits == SchemaType.SIZE_BIG_INTEGER) {
                     emit("java.math.BigInteger getBigIntegerValue();");
                     emit("void setBigIntegerValue(java.math.BigInteger bi);");
                     emit("/** @deprecated */");
-                    if (_useJava15)
+                    if (_useJava15) {
                         emit("@Deprecated");
+                    }
                     emit("java.math.BigInteger bigIntegerValue();");
                     emit("/** @deprecated */");
-                    if (_useJava15)
+                    if (_useJava15) {
                         emit("@Deprecated");
+                    }
                     emit("void set(java.math.BigInteger bi);");
-                }
-                else if (bits == SchemaType.SIZE_LONG)
-                {
+                } else if (bits == SchemaType.SIZE_LONG) {
                     emit("long getLongValue();");
                     emit("void setLongValue(long l);");
                     emit("/** @deprecated */");
-                    if (_useJava15)
+                    if (_useJava15) {
                         emit("@Deprecated");
+                    }
                     emit("long longValue();");
                     emit("/** @deprecated */");
-                    if (_useJava15)
+                    if (_useJava15) {
                         emit("@Deprecated");
+                    }
                     emit("void set(long l);");
-                }
-                else if (bits == SchemaType.SIZE_INT)
-                {
+                } else if (bits == SchemaType.SIZE_INT) {
                     emit("int getIntValue();");
                     emit("void setIntValue(int i);");
                     emit("/** @deprecated */");
-                    if (_useJava15)
+                    if (_useJava15) {
                         emit("@Deprecated");
+                    }
                     emit("int intValue();");
                     emit("/** @deprecated */");
-                    if (_useJava15)
+                    if (_useJava15) {
                         emit("@Deprecated");
+                    }
                     emit("void set(int i);");
-                }
-                else if (bits == SchemaType.SIZE_SHORT)
-                {
+                } else if (bits == SchemaType.SIZE_SHORT) {
                     emit("short getShortValue();");
                     emit("void setShortValue(short s);");
                     emit("/** @deprecated */");
-                    if (_useJava15)
+                    if (_useJava15) {
                         emit("@Deprecated");
+                    }
                     emit("short shortValue();");
                     emit("/** @deprecated */");
-                    if (_useJava15)
+                    if (_useJava15) {
                         emit("@Deprecated");
+                    }
                     emit("void set(short s);");
-                }
-                else if (bits == SchemaType.SIZE_BYTE)
-                {
+                } else if (bits == SchemaType.SIZE_BYTE) {
                     emit("byte getByteValue();");
                     emit("void setByteValue(byte b);");
                     emit("/** @deprecated */");
-                    if (_useJava15)
+                    if (_useJava15) {
                         emit("@Deprecated");
+                    }
                     emit("byte byteValue();");
                     emit("/** @deprecated */");
-                    if (_useJava15)
+                    if (_useJava15) {
                         emit("@Deprecated");
+                    }
                     emit("void set(byte b);");
                 }
             }
         }
 
-        if (sType.getSimpleVariety() == SchemaType.UNION)
-        {
+        if (sType.getSimpleVariety() == SchemaType.UNION) {
             emit("java.lang.Object getObjectValue();");
             emit("void setObjectValue(java.lang.Object val);");
             emit("/** @deprecated */");
-            if (_useJava15)
+            if (_useJava15) {
                 emit("@Deprecated");
+            }
             emit("java.lang.Object objectValue();");
             emit("/** @deprecated */");
-            if (_useJava15)
+            if (_useJava15) {
                 emit("@Deprecated");
+            }
             emit("void objectSet(java.lang.Object val);");
             emit("org.apache.xmlbeans.SchemaType instanceType();");
             SchemaType ctype = sType.getUnionCommonBaseType();
-            if (ctype != null && ctype.getSimpleVariety() != SchemaType.UNION);
+            if (ctype != null && ctype.getSimpleVariety() != SchemaType.UNION) {
                 emitSpecializedAccessors(ctype);
+            }
         }
 
-        if (sType.getSimpleVariety() == SchemaType.LIST)
-        {
+        if (sType.getSimpleVariety() == SchemaType.LIST) {
             emit("java.util.List getListValue();");
             emit("java.util.List xgetListValue();");
             emit("void setListValue(java.util.List list);");
             emit("/** @deprecated */");
-            if (_useJava15)
+            if (_useJava15) {
                 emit("@Deprecated");
+            }
             emit("java.util.List listValue();");
             emit("/** @deprecated */");
-            if (_useJava15)
+            if (_useJava15) {
                 emit("@Deprecated");
+            }
             emit("java.util.List xlistValue();");
             emit("/** @deprecated */");
-            if (_useJava15)
+            if (_useJava15) {
                 emit("@Deprecated");
+            }
             emit("void set(java.util.List list);");
         }
     }
 
-    void startBlock() throws IOException
-    {
+    void startBlock() throws IOException {
         emit("{");
         indent();
     }
-    void endBlock() throws IOException
-    {
+
+    void endBlock() throws IOException {
         outdent();
         emit("}");
     }
 
-    void printJavaDoc(String sentence) throws IOException
-    {
+    void printJavaDoc(String sentence) throws IOException {
         emit("");
         emit("/**");
         emit(" * " + sentence);
         emit(" */");
     }
 
-    void printShortJavaDoc(String sentence) throws IOException
-    {
+    void printShortJavaDoc(String sentence) throws IOException {
         emit("/** " + sentence + " */");
     }
 
-    public static String javaStringEscape(String str)
-    {
+    public static String javaStringEscape(String str) {
         // forbidden: \n, \r, \", \\.
-        test: {
-            for (int i = 0; i < str.length(); i++)
-            {
-                switch (str.charAt(i))
-                {
+        test:
+        {
+            for (int i = 0; i < str.length(); i++) {
+                switch (str.charAt(i)) {
                     case '\n':
                     case '\r':
                     case '\"':
@@ -872,11 +828,9 @@
             return str;
         }
         StringBuilder sb = new StringBuilder();
-        for (int i = 0; i < str.length(); i++)
-        {
+        for (int i = 0; i < str.length(); i++) {
             char ch = str.charAt(i);
-            switch (ch)
-            {
+            switch (ch) {
                 default:
                     sb.append(ch);
                     break;
@@ -897,14 +851,12 @@
         return sb.toString();
     }
 
-    void printStringEnumeration(SchemaType sType) throws IOException
-    {
+    void printStringEnumeration(SchemaType sType) throws IOException {
         SchemaType baseEnumType = sType.getBaseEnumType();
         String baseEnumClass = baseEnumType.getFullJavaName();
         boolean hasBase = hasBase(sType);
 
-        if (!hasBase)
-        {
+        if (!hasBase) {
             emit("");
             emit("org.apache.xmlbeans.StringEnumAbstractBase enumValue();");
             emit("void set(org.apache.xmlbeans.StringEnumAbstractBase e);");
@@ -914,35 +866,34 @@
         SchemaStringEnumEntry[] entries = sType.getStringEnumEntries();
         HashSet seenValues = new HashSet();
         HashSet repeatValues = new HashSet();
-        for (int i = 0; i < entries.length; i++)
-        {
+        for (int i = 0; i < entries.length; i++) {
             String enumValue = entries[i].getString();
-            if (seenValues.contains(enumValue))
-            {
+            if (seenValues.contains(enumValue)) {
                 repeatValues.add(enumValue);
                 continue;
-            }
-            else
+            } else {
                 seenValues.add(enumValue);
+            }
             String constName = entries[i].getEnumName();
-            if (hasBase)
+            if (hasBase) {
                 emit("static final " + baseEnumClass + ".Enum " + constName + " = " + baseEnumClass + "." + constName + ";");
-            else
+            } else {
                 emit("static final Enum " + constName + " = Enum.forString(\"" + javaStringEscape(enumValue) + "\");");
+            }
         }
         emit("");
-        for (int i = 0; i < entries.length; i++)
-        {
-            if (repeatValues.contains(entries[i].getString()))
+        for (int i = 0; i < entries.length; i++) {
+            if (repeatValues.contains(entries[i].getString())) {
                 continue;
+            }
             String constName = "INT_" + entries[i].getEnumName();
-            if (hasBase)
+            if (hasBase) {
                 emit("static final int " + constName + " = " + baseEnumClass + "." + constName + ";");
-            else
+            } else {
                 emit("static final int " + constName + " = Enum." + constName + ";");
+            }
         }
-        if (!hasBase)
-        {
+        if (!hasBase) {
             emit("");
             emit("/**");
             emit(" * Enumeration value class for " + baseEnumClass + ".");
@@ -950,8 +901,9 @@
             emit(" * <pre>");
             emit(" * enum.toString(); // returns the string value of the enum");
             emit(" * enum.intValue(); // returns an int value, useful for switches");
-            if (entries.length > 0)
-            emit(" * // e.g., case Enum.INT_" + entries[0].getEnumName());
+            if (entries.length > 0) {
+                emit(" * // e.g., case Enum.INT_" + entries[0].getEnumName());
+            }
             emit(" * Enum.forString(s); // returns the enum value for a string");
             emit(" * Enum.forInt(i); // returns the enum value for an int");
             emit(" * </pre>");
@@ -977,8 +929,7 @@
             emit("private Enum(java.lang.String s, int i)");
             emit("    { super(s, i); }");
             emit("");
-            for (int i = 0; i < entries.length; i++)
-            {
+            for (int i = 0; i < entries.length; i++) {
                 String constName = "INT_" + entries[i].getEnumName();
                 int intValue = entries[i].getIntValue();
                 emit("static final int " + constName + " = " + intValue + ";");
@@ -991,8 +942,7 @@
             emit("new Enum[]");
             emit("{");
             indent();
-            for (int i = 0; i < entries.length; i++)
-            {
+            for (int i = 0; i < entries.length; i++) {
                 String enumValue = entries[i].getString();
                 String constName = "INT_" + entries[i].getEnumName();
                 emit("new Enum(\"" + javaStringEscape(enumValue) + "\", " + constName + "),");
@@ -1008,45 +958,41 @@
         }
     }
 
-    private boolean hasBase(SchemaType sType)
-    {
+    private boolean hasBase(SchemaType sType) {
         boolean hasBase;
-       	SchemaType baseEnumType = sType.getBaseEnumType();
-        if (baseEnumType.isAnonymousType() && baseEnumType.isSkippedAnonymousType())
-        {
-            if (sType.getContentBasedOnType() != null)
+        SchemaType baseEnumType = sType.getBaseEnumType();
+        if (baseEnumType.isAnonymousType() && baseEnumType.isSkippedAnonymousType()) {
+            if (sType.getContentBasedOnType() != null) {
                 hasBase = sType.getContentBasedOnType().getBaseType() != baseEnumType;
-            else
+            } else {
                 hasBase = sType.getBaseType() != baseEnumType;
-        }
-        else
+            }
+        } else {
             hasBase = baseEnumType != sType;
-	return hasBase;
+        }
+        return hasBase;
     }
 
-    String xmlTypeForProperty(SchemaProperty sProp)
-    {
+    String xmlTypeForProperty(SchemaProperty sProp) {
         SchemaType sType = sProp.javaBasedOnType();
         return findJavaType(sType).replace('$', '.');
     }
 
-    static boolean xmlTypeForPropertyIsUnion(SchemaProperty sProp)
-    {
+    static boolean xmlTypeForPropertyIsUnion(SchemaProperty sProp) {
         SchemaType sType = sProp.javaBasedOnType();
         return (sType.isSimpleType() && sType.getSimpleVariety() == SchemaType.UNION);
     }
 
-    static boolean isJavaPrimitive(int javaType)
-    {
+    static boolean isJavaPrimitive(int javaType) {
         return (javaType < SchemaProperty.JAVA_FIRST_PRIMITIVE ? false :
             (javaType > SchemaProperty.JAVA_LAST_PRIMITIVE ? false : true));
     }
 
-    /** Returns the wrapped type for a java primitive. */
-    static String javaWrappedType(int javaType)
-    {
-        switch (javaType)
-        {
+    /**
+     * Returns the wrapped type for a java primitive.
+     */
+    static String javaWrappedType(int javaType) {
+        switch (javaType) {
             case SchemaProperty.JAVA_BOOLEAN:
                 return "java.lang.Boolean";
             case SchemaProperty.JAVA_FLOAT:
@@ -1069,22 +1015,18 @@
         }
     }
 
-    String javaTypeForProperty(SchemaProperty sProp)
-    {
+    String javaTypeForProperty(SchemaProperty sProp) {
         // The type to use is the XML object....
-        if (sProp.getJavaTypeCode() == SchemaProperty.XML_OBJECT)
-        {
+        if (sProp.getJavaTypeCode() == SchemaProperty.XML_OBJECT) {
             SchemaType sType = sProp.javaBasedOnType();
             return findJavaType(sType).replace('$', '.');
         }
 
-        if (sProp.getJavaTypeCode() == SchemaProperty.JAVA_USER)
-        {
-               return ((SchemaTypeImpl)sProp.getType()).getUserTypeName();
+        if (sProp.getJavaTypeCode() == SchemaProperty.JAVA_USER) {
+            return ((SchemaTypeImpl) sProp.getType()).getUserTypeName();
         }
 
-        switch (sProp.getJavaTypeCode())
-        {
+        switch (sProp.getJavaTypeCode()) {
             case SchemaProperty.JAVA_BOOLEAN:
                 return "boolean";
             case SchemaProperty.JAVA_FLOAT:
@@ -1123,66 +1065,62 @@
 
             case SchemaProperty.JAVA_ENUM:
                 SchemaType sType = sProp.javaBasedOnType();
-                if (sType.getSimpleVariety() == SchemaType.UNION)
+                if (sType.getSimpleVariety() == SchemaType.UNION) {
                     sType = sType.getUnionCommonBaseType();
+                }
                 assert sType.getBaseEnumType() != null;
-                if (hasBase(sType))
+                if (hasBase(sType)) {
                     return findJavaType(sType.getBaseEnumType()).replace('$', '.') + ".Enum";
-                else
+                } else {
                     return findJavaType(sType).replace('$', '.') + ".Enum";
+                }
 
             case SchemaProperty.JAVA_OBJECT:
                 return "java.lang.Object";
 
             default:
-                assert(false);
+                assert (false);
                 throw new IllegalStateException();
         }
     }
 
     void printPropertyGetters(QName qName, boolean isAttr,
-                       String propertyName, int javaType,
-                       String type, String xtype,
-                       boolean nillable, boolean optional,
-                       boolean several, boolean singleton)
-       throws IOException
-    {
+                              String propertyName, int javaType,
+                              String type, String xtype,
+                              boolean nillable, boolean optional,
+                              boolean several, boolean singleton)
+        throws IOException {
         String propdesc = "\"" + qName.getLocalPart() + "\"" + (isAttr ? " attribute" : " element");
         boolean xmltype = (javaType == SchemaProperty.XML_OBJECT);
 
-        if (singleton)
-        {
+        if (singleton) {
             printJavaDoc((several ? "Gets first " : "Gets the ") + propdesc);
             emit(type + " get" + propertyName + "();");
 
-            if (!xmltype)
-            {
+            if (!xmltype) {
                 printJavaDoc((several ? "Gets (as xml) first " : "Gets (as xml) the ") + propdesc);
                 emit(xtype + " xget" + propertyName + "();");
             }
 
-            if (nillable)
-            {
+            if (nillable) {
                 printJavaDoc((several ? "Tests for nil first " : "Tests for nil ") + propdesc);
                 emit("boolean isNil" + propertyName + "();");
             }
         }
 
-        if (optional)
-        {
+        if (optional) {
             printJavaDoc((several ? "True if has at least one " : "True if has ") + propdesc);
             emit("boolean isSet" + propertyName + "();");
         }
 
-        if (several)
-        {
+        if (several) {
             String arrayName = propertyName + "Array";
 
-            if (_useJava15)
-            {
+            if (_useJava15) {
                 String wrappedType = type;
-                if (isJavaPrimitive(javaType))
+                if (isJavaPrimitive(javaType)) {
                     wrappedType = javaWrappedType(javaType);
+                }
 
                 printJavaDoc("Gets a List of " + propdesc + "s");
                 emit("java.util.List<" + wrappedType + "> get" + propertyName + "List();");
@@ -1194,10 +1132,8 @@
             printJavaDoc("Gets ith " + propdesc);
             emit(type + " get" + arrayName + "(int i);");
 
-            if (!xmltype)
-            {
-                if (_useJava15)
-                {
+            if (!xmltype) {
+                if (_useJava15) {
                     printJavaDoc("Gets (as xml) a List of " + propdesc + "s");
                     emit("java.util.List<" + xtype + "> xget" + propertyName + "List();");
                 }
@@ -1209,8 +1145,7 @@
                 emit(xtype + " xget" + arrayName + "(int i);");
             }
 
-            if (nillable)
-            {
+            if (nillable) {
                 printJavaDoc("Tests for nil ith " + propdesc);
                 emit("boolean isNil" + arrayName + "(int i);");
             }
@@ -1221,50 +1156,44 @@
     }
 
     void printPropertySetters(QName qName, boolean isAttr,
-                       String propertyName, int javaType, String type, String xtype,
-                       boolean nillable, boolean optional,
-                       boolean several, boolean singleton)
-       throws IOException
-    {
+                              String propertyName, int javaType, String type, String xtype,
+                              boolean nillable, boolean optional,
+                              boolean several, boolean singleton)
+        throws IOException {
         String safeVarName = NameUtil.nonJavaKeyword(NameUtil.lowerCamelCase(propertyName));
-        if (safeVarName.equals("i"))
+        if (safeVarName.equals("i")) {
             safeVarName = "iValue";
+        }
         boolean xmltype = (javaType == SchemaProperty.XML_OBJECT);
 
         String propdesc = "\"" + qName.getLocalPart() + "\"" + (isAttr ? " attribute" : " element");
 
-        if (singleton)
-        {
+        if (singleton) {
             printJavaDoc((several ? "Sets first " : "Sets the ") + propdesc);
             emit("void set" + propertyName + "(" + type + " " + safeVarName + ");");
 
-            if (!xmltype)
-            {
+            if (!xmltype) {
                 printJavaDoc((several ? "Sets (as xml) first " : "Sets (as xml) the ") + propdesc);
                 emit("void xset" + propertyName + "(" + xtype + " " + safeVarName + ");");
             }
 
-            if (xmltype && !several)
-            {
+            if (xmltype && !several) {
                 printJavaDoc("Appends and returns a new empty " + propdesc);
                 emit(xtype + " addNew" + propertyName + "();");
             }
 
-            if (nillable)
-            {
+            if (nillable) {
                 printJavaDoc((several ? "Nils the first " : "Nils the ") + propdesc);
                 emit("void setNil" + propertyName + "();");
             }
         }
 
-        if (optional)
-        {
+        if (optional) {
             printJavaDoc((several ? "Removes first " : "Unsets the ") + propdesc);
             emit("void unset" + propertyName + "();");
         }
 
-        if (several)
-        {
+        if (several) {
             String arrayName = propertyName + "Array";
 
             printJavaDoc("Sets array of all " + propdesc);
@@ -1273,8 +1202,7 @@
             printJavaDoc("Sets ith " + propdesc);
             emit("void set" + arrayName + "(int i, " + type + " " + safeVarName + ");");
 
-            if (!xmltype)
-            {
+            if (!xmltype) {
                 printJavaDoc("Sets (as xml) array of all " + propdesc);
                 emit("void xset" + arrayName + "(" + xtype + "[] " + safeVarName + "Array);");
 
@@ -1282,14 +1210,12 @@
                 emit("void xset" + arrayName + "(int i, " + xtype + " " + safeVarName + ");");
             }
 
-            if (nillable)
-            {
+            if (nillable) {
                 printJavaDoc("Nils the ith " + propdesc);
                 emit("void setNil" + arrayName + "(int i);");
             }
 
-            if (!xmltype)
-            {
+            if (!xmltype) {
                 printJavaDoc("Inserts the value as the ith " + propdesc);
                 emit("void insert" + propertyName + "(int i, " + type + " " + safeVarName + ");");
 
@@ -1310,8 +1236,7 @@
 
     String getAtomicRestrictionType(SchemaType sType) {
         SchemaType pType = sType.getPrimitiveType();
-        switch (pType.getBuiltinTypeCode())
-        {
+        switch (pType.getBuiltinTypeCode()) {
             case SchemaType.BTC_ANY_SIMPLE:
                 return "org.apache.xmlbeans.impl.values.XmlAnySimpleTypeImpl";
             case SchemaType.BTC_BOOLEAN:
@@ -1331,10 +1256,9 @@
             case SchemaType.BTC_DOUBLE:
                 return "org.apache.xmlbeans.impl.values.JavaDoubleHolderEx";
             case SchemaType.BTC_DECIMAL:
-                switch (sType.getDecimalSize())
-                {
+                switch (sType.getDecimalSize()) {
                     default:
-                        assert(false);
+                        assert (false);
                     case SchemaType.SIZE_BIG_DECIMAL:
                         return "org.apache.xmlbeans.impl.values.JavaDecimalHolderEx";
                     case SchemaType.SIZE_BIG_INTEGER:
@@ -1347,10 +1271,11 @@
                         return "org.apache.xmlbeans.impl.values.JavaIntHolderEx";
                 }
             case SchemaType.BTC_STRING:
-                if (sType.hasStringEnumValues())
+                if (sType.hasStringEnumValues()) {
                     return "org.apache.xmlbeans.impl.values.JavaStringEnumerationHolderEx";
-                else
+                } else {
                     return "org.apache.xmlbeans.impl.values.JavaStringHolderEx";
+                }
 
             case SchemaType.BTC_DATE_TIME:
             case SchemaType.BTC_TIME:
@@ -1365,32 +1290,32 @@
             case SchemaType.BTC_DURATION:
                 return "org.apache.xmlbeans.impl.values.JavaGDurationHolderEx";
             default:
-                assert(false) : "unrecognized primitive type";
+                assert (false) : "unrecognized primitive type";
                 return null;
         }
     }
 
-    static SchemaType findBaseType(SchemaType sType)
-    {
-        while (sType.getFullJavaName() == null)
+    static SchemaType findBaseType(SchemaType sType) {
+        while (sType.getFullJavaName() == null) {
             sType = sType.getBaseType();
+        }
         return sType;
     }
 
     String getBaseClass(SchemaType sType) {
         SchemaType baseType = findBaseType(sType.getBaseType());
 
-        switch (sType.getSimpleVariety())
-        {
+        switch (sType.getSimpleVariety()) {
             case SchemaType.NOT_SIMPLE:
                 // non-simple-content: inherit from base type impl
-                if (!XmlObject.type.equals(baseType))
+                if (!XmlObject.type.equals(baseType)) {
                     return baseType.getFullJavaImplName();
+                }
                 return "org.apache.xmlbeans.impl.values.XmlComplexContentImpl";
 
             case SchemaType.ATOMIC:
                 // We should only get called for restrictions
-                assert(! sType.isBuiltinType());
+                assert (!sType.isBuiltinType());
                 return getAtomicRestrictionType(sType);
 
             case SchemaType.LIST:
@@ -1409,13 +1334,12 @@
         emit("public " + shortName + "(org.apache.xmlbeans.SchemaType sType)");
         startBlock();
         emit("super(sType" + (sType.getSimpleVariety() == SchemaType.NOT_SIMPLE ?
-                             "":
-                             ", " + !sType.isSimpleType()) +
+            "" :
+            ", " + !sType.isSimpleType()) +
              ");");
         endBlock();
 
-        if (sType.getSimpleVariety() != SchemaType.NOT_SIMPLE)
-        {
+        if (sType.getSimpleVariety() != SchemaType.NOT_SIMPLE) {
             emit("");
             emit("protected " + shortName + "(org.apache.xmlbeans.SchemaType sType, boolean b)");
             startBlock();
@@ -1424,8 +1348,7 @@
         }
     }
 
-    void startClass(SchemaType sType, boolean isInner) throws IOException
-    {
+    void startClass(SchemaType sType, boolean isInner) throws IOException {
         String shortName = sType.getShortJavaImplName();
         String baseClass = getBaseClass(sType);
         StringBuilder interfaces = new StringBuilder();
@@ -1433,47 +1356,51 @@
 
         if (sType.getSimpleVariety() == SchemaType.UNION) {
             SchemaType[] memberTypes = sType.getUnionMemberTypes();
-            for (int i = 0 ; i < memberTypes.length ; i++)
+            for (int i = 0; i < memberTypes.length; i++) {
                 interfaces.append(", " + memberTypes[i].getFullJavaName().replace('$', '.'));
+            }
         }
 
-        emit("public " + ( isInner ? "static ": "" ) + "class " + shortName +
-            " extends " + baseClass + " implements " + interfaces.toString());
+        emit("public " + (isInner ? "static " : "") + "class " + shortName +
+             " extends " + baseClass + " implements " + interfaces.toString());
 
         startBlock();
 
         emit("private static final long serialVersionUID = 1L;");
     }
 
-    void makeAttributeDefaultValue(String jtargetType, SchemaProperty prop, String identifier) throws IOException
-    {
+    void makeAttributeDefaultValue(String jtargetType, SchemaProperty prop, String identifier) throws IOException {
         String fullName = jtargetType;
-        if (fullName == null)
+        if (fullName == null) {
             fullName = prop.javaBasedOnType().getFullJavaName().replace('$', '.');
+        }
 
         emit("target = (" + fullName + ")get_default_attribute_value(" + identifier + ");");
     }
 
-    void makeMissingValue(int javaType) throws IOException
-    {
-        switch (javaType)
-        {
+    void makeMissingValue(int javaType) throws IOException {
+        switch (javaType) {
             case SchemaProperty.JAVA_BOOLEAN:
-                emit("return false;"); break;
+                emit("return false;");
+                break;
 
             case SchemaProperty.JAVA_FLOAT:
-                emit("return 0.0f;"); break;
+                emit("return 0.0f;");
+                break;
 
             case SchemaProperty.JAVA_DOUBLE:
-                emit("return 0.0;"); break;
+                emit("return 0.0;");
+                break;
 
             case SchemaProperty.JAVA_BYTE:
             case SchemaProperty.JAVA_SHORT:
             case SchemaProperty.JAVA_INT:
-                emit("return 0;"); break;
+                emit("return 0;");
+                break;
 
             case SchemaProperty.JAVA_LONG:
-                emit("return 0L;"); break;
+                emit("return 0L;");
+                break;
 
             default:
             case SchemaProperty.XML_OBJECT:
@@ -1489,13 +1416,13 @@
             case SchemaProperty.JAVA_CALENDAR:
             case SchemaProperty.JAVA_ENUM:
             case SchemaProperty.JAVA_OBJECT:
-                emit("return null;"); break;
+                emit("return null;");
+                break;
         }
     }
 
     void printJGetArrayValue(int javaType, String type, SchemaTypeImpl stype) throws IOException {
-        switch (javaType)
-        {
+        switch (javaType) {
             case SchemaProperty.XML_OBJECT:
                 emit(type + "[] result = new " + type + "[targetList.size()];");
                 emit("targetList.toArray(result);");
@@ -1619,7 +1546,7 @@
                 emit(stype.getUserTypeName() + "[] result = new " + stype.getUserTypeName() + "[targetList.size()];");
                 emit("for (int i = 0, len = targetList.size() ; i < len ; i++)");
                 emit("    result[i] = " + getUserTypeStaticHandlerMethod(false, stype)
-                        + "((org.apache.xmlbeans.SimpleValue)targetList.get(i));");
+                     + "((org.apache.xmlbeans.SimpleValue)targetList.get(i));");
                 break;
 
             default:
@@ -1627,144 +1554,184 @@
         }
         emit("return result;");
     }
+
     void printJGetValue(int javaType, String type, SchemaTypeImpl stype) throws IOException {
-        switch (javaType)
-        {
-        case SchemaProperty.XML_OBJECT:
-            emit("return target;"); break;
-
-        case SchemaProperty.JAVA_BOOLEAN:
-            emit("return target.getBooleanValue();"); break;
-
-        case SchemaProperty.JAVA_FLOAT:
-            emit("return target.getFloatValue();"); break;
-
-        case SchemaProperty.JAVA_DOUBLE:
-            emit("return target.getDoubleValue();"); break;
-
-        case SchemaProperty.JAVA_BYTE:
-            emit("return target.getByteValue();"); break;
-
-        case SchemaProperty.JAVA_SHORT:
-            emit("return target.getShortValue();"); break;
-
-        case SchemaProperty.JAVA_INT:
-            emit("return target.getIntValue();"); break;
-
-        case SchemaProperty.JAVA_LONG:
-            emit("return target.getLongValue();"); break;
-
-        case SchemaProperty.JAVA_BIG_DECIMAL:
-            emit("return target.getBigDecimalValue();"); break;
-
-        case SchemaProperty.JAVA_BIG_INTEGER:
-            emit("return target.getBigIntegerValue();"); break;
-
-        case SchemaProperty.JAVA_STRING:
-            emit("return target.getStringValue();"); break;
-
-        case SchemaProperty.JAVA_BYTE_ARRAY:
-            emit("return target.getByteArrayValue();"); break;
-
-        case SchemaProperty.JAVA_GDATE:
-            emit("return target.getGDateValue();"); break;
-
-        case SchemaProperty.JAVA_GDURATION:
-            emit("return target.getGDurationValue();"); break;
-
-        case SchemaProperty.JAVA_CALENDAR:
-            emit("return target.getCalendarValue();"); break;
-
-        case SchemaProperty.JAVA_DATE:
-            emit("return target.getDateValue();"); break;
-
-        case SchemaProperty.JAVA_QNAME:
-            emit("return target.getQNameValue();"); break;
-
-        case SchemaProperty.JAVA_LIST:
-            emit("return target.getListValue();"); break;
-
-        case SchemaProperty.JAVA_ENUM:
-            emit("return (" + type + ")target.getEnumValue();"); break;
-
-        case SchemaProperty.JAVA_OBJECT:
-            emit("return target.getObjectValue();"); break;
-
-        case SchemaProperty.JAVA_USER:
-            emit("return " + getUserTypeStaticHandlerMethod(false, stype)
-                    + "(target);");
-            break;
-
-        default:
-            throw new IllegalStateException();
-        }
-    }
-    void printJSetValue(int javaType, String safeVarName, SchemaTypeImpl stype) throws IOException {
-        switch (javaType)
-        {
+        switch (javaType) {
             case SchemaProperty.XML_OBJECT:
-                emit("target.set(" + safeVarName + ");"); break;
+                emit("return target;");
+                break;
 
             case SchemaProperty.JAVA_BOOLEAN:
-                emit("target.setBooleanValue(" + safeVarName + ");"); break;
+                emit("return target.getBooleanValue();");
+                break;
 
             case SchemaProperty.JAVA_FLOAT:
-                emit("target.setFloatValue(" + safeVarName + ");"); break;
+                emit("return target.getFloatValue();");
+                break;
 
             case SchemaProperty.JAVA_DOUBLE:
-                emit("target.setDoubleValue(" + safeVarName + ");"); break;
+                emit("return target.getDoubleValue();");
+                break;
 
             case SchemaProperty.JAVA_BYTE:
-                emit("target.setByteValue(" + safeVarName + ");"); break;
+                emit("return target.getByteValue();");
+                break;
 
             case SchemaProperty.JAVA_SHORT:
-                emit("target.setShortValue(" + safeVarName + ");"); break;
+                emit("return target.getShortValue();");
+                break;
 
             case SchemaProperty.JAVA_INT:
-                emit("target.setIntValue(" + safeVarName + ");"); break;
+                emit("return target.getIntValue();");
+                break;
 
             case SchemaProperty.JAVA_LONG:
-                emit("target.setLongValue(" + safeVarName + ");"); break;
+                emit("return target.getLongValue();");
+                break;
 
             case SchemaProperty.JAVA_BIG_DECIMAL:
-                emit("target.setBigDecimalValue(" + safeVarName + ");"); break;
+                emit("return target.getBigDecimalValue();");
+                break;
 
             case SchemaProperty.JAVA_BIG_INTEGER:
-                emit("target.setBigIntegerValue(" + safeVarName + ");"); break;
+                emit("return target.getBigIntegerValue();");
+                break;
 
             case SchemaProperty.JAVA_STRING:
-                emit("target.setStringValue(" + safeVarName + ");"); break;
+                emit("return target.getStringValue();");
+                break;
 
             case SchemaProperty.JAVA_BYTE_ARRAY:
-                emit("target.setByteArrayValue(" + safeVarName + ");"); break;
+                emit("return target.getByteArrayValue();");
+                break;
 
             case SchemaProperty.JAVA_GDATE:
-                emit("target.setGDateValue(" + safeVarName + ");"); break;
+                emit("return target.getGDateValue();");
+                break;
 
             case SchemaProperty.JAVA_GDURATION:
-                emit("target.setGDurationValue(" + safeVarName + ");"); break;
+                emit("return target.getGDurationValue();");
+                break;
 
             case SchemaProperty.JAVA_CALENDAR:
-                emit("target.setCalendarValue(" + safeVarName + ");"); break;
+                emit("return target.getCalendarValue();");
+                break;
 
             case SchemaProperty.JAVA_DATE:
-                emit("target.setDateValue(" + safeVarName + ");"); break;
+                emit("return target.getDateValue();");
+                break;
 
             case SchemaProperty.JAVA_QNAME:
-                emit("target.setQNameValue(" + safeVarName + ");"); break;
+                emit("return target.getQNameValue();");
+                break;
 
             case SchemaProperty.JAVA_LIST:
-                emit("target.setListValue(" + safeVarName + ");"); break;
+                emit("return target.getListValue();");
+                break;
 
             case SchemaProperty.JAVA_ENUM:
-                emit("target.setEnumValue(" + safeVarName + ");"); break;
+                emit("return (" + type + ")target.getEnumValue();");
+                break;
 
             case SchemaProperty.JAVA_OBJECT:
-                emit("target.setObjectValue(" + safeVarName + ");"); break;
+                emit("return target.getObjectValue();");
+                break;
+
+            case SchemaProperty.JAVA_USER:
+                emit("return " + getUserTypeStaticHandlerMethod(false, stype)
+                     + "(target);");
+                break;
+
+            default:
+                throw new IllegalStateException();
+        }
+    }
+
+    void printJSetValue(int javaType, String safeVarName, SchemaTypeImpl stype) throws IOException {
+        switch (javaType) {
+            case SchemaProperty.XML_OBJECT:
+                emit("target.set(" + safeVarName + ");");
+                break;
+
+            case SchemaProperty.JAVA_BOOLEAN:
+                emit("target.setBooleanValue(" + safeVarName + ");");
+                break;
+
+            case SchemaProperty.JAVA_FLOAT:
+                emit("target.setFloatValue(" + safeVarName + ");");
+                break;
+
+            case SchemaProperty.JAVA_DOUBLE:
+                emit("target.setDoubleValue(" + safeVarName + ");");
+                break;
+
+            case SchemaProperty.JAVA_BYTE:
+                emit("target.setByteValue(" + safeVarName + ");");
+                break;
+
+            case SchemaProperty.JAVA_SHORT:
+                emit("target.setShortValue(" + safeVarName + ");");
+                break;
+
+            case SchemaProperty.JAVA_INT:
+                emit("target.setIntValue(" + safeVarName + ");");
+                break;
+
+            case SchemaProperty.JAVA_LONG:
+                emit("target.setLongValue(" + safeVarName + ");");
+                break;
+
+            case SchemaProperty.JAVA_BIG_DECIMAL:
+                emit("target.setBigDecimalValue(" + safeVarName + ");");
+                break;
+
+            case SchemaProperty.JAVA_BIG_INTEGER:
+                emit("target.setBigIntegerValue(" + safeVarName + ");");
+                break;
+
+            case SchemaProperty.JAVA_STRING:
+                emit("target.setStringValue(" + safeVarName + ");");
+                break;
+
+            case SchemaProperty.JAVA_BYTE_ARRAY:
+                emit("target.setByteArrayValue(" + safeVarName + ");");
+                break;
+
+            case SchemaProperty.JAVA_GDATE:
+                emit("target.setGDateValue(" + safeVarName + ");");
+                break;
+
+            case SchemaProperty.JAVA_GDURATION:
+                emit("target.setGDurationValue(" + safeVarName + ");");
+                break;
+
+            case SchemaProperty.JAVA_CALENDAR:
+                emit("target.setCalendarValue(" + safeVarName + ");");
+                break;
+
+            case SchemaProperty.JAVA_DATE:
+                emit("target.setDateValue(" + safeVarName + ");");
+                break;
+
+            case SchemaProperty.JAVA_QNAME:
+                emit("target.setQNameValue(" + safeVarName + ");");
+                break;
+
+            case SchemaProperty.JAVA_LIST:
+                emit("target.setListValue(" + safeVarName + ");");
+                break;
+
+            case SchemaProperty.JAVA_ENUM:
+                emit("target.setEnumValue(" + safeVarName + ");");
+                break;
+
+            case SchemaProperty.JAVA_OBJECT:
+                emit("target.setObjectValue(" + safeVarName + ");");
+                break;
 
             case SchemaProperty.JAVA_USER:
                 emit(getUserTypeStaticHandlerMethod(true, stype)
-                        + "(" + safeVarName + ", target);");
+                     + "(" + safeVarName + ", target);");
                 break;
 
             default:
@@ -1773,11 +1740,11 @@
     }
 
     String getIdentifier(Map qNameMap, QName qName) {
-        return ((String[])qNameMap.get(qName))[0];
+        return ((String[]) qNameMap.get(qName))[0];
     }
 
     String getSetIdentifier(Map qNameMap, QName qName) {
-        String[] identifiers = (String[])qNameMap.get(qName);
+        String[] identifiers = (String[]) qNameMap.get(qName);
         return identifiers[1] == null ? identifiers[0] : identifiers[1];
     }
 
@@ -1785,38 +1752,34 @@
         final Map results = new HashMap();
 
         emit("");
-        for (int i = 0; i < properties.length; i++)
-        {
+        for (int i = 0; i < properties.length; i++) {
             final String[] identifiers = new String[2];
             final SchemaProperty prop = properties[i];
             final QName name = prop.getName();
             results.put(name, identifiers);
             final String javaName = prop.getJavaPropertyName();
             identifiers[0] = (javaName + "$" + (i * 2)).toUpperCase();
-            final String uriString =  "\"" + name.getNamespaceURI() + "\"";
+            final String uriString = "\"" + name.getNamespaceURI() + "\"";
 
             emit("private static final javax.xml.namespace.QName " + identifiers[0] +
-                 " = " );
+                 " = ");
             indent();
             emit("new javax.xml.namespace.QName(" +
                  uriString + ", \"" + name.getLocalPart() + "\");");
             outdent();
 
-            if (properties[i].acceptedNames() != null)
-            {
+            if (properties[i].acceptedNames() != null) {
                 final QName[] qnames = properties[i].acceptedNames();
 
-                if (qnames.length > 1)
-                {
-                    identifiers[1] = (javaName + "$" + (i*2+1)).toUpperCase();
+                if (qnames.length > 1) {
+                    identifiers[1] = (javaName + "$" + (i * 2 + 1)).toUpperCase();
 
                     emit("private static final org.apache.xmlbeans.QNameSet " + identifiers[1] +
-                        " = org.apache.xmlbeans.QNameSet.forArray( new javax.xml.namespace.QName[] { " );
+                         " = org.apache.xmlbeans.QNameSet.forArray( new javax.xml.namespace.QName[] { ");
                     indent();
-                    for (int j = 0 ; j < qnames.length ; j++)
-                    {
+                    for (int j = 0; j < qnames.length; j++) {
                         emit("new javax.xml.namespace.QName(\"" + qnames[j].getNamespaceURI() +
-                            "\", \"" + qnames[j].getLocalPart() + "\"),");
+                             "\", \"" + qnames[j].getLocalPart() + "\"),");
                     }
 
                     outdent();
@@ -1829,86 +1792,77 @@
         return results;
     }
 
-    void emitImplementationPreamble() throws IOException
-    {
+    void emitImplementationPreamble() throws IOException {
         emit("synchronized (monitor())");
         emit("{");
         indent();
         emit("check_orphaned();");
     }
 
-    void emitImplementationPostamble() throws IOException
-    {
+    void emitImplementationPostamble() throws IOException {
         outdent();
         emit("}");
     }
 
     void emitDeclareTarget(boolean declareTarget, String xtype)
-        throws IOException
-    {
-         if (declareTarget)
-             emit(xtype + " target = null;");
-  	}
-
-    void emitAddTarget(String identifier, boolean isAttr, boolean declareTarget, String xtype)
-        throws IOException
-    {
-        if (isAttr)
-            emit("target = (" + xtype + ")get_store().add_attribute_user(" + identifier + ");");
-        else
-            emit("target = (" + xtype + ")get_store().add_element_user(" + identifier + ");");
+        throws IOException {
+        if (declareTarget) {
+            emit(xtype + " target = null;");
+        }
     }
 
-    void emitPre(SchemaType sType, int opType, String identifier, boolean isAttr) throws IOException
-    {
+    void emitAddTarget(String identifier, boolean isAttr, boolean declareTarget, String xtype)
+        throws IOException {
+        if (isAttr) {
+            emit("target = (" + xtype + ")get_store().add_attribute_user(" + identifier + ");");
+        } else {
+            emit("target = (" + xtype + ")get_store().add_element_user(" + identifier + ");");
+        }
+    }
+
+    void emitPre(SchemaType sType, int opType, String identifier, boolean isAttr) throws IOException {
         emitPre(sType, opType, identifier, isAttr, "-1");
     }
 
-    void emitPre(SchemaType sType, int opType, String identifier, boolean isAttr, String index) throws IOException
-    {
+    void emitPre(SchemaType sType, int opType, String identifier, boolean isAttr, String index) throws IOException {
         SchemaTypeImpl sImpl = getImpl(sType);
-        if (sImpl == null)
+        if (sImpl == null) {
             return;
+        }
 
         PrePostExtension ext = sImpl.getPrePostExtension();
-        if (ext != null)
-        {
-            if (ext.hasPreCall())
-            {
+        if (ext != null) {
+            if (ext.hasPreCall()) {
                 emit("if ( " + ext.getStaticHandler() + ".preSet(" + prePostOpString(opType) + ", this, " + identifier + ", " + isAttr + ", " + index + "))");
                 startBlock();
             }
         }
     }
 
-    void emitPost(SchemaType sType, int opType, String identifier, boolean isAttr) throws IOException
-    {
+    void emitPost(SchemaType sType, int opType, String identifier, boolean isAttr) throws IOException {
         emitPost(sType, opType, identifier, isAttr, "-1");
     }
 
-    void emitPost(SchemaType sType, int opType, String identifier, boolean isAttr, String index) throws IOException
-    {
+    void emitPost(SchemaType sType, int opType, String identifier, boolean isAttr, String index) throws IOException {
         SchemaTypeImpl sImpl = getImpl(sType);
-        if (sImpl == null)
+        if (sImpl == null) {
             return;
+        }
 
         PrePostExtension ext = sImpl.getPrePostExtension();
-        if (ext != null)
-        {
-            if (ext.hasPreCall())
-            {
+        if (ext != null) {
+            if (ext.hasPreCall()) {
                 endBlock();
             }
 
-            if (ext.hasPostCall())
+            if (ext.hasPostCall()) {
                 emit(ext.getStaticHandler() + ".postSet(" + prePostOpString(opType) + ", this, " + identifier + ", " + isAttr + ", " + index + ");");
+            }
         }
     }
 
-    String prePostOpString(int opType)
-    {
-        switch (opType)
-        {
+    String prePostOpString(int opType) {
+        switch (opType) {
             default:
                 assert false;
 
@@ -1933,26 +1887,26 @@
                        String index,
                        int nullBehaviour,
                        String xtype)
-        throws IOException
-    {
+        throws IOException {
         assert setIdentifier != null && identifier != null;
 
         emit(xtype + " target = null;");
 
-        if (isAttr)
+        if (isAttr) {
             emit("target = (" + xtype + ")get_store().find_attribute_user(" + identifier + ");");
-        else
+        } else {
             emit("target = (" + xtype + ")get_store().find_element_user(" + setIdentifier + ", " + index + ");");
+        }
 
-        if (nullBehaviour == NOTHING)
+        if (nullBehaviour == NOTHING) {
             return;
+        }
 
         emit("if (target == null)");
 
         startBlock();
 
-        switch (nullBehaviour)
-        {
+        switch (nullBehaviour) {
             case ADD_NEW_VALUE:
                 // target already emited, no need for emitDeclareTarget(false, xtype);
                 emitAddTarget(identifier, isAttr, false, xtype);
@@ -1973,11 +1927,10 @@
     }
 
     void printListGetter15Impl(String parentJavaName,
-        String propdesc, String propertyName,
-        String wrappedType, String xtype,
-        boolean xmltype, boolean xget)
-            throws IOException
-    {
+                               String propdesc, String propertyName,
+                               String wrappedType, String xtype,
+                               boolean xmltype, boolean xget)
+        throws IOException {
         String arrayName = propertyName + "Array";
         String listName = propertyName + "List";
         String parentThis = parentJavaName + ".this.";
@@ -1987,22 +1940,24 @@
 
         printJavaDoc("Gets " + (xget ? "(as xml) " : "") + "a List of " + propdesc + "s");
 
-        emit("public java.util.List<" + wrappedType + "> " + xgetMethod + listName  + "()");
+        emit("public java.util.List<" + wrappedType + "> " + xgetMethod + listName + "()");
         startBlock();
 
         emit("final class " + listName + " extends java.util.AbstractList<" + wrappedType + ">");
         startBlock();
 
         // Object get(i)
-        if (_useJava15)
+        if (_useJava15) {
             emit("@Override");
+        }
         emit("public " + wrappedType + " get(int i)");
         emit("    { return " + parentThis + xgetMethod + arrayName + "(i); }");
         emit("");
 
         // Object set(i, o)
-        if (_useJava15)
+        if (_useJava15) {
             emit("@Override");
+        }
         emit("public " + wrappedType + " set(int i, " + wrappedType + " o)");
         startBlock();
         emit(wrappedType + " old = " + parentThis + xgetMethod + arrayName + "(i);");
@@ -2012,19 +1967,22 @@
         emit("");
 
         // void add(i, o)
-        if (_useJava15)
+        if (_useJava15) {
             emit("@Override");
-        emit("public void add(int i, " + wrappedType +" o)");
-        if (xmltype || xget)
+        }
+        emit("public void add(int i, " + wrappedType + " o)");
+        if (xmltype || xget) {
             emit("    { " + parentThis + "insertNew" + propertyName + "(i).set(o); }");
-        else
+        } else {
             emit("    { " + parentThis + "insert" + propertyName + "(i, o); }");
+        }
         emit("");
 
         // Object remove(i)
-        if (_useJava15)
+        if (_useJava15) {
             emit("@Override");
-        emit("public " + wrappedType +" remove(int i)");
+        }
+        emit("public " + wrappedType + " remove(int i)");
         startBlock();
         emit(wrappedType + " old = " + parentThis + xgetMethod + arrayName + "(i);");
         emit(parentThis + "remove" + propertyName + "(i);");
@@ -2033,8 +1991,9 @@
         emit("");
 
         // int size()
-        if (_useJava15)
+        if (_useJava15) {
             emit("@Override");
+        }
         emit("public int size()");
         emit("    { return " + parentThis + "sizeOf" + arrayName + "(); }");
         emit("");
@@ -2052,19 +2011,17 @@
     }
 
     void printGetterImpls(String parentJavaName,
-        SchemaProperty prop, QName qName, boolean isAttr, String propertyName,
-        int javaType, String type, String xtype, boolean nillable,
-        boolean optional, boolean several, boolean singleton,
-        boolean isunion,
-        String identifier, String setIdentifier )
-            throws IOException
-    {
+                          SchemaProperty prop, QName qName, boolean isAttr, String propertyName,
+                          int javaType, String type, String xtype, boolean nillable,
+                          boolean optional, boolean several, boolean singleton,
+                          boolean isunion,
+                          String identifier, String setIdentifier)
+        throws IOException {
         String propdesc = "\"" + qName.getLocalPart() + "\"" + (isAttr ? " attribute" : " element");
         boolean xmltype = (javaType == SchemaProperty.XML_OBJECT);
         String jtargetType = (isunion || !xmltype) ? "org.apache.xmlbeans.SimpleValue" : xtype;
 
-        if (singleton)
-        {
+        if (singleton) {
             // Value getProp()
             printJavaDoc((several ? "Gets first " : "Gets the ") + propdesc);
             emit("public " + type + " get" + propertyName + "()");
@@ -2074,8 +2031,7 @@
             emitGetTarget(setIdentifier, identifier, isAttr, "0", NOTHING, jtargetType);
 
             if (isAttr && (prop.hasDefault() == SchemaProperty.CONSISTENTLY ||
-                    prop.hasFixed() == SchemaProperty.CONSISTENTLY))
-            {
+                           prop.hasFixed() == SchemaProperty.CONSISTENTLY)) {
                 emit("if (target == null)");
                 startBlock();
                 makeAttributeDefaultValue(jtargetType, prop, identifier);
@@ -2087,15 +2043,14 @@
             endBlock();
 
 
-            printJGetValue(javaType, type, (SchemaTypeImpl)prop.getType());
+            printJGetValue(javaType, type, (SchemaTypeImpl) prop.getType());
 
 
             emitImplementationPostamble();
 
             endBlock();
 
-            if (!xmltype)
-            {
+            if (!xmltype) {
                 // Value xgetProp()
                 printJavaDoc((several ? "Gets (as xml) first " : "Gets (as xml) the ") + propdesc);
                 emit("public " + xtype + " xget" + propertyName + "()");
@@ -2104,8 +2059,7 @@
                 emitGetTarget(setIdentifier, identifier, isAttr, "0", NOTHING, xtype);
 
                 if (isAttr && (prop.hasDefault() == SchemaProperty.CONSISTENTLY ||
-                        prop.hasFixed() == SchemaProperty.CONSISTENTLY))
-                {
+                               prop.hasFixed() == SchemaProperty.CONSISTENTLY)) {
                     emit("if (target == null)");
                     startBlock();
                     makeAttributeDefaultValue(xtype, prop, identifier);
@@ -2117,8 +2071,7 @@
                 endBlock();
             }
 
-            if (nillable)
-            {
+            if (nillable) {
                 // boolean isNilProp()
                 printJavaDoc((several ? "Tests for nil first " : "Tests for nil ") + propdesc);
                 emit("public boolean isNil" + propertyName + "()");
@@ -2133,8 +2086,7 @@
             }
         }
 
-        if (optional)
-        {
+        if (optional) {
             // boolean isSetProp()
             printJavaDoc((several ? "True if has at least one " : "True if has ") + propdesc);
             emit("public boolean isSet" + propertyName + "()");
@@ -2142,26 +2094,26 @@
             startBlock();
             emitImplementationPreamble();
 
-            if (isAttr)
-                emit("return get_store().find_attribute_user(" + identifier +") != null;");
-            else
+            if (isAttr) {
+                emit("return get_store().find_attribute_user(" + identifier + ") != null;");
+            } else {
                 emit("return get_store().count_elements(" + setIdentifier + ") != 0;");
+            }
 
             emitImplementationPostamble();
             endBlock();
         }
 
-        if (several)
-        {
+        if (several) {
             String arrayName = propertyName + "Array";
 
-            if (_useJava15)
-            {
+            if (_useJava15) {
                 // use boxed type if the java type is a primitive and jdk1.5
                 // jdk1.5 will box/unbox for us
                 String wrappedType = type;
-                if (isJavaPrimitive(javaType))
+                if (isJavaPrimitive(javaType)) {
                     wrappedType = javaWrappedType(javaType);
+                }
 
                 printListGetter15Impl(parentJavaName, propdesc, propertyName, wrappedType, xtype, xmltype, false);
             }
@@ -2172,13 +2124,14 @@
             startBlock();
             emitImplementationPreamble();
 
-            if (_useJava15)
+            if (_useJava15) {
                 emit("java.util.List<" + xtype + "> targetList = new java.util.ArrayList<" + xtype + ">();");
-            else
+            } else {
                 emit("java.util.List targetList = new java.util.ArrayList();");
+            }
             emit("get_store().find_all_element_users(" + setIdentifier + ", targetList);");
 
-            printJGetArrayValue(javaType, type, (SchemaTypeImpl)prop.getType());
+            printJGetArrayValue(javaType, type, (SchemaTypeImpl) prop.getType());
 
             emitImplementationPostamble();
             endBlock();
@@ -2190,15 +2143,13 @@
             emitImplementationPreamble();
 
             emitGetTarget(setIdentifier, identifier, isAttr, "i", THROW_EXCEPTION, jtargetType);
-            printJGetValue(javaType, type, (SchemaTypeImpl)prop.getType());
+            printJGetValue(javaType, type, (SchemaTypeImpl) prop.getType());
 
             emitImplementationPostamble();
             endBlock();
 
-            if (!xmltype)
-            {
-                if (_useJava15)
-                {
+            if (!xmltype) {
+                if (_useJava15) {
                     printListGetter15Impl(parentJavaName, propdesc, propertyName, xtype, xtype, xmltype, true);
                 }
 
@@ -2207,10 +2158,11 @@
                 emit("public " + xtype + "[] xget" + arrayName + "()");
                 startBlock();
                 emitImplementationPreamble();
-                if (_useJava15)
-                    emit("java.util.List<" + xtype +  "> targetList = new java.util.ArrayList<" + xtype +  ">();");
-                else
+                if (_useJava15) {
+                    emit("java.util.List<" + xtype + "> targetList = new java.util.ArrayList<" + xtype + ">();");
+                } else {
                     emit("java.util.List targetList = new java.util.ArrayList();");
+                }
                 emit("get_store().find_all_element_users(" + setIdentifier + ", targetList);");
                 emit(xtype + "[] result = new " + xtype + "[targetList.size()];");
                 emit("targetList.toArray(result);");
@@ -2230,8 +2182,7 @@
 
             }
 
-            if (nillable)
-            {
+            if (nillable) {
                 // boolean isNil(int i);
                 printJavaDoc("Tests for nil ith " + propdesc);
                 emit("public boolean isNil" + arrayName + "(int i)");
@@ -2248,18 +2199,17 @@
             emit("public int sizeOf" + arrayName + "()");
             startBlock();
             emitImplementationPreamble();
-            emit("return get_store().count_elements(" + setIdentifier +");");
+            emit("return get_store().count_elements(" + setIdentifier + ");");
             emitImplementationPostamble();
             endBlock();
         }
     }
 
     void printSetterImpls(QName qName, SchemaProperty prop, boolean isAttr,
-        String propertyName, int javaType, String type, String xtype,
-        boolean nillable, boolean optional, boolean several, boolean singleton,
-        boolean isunion, String identifier, String setIdentifier, SchemaType sType)
-        throws IOException
-    {
+                          String propertyName, int javaType, String type, String xtype,
+                          boolean nillable, boolean optional, boolean several, boolean singleton,
+                          boolean isunion, String identifier, String setIdentifier, SchemaType sType)
+        throws IOException {
         String safeVarName = NameUtil.nonJavaKeyword(NameUtil.lowerCamelCase(propertyName));
         safeVarName = NameUtil.nonExtraKeyword(safeVarName);
 
@@ -2270,32 +2220,27 @@
 
         String propdesc = "\"" + qName.getLocalPart() + "\"" + (isAttr ? " attribute" : " element");
 
-        if (singleton)
-        {
+        if (singleton) {
             // void setProp(Value v);
             printJavaDoc((several ? "Sets first " : "Sets the ") + propdesc);
             emit("public void set" + propertyName + "(" + type + " " + safeVarName + ")");
             startBlock();
-            if ( xmltype && !isSubstGroup && !isAttr )
-            {
+            if (xmltype && !isSubstGroup && !isAttr) {
                 emitPre(sType, PrePostExtension.OPERATION_SET, identifier, isAttr, several ? "0" : "-1");
                 emit("generatedSetterHelperImpl(" + safeVarName + ", " + setIdentifier + ", 0, " +
-                        "org.apache.xmlbeans.impl.values.XmlObjectBase.KIND_SETTERHELPER_SINGLETON);");
+                     "org.apache.xmlbeans.impl.values.XmlObjectBase.KIND_SETTERHELPER_SINGLETON);");
                 emitPost(sType, PrePostExtension.OPERATION_SET, identifier, isAttr, several ? "0" : "-1");
-            }
-            else
-            {
+            } else {
                 emitImplementationPreamble();
                 emitPre(sType, PrePostExtension.OPERATION_SET, identifier, isAttr, several ? "0" : "-1");
                 emitGetTarget(setIdentifier, identifier, isAttr, "0", ADD_NEW_VALUE, jtargetType);
-                printJSetValue(javaType, safeVarName, (SchemaTypeImpl)prop.getType());
+                printJSetValue(javaType, safeVarName, (SchemaTypeImpl) prop.getType());
                 emitPost(sType, PrePostExtension.OPERATION_SET, identifier, isAttr, several ? "0" : "-1");
                 emitImplementationPostamble();
             }
             endBlock();
 
-            if (!xmltype)
-            {
+            if (!xmltype) {
                 // void xsetProp(Value v)
                 printJavaDoc((several ? "Sets (as xml) first " : "Sets (as xml) the ") + propdesc);
                 emit("public void xset" + propertyName + "(" + xtype + " " + safeVarName + ")");
@@ -2310,15 +2255,14 @@
 
             }
 
-            if (xmltype && !several)
-            {
+            if (xmltype && !several) {
                 // Value addNewProp()
                 printJavaDoc("Appends and returns a new empty " + propdesc);
                 emit("public " + xtype + " addNew" + propertyName + "()");
                 startBlock();
                 emitImplementationPreamble();
                 emitDeclareTarget(true, xtype);
-  	            emitPre(sType, PrePostExtension.OPERATION_INSERT, identifier, isAttr);
+                emitPre(sType, PrePostExtension.OPERATION_INSERT, identifier, isAttr);
                 emitAddTarget(identifier, isAttr, true, xtype);
                 emitPost(sType, PrePostExtension.OPERATION_INSERT, identifier, isAttr);
                 emit("return target;");
@@ -2326,8 +2270,7 @@
                 endBlock();
             }
 
-            if (nillable)
-            {
+            if (nillable) {
                 printJavaDoc((several ? "Nils the first " : "Nils the ") + propdesc);
                 emit("public void setNil" + propertyName + "()");
                 startBlock();
@@ -2341,28 +2284,26 @@
             }
         }
 
-        if (optional)
-        {
+        if (optional) {
             printJavaDoc((several ? "Removes first " : "Unsets the ") + propdesc);
             emit("public void unset" + propertyName + "()");
             startBlock();
             emitImplementationPreamble();
             emitPre(sType, PrePostExtension.OPERATION_REMOVE, identifier, isAttr, several ? "0" : "-1");
-            if (isAttr)
+            if (isAttr) {
                 emit("get_store().remove_attribute(" + identifier + ");");
-            else
+            } else {
                 emit("get_store().remove_element(" + setIdentifier + ", 0);");
+            }
             emitPost(sType, PrePostExtension.OPERATION_REMOVE, identifier, isAttr, several ? "0" : "-1");
             emitImplementationPostamble();
             endBlock();
         }
 
-        if (several)
-        {
+        if (several) {
             String arrayName = propertyName + "Array";
 
-            if ( xmltype )
-            {
+            if (xmltype) {
                 printJavaDoc("Sets array of all " + propdesc + "  WARNING: This method is not atomicaly synchronized.");
                 emit("public void set" + arrayName + "(" + type + "[] " + safeVarName + "Array)");
                 startBlock();
@@ -2371,66 +2312,57 @@
                 emit("check_orphaned();");
                 emitPre(sType, PrePostExtension.OPERATION_SET, identifier, isAttr);
 
-                if (isobj)
-                {
-                    if (!isSubstGroup)
-                        emit("unionArraySetterHelper(" + safeVarName + "Array" + ", " + identifier + ");" );
-                    else
-                        emit("unionArraySetterHelper(" + safeVarName + "Array" + ", " + identifier + ", " + setIdentifier + ");" );
-                }
-                else
-                {
-                    if (!isSubstGroup)
-                        emit("arraySetterHelper(" + safeVarName + "Array" + ", " + identifier + ");" );
-                    else
-                        emit("arraySetterHelper(" + safeVarName + "Array" + ", " + identifier + ", " + setIdentifier + ");" );
+                if (isobj) {
+                    if (!isSubstGroup) {
+                        emit("unionArraySetterHelper(" + safeVarName + "Array" + ", " + identifier + ");");
+                    } else {
+                        emit("unionArraySetterHelper(" + safeVarName + "Array" + ", " + identifier + ", " + setIdentifier + ");");
+                    }
+                } else {
+                    if (!isSubstGroup) {
+                        emit("arraySetterHelper(" + safeVarName + "Array" + ", " + identifier + ");");
+                    } else {
+                        emit("arraySetterHelper(" + safeVarName + "Array" + ", " + identifier + ", " + setIdentifier + ");");
+                    }
                 }
 
                 emitPost(sType, PrePostExtension.OPERATION_SET, identifier, isAttr);
                 //emitImplementationPostamble();  to avoid deadlock
                 endBlock();
-            }
-            else
-            {
-                printJavaDoc("Sets array of all " + propdesc );
+            } else {
+                printJavaDoc("Sets array of all " + propdesc);
                 emit("public void set" + arrayName + "(" + type + "[] " + safeVarName + "Array)");
                 startBlock();
                 emitImplementationPreamble();
                 emitPre(sType, PrePostExtension.OPERATION_SET, identifier, isAttr);
 
-                if (isobj)
-                {
-                    if (!isSubstGroup)
-                        emit("unionArraySetterHelper(" + safeVarName + "Array" + ", " + identifier + ");" );
-                    else
-                        emit("unionArraySetterHelper(" + safeVarName + "Array" + ", " + identifier + ", " + setIdentifier + ");" );
-                }
-                else if (prop.getJavaTypeCode() == SchemaProperty.JAVA_USER)
-                {
-                    if (!isSubstGroup)
-                    {
-                        emit("org.apache.xmlbeans.SimpleValue[] dests = arraySetterHelper(" + safeVarName + "Array.length" + ", " + identifier + ");" );
+                if (isobj) {
+                    if (!isSubstGroup) {
+                        emit("unionArraySetterHelper(" + safeVarName + "Array" + ", " + identifier + ");");
+                    } else {
+                        emit("unionArraySetterHelper(" + safeVarName + "Array" + ", " + identifier + ", " + setIdentifier + ");");
+                    }
+                } else if (prop.getJavaTypeCode() == SchemaProperty.JAVA_USER) {
+                    if (!isSubstGroup) {
+                        emit("org.apache.xmlbeans.SimpleValue[] dests = arraySetterHelper(" + safeVarName + "Array.length" + ", " + identifier + ");");
                         emit("for ( int i = 0 ; i < dests.length ; i++ ) {");
-                        emit("    " + getUserTypeStaticHandlerMethod(true, (SchemaTypeImpl)prop.getType())
-                                + "(" + safeVarName + "Array[i], dests[i]);");
+                        emit("    " + getUserTypeStaticHandlerMethod(true, (SchemaTypeImpl) prop.getType())
+                             + "(" + safeVarName + "Array[i], dests[i]);");
+                        emit("}");
+                    } else {
+                        emit("org.apache.xmlbeans.SimpleValue[] dests = arraySetterHelper(" + safeVarName + "Array.length" + ", " + identifier + ", " + setIdentifier + ");");
+                        emit("for ( int i = 0 ; i < dests.length ; i++ ) {");
+                        emit("    " + getUserTypeStaticHandlerMethod(true, (SchemaTypeImpl) prop.getType())
+                             + "(" + safeVarName + "Array[i], dests[i]);");
                         emit("}");
                     }
-                    else
-                    {
-                        emit("org.apache.xmlbeans.SimpleValue[] dests = arraySetterHelper(" + safeVarName + "Array.length" + ", " + identifier + ", " + setIdentifier + ");" );
-                        emit("for ( int i = 0 ; i < dests.length ; i++ ) {");
-                        emit("    " + getUserTypeStaticHandlerMethod(true, (SchemaTypeImpl)prop.getType())
-                                + "(" + safeVarName + "Array[i], dests[i]);");
-                        emit("}");
+                } else {
+                    if (!isSubstGroup) {
+                        emit("arraySetterHelper(" + safeVarName + "Array" + ", " + identifier + ");");
+                    } else {
+                        emit("arraySetterHelper(" + safeVarName + "Array" + ", " + identifier + ", " + setIdentifier + ");");
                     }
                 }
-                else
-                {
-                    if (!isSubstGroup)
-                        emit("arraySetterHelper(" + safeVarName + "Array" + ", " + identifier + ");" );
-                    else
-                        emit("arraySetterHelper(" + safeVarName + "Array" + ", " + identifier + ", " + setIdentifier + ");" );
-                }
 
                 emitPost(sType, PrePostExtension.OPERATION_SET, identifier, isAttr);
                 emitImplementationPostamble();
@@ -2440,32 +2372,28 @@
             printJavaDoc("Sets ith " + propdesc);
             emit("public void set" + arrayName + "(int i, " + type + " " + safeVarName + ")");
             startBlock();
-            if ( xmltype && !isSubstGroup )
-            {
+            if (xmltype && !isSubstGroup) {
                 emitPre(sType, PrePostExtension.OPERATION_SET, identifier, isAttr, "i");
                 emit("generatedSetterHelperImpl(" + safeVarName + ", " + setIdentifier + ", i, " +
-                        "org.apache.xmlbeans.impl.values.XmlObjectBase.KIND_SETTERHELPER_ARRAYITEM);");
+                     "org.apache.xmlbeans.impl.values.XmlObjectBase.KIND_SETTERHELPER_ARRAYITEM);");
                 emitPost(sType, PrePostExtension.OPERATION_SET, identifier, isAttr, "i");
-            }
-            else
-            {
+            } else {
                 emitImplementationPreamble();
                 emitPre(sType, PrePostExtension.OPERATION_SET, identifier, isAttr, "i");
                 emitGetTarget(setIdentifier, identifier, isAttr, "i", THROW_EXCEPTION, jtargetType);
-                printJSetValue(javaType, safeVarName, (SchemaTypeImpl)prop.getType());
+                printJSetValue(javaType, safeVarName, (SchemaTypeImpl) prop.getType());
                 emitPost(sType, PrePostExtension.OPERATION_SET, identifier, isAttr, "i");
                 emitImplementationPostamble();
             }
             endBlock();
 
-            if (!xmltype)
-            {
+            if (!xmltype) {
                 printJavaDoc("Sets (as xml) array of all " + propdesc);
                 emit("public void xset" + arrayName + "(" + xtype + "[]" + safeVarName + "Array)");
                 startBlock();
                 emitImplementationPreamble();
                 emitPre(sType, PrePostExtension.OPERATION_SET, identifier, isAttr);
-                emit("arraySetterHelper(" + safeVarName + "Array" + ", " + identifier + ");" );
+                emit("arraySetterHelper(" + safeVarName + "Array" + ", " + identifier + ");");
                 emitPost(sType, PrePostExtension.OPERATION_SET, identifier, isAttr);
                 emitImplementationPostamble();
                 endBlock();
@@ -2482,8 +2410,7 @@
                 endBlock();
             }
 
-            if (nillable)
-            {
+            if (nillable) {
                 printJavaDoc("Nils the ith " + propdesc);
                 emit("public void setNil" + arrayName + "(int i)");
                 startBlock();
@@ -2496,8 +2423,7 @@
                 endBlock();
             }
 
-            if (!xmltype)
-            {
+            if (!xmltype) {
                 printJavaDoc("Inserts the value as the ith " + propdesc);
                 emit("public void insert" + propertyName + "(int i, " + type + " " + safeVarName + ")");
                 startBlock();
@@ -2505,13 +2431,15 @@
                 emitPre(sType, PrePostExtension.OPERATION_INSERT, identifier, isAttr, "i");
                 emit(jtargetType + " target = ");
                 indent();
-                if (!isSubstGroup)
+                if (!isSubstGroup) {
                     emit("(" + jtargetType + ")get_store().insert_element_user(" + identifier + ", i);");
-                else // This is a subst group case
-                    emit ("(" + jtargetType +")get_store().insert_element_user(" + setIdentifier + ", " +
-                            identifier + ", i);");
+                } else // This is a subst group case
+                {
+                    emit("(" + jtargetType + ")get_store().insert_element_user(" + setIdentifier + ", " +
+                         identifier + ", i);");
+                }
                 outdent();
-                printJSetValue(javaType, safeVarName, (SchemaTypeImpl)prop.getType());
+                printJSetValue(javaType, safeVarName, (SchemaTypeImpl) prop.getType());
                 emitPost(sType, PrePostExtension.OPERATION_INSERT, identifier, isAttr, "i");
                 emitImplementationPostamble();
                 endBlock();
@@ -2521,9 +2449,9 @@
                 startBlock();
                 emitImplementationPreamble();
                 emitDeclareTarget(true, jtargetType);
-  	            emitPre(sType, PrePostExtension.OPERATION_INSERT, identifier, isAttr);
+                emitPre(sType, PrePostExtension.OPERATION_INSERT, identifier, isAttr);
                 emitAddTarget(identifier, isAttr, true, jtargetType);
-                printJSetValue(javaType, safeVarName, (SchemaTypeImpl)prop.getType());
+                printJSetValue(javaType, safeVarName, (SchemaTypeImpl) prop.getType());
                 emitPost(sType, PrePostExtension.OPERATION_INSERT, identifier, isAttr);
                 emitImplementationPostamble();
                 endBlock();
@@ -2535,14 +2463,12 @@
             emitImplementationPreamble();
             emitDeclareTarget(true, xtype);
             emitPre(sType, PrePostExtension.OPERATION_INSERT, identifier, isAttr, "i");
-            if (!isSubstGroup)
-            {
+            if (!isSubstGroup) {
                 emit("target = (" + xtype + ")get_store().insert_element_user(" + identifier + ", i);");
-            }
-            else // This is a subst group case
+            } else // This is a subst group case
             {
                 emit("target = (" + xtype + ")get_store().insert_element_user(" +
-                        setIdentifier + ", " + identifier + ", i);");
+                     setIdentifier + ", " + identifier + ", i);");
             }
             emitPost(sType, PrePostExtension.OPERATION_INSERT, identifier, isAttr, "i");
             emit("return target;");
@@ -2582,14 +2508,14 @@
 
         sb.append(c.getName());
 
-        for (int i = 0 ; i < arrayCount; i++)
+        for (int i = 0; i < arrayCount; i++) {
             sb.append("[]");
+        }
 
     }
 
     void printInnerTypeImpl(
-        SchemaType sType, SchemaTypeSystem system, boolean isInner ) throws IOException
-    {
+        SchemaType sType, SchemaTypeSystem system, boolean isInner) throws IOException {
         String shortName = sType.getShortJavaImplName();
 
         printInnerTypeJavaDoc(sType);
@@ -2600,12 +2526,10 @@
 
         printExtensionImplMethods(sType);
 
-        if (!sType.isSimpleType())
-        {
+        if (!sType.isSimpleType()) {
             SchemaProperty[] properties;
 
-            if (sType.getContentType() == SchemaType.SIMPLE_CONTENT)
-            {
+            if (sType.getContentType() == SchemaType.SIMPLE_CONTENT) {
                 // simple content types impls derive directly from "holder" impls
                 // in order to handle the case (for ints or string enums e.g.) where
                 // there is a simple type restriction.  So property getters need to
@@ -2615,31 +2539,29 @@
                 // also implement all the interfaces
                 SchemaType baseType = sType.getBaseType();
                 List extraProperties = null;
-                while (!baseType.isSimpleType() && !baseType.isBuiltinType())
-                {
+                while (!baseType.isSimpleType() && !baseType.isBuiltinType()) {
                     SchemaProperty[] baseProperties = baseType.getDerivedProperties();
-                    for (int i = 0; i < baseProperties.length; i++)
+                    for (int i = 0; i < baseProperties.length; i++) {
                         if (!(baseProperties[i].isAttribute() &&
-                                sType.getAttributeProperty(baseProperties[i].getName()) != null))
-                        {
-                            if (extraProperties == null)
+                              sType.getAttributeProperty(baseProperties[i].getName()) != null)) {
+                            if (extraProperties == null) {
                                 extraProperties = new ArrayList();
+                            }
                             extraProperties.add(baseProperties[i]);
                         }
+                    }
                     baseType = baseType.getBaseType();
                 }
 
                 properties = sType.getProperties();
-                if (extraProperties != null)
-                {
-                    for (int i = 0; i < properties.length; i++)
+                if (extraProperties != null) {
+                    for (int i = 0; i < properties.length; i++) {
                         extraProperties.add(properties[i]);
+                    }
                     properties = (SchemaProperty[]) extraProperties.
                         toArray(new SchemaProperty[extraProperties.size()]);
                 }
-            }
-            else
-            {
+            } else {
                 // complex content type implementations derive from base type impls
                 // so derived property impls can be reused
 
@@ -2648,12 +2570,11 @@
 
             Map qNameMap = printStaticFields(properties);
 
-            for (int i = 0; i < properties.length; i++)
-            {
+            for (int i = 0; i < properties.length; i++) {
                 SchemaProperty prop = properties[i];
 
                 QName name = prop.getName();
-                String xmlType = xmlTypeForProperty( prop );
+                String xmlType = xmlTypeForProperty(prop);
 
                 printGetterImpls(
                     shortName,
@@ -2673,8 +2594,7 @@
                     getSetIdentifier(qNameMap, name)
                 );
 
-                if (!prop.isReadOnly())
-                {
+                if (!prop.isReadOnly()) {
                     printSetterImpls(
                         name,
                         prop,
@@ -2690,7 +2610,7 @@
                         xmlTypeForPropertyIsUnion(prop),
                         getIdentifier(qNameMap, name),
                         getSetIdentifier(qNameMap, name),
-  	                    sType
+                        sType
                     );
                 }
             }
@@ -2701,120 +2621,119 @@
         endBlock();
     }
 
-    private SchemaProperty[] getDerivedProperties(SchemaType sType)
-    {
+    private SchemaProperty[] getDerivedProperties(SchemaType sType) {
         // We have to see if this is redefined, because if it is we have
         // to include all properties associated to its supertypes
         QName name = sType.getName();
-        if (name != null && name.equals(sType.getBaseType().getName()))
-        {
+        if (name != null && name.equals(sType.getBaseType().getName())) {
             SchemaType sType2 = sType.getBaseType();
             // Walk all the redefined types and record any properties
             // 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++)
+            for (int i = 0; i < props.length; i++) {
                 propsByName.put(props[i].getName(), props[i]);
-            while (sType2 != null && name.equals(sType2.getName()))
-            {
+            }
+            while (sType2 != null && name.equals(sType2.getName())) {
                 props = sType2.getDerivedProperties();
-                for (int i = 0; i < props.length; i++)
-                    if (!propsByName.containsKey(props[i].getName()))
+                for (int i = 0; i < props.length; i++) {
+                    if (!propsByName.containsKey(props[i].getName())) {
                         propsByName.put(props[i].getName(), props[i]);
+                    }
+                }
                 sType2 = sType2.getBaseType();
             }
             return (SchemaProperty[]) propsByName.values().toArray(new SchemaProperty[0]);
-        }
-        else
+        } else {
             return sType.getDerivedProperties();
+        }
     }
 
-    private void printExtensionImplMethods(SchemaType sType) throws IOException
-    {
+    private void printExtensionImplMethods(SchemaType sType) throws IOException {
         SchemaTypeImpl sImpl = getImpl(sType);
-        if (sImpl == null)
+        if (sImpl == null) {
             return;
+        }
 
         InterfaceExtension[] exts = sImpl.getInterfaceExtensions();
-        if (exts != null) for (int i = 0; i < exts.length; i++)
-        {
-            InterfaceExtension.MethodSignature[] methods = exts[i].getMethods();
-            if (methods != null)
-            {
-                for (int j = 0; j < methods.length; j++)
-                {
-                    printJavaDoc("Implementation method for interface " + exts[i].getStaticHandler());
-                    printInterfaceMethodDecl(methods[j]);
-                    startBlock();
-                    printInterfaceMethodImpl(exts[i].getStaticHandler(), methods[j]);
-                    endBlock();
+        if (exts != null) {
+            for (int i = 0; i < exts.length; i++) {
+                InterfaceExtension.MethodSignature[] methods = exts[i].getMethods();
+                if (methods != null) {
+                    for (int j = 0; j < methods.length; j++) {
+                        printJavaDoc("Implementation method for interface " + exts[i].getStaticHandler());
+                        printInterfaceMethodDecl(methods[j]);
+                        startBlock();
+                        printInterfaceMethodImpl(exts[i].getStaticHandler(), methods[j]);
+                        endBlock();
+                    }
                 }
             }
         }
     }
 
-    void printInterfaceMethodDecl(InterfaceExtension.MethodSignature method) throws IOException
-    {
+    void printInterfaceMethodDecl(InterfaceExtension.MethodSignature method) throws IOException {
         StringBuilder decl = new StringBuilder(60);
 
         decl.append("public ").append(method.getReturnType());
         decl.append(" ").append(method.getName()).append("(");
 
         String[] paramTypes = method.getParameterTypes();
-        for (int i = 0; i < paramTypes.length; i++)
-        {
-            if (i != 0)
+        for (int i = 0; i < paramTypes.length; i++) {
+            if (i != 0) {
                 decl.append(", ");
+            }
             decl.append(paramTypes[i]).append(" p").append(i);
         }
 
         decl.append(")");
 
         String[] exceptions = method.getExceptionTypes();
-        for (int i = 0; i < exceptions.length; i++)
+        for (int i = 0; i < exceptions.length; i++) {
             decl.append((i == 0 ? " throws " : ", ") + exceptions[i]);
+        }
 
         emit(decl.toString());
     }
 
-    void printInterfaceMethodImpl(String handler, InterfaceExtension.MethodSignature method) throws IOException
-    {
+    void printInterfaceMethodImpl(String handler, InterfaceExtension.MethodSignature method) throws IOException {
         StringBuilder impl = new StringBuilder(60);
 
-        if (!method.getReturnType().equals("void"))
+        if (!method.getReturnType().equals("void")) {
             impl.append("return ");
+        }
 
         impl.append(handler).append(".").append(method.getName()).append("(this");
 
         String[] params = method.getParameterTypes();
-        for (int i = 0; i < params.length; i++)
+        for (int i = 0; i < params.length; i++) {
             impl.append(", p" + i);
+        }
 
         impl.append(");");
 
         emit(impl.toString());
     }
 
-    void printNestedTypeImpls(SchemaType sType, SchemaTypeSystem system) throws IOException
-    {
+    void printNestedTypeImpls(SchemaType sType, SchemaTypeSystem system) throws IOException {
         boolean redefinition = sType.getName() != null &&
-            sType.getName().equals(sType.getBaseType().getName());
-        while (sType != null)
-        {
+                               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())
+            for (int i = 0; i < anonTypes.length; i++) {
+                if (anonTypes[i].isSkippedAnonymousType()) {
                     printNestedTypeImpls(anonTypes[i], system);
-                else
+                } else {
                     printInnerTypeImpl(anonTypes[i], system, true);
+                }
             }
             // For redefinition by extension, go ahead and print the anonymous
             // types in the base
             if (!redefinition ||
-                (sType.getDerivationType() != SchemaType.DT_EXTENSION && !sType.isSimpleType()))
+                (sType.getDerivationType() != SchemaType.DT_EXTENSION && !sType.isSimpleType())) {
                 break;
+            }
             sType = sType.getBaseType();
         }
     }
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 6f2e734..eaaca47 100644
--- a/src/main/java/org/apache/xmlbeans/impl/schema/SchemaTypeSystemCompiler.java
+++ b/src/main/java/org/apache/xmlbeans/impl/schema/SchemaTypeSystemCompiler.java
@@ -15,40 +15,19 @@
 
 package org.apache.xmlbeans.impl.schema;
 
-import org.apache.xmlbeans.XmlBeans;
-import org.apache.xmlbeans.SchemaTypeLoader;
-import org.apache.xmlbeans.XmlException;
-import org.apache.xmlbeans.XmlErrorCodes;
-import org.apache.xmlbeans.XmlObject;
-import org.apache.xmlbeans.XmlOptions;
-import org.apache.xmlbeans.SchemaTypeSystem;
-import org.apache.xmlbeans.Filer;
-import org.apache.xmlbeans.SchemaType;
-import org.apache.xmlbeans.BindingConfig;
-
-import java.util.ArrayList;
-import java.util.HashSet;
-import java.util.HashMap;
-import java.util.Map;
-import java.util.List;
-import java.util.Set;
-import java.util.Arrays;
-import java.net.URI;
-
-import org.apache.xmlbeans.impl.xb.xsdschema.SchemaDocument.Schema;
-import org.apache.xmlbeans.impl.xb.xsdschema.SchemaDocument;
+import org.apache.xmlbeans.*;
 import org.apache.xmlbeans.impl.common.XmlErrorWatcher;
+import org.apache.xmlbeans.impl.xb.xsdschema.SchemaDocument;
+import org.apache.xmlbeans.impl.xb.xsdschema.SchemaDocument.Schema;
 
-import java.util.Collection;
-import java.util.Iterator;
 import java.io.File;
 import java.io.IOException;
 import java.io.Writer;
+import java.net.URI;
+import java.util.*;
 
-public class SchemaTypeSystemCompiler
-{
-    public static class Parameters
-    {
+public class SchemaTypeSystemCompiler {
+    public static class Parameters {
         private SchemaTypeSystem existingSystem;
         private String name;
         private Schema[] schemas;
@@ -61,113 +40,91 @@
         private Map sourcesToCopyMap;
         private File schemasDir;
 
-        public SchemaTypeSystem getExistingTypeSystem()
-        {
+        public SchemaTypeSystem getExistingTypeSystem() {
             return existingSystem;
         }
 
-        public void setExistingTypeSystem(SchemaTypeSystem system)
-        {
+        public void setExistingTypeSystem(SchemaTypeSystem system) {
             this.existingSystem = system;
         }
 
-        public String getName()
-        {
+        public String getName() {
             return name;
         }
 
-        public void setName(String name)
-        {
+        public void setName(String name) {
             this.name = name;
         }
 
-        public SchemaDocument.Schema[] getSchemas()
-        {
+        public SchemaDocument.Schema[] getSchemas() {
             return schemas;
         }
 
-        public void setSchemas(SchemaDocument.Schema[] schemas)
-        {
+        public void setSchemas(SchemaDocument.Schema[] schemas) {
             this.schemas = schemas;
         }
 
-        public BindingConfig getConfig()
-        {
+        public BindingConfig getConfig() {
             return config;
         }
 
-        public void setConfig(BindingConfig config)
-        {
+        public void setConfig(BindingConfig config) {
             this.config = config;
         }
 
-        public SchemaTypeLoader getLinkTo()
-        {
+        public SchemaTypeLoader getLinkTo() {
             return linkTo;
         }
 
-        public void setLinkTo(SchemaTypeLoader linkTo)
-        {
+        public void setLinkTo(SchemaTypeLoader linkTo) {
             this.linkTo = linkTo;
         }
 
-        public XmlOptions getOptions()
-        {
+        public XmlOptions getOptions() {
             return options;
         }
 
-        public void setOptions(XmlOptions options)
-        {
+        public void setOptions(XmlOptions options) {
             this.options = options;
         }
 
-        public Collection getErrorListener()
-        {
+        public Collection getErrorListener() {
             return errorListener;
         }
 
-        public void setErrorListener(Collection errorListener)
-        {
+        public void setErrorListener(Collection errorListener) {
             this.errorListener = errorListener;
         }
 
-        public boolean isJavaize()
-        {
+        public boolean isJavaize() {
             return javaize;
         }
 
-        public void setJavaize(boolean javaize)
-        {
+        public void setJavaize(boolean javaize) {
             this.javaize = javaize;
         }
 
-        public URI getBaseURI()
-        {
+        public URI getBaseURI() {
             return baseURI;
         }
 
-        public void setBaseURI(URI baseURI)
-        {
+        public void setBaseURI(URI baseURI) {
             this.baseURI = baseURI;
         }
 
-        public Map getSourcesToCopyMap()
-        {
+        public Map getSourcesToCopyMap() {
             return sourcesToCopyMap;
         }
 
-        public void setSourcesToCopyMap(Map sourcesToCopyMap)
-        {
+        public void setSourcesToCopyMap(Map sourcesToCopyMap) {
             this.sourcesToCopyMap = sourcesToCopyMap;
         }
 
-        public File getSchemasDir()
-        {
+        public File getSchemasDir() {
             return schemasDir;
         }
 
-        public void setSchemasDir(File schemasDir)
-        {
+        public void setSchemasDir(File schemasDir) {
             this.schemasDir = schemasDir;
         }
 
@@ -176,8 +133,7 @@
     /**
      * Compiles a SchemaTypeSystem.  Use XmlBeans.compileXmlBeans() if you can.
      */
-    public static SchemaTypeSystem compile(Parameters params)
-    {
+    public static SchemaTypeSystem compile(Parameters params) {
         return compileImpl(params.getExistingTypeSystem(), params.getName(),
             params.getSchemas(), params.getConfig(), params.getLinkTo(),
             params.getOptions(), params.getErrorListener(), params.isJavaize(),
@@ -193,41 +149,37 @@
      * {@link XmlBeans#compileXmlBeans(String, SchemaTypeSystem, XmlObject[], BindingConfig, SchemaTypeLoader, Filer, XmlOptions)}
      */
     public static SchemaTypeSystemImpl compile(String name, SchemaTypeSystem existingSTS,
-        XmlObject[] input, BindingConfig config, SchemaTypeLoader linkTo, Filer filer, XmlOptions options)
-        throws XmlException
-    {
+                                               XmlObject[] input, BindingConfig config, SchemaTypeLoader linkTo, Filer filer, XmlOptions options)
+        throws XmlException {
         options = XmlOptions.maskNull(options);
         ArrayList schemas = new ArrayList();
 
-        if (input != null)
-        {
-            for (int i = 0; i < input.length; i++)
-            {
-                if (input[i] instanceof Schema)
+        if (input != null) {
+            for (int i = 0; i < input.length; i++) {
+                if (input[i] instanceof Schema) {
                     schemas.add(input[i]);
-                else if (input[i] instanceof SchemaDocument && ((SchemaDocument)input[i]).getSchema() != null)
-                    schemas.add(((SchemaDocument)input[i]).getSchema());
-                else
-                    throw new XmlException("Thread " + Thread.currentThread().getName() +  ": The " + i + "th supplied input is not a schema document: its type is " + input[i].schemaType());
+                } else if (input[i] instanceof SchemaDocument && ((SchemaDocument) input[i]).getSchema() != null) {
+                    schemas.add(((SchemaDocument) input[i]).getSchema());
+                } else {
+                    throw new XmlException("Thread " + Thread.currentThread().getName() + ": The " + i + "th supplied input is not a schema document: its type is " + input[i].schemaType());
+                }
             }
         }
 
-        Collection userErrors = (Collection)options.get(XmlOptions.ERROR_LISTENER);
+        Collection userErrors = (Collection) options.get(XmlOptions.ERROR_LISTENER);
         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),
+            (Schema[]) schemas.toArray(new Schema[schemas.size()]),
+            config, linkTo, options, errorWatcher, filer != null, (URI) options.get(XmlOptions.BASE_URI),
             null, null);
 
         // if there is an error and compile didn't recover (stsi==null), throw exception
-        if (errorWatcher.hasError() && stsi == null)
-        {
+        if (errorWatcher.hasError() && stsi == null) {
             throw new XmlException(errorWatcher.firstError());
         }
 
-        if (stsi != null && !stsi.isIncomplete() && filer != null)
-        {
+        if (stsi != null && !stsi.isIncomplete() && filer != null) {
             stsi.save(filer);
             generateTypes(stsi, filer, options);
         }
@@ -238,13 +190,14 @@
     //
     // Compiles a SchemaTypeSystem
     //
-    /* 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)
-    {
-        if (linkTo == null)
+    /* 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) {
+        if (linkTo == null) {
             throw new IllegalArgumentException("Must supply linkTo");
+        }
 
         XmlErrorWatcher errorWatcher = new XmlErrorWatcher(outsideErrors);
         boolean incremental = system != null;
@@ -252,49 +205,44 @@
         // construct the state
         StscState state = StscState.start();
         boolean validate = (options == null || !options.hasOption(XmlOptions.COMPILE_NO_VALIDATION));
-        try
-        {
+        try {
             state.setErrorListener(errorWatcher);
             state.setBindingConfig(config);
             state.setOptions(options);
             state.setGivenTypeSystemName(name);
             state.setSchemasDir(schemasDir);
-            if (baseURI != null)
+            if (baseURI != null) {
                 state.setBaseUri(baseURI);
+            }
 
             // construct the classpath (you always get the builtin types)
-            linkTo = SchemaTypeLoaderImpl.build(new SchemaTypeLoader[] { BuiltinSchemaTypeSystem.get(), linkTo }, null, null);
+            linkTo = SchemaTypeLoaderImpl.build(new SchemaTypeLoader[]{BuiltinSchemaTypeSystem.get(), linkTo}, null, null);
             state.setImportingTypeLoader(linkTo);
 
             List validSchemas = new ArrayList(schemas.length);
 
             // load all the xsd files into it
-            if (validate)
-            {
+            if (validate) {
                 XmlOptions validateOptions = new XmlOptions().setErrorListener(errorWatcher);
-                if (options.hasOption(XmlOptions.VALIDATE_TREAT_LAX_AS_SKIP))
+                if (options.hasOption(XmlOptions.VALIDATE_TREAT_LAX_AS_SKIP)) {
                     validateOptions.setValidateTreatLaxAsSkip();
-                for (int i = 0; i < schemas.length; i++)
-                {
-                    if (schemas[i].validate(validateOptions))
-                        validSchemas.add(schemas[i]);
                 }
-            }
-            else
-            {
+                for (int i = 0; i < schemas.length; i++) {
+                    if (schemas[i].validate(validateOptions)) {
+                        validSchemas.add(schemas[i]);
+                    }
+                }
+            } else {
                 validSchemas.addAll(Arrays.asList(schemas));
             }
 
-            Schema[] startWith = (Schema[])validSchemas.toArray(new Schema[validSchemas.size()]);
+            Schema[] startWith = (Schema[]) validSchemas.toArray(new Schema[validSchemas.size()]);
 
-            if (incremental)
-            {
+            if (incremental) {
                 Set namespaces = new HashSet();
-                startWith = getSchemasToRecompile((SchemaTypeSystemImpl)system, startWith, namespaces);
-                state.initFromTypeSystem((SchemaTypeSystemImpl)system, namespaces);
-            }
-            else
-            {
+                startWith = getSchemasToRecompile((SchemaTypeSystemImpl) system, startWith, namespaces);
+                state.initFromTypeSystem((SchemaTypeSystemImpl) system, namespaces);
+            } else {
                 state.setDependencies(new SchemaDependencies());
             }
 
@@ -306,7 +254,7 @@
 
             // call the resolver to do its magic
             StscResolver.resolveAll();
-            
+
             // call the checker to check both restrictions and defaults
             StscChecker.checkAll();
 
@@ -317,31 +265,27 @@
             state.get().sts().loadFromStscState(state);
 
             // fill in the source-copy map
-            if (sourcesToCopyMap != null)
+            if (sourcesToCopyMap != null) {
                 sourcesToCopyMap.putAll(state.sourceCopyMap());
+            }
 
-            if (errorWatcher.hasError())
-            {
+            if (errorWatcher.hasError()) {
                 // EXPERIMENTAL: recovery from compilation errors and partial type system
-                if (state.allowPartial() && state.getRecovered() == errorWatcher.size())
-                {
+                if (state.allowPartial() && state.getRecovered() == errorWatcher.size()) {
                     // if partial type system allowed and all errors were recovered
                     state.get().sts().setIncomplete(true);
-                }
-                else
-                {
+                } else {
                     // if any non-recoverable errors, return null
                     return null;
                 }
             }
 
-            if (system != null)
+            if (system != null) {
                 ((SchemaTypeSystemImpl) system).setIncomplete(true);
+            }
 
             return state.get().sts();
-        }
-        finally
-        {
+        } finally {
             StscState.end();
         }
     }
@@ -353,18 +297,17 @@
      * and of the entity resolvers that have been set up
      */
     private static Schema[] getSchemasToRecompile(SchemaTypeSystemImpl system,
-        Schema[] modified, Set namespaces)
-    {
+                                                  Schema[] modified, Set namespaces) {
         Set modifiedFiles = new HashSet();
         Map haveFile = new HashMap();
         List result = new ArrayList();
-        for (int i = 0; i < modified.length; i++)
-        {
+        for (int i = 0; i < modified.length; i++) {
             String fileURL = modified[i].documentProperties().getSourceName();
-            if (fileURL == null)
+            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");
+                                                   " 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]);
@@ -374,42 +317,32 @@
         namespaces.addAll(dep.computeTransitiveClosure(nss));
         List needRecompilation = dep.getFilesTouched(namespaces);
         StscState.get().setDependencies(new SchemaDependencies(dep, namespaces));
-        for (int i = 0; i < needRecompilation.size(); i++)
-        {
+        for (int i = 0; i < needRecompilation.size(); i++) {
             String url = (String) needRecompilation.get(i);
             Schema have = (Schema) haveFile.get(url);
-            if (have == null)
-            {
+            if (have == null) {
                 // We have to load the file from the entity resolver
-                try
-                {
+                try {
                     XmlObject xdoc = StscImporter.DownloadTable.
                         downloadDocument(StscState.get().getS4SLoader(), null, url);
                     XmlOptions voptions = new XmlOptions();
                     voptions.setErrorListener(StscState.get().getErrorListener());
-                    if (!(xdoc instanceof SchemaDocument) || !xdoc.validate(voptions))
-                    {
+                    if (!(xdoc instanceof SchemaDocument) || !xdoc.validate(voptions)) {
                         StscState.get().error("Referenced document is not a valid schema, URL = " + url, XmlErrorCodes.CANNOT_FIND_RESOURCE, null);
                         continue;
                     }
 
-                    SchemaDocument sDoc = (SchemaDocument)xdoc;
+                    SchemaDocument sDoc = (SchemaDocument) xdoc;
 
                     result.add(sDoc.getSchema());
-                }
-                catch (java.net.MalformedURLException mfe)
-                {
-                    StscState.get().error(XmlErrorCodes.EXCEPTION_LOADING_URL, new Object[] { "MalformedURLException", url, mfe.getMessage() }, null);
+                } 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)
-                {
-                    StscState.get().error(XmlErrorCodes.EXCEPTION_LOADING_URL, new Object[] { "IOException", url, ioe.getMessage() }, null);
+                } catch (java.io.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);
+                } catch (XmlException xmle) {
+                    StscState.get().error(XmlErrorCodes.EXCEPTION_LOADING_URL, new Object[]{"XmlException", url, xmle.getMessage()}, null);
                     continue;
                 }
             }
@@ -423,17 +356,17 @@
      * Please do not invoke this method directly as the signature could change unexpectedly.
      * Use {@link org.apache.xmlbeans.XmlBeans#compileXmlBeans}
      *
-     * @param system the SchemaTypeSystem to generated java source for
-     * @param filer to create the java source files
+     * @param system  the SchemaTypeSystem to generated java source for
+     * @param filer   to create the java source files
      * @param options See {@link XmlOptions#setSchemaCodePrinter(org.apache.xmlbeans.SchemaCodePrinter)}
      * @return true if saving the generated source succeeded.
      */
-    public static boolean generateTypes(SchemaTypeSystem system, Filer filer, XmlOptions options)
-    {
+    public static boolean generateTypes(SchemaTypeSystem system, Filer filer, XmlOptions options) {
         // partial type systems not allowed to be saved
-        if (system instanceof SchemaTypeSystemImpl && ((SchemaTypeSystemImpl)system).isIncomplete())
+        if (system instanceof SchemaTypeSystemImpl && ((SchemaTypeSystemImpl) system).isIncomplete()) {
             return false;
-        
+        }
+
         boolean success = true;
 
         List types = new ArrayList();
@@ -441,48 +374,51 @@
         types.addAll(Arrays.asList(system.documentTypes()));
         types.addAll(Arrays.asList(system.attributeTypes()));
 
-        for (Iterator i = types.iterator(); i.hasNext(); )
-        {
-            SchemaType type = (SchemaType)i.next();
-            if (type.isBuiltinType())
+        for (Iterator i = types.iterator(); i.hasNext(); ) {
+            SchemaType type = (SchemaType) i.next();
+            if (type.isBuiltinType()) {
                 continue;
-            if (type.getFullJavaName() == null)
+            }
+            if (type.getFullJavaName() == null) {
                 continue;
+            }
 
             String fjn = type.getFullJavaName();
 
             Writer writer = null;
 
-            try
-            {
+            try {
                 // Generate interface class
                 writer = filer.createSourceFile(fjn);
                 SchemaTypeCodePrinter.printType(writer, type, options);
-            }
-            catch (IOException e)
-            {
+            } catch (IOException e) {
                 System.err.println("IO Error " + e);
                 success = false;
-            }
-            finally {
-                try { if (writer != null) writer.close(); } catch (IOException e) {}
+            } finally {
+                try {
+                    if (writer != null) {
+                        writer.close();
+                    }
+                } catch (IOException e) {
+                }
             }
 
-            try
-            {
+            try {
                 // Generate Implementation class
                 fjn = type.getFullJavaImplName();
                 writer = filer.createSourceFile(fjn);
 
                 SchemaTypeCodePrinter.printTypeImpl(writer, type, options);
-            }
-            catch (IOException e)
-            {
+            } catch (IOException e) {
                 System.err.println("IO Error " + e);
                 success = false;
-            }
-            finally {
-                try { if (writer != null) writer.close(); } catch (IOException e) {}
+            } finally {
+                try {
+                    if (writer != null) {
+                        writer.close();
+                    }
+                } catch (IOException e) {
+                }
             }
         }
 
diff --git a/src/main/java/org/apache/xmlbeans/impl/schema/SchemaTypeSystemImpl.java b/src/main/java/org/apache/xmlbeans/impl/schema/SchemaTypeSystemImpl.java
index 12c1b93..8b1b5fb 100644
--- a/src/main/java/org/apache/xmlbeans/impl/schema/SchemaTypeSystemImpl.java
+++ b/src/main/java/org/apache/xmlbeans/impl/schema/SchemaTypeSystemImpl.java
@@ -15,35 +15,12 @@
 
 package org.apache.xmlbeans.impl.schema;
 
-import org.apache.xmlbeans.Filer;
-import org.apache.xmlbeans.QNameSet;
-import org.apache.xmlbeans.SchemaAnnotation;
-import org.apache.xmlbeans.SchemaAttributeGroup;
-import org.apache.xmlbeans.SchemaAttributeModel;
-import org.apache.xmlbeans.SchemaComponent;
-import org.apache.xmlbeans.SchemaGlobalAttribute;
-import org.apache.xmlbeans.SchemaGlobalElement;
-import org.apache.xmlbeans.SchemaIdentityConstraint;
-import org.apache.xmlbeans.SchemaLocalAttribute;
-import org.apache.xmlbeans.SchemaLocalElement;
-import org.apache.xmlbeans.SchemaModelGroup;
-import org.apache.xmlbeans.SchemaParticle;
-import org.apache.xmlbeans.SchemaProperty;
-import org.apache.xmlbeans.SchemaStringEnumEntry;
-import org.apache.xmlbeans.SchemaType;
-import org.apache.xmlbeans.SchemaTypeLoader;
-import org.apache.xmlbeans.SchemaTypeLoaderException;
-import org.apache.xmlbeans.SchemaTypeSystem;
-import org.apache.xmlbeans.SimpleValue;
-import org.apache.xmlbeans.SystemProperties;
-import org.apache.xmlbeans.XmlAnySimpleType;
-import org.apache.xmlbeans.XmlObject;
-import org.apache.xmlbeans.XmlOptions;
-import org.apache.xmlbeans.ResourceLoader;
+import org.apache.xmlbeans.*;
 import org.apache.xmlbeans.impl.common.DefaultClassLoaderResourceLoader;
 import org.apache.xmlbeans.impl.common.NameUtil;
 import org.apache.xmlbeans.impl.common.QNameHelper;
 import org.apache.xmlbeans.impl.common.XBeanDebug;
+import org.apache.xmlbeans.impl.repackage.Repackager;
 import org.apache.xmlbeans.impl.util.FilerImpl;
 import org.apache.xmlbeans.impl.util.HexBin;
 import org.apache.xmlbeans.impl.values.XmlObjectBase;
@@ -51,36 +28,17 @@
 import org.apache.xmlbeans.impl.xb.xsdschema.GroupDocument;
 import org.apache.xmlbeans.soap.SOAPArrayType;
 import org.apache.xmlbeans.soap.SchemaWSDLArrayType;
-import org.apache.xmlbeans.impl.repackage.Repackager;
 
 import javax.xml.namespace.QName;
-import java.io.ByteArrayOutputStream;
-import java.io.DataInputStream;
-import java.io.DataOutputStream;
-import java.io.File;
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.OutputStream;
+import java.io.*;
 import java.math.BigInteger;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Collections;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.Iterator;
-import java.util.LinkedHashMap;
-import java.util.LinkedHashSet;
-import java.util.List;
-import java.util.Map;
-import java.util.Random;
-import java.util.Set;
+import java.util.*;
 import java.util.regex.Matcher;
 import java.util.regex.Pattern;
 import java.util.zip.ZipEntry;
 import java.util.zip.ZipFile;
 
-public class SchemaTypeSystemImpl extends SchemaTypeLoaderBase implements SchemaTypeSystem
-{
+public class SchemaTypeSystemImpl extends SchemaTypeLoaderBase implements SchemaTypeSystem {
     public static final int DATA_BABE = 0xDA7ABABE;
     public static final int MAJOR_VERSION = 2;  // must match == to be compatible
     public static final int MINOR_VERSION = 24; // must be <= to be compatible
@@ -116,26 +74,26 @@
     public static final int FIELD_LOCALELT = 3;
 
     // type flags
-    static final int FLAG_SIMPLE_TYPE     = 0x1;
-    static final int FLAG_DOCUMENT_TYPE   = 0x2;
-    static final int FLAG_ORDERED         = 0x4;
-    static final int FLAG_BOUNDED         = 0x8;
-    static final int FLAG_FINITE          = 0x10;
-    static final int FLAG_NUMERIC         = 0x20;
-    static final int FLAG_STRINGENUM      = 0x40;
-    static final int FLAG_UNION_OF_LISTS  = 0x80;
-    static final int FLAG_HAS_PATTERN     = 0x100;
+    static final int FLAG_SIMPLE_TYPE = 0x1;
+    static final int FLAG_DOCUMENT_TYPE = 0x2;
+    static final int FLAG_ORDERED = 0x4;
+    static final int FLAG_BOUNDED = 0x8;
+    static final int FLAG_FINITE = 0x10;
+    static final int FLAG_NUMERIC = 0x20;
+    static final int FLAG_STRINGENUM = 0x40;
+    static final int FLAG_UNION_OF_LISTS = 0x80;
+    static final int FLAG_HAS_PATTERN = 0x100;
     static final int FLAG_ORDER_SENSITIVE = 0x200;
-    static final int FLAG_TOTAL_ORDER     = 0x400;
-    static final int FLAG_COMPILED        = 0x800;
-    static final int FLAG_BLOCK_EXT       = 0x1000;
-    static final int FLAG_BLOCK_REST      = 0x2000;
-    static final int FLAG_FINAL_EXT       = 0x4000;
-    static final int FLAG_FINAL_REST      = 0x8000;
-    static final int FLAG_FINAL_UNION     = 0x10000;
-    static final int FLAG_FINAL_LIST      = 0x20000;
-    static final int FLAG_ABSTRACT        = 0x40000;
-    static final int FLAG_ATTRIBUTE_TYPE  = 0x80000;
+    static final int FLAG_TOTAL_ORDER = 0x400;
+    static final int FLAG_COMPILED = 0x800;
+    static final int FLAG_BLOCK_EXT = 0x1000;
+    static final int FLAG_BLOCK_REST = 0x2000;
+    static final int FLAG_FINAL_EXT = 0x4000;
+    static final int FLAG_FINAL_REST = 0x8000;
+    static final int FLAG_FINAL_UNION = 0x10000;
+    static final int FLAG_FINAL_LIST = 0x20000;
+    static final int FLAG_ABSTRACT = 0x40000;
+    static final int FLAG_ATTRIBUTE_TYPE = 0x80000;
 
     /**
      * regex to identify the type system holder package namespace
@@ -148,10 +106,10 @@
      * xmlbeans one.
      * METADATA_PACKAGE_GEN will be "" for the original and something like
      * com.mycompany.private.xmlbeans for a private distribution of XMLBeans.
-     *
+     * <p>
      * There are two properties:
-     *   METADATA_PACKAGE_GEN - used for generating metadata
-     *   and METADATA_PACKAGE_LOAD - used for loading the metadata.
+     * METADATA_PACKAGE_GEN - used for generating metadata
+     * and METADATA_PACKAGE_LOAD - used for loading the metadata.
      * Most of the time they have the same value, with one exception, during the
      * repackage process scomp needs to load from old package and generate into
      * a new package.
@@ -169,12 +127,12 @@
 //        METADATA_PACKAGE_GEN = stsPackageName.replace('.', '/') + "/metadata";
 //    }
 
-    private static String nameToPathString(String nameForSystem)
-    {
+    private static String nameToPathString(String nameForSystem) {
         nameForSystem = nameForSystem.replace('.', '/');
 
-        if (!nameForSystem.endsWith("/") && nameForSystem.length() > 0)
+        if (!nameForSystem.endsWith("/") && nameForSystem.length() > 0) {
             nameForSystem = nameForSystem + "/";
+        }
 
         return nameForSystem;
     }
@@ -187,17 +145,9 @@
         _classloader = getClass().getClassLoader();
         _linker = this;
         _resourceLoader = new ClassLoaderResourceLoader(_classloader);
-        try
-        {
+        try {
             initFromHeader();
-        }
-        catch (RuntimeException e)
-        {
-            XBeanDebug.logException(e);
-            throw e;
-        }
-        catch (Error e)
-        {
+        } catch (Error | RuntimeException e) {
             XBeanDebug.logException(e);
             throw e;
         }
@@ -212,95 +162,64 @@
         _classloader = indexclass.getClassLoader();
         _linker = SchemaTypeLoaderImpl.build(null, null, _classloader, getMetadataPath());
         _resourceLoader = new ClassLoaderResourceLoader(_classloader);
-        try
-        {
+        try {
             initFromHeader();
-        }
-        catch (RuntimeException e)
-        {
+        } catch (RuntimeException e) {
             XBeanDebug.logException(e);
             throw e;
-        }
-        catch (Error e)
-        {
+        } catch (Error e) {
             XBeanDebug.logException(e);
             throw e;
         }
         XBeanDebug.trace(XBeanDebug.TRACE_SCHEMA_LOADING, "Finished loading type system " + _name, -1);
     }
 
-    public static boolean fileContainsTypeSystem(File file, String name)
-    {
+    public static boolean fileContainsTypeSystem(File file, String name) {
         String indexname = nameToPathString(name) + "index.xsb";
 
-        if (file.isDirectory())
-        {
+        if (file.isDirectory()) {
             return (new File(file, indexname)).isFile();
-        }
-        else
-        {
-            ZipFile zipfile = null;
-            try
-            {
-                zipfile = new ZipFile(file);
+        } else {
+            try (ZipFile zipfile = new ZipFile(file)) {
                 ZipEntry entry = zipfile.getEntry(indexname);
                 return (entry != null && !entry.isDirectory());
-            }
-            catch (IOException e)
-            {
+            } catch (IOException e) {
                 XBeanDebug.log("Problem loading SchemaTypeSystem, zipfilename " + file);
                 XBeanDebug.logException(e);
-                throw new SchemaTypeLoaderException(e.getMessage(), name, "index", SchemaTypeLoaderException.IO_EXCEPTION);
-            }
-            finally
-            {
-                if (zipfile != null)
-                    try { zipfile.close(); } catch (IOException e) {}
+                throw new SchemaTypeLoaderException(e.getMessage(), name, "index", SchemaTypeLoaderException.IO_EXCEPTION, e);
             }
         }
     }
 
-    public static SchemaTypeSystemImpl forName(String name, ClassLoader loader)
-    {
-        try
-        {
+    public static SchemaTypeSystemImpl forName(String name, ClassLoader loader) {
+        try {
             Class c = Class.forName(name + "." + SchemaTypeCodePrinter.INDEX_CLASSNAME, true, loader);
-            return (SchemaTypeSystemImpl)c.getField("typeSystem").get(null);
-        }
-        catch (Throwable e)
-        {
+            return (SchemaTypeSystemImpl) c.getField("typeSystem").get(null);
+        } catch (Throwable e) {
             return null;
         }
     }
 
-    public SchemaTypeSystemImpl(ResourceLoader resourceLoader, String name, SchemaTypeLoader linker)
-    {
+    public SchemaTypeSystemImpl(ResourceLoader resourceLoader, String name, SchemaTypeLoader linker) {
         _name = name;
         _basePackage = nameToPathString(_name);
         _linker = linker;
         _resourceLoader = resourceLoader;
-        try
-        {
+        try {
             initFromHeader();
-        }
-        catch (RuntimeException e)
-        {
+        } catch (RuntimeException e) {
             XBeanDebug.logException(e);
             throw e;
-        }
-        catch (Error e)
-        {
+        } catch (Error e) {
             XBeanDebug.logException(e);
             throw e;
         }
     }
 
-    private void initFromHeader()
-    {
+    private void initFromHeader() {
         XBeanDebug.trace(XBeanDebug.TRACE_SCHEMA_LOADING, "Reading unresolved handles for type system " + _name, 0);
         XsbReader reader = null;
-        try
-        {
+        try {
             // Read the index file, which starts with a header.
             reader = new XsbReader("index", FILETYPE_SCHEMAINDEX);
 
@@ -340,28 +259,24 @@
             List typeNames = new ArrayList();
             List modelGroupNames = new ArrayList();
             List attributeGroupNames = new ArrayList();
-            if (reader.atLeast(2, 15, 0))
-            {
+            if (reader.atLeast(2, 15, 0)) {
                 _redefinedGlobalTypes = reader.readQNameRefMapAsList(typeNames);
                 _redefinedModelGroups = reader.readQNameRefMapAsList(modelGroupNames);
                 _redefinedAttributeGroups = reader.readQNameRefMapAsList(attributeGroupNames);
             }
-            if (reader.atLeast(2, 19, 0))
-            {
+            if (reader.atLeast(2, 19, 0)) {
                 _annotations = reader.readAnnotations();
             }
 
             buildContainers(typeNames, modelGroupNames, attributeGroupNames);
-        }
-        finally
-        {
-            if (reader != null)
+        } finally {
+            if (reader != null) {
                 reader.readEnd();
+            }
         }
     }
 
-    void saveIndex()
-    {
+    void saveIndex() {
         String handle = "index";
         XsbReader saver = new XsbReader(handle);
         saver.writeIndexData();
@@ -370,8 +285,7 @@
         saver.writeEnd();
     }
 
-    void savePointers()
-    {
+    void savePointers() {
         savePointersForComponents(globalElements(), getMetadataPath() + "/element/");
         savePointersForComponents(globalAttributes(), getMetadataPath() + "/attribute/");
         savePointersForComponents(modelGroups(), getMetadataPath() + "/modelgroup/");
@@ -385,34 +299,27 @@
         savePointersForComponents(redefinedGlobalTypes(), getMetadataPath() + "/redefinedtype/");
     }
 
-    void savePointersForComponents(SchemaComponent[] components, String dir)
-    {
-        for (int i = 0; i < components.length; i++)
-        {
+    void savePointersForComponents(SchemaComponent[] components, String dir) {
+        for (int i = 0; i < components.length; i++) {
             savePointerFile(dir + QNameHelper.hexsafedir(components[i].getName()), _name);
         }
     }
 
-    void savePointersForClassnames(Set classnames, String dir)
-    {
-        for (Iterator i = classnames.iterator(); i.hasNext(); )
-        {
-            String classname = (String)i.next();
+    void savePointersForClassnames(Set classnames, String dir) {
+        for (Iterator i = classnames.iterator(); i.hasNext(); ) {
+            String classname = (String) i.next();
             savePointerFile(dir + classname.replace('.', '/'), _name);
         }
     }
 
-    void savePointersForNamespaces(Set namespaces, String dir)
-    {
-        for (Iterator i = namespaces.iterator(); i.hasNext(); )
-        {
-            String ns = (String)i.next();
+    void savePointersForNamespaces(Set namespaces, String dir) {
+        for (Iterator i = namespaces.iterator(); i.hasNext(); ) {
+            String ns = (String) i.next();
             savePointerFile(dir + QNameHelper.hexsafedir(new QName(ns, "xmlns")), _name);
         }
     }
 
-    void savePointerFile(String filename, String name)
-    {
+    void savePointerFile(String filename, String name) {
         XsbReader saver = new XsbReader(filename);
         saver.writeString(name);
         saver.writeRealHeader(filename, FILETYPE_SCHEMAPOINTER);
@@ -427,39 +334,22 @@
      * swap out the utf8 string constants with new ones to create a new
      * TypeSystemHolder class file.  This saves us the need to rely on javac
      * to compile a generated .java file into the class file.
-     *
+     * <p>
      * See the JVM spec on how to interpret the bytes of a class file.
      */
-    void saveLoader()
-    {
+    void saveLoader() {
         String indexClassName = SchemaTypeCodePrinter.indexClassForSystem(this);
         String[] replace = makeClassStrings(indexClassName);
         assert replace.length == HOLDER_TEMPLATE_NAMES.length;
 
-        InputStream is = null;
-        OutputStream os = null;
-
-        DataInputStream in = null;
-        DataOutputStream out = null;
-
         Repackager repackager = null;
-        if (_filer instanceof FilerImpl)
-            repackager = ((FilerImpl)_filer).getRepackager();
+        if (_filer instanceof FilerImpl) {
+            repackager = ((FilerImpl) _filer).getRepackager();
+        }
 
-        try
-        {
-            is = SchemaTypeSystemImpl.class.getResourceAsStream(HOLDER_TEMPLATE_CLASSFILE);
-            if (is == null) {
-                DefaultClassLoaderResourceLoader clLoader = new DefaultClassLoaderResourceLoader();
-                is = clLoader.getResourceAsStream(HOLDER_TEMPLATE_CLASSFILE);
-            }
-            if (is == null) {
-                throw new SchemaTypeLoaderException("couldn't find resource: " + HOLDER_TEMPLATE_CLASSFILE, _name, null, SchemaTypeLoaderException.IO_EXCEPTION);
-            }
-            in = new DataInputStream(is);
-
-            os = _filer.createBinaryFile(indexClassName.replace('.', '/') + ".class");
-            out = new DataOutputStream(os);
+        final String outName = indexClassName.replace('.', '/') + ".class";
+        try (DataInputStream in = new DataInputStream(getHolder());
+             DataOutputStream out = new DataOutputStream(_filer.createBinaryFile(outName))) {
 
             // java magic
             out.writeInt(in.readInt());
@@ -472,13 +362,11 @@
             out.writeShort(poolsize);
 
             // the constant pool is indexed from 1 to poolsize-1
-            for (int i = 1; i < poolsize; i++)
-            {
+            for (int i = 1; i < poolsize; i++) {
                 int tag = in.readUnsignedByte();
                 out.writeByte(tag);
 
-                switch (tag)
-                {
+                switch (tag) {
                     case CONSTANT_UTF8:
                         String value = in.readUTF();
                         out.writeUTF(repackageConstant(value, replace, repackager));
@@ -515,26 +403,40 @@
 
             // we're done with the class' constant pool,
             // we can just copy the rest of the bytes
-            try
-            {
-                while (true)
-                    out.writeByte(in.readByte());
-            }
-            catch (java.io.EOFException e)
-            {
-                // ok
-            }
-
-        }
-        catch (IOException e)
-        {
+            copy(in, out);
+        } catch (IOException e) {
             // ok
+            }
         }
-        finally
-        {
-            if (is != null) try { is.close(); } catch (Exception e) { }
-            if (os != null) try { os.close(); } catch (Exception e) { }
+
+    private InputStream getHolder() {
+        InputStream is = SchemaTypeSystemImpl.class.getResourceAsStream(HOLDER_TEMPLATE_CLASSFILE);
+        if (is != null) {
+            return is;
         }
+        DefaultClassLoaderResourceLoader clLoader = new DefaultClassLoaderResourceLoader();
+        is = clLoader.getResourceAsStream(HOLDER_TEMPLATE_CLASSFILE);
+        if (is != null) {
+            return is;
+        }
+        throw new SchemaTypeLoaderException("couldn't find resource: " + HOLDER_TEMPLATE_CLASSFILE,
+            _name, null, SchemaTypeLoaderException.IO_EXCEPTION);
+    }
+
+    private static long copy(InputStream inp, OutputStream out) throws IOException {
+        final byte[] buff = new byte[4096];
+        long totalCount = 0;
+        int readBytes;
+        do {
+            int todoBytes = buff.length;
+            readBytes = inp.read(buff, 0, todoBytes);
+            if (readBytes > 0) {
+                out.write(buff, 0, readBytes);
+                totalCount += readBytes;
+            }
+        } while (readBytes >= 0);
+
+        return totalCount;
     }
 
     private static final String HOLDER_TEMPLATE_CLASS = "org.apache.xmlbeans.impl.schema.TypeSystemHolder";
@@ -558,14 +460,16 @@
     // MAX_UNSIGNED_SHORT
     private static final int MAX_UNSIGNED_SHORT = Short.MAX_VALUE * 2 + 1;
 
-    private static String repackageConstant(String value, String[] replace, Repackager repackager)
-    {
-        for (int i = 0; i < HOLDER_TEMPLATE_NAMES.length; i++)
-            if (HOLDER_TEMPLATE_NAMES[i].equals(value))
+    private static String repackageConstant(String value, String[] replace, Repackager repackager) {
+        for (int i = 0; i < HOLDER_TEMPLATE_NAMES.length; i++) {
+            if (HOLDER_TEMPLATE_NAMES[i].equals(value)) {
                 return replace[i];
+            }
+        }
 
-        if (repackager != null)
+        if (repackager != null) {
             return repackager.repackage(new StringBuffer(value)).toString();
+        }
 
         return value;
     }
@@ -575,8 +479,7 @@
      * For the class name 'a.b.C' it will generate an array of:
      * 'a.b.C', 'a/b/C', 'La/b/C;', and 'class$a$b$C'.
      */
-    private static String[] makeClassStrings(String classname)
-    {
+    private static String[] makeClassStrings(String classname) {
         String[] result = new String[4];
 
         result[0] = classname;
@@ -590,8 +493,7 @@
     /**
      * Only used in the nonbootstrapped case.
      */
-    private Map buildTypeRefsByClassname()
-    {
+    private Map buildTypeRefsByClassname() {
         List allSeenTypes = new ArrayList();
         Map result = new LinkedHashMap();
         allSeenTypes.addAll(Arrays.asList(documentTypes()));
@@ -599,12 +501,10 @@
         allSeenTypes.addAll(Arrays.asList(globalTypes()));
 
         // now fully javaize everything deeply.
-        for (int i = 0; i < allSeenTypes.size(); i++)
-        {
-            SchemaType gType = (SchemaType)allSeenTypes.get(i);
+        for (int i = 0; i < allSeenTypes.size(); i++) {
+            SchemaType gType = (SchemaType) allSeenTypes.get(i);
             String className = gType.getFullJavaName();
-            if (className != null)
-            {
+            if (className != null) {
                 result.put(className.replace('$', '.'), gType.getRef());
             }
             allSeenTypes.addAll(Arrays.asList(gType.getAnonymousTypes()));
@@ -612,67 +512,61 @@
         return result;
     }
 
-    private Map buildTypeRefsByClassname(Map typesByClassname)
-    {
+    private Map buildTypeRefsByClassname(Map typesByClassname) {
         Map result = new LinkedHashMap();
-        for (Iterator i = typesByClassname.keySet().iterator(); i.hasNext(); )
-        {
-            String className = (String)i.next();
-            result.put(className, ((SchemaType)typesByClassname.get(className)).getRef());
+        for (Iterator i = typesByClassname.keySet().iterator(); i.hasNext(); ) {
+            String className = (String) i.next();
+            result.put(className, ((SchemaType) typesByClassname.get(className)).getRef());
         }
         return result;
     }
 
-    private static Map buildComponentRefMap(SchemaComponent[] components)
-    {
+    private static Map buildComponentRefMap(SchemaComponent[] components) {
         Map result = new LinkedHashMap();
-        for (int i = 0; i < components.length; i++)
+        for (int i = 0; i < components.length; i++) {
             result.put(components[i].getName(), components[i].getComponentRef());
+        }
         return result;
     }
 
-    private static List buildComponentRefList(SchemaComponent[] components)
-    {
+    private static List buildComponentRefList(SchemaComponent[] components) {
         List result = new ArrayList();
-        for (int i = 0; i < components.length; i++)
+        for (int i = 0; i < components.length; i++) {
             result.add(components[i].getComponentRef());
+        }
         return result;
     }
 
-    private static Map buildDocumentMap(SchemaType[] types)
-    {
+    private static Map buildDocumentMap(SchemaType[] types) {
         Map result = new LinkedHashMap();
-        for (int i = 0; i < types.length; i++)
+        for (int i = 0; i < types.length; i++) {
             result.put(types[i].getDocumentElementName(), types[i].getRef());
+        }
         return result;
     }
 
-    private static Map buildAttributeTypeMap(SchemaType[] types)
-    {
+    private static Map buildAttributeTypeMap(SchemaType[] types) {
         Map result = new LinkedHashMap();
-        for (int i = 0; i < types.length; i++)
+        for (int i = 0; i < types.length; i++) {
             result.put(types[i].getAttributeTypeAttributeName(), types[i].getRef());
+        }
         return result;
     }
 
     // Container operation
-    private SchemaContainer getContainer(String namespace)
-    {
+    private SchemaContainer getContainer(String namespace) {
         return (SchemaContainer) _containers.get(namespace);
     }
 
-    private void addContainer(String namespace)
-    {
+    private void addContainer(String namespace) {
         SchemaContainer c = new SchemaContainer(namespace);
         c.setTypeSystem(this);
         _containers.put(namespace, c);
     }
 
-    private SchemaContainer getContainerNonNull(String namespace)
-    {
+    private SchemaContainer getContainerNonNull(String namespace) {
         SchemaContainer result = getContainer(namespace);
-        if (result == null)
-        {
+        if (result == null) {
             addContainer(namespace);
             result = getContainer(namespace);
         }
@@ -680,91 +574,77 @@
     }
 
     // Only called during init
-    private void buildContainers(List redefTypeNames, List redefModelGroupNames, List redefAttributeGroupNames)
-    {
+    private void buildContainers(List redefTypeNames, List redefModelGroupNames, List redefAttributeGroupNames) {
         // This method walks the reference maps and copies said references
         // into the appropriate container
-        for (Iterator it = _globalElements.entrySet().iterator(); it.hasNext(); )
-        {
+        for (Iterator it = _globalElements.entrySet().iterator(); it.hasNext(); ) {
             Map.Entry entry = (Map.Entry) it.next();
             String ns = ((QName) entry.getKey()).getNamespaceURI();
             getContainerNonNull(ns).addGlobalElement((SchemaGlobalElement.Ref) entry.getValue());
         }
-        for (Iterator it = _globalAttributes.entrySet().iterator(); it.hasNext(); )
-        {
+        for (Iterator it = _globalAttributes.entrySet().iterator(); it.hasNext(); ) {
             Map.Entry entry = (Map.Entry) it.next();
             String ns = ((QName) entry.getKey()).getNamespaceURI();
             getContainerNonNull(ns).addGlobalAttribute((SchemaGlobalAttribute.Ref) entry.getValue());
         }
-        for (Iterator it = _modelGroups.entrySet().iterator(); it.hasNext(); )
-        {
+        for (Iterator it = _modelGroups.entrySet().iterator(); it.hasNext(); ) {
             Map.Entry entry = (Map.Entry) it.next();
             String ns = ((QName) entry.getKey()).getNamespaceURI();
             getContainerNonNull(ns).addModelGroup((SchemaModelGroup.Ref) entry.getValue());
         }
-        for (Iterator it = _attributeGroups.entrySet().iterator(); it.hasNext(); )
-        {
+        for (Iterator it = _attributeGroups.entrySet().iterator(); it.hasNext(); ) {
             Map.Entry entry = (Map.Entry) it.next();
             String ns = ((QName) entry.getKey()).getNamespaceURI();
             getContainerNonNull(ns).addAttributeGroup((SchemaAttributeGroup.Ref) entry.getValue());
         }
-        for (Iterator it = _identityConstraints.entrySet().iterator(); it.hasNext(); )
-        {
+        for (Iterator it = _identityConstraints.entrySet().iterator(); it.hasNext(); ) {
             Map.Entry entry = (Map.Entry) it.next();
             String ns = ((QName) entry.getKey()).getNamespaceURI();
             getContainerNonNull(ns).addIdentityConstraint((SchemaIdentityConstraint.Ref) entry.getValue());
         }
-        for (Iterator it = _globalTypes.entrySet().iterator(); it.hasNext(); )
-        {
+        for (Iterator it = _globalTypes.entrySet().iterator(); it.hasNext(); ) {
             Map.Entry entry = (Map.Entry) it.next();
             String ns = ((QName) entry.getKey()).getNamespaceURI();
             getContainerNonNull(ns).addGlobalType((SchemaType.Ref) entry.getValue());
         }
-        for (Iterator it = _documentTypes.entrySet().iterator(); it.hasNext(); )
-        {
+        for (Iterator it = _documentTypes.entrySet().iterator(); it.hasNext(); ) {
             Map.Entry entry = (Map.Entry) it.next();
             String ns = ((QName) entry.getKey()).getNamespaceURI();
             getContainerNonNull(ns).addDocumentType((SchemaType.Ref) entry.getValue());
         }
-        for (Iterator it = _attributeTypes.entrySet().iterator(); it.hasNext(); )
-        {
+        for (Iterator it = _attributeTypes.entrySet().iterator(); it.hasNext(); ) {
             Map.Entry entry = (Map.Entry) it.next();
             String ns = ((QName) entry.getKey()).getNamespaceURI();
             getContainerNonNull(ns).addAttributeType((SchemaType.Ref) entry.getValue());
         }
         // Some earlier .xsb versions don't have records for redefinitions
         if (_redefinedGlobalTypes != null && _redefinedModelGroups != null &&
-            _redefinedAttributeGroups != null)
-        {
+            _redefinedAttributeGroups != null) {
             assert _redefinedGlobalTypes.size() == redefTypeNames.size();
-            for (Iterator it = _redefinedGlobalTypes.iterator(), itname = redefTypeNames.iterator(); it.hasNext(); )
-            {
+            for (Iterator it = _redefinedGlobalTypes.iterator(), itname = redefTypeNames.iterator(); it.hasNext(); ) {
                 String ns = ((QName) itname.next()).getNamespaceURI();
                 getContainerNonNull(ns).addRedefinedType((SchemaType.Ref) it.next());
             }
-            for (Iterator it = _redefinedModelGroups.iterator(), itname = redefModelGroupNames.iterator(); it.hasNext(); )
-            {
+            for (Iterator it = _redefinedModelGroups.iterator(), itname = redefModelGroupNames.iterator(); it.hasNext(); ) {
                 String ns = ((QName) itname.next()).getNamespaceURI();
                 getContainerNonNull(ns).addRedefinedModelGroup((SchemaModelGroup.Ref) it.next());
             }
-            for (Iterator it = _redefinedAttributeGroups.iterator(), itname = redefAttributeGroupNames.iterator(); it.hasNext(); )
-            {
+            for (Iterator it = _redefinedAttributeGroups.iterator(), itname = redefAttributeGroupNames.iterator(); it.hasNext(); ) {
                 String ns = ((QName) itname.next()).getNamespaceURI();
                 getContainerNonNull(ns).addRedefinedAttributeGroup((SchemaAttributeGroup.Ref) it.next());
             }
         }
         // Some earlier .xsb versions don't have records for annotations
-        if (_annotations != null)
-        {
-            for (Iterator it = _annotations.iterator(); it.hasNext(); )
-            {
+        if (_annotations != null) {
+            for (Iterator it = _annotations.iterator(); it.hasNext(); ) {
                 SchemaAnnotation ann = (SchemaAnnotation) it.next();
                 // BUGBUG(radup)
                 getContainerNonNull("").addAnnotation(ann);
             }
         }
-        for (Iterator it = _containers.values().iterator(); it.hasNext(); )
+        for (Iterator it = _containers.values().iterator(); it.hasNext(); ) {
             ((SchemaContainer) it.next()).setImmutable();
+        }
     }
 
     /**
@@ -775,88 +655,99 @@
      * effect all components now indirectly pointing to this typesystem
      * even though they (as well as the typesystem itself) are immutable.
      */
-    private void fixupContainers()
-    {
-        for (Iterator it = _containers.values().iterator(); it.hasNext(); )
-        {
+    private void fixupContainers() {
+        for (Iterator it = _containers.values().iterator(); it.hasNext(); ) {
             SchemaContainer container = (SchemaContainer) it.next();
             container.setTypeSystem(this);
             container.setImmutable();
         }
     }
 
-    private void assertContainersSynchronized()
-    {
+    private void assertContainersSynchronized() {
         boolean assertEnabled = false;
         // This code basically checks whether asserts are enabled so we don't do
         // all the work if they arent
         assert assertEnabled = true;
-        if (!assertEnabled)
+        if (!assertEnabled) {
             return;
+        }
         // global elements
         Map temp = new HashMap();
-        for (Iterator it = _containers.values().iterator(); it.hasNext(); )
+        for (Iterator it = _containers.values().iterator(); it.hasNext(); ) {
             temp.putAll(buildComponentRefMap((SchemaComponent[]) ((SchemaContainer) it.next()).globalElements().toArray(new SchemaComponent[0])));
+        }
         assert _globalElements.equals(temp);
         // global attributes
         temp = new HashMap();
-        for (Iterator it = _containers.values().iterator(); it.hasNext(); )
+        for (Iterator it = _containers.values().iterator(); it.hasNext(); ) {
             temp.putAll(buildComponentRefMap((SchemaComponent[]) ((SchemaContainer) it.next()).globalAttributes().toArray(new SchemaComponent[0])));
+        }
         assert _globalAttributes.equals(temp);
         // model groups
         temp = new HashMap();
-        for (Iterator it = _containers.values().iterator(); it.hasNext(); )
+        for (Iterator it = _containers.values().iterator(); it.hasNext(); ) {
             temp.putAll(buildComponentRefMap((SchemaComponent[]) ((SchemaContainer) it.next()).modelGroups().toArray(new SchemaComponent[0])));
+        }
         assert _modelGroups.equals(temp);
         // redefined model groups
         Set temp2 = new HashSet();
-        for (Iterator it = _containers.values().iterator(); it.hasNext(); )
+        for (Iterator it = _containers.values().iterator(); it.hasNext(); ) {
             temp2.addAll(buildComponentRefList((SchemaComponent[]) ((SchemaContainer) it.next()).redefinedModelGroups().toArray(new SchemaComponent[0])));
+        }
         assert new HashSet(_redefinedModelGroups).equals(temp2);
         // attribute groups
         temp = new HashMap();
-        for (Iterator it = _containers.values().iterator(); it.hasNext(); )
+        for (Iterator it = _containers.values().iterator(); it.hasNext(); ) {
             temp.putAll(buildComponentRefMap((SchemaComponent[]) ((SchemaContainer) it.next()).attributeGroups().toArray(new SchemaComponent[0])));
+        }
         assert _attributeGroups.equals(temp);
         // redefined attribute groups
         temp2 = new HashSet();
-        for (Iterator it = _containers.values().iterator(); it.hasNext(); )
+        for (Iterator it = _containers.values().iterator(); it.hasNext(); ) {
             temp2.addAll(buildComponentRefList((SchemaComponent[]) ((SchemaContainer) it.next()).redefinedAttributeGroups().toArray(new SchemaComponent[0])));
+        }
         assert new HashSet(_redefinedAttributeGroups).equals(temp2);
         // global types
         temp = new HashMap();
-        for (Iterator it = _containers.values().iterator(); it.hasNext(); )
+        for (Iterator it = _containers.values().iterator(); it.hasNext(); ) {
             temp.putAll(buildComponentRefMap((SchemaComponent[]) ((SchemaContainer) it.next()).globalTypes().toArray(new SchemaComponent[0])));
+        }
         assert _globalTypes.equals(temp);
         // redefined global types
         temp2 = new HashSet();
-        for (Iterator it = _containers.values().iterator(); it.hasNext(); )
+        for (Iterator it = _containers.values().iterator(); it.hasNext(); ) {
             temp2.addAll(buildComponentRefList((SchemaComponent[]) ((SchemaContainer) it.next()).redefinedGlobalTypes().toArray(new SchemaComponent[0])));
+        }
         assert new HashSet(_redefinedGlobalTypes).equals(temp2);
         // document types
         temp = new HashMap();
-        for (Iterator it = _containers.values().iterator(); it.hasNext(); )
+        for (Iterator it = _containers.values().iterator(); it.hasNext(); ) {
             temp.putAll(buildDocumentMap((SchemaType[]) ((SchemaContainer) it.next()).documentTypes().toArray(new SchemaType[0])));
+        }
         assert _documentTypes.equals(temp);
         // attribute types
         temp = new HashMap();
-        for (Iterator it = _containers.values().iterator(); it.hasNext(); )
+        for (Iterator it = _containers.values().iterator(); it.hasNext(); ) {
             temp.putAll(buildAttributeTypeMap((SchemaType[]) ((SchemaContainer) it.next()).attributeTypes().toArray(new SchemaType[0])));
+        }
         assert _attributeTypes.equals(temp);
         // identity constraints
         temp = new HashMap();
-        for (Iterator it = _containers.values().iterator(); it.hasNext(); )
+        for (Iterator it = _containers.values().iterator(); it.hasNext(); ) {
             temp.putAll(buildComponentRefMap((SchemaComponent[]) ((SchemaContainer) it.next()).identityConstraints().toArray(new SchemaComponent[0])));
+        }
         assert _identityConstraints.equals(temp);
         // annotations
         temp2 = new HashSet();
-        for (Iterator it = _containers.values().iterator(); it.hasNext(); )
+        for (Iterator it = _containers.values().iterator(); it.hasNext(); ) {
             temp2.addAll(((SchemaContainer) it.next()).annotations());
+        }
         assert new HashSet(_annotations).equals(temp2);
         // namespaces
         temp2 = new HashSet();
-        for (Iterator it = _containers.values().iterator(); it.hasNext(); )
+        for (Iterator it = _containers.values().iterator(); it.hasNext(); ) {
             temp2.add(((SchemaContainer) it.next()).getNamespace());
+        }
         assert _namespaces.equals(temp2);
     }
 
@@ -868,11 +759,11 @@
      * We used to use SecureRandom, but now we don't because SecureRandom
      * hits the filesystem and hangs us on a filesystem lock.  It also eats
      * a thread and other expensive resources.. :-).
-     *
+     * <p>
      * We don't really care that non-secure Random() can only do 48 bits of
      * randomness, since we're certainly not going to be called more than 2^48
      * times within our process lifetime.
-     *
+     * <p>
      * Our real concern is that by seeding Random() with the current
      * time, two users will end up with the same bits if they start a
      * schema compilation within the same millisecond.  That makes the
@@ -880,7 +771,7 @@
      * We're going to have millions of users, remember?  With a million
      * users, and one-compilation-per-day each, we'd see a collision every
      * few months.
-     *
+     * <p>
      * So we'll just xor the results of random with our few extra
      * bits of information computed below to help reduce the probability
      * of collision by a few decimal places.  To collide, you will have had
@@ -891,23 +782,18 @@
      * millisecond. Or you can collide if you have a cosmic 128-bit mathematical
      * coincidence. No worries.
      */
-    private static synchronized void nextBytes(byte[] result)
-    {
-        if (_random == null)
-        {
-            try
-            {
+    private static synchronized void nextBytes(byte[] result) {
+        if (_random == null) {
+            try {
                 ByteArrayOutputStream baos = new ByteArrayOutputStream();
                 DataOutputStream daos = new DataOutputStream(baos);
 
                 // at least 10 bits of unqieueness, right?  Maybe even 50 or 60.
                 daos.writeInt(System.identityHashCode(SchemaTypeSystemImpl.class));
-                String[] props = new String[] { "user.name", "user.dir", "user.timezone", "user.country", "java.class.path", "java.home", "java.vendor", "java.version", "os.version" };
-                for (int i = 0; i < props.length; i++)
-                {
+                String[] props = new String[]{"user.name", "user.dir", "user.timezone", "user.country", "java.class.path", "java.home", "java.vendor", "java.version", "os.version"};
+                for (int i = 0; i < props.length; i++) {
                     String prop = SystemProperties.getProperty(props[i]);
-                    if (prop != null)
-                    {
+                    if (prop != null) {
                         daos.writeUTF(prop);
                         daos.writeInt(System.identityHashCode(prop));
                     }
@@ -915,23 +801,19 @@
                 daos.writeLong(Runtime.getRuntime().freeMemory());
                 daos.close();
                 byte[] bytes = baos.toByteArray();
-                for (int i = 0; i < bytes.length; i++)
-                {
+                for (int i = 0; i < bytes.length; i++) {
                     int j = i % _mask.length;
                     _mask[j] *= 21;
                     _mask[j] += i;
                 }
-            }
-            catch (IOException e)
-            {
+            } catch (IOException e) {
                 XBeanDebug.logException(e);
             }
 
             _random = new Random(System.currentTimeMillis());
         }
         _random.nextBytes(result);
-        for (int i = 0; i < result.length; i++)
-        {
+        for (int i = 0; i < result.length; i++) {
             int j = i & _mask.length;
             result[i] ^= _mask[j];
         }
@@ -939,15 +821,14 @@
 
     public SchemaTypeSystemImpl(String nameForSystem) {
         // if we have no name, select a random one
-        if (nameForSystem == null)
-        {
+        if (nameForSystem == null) {
             // get 128 random bits (that'll be 32 hex digits)
-            byte[] bytes = new byte[128/8];
+            byte[] bytes = new byte[128 / 8];
             nextBytes(bytes);
             nameForSystem = "s" + new String(HexBin.encode(bytes));
         }
 
-        _name = SchemaTypeSystemImpl.METADATA_PACKAGE_GEN.replace('/','.') + ".system." + nameForSystem;
+        _name = SchemaTypeSystemImpl.METADATA_PACKAGE_GEN.replace('/', '.') + ".system." + nameForSystem;
         _basePackage = nameToPathString(_name);
         _classloader = null;
     }
@@ -956,9 +837,8 @@
                                 SchemaGlobalAttribute[] globalAttributes,
                                 SchemaType[] globalTypes,
                                 SchemaType[] documentTypes,
-                                SchemaType[] attributeTypes)
-    {
-        assert(_classloader == null);
+                                SchemaType[] attributeTypes) {
+        assert (_classloader == null);
         _localHandles = new HandlePool();
         _globalElements = buildComponentRefMap(globalElements);
         _globalAttributes = buildComponentRefMap(globalAttributes);
@@ -971,9 +851,8 @@
         _namespaces = new HashSet();
     }
 
-    public void loadFromStscState(StscState state)
-    {
-        assert(_classloader == null);
+    public void loadFromStscState(StscState state) {
+        assert (_classloader == null);
         _localHandles = new HandlePool();
         _globalElements = buildComponentRefMap(state.globalElements());
         _globalAttributes = buildComponentRefMap(state.globalAttributes());
@@ -996,25 +875,29 @@
         setDependencies(state.getDependencies());
     }
 
-    final SchemaTypeSystemImpl getTypeSystem()
-    {
+    final SchemaTypeSystemImpl getTypeSystem() {
         return this;
     }
 
-    void setDependencies(SchemaDependencies deps)
-    {   _deps = deps; }
+    void setDependencies(SchemaDependencies deps) {
+        _deps = deps;
+    }
 
-    SchemaDependencies getDependencies()
-    {   return _deps; }
+    SchemaDependencies getDependencies() {
+        return _deps;
+    }
 
     // EXPERIMENTAL
-    public boolean isIncomplete() { return _incomplete; }
+    public boolean isIncomplete() {
+        return _incomplete;
+    }
 
     // EXPERIMENTAL
-    void setIncomplete(boolean incomplete) { _incomplete = incomplete; }
+    void setIncomplete(boolean incomplete) {
+        _incomplete = incomplete;
+    }
 
-    static class StringPool
-    {
+    static class StringPool {
         private List intsToStrings = new ArrayList();
         private Map stringsToInts = new HashMap();
         private String _handle;
@@ -1023,20 +906,18 @@
         /**
          * Constructs an empty StringPool to be filled with strings.
          */
-        StringPool(String handle, String name)
-        {
+        StringPool(String handle, String name) {
             _handle = handle;
             _name = name;
             intsToStrings.add(null);
         }
 
-        int codeForString(String str)
-        {
-            if (str == null)
+        int codeForString(String str) {
+            if (str == null) {
                 return 0;
-            Integer result = (Integer)stringsToInts.get(str);
-            if (result == null)
-            {
+            }
+            Integer result = (Integer) stringsToInts.get(str);
+            if (result == null) {
                 result = new Integer(intsToStrings.size());
                 intsToStrings.add(str);
                 stringsToInts.put(str, result);
@@ -1044,59 +925,51 @@
             return result.intValue();
         }
 
-        String stringForCode(int code)
-        {
-            if (code == 0)
+        String stringForCode(int code) {
+            if (code == 0) {
                 return null;
-            return (String)intsToStrings.get(code);
+            }
+            return (String) intsToStrings.get(code);
         }
 
-        void writeTo(DataOutputStream output)
-        {
-            if (intsToStrings.size() >= MAX_UNSIGNED_SHORT)
+        void writeTo(DataOutputStream output) {
+            if (intsToStrings.size() >= MAX_UNSIGNED_SHORT) {
                 throw new SchemaTypeLoaderException("Too many strings (" + intsToStrings.size() + ")", _name, _handle, SchemaTypeLoaderException.INT_TOO_LARGE);
+            }
 
-            try
-            {
+            try {
                 output.writeShort(intsToStrings.size());
                 Iterator i = intsToStrings.iterator();
-                for (i.next(); i.hasNext(); )
-                {
-                    String str = (String)i.next();
+                for (i.next(); i.hasNext(); ) {
+                    String str = (String) i.next();
                     output.writeUTF(str);
                 }
-            }
-            catch (IOException e)
-            {
-                throw new SchemaTypeLoaderException(e.getMessage(), _name, _handle, SchemaTypeLoaderException.IO_EXCEPTION);
+            } catch (IOException e) {
+                throw new SchemaTypeLoaderException(e.getMessage(), _name, _handle, SchemaTypeLoaderException.IO_EXCEPTION, e);
             }
         }
 
-        void readFrom(DataInputStream input)
-        {
-            if (intsToStrings.size() != 1 || stringsToInts.size() != 0)
+        void readFrom(DataInputStream input) {
+            if (intsToStrings.size() != 1 || stringsToInts.size() != 0) {
                 throw new IllegalStateException();
+            }
 
-            try
-            {
+            try {
                 int size = input.readUnsignedShort();
-                for (int i = 1; i < size; i++)
-                {
+                for (int i = 1; i < size; i++) {
                     String str = input.readUTF().intern();
                     int code = codeForString(str);
-                    if (code != i)
+                    if (code != i) {
                         throw new IllegalStateException();
+                    }
                 }
-            }
-            catch (IOException e)
-            {
+            } catch (IOException e) {
                 throw new SchemaTypeLoaderException(e.getMessage() == null ? e.getMessage() : "IO Exception", _name, _handle, SchemaTypeLoaderException.IO_EXCEPTION, e);
             }
         }
     }
 
-    class HandlePool
-    {
+    class HandlePool {
         private Map _handlesToRefs = new LinkedHashMap();
         private Map _componentsToHandles = new LinkedHashMap(); // populated on write
         private boolean _started;
@@ -1104,16 +977,13 @@
         /**
          * Constructs an empty HandlePool to be populated.
          */
-        HandlePool()
-        {
+        HandlePool() {
         }
 
-        private String addUniqueHandle(SchemaComponent obj, String base)
-        {
+        private String addUniqueHandle(SchemaComponent obj, String base) {
             base = base.toLowerCase();  // we lowercase handles because of case-insensitive Windows filenames!!!
             String handle = base;
-            for (int index = 2; _handlesToRefs.containsKey(handle); index++)
-            {
+            for (int index = 2; _handlesToRefs.containsKey(handle); index++) {
                 handle = base + index;
             }
             _handlesToRefs.put(handle, obj.getComponentRef());
@@ -1121,112 +991,123 @@
             return handle;
         }
 
-        String handleForComponent(SchemaComponent comp)
-        {
-            if (comp == null)
+        String handleForComponent(SchemaComponent comp) {
+            if (comp == null) {
                 return null;
-            if (comp.getTypeSystem() != getTypeSystem())
+            }
+            if (comp.getTypeSystem() != getTypeSystem()) {
                 throw new IllegalArgumentException("Cannot supply handles for types from another type system");
-            if (comp instanceof SchemaType)
-                return handleForType((SchemaType)comp);
-            if (comp instanceof SchemaGlobalElement)
-                return handleForElement((SchemaGlobalElement)comp);
-            if (comp instanceof SchemaGlobalAttribute)
-                return handleForAttribute((SchemaGlobalAttribute)comp);
-            if (comp instanceof SchemaModelGroup)
-                return handleForModelGroup((SchemaModelGroup)comp);
-            if (comp instanceof SchemaAttributeGroup)
-                return handleForAttributeGroup((SchemaAttributeGroup)comp);
-            if (comp instanceof SchemaIdentityConstraint)
-                return handleForIdentityConstraint((SchemaIdentityConstraint)comp);
+            }
+            if (comp instanceof SchemaType) {
+                return handleForType((SchemaType) comp);
+            }
+            if (comp instanceof SchemaGlobalElement) {
+                return handleForElement((SchemaGlobalElement) comp);
+            }
+            if (comp instanceof SchemaGlobalAttribute) {
+                return handleForAttribute((SchemaGlobalAttribute) comp);
+            }
+            if (comp instanceof SchemaModelGroup) {
+                return handleForModelGroup((SchemaModelGroup) comp);
+            }
+            if (comp instanceof SchemaAttributeGroup) {
+                return handleForAttributeGroup((SchemaAttributeGroup) comp);
+            }
+            if (comp instanceof SchemaIdentityConstraint) {
+                return handleForIdentityConstraint((SchemaIdentityConstraint) comp);
+            }
             throw new IllegalStateException("Component type cannot have a handle");
         }
 
-        String handleForElement(SchemaGlobalElement element)
-        {
-            if (element == null)
+        String handleForElement(SchemaGlobalElement element) {
+            if (element == null) {
                 return null;
-            if (element.getTypeSystem() != getTypeSystem())
+            }
+            if (element.getTypeSystem() != getTypeSystem()) {
                 throw new IllegalArgumentException("Cannot supply handles for types from another type system");
-            String handle = (String)_componentsToHandles.get(element);
-            if (handle == null)
+            }
+            String handle = (String) _componentsToHandles.get(element);
+            if (handle == null) {
                 handle = addUniqueHandle(element, NameUtil.upperCamelCase(element.getName().getLocalPart()) + "Element");
+            }
             return handle;
         }
 
-        String handleForAttribute(SchemaGlobalAttribute attribute)
-        {
-            if (attribute == null)
+        String handleForAttribute(SchemaGlobalAttribute attribute) {
+            if (attribute == null) {
                 return null;
-            if (attribute.getTypeSystem() != getTypeSystem())
+            }
+            if (attribute.getTypeSystem() != getTypeSystem()) {
                 throw new IllegalArgumentException("Cannot supply handles for types from another type system");
-            String handle = (String)_componentsToHandles.get(attribute);
-            if (handle == null)
+            }
+            String handle = (String) _componentsToHandles.get(attribute);
+            if (handle == null) {
                 handle = addUniqueHandle(attribute, NameUtil.upperCamelCase(attribute.getName().getLocalPart()) + "Attribute");
+            }
             return handle;
         }
 
-        String handleForModelGroup(SchemaModelGroup group)
-        {
-            if (group == null)
+        String handleForModelGroup(SchemaModelGroup group) {
+            if (group == null) {
                 return null;
-            if (group.getTypeSystem() != getTypeSystem())
+            }
+            if (group.getTypeSystem() != getTypeSystem()) {
                 throw new IllegalArgumentException("Cannot supply handles for types from another type system");
-            String handle = (String)_componentsToHandles.get(group);
-            if (handle == null)
+            }
+            String handle = (String) _componentsToHandles.get(group);
+            if (handle == null) {
                 handle = addUniqueHandle(group, NameUtil.upperCamelCase(group.getName().getLocalPart()) + "ModelGroup");
+            }
             return handle;
         }
 
-        String handleForAttributeGroup(SchemaAttributeGroup group)
-        {
-            if (group == null)
+        String handleForAttributeGroup(SchemaAttributeGroup group) {
+            if (group == null) {
                 return null;
-            if (group.getTypeSystem() != getTypeSystem())
+            }
+            if (group.getTypeSystem() != getTypeSystem()) {
                 throw new IllegalArgumentException("Cannot supply handles for types from another type system");
-            String handle = (String)_componentsToHandles.get(group);
-            if (handle == null)
+            }
+            String handle = (String) _componentsToHandles.get(group);
+            if (handle == null) {
                 handle = addUniqueHandle(group, NameUtil.upperCamelCase(group.getName().getLocalPart()) + "AttributeGroup");
+            }
             return handle;
         }
 
-        String handleForIdentityConstraint(SchemaIdentityConstraint idc)
-        {
-            if (idc == null)
+        String handleForIdentityConstraint(SchemaIdentityConstraint idc) {
+            if (idc == null) {
                 return null;
-            if (idc.getTypeSystem() != getTypeSystem())
+            }
+            if (idc.getTypeSystem() != getTypeSystem()) {
                 throw new IllegalArgumentException("Cannot supply handles for types from another type system");
-            String handle = (String)_componentsToHandles.get(idc);
-            if (handle == null)
+            }
+            String handle = (String) _componentsToHandles.get(idc);
+            if (handle == null) {
                 handle = addUniqueHandle(idc, NameUtil.upperCamelCase(idc.getName().getLocalPart()) + "IdentityConstraint");
+            }
             return handle;
         }
 
-        String handleForType(SchemaType type)
-        {
-            if (type == null)
+        String handleForType(SchemaType type) {
+            if (type == null) {
                 return null;
-            if (type.getTypeSystem() != getTypeSystem())
+            }
+            if (type.getTypeSystem() != getTypeSystem()) {
                 throw new IllegalArgumentException("Cannot supply handles for types from another type system");
-            String handle = (String)_componentsToHandles.get(type);
-            if (handle == null)
-            {
+            }
+            String handle = (String) _componentsToHandles.get(type);
+            if (handle == null) {
                 QName name = type.getName();
                 String suffix = "";
-                if (name == null)
-                {
-                    if (type.isDocumentType())
-                    {
+                if (name == null) {
+                    if (type.isDocumentType()) {
                         name = type.getDocumentElementName();
                         suffix = "Doc";
-                    }
-                    else if (type.isAttributeType())
-                    {
+                    } else if (type.isAttributeType()) {
                         name = type.getAttributeTypeAttributeName();
                         suffix = "AttrType";
-                    }
-                    else if (type.getContainerField() != null)
-                    {
+                    } else if (type.getContainerField() != null) {
                         name = type.getContainerField().getName();
                         suffix = type.getContainerField().isAttribute() ? "Attr" : "Elem";
                     }
@@ -1234,10 +1115,11 @@
 
                 String baseName;
                 String uniq = Integer.toHexString(type.toString().hashCode() | 0x80000000).substring(4).toUpperCase();
-                if (name == null)
+                if (name == null) {
                     baseName = "Anon" + uniq + "Type";
-                else
+                } else {
                     baseName = NameUtil.upperCamelCase(name.getLocalPart()) + uniq + suffix + "Type";
+                }
 
                 handle = addUniqueHandle(type, baseName);
             }
@@ -1245,28 +1127,25 @@
             return handle;
         }
 
-        SchemaComponent.Ref refForHandle(String handle)
-        {
-            if (handle == null)
+        SchemaComponent.Ref refForHandle(String handle) {
+            if (handle == null) {
                 return null;
+            }
 
-            return (SchemaComponent.Ref)_handlesToRefs.get(handle);
+            return (SchemaComponent.Ref) _handlesToRefs.get(handle);
         }
 
-        Set getAllHandles()
-        {
+        Set getAllHandles() {
             return _handlesToRefs.keySet();
         }
 
-        void startWriteMode()
-        {
+        void startWriteMode() {
             _started = true;
             _componentsToHandles = new LinkedHashMap();
-            for (Iterator i = _handlesToRefs.keySet().iterator(); i.hasNext(); )
-            {
-                String handle = (String)i.next();
+            for (Iterator i = _handlesToRefs.keySet().iterator(); i.hasNext(); ) {
+                String handle = (String) i.next();
 //                System.err.println("Writing preexisting handle " + handle);
-                SchemaComponent comp = ((SchemaComponent.Ref)_handlesToRefs.get(handle)).getComponent();
+                SchemaComponent comp = ((SchemaComponent.Ref) _handlesToRefs.get(handle)).getComponent();
                 _componentsToHandles.put(comp, handle);
             }
         }
@@ -1323,18 +1202,18 @@
     static private final SchemaIdentityConstraint[] EMPTY_IC_ARRAY = new SchemaIdentityConstraint[0];
     static private final SchemaAnnotation[] EMPTY_ANN_ARRAY = new SchemaAnnotation[0];
 
-    public void saveToDirectory(File classDir)
-    {
+    public void saveToDirectory(File classDir) {
         save(new FilerImpl(classDir, null, null, false, false));
     }
 
-    public void save(Filer filer)
-    {
-        if (_incomplete)
+    public void save(Filer filer) {
+        if (_incomplete) {
             throw new IllegalStateException("Incomplete SchemaTypeSystems cannot be saved.");
+        }
 
-        if (filer == null)
+        if (filer == null) {
             throw new IllegalArgumentException("filer must not be null");
+        }
         _filer = filer;
 
         _localHandles.startWriteMode();
@@ -1357,85 +1236,79 @@
         saveLoader();
     }
 
-    void saveTypesRecursively(SchemaType[] types)
-    {
-        for (int i = 0; i < types.length; i++)
-        {
-            if (types[i].getTypeSystem() != getTypeSystem())
+    void saveTypesRecursively(SchemaType[] types) {
+        for (int i = 0; i < types.length; i++) {
+            if (types[i].getTypeSystem() != getTypeSystem()) {
                 continue;
+            }
             saveType(types[i]);
             saveTypesRecursively(types[i].getAnonymousTypes());
         }
     }
 
-    public void saveGlobalElements(SchemaGlobalElement[] elts)
-    {
-        if (_incomplete)
+    public void saveGlobalElements(SchemaGlobalElement[] elts) {
+        if (_incomplete) {
             throw new IllegalStateException("This SchemaTypeSystem cannot be saved.");
-        for (int i = 0; i < elts.length; i++)
-        {
+        }
+        for (int i = 0; i < elts.length; i++) {
             saveGlobalElement(elts[i]);
         }
     }
 
-    public void saveGlobalAttributes(SchemaGlobalAttribute[] attrs)
-    {
-        if (_incomplete)
+    public void saveGlobalAttributes(SchemaGlobalAttribute[] attrs) {
+        if (_incomplete) {
             throw new IllegalStateException("This SchemaTypeSystem cannot be saved.");
-        for (int i = 0; i < attrs.length; i++)
-        {
+        }
+        for (int i = 0; i < attrs.length; i++) {
             saveGlobalAttribute(attrs[i]);
         }
     }
 
-    public void saveModelGroups(SchemaModelGroup[] groups)
-    {
-        if (_incomplete)
+    public void saveModelGroups(SchemaModelGroup[] groups) {
+        if (_incomplete) {
             throw new IllegalStateException("This SchemaTypeSystem cannot be saved.");
-        for (int i = 0; i < groups.length; i++)
-        {
+        }
+        for (int i = 0; i < groups.length; i++) {
             saveModelGroup(groups[i]);
         }
     }
 
-    public void saveAttributeGroups(SchemaAttributeGroup[] groups)
-    {
-        if (_incomplete)
+    public void saveAttributeGroups(SchemaAttributeGroup[] groups) {
+        if (_incomplete) {
             throw new IllegalStateException("This SchemaTypeSystem cannot be saved.");
-        for (int i = 0; i < groups.length; i++)
-        {
+        }
+        for (int i = 0; i < groups.length; i++) {
             saveAttributeGroup(groups[i]);
         }
     }
 
-    public void saveIdentityConstraints(SchemaIdentityConstraint[] idcs)
-    {
-        if (_incomplete)
+    public void saveIdentityConstraints(SchemaIdentityConstraint[] idcs) {
+        if (_incomplete) {
             throw new IllegalStateException("This SchemaTypeSystem cannot be saved.");
-        for (int i = 0; i < idcs.length; i++)
-        {
+        }
+        for (int i = 0; i < idcs.length; i++) {
             saveIdentityConstraint(idcs[i]);
         }
     }
 
-    public void saveGlobalElement(SchemaGlobalElement elt)
-    {
-        if (_incomplete)
+    public void saveGlobalElement(SchemaGlobalElement elt) {
+        if (_incomplete) {
             throw new IllegalStateException("This SchemaTypeSystem cannot be saved.");
+        }
         String handle = _localHandles.handleForElement(elt);
         XsbReader saver = new XsbReader(handle);
-        saver.writeParticleData((SchemaParticle)elt);
+        saver.writeParticleData((SchemaParticle) elt);
         saver.writeString(elt.getSourceName());
         saver.writeRealHeader(handle, FILETYPE_SCHEMAELEMENT);
-        saver.writeParticleData((SchemaParticle)elt);
+        saver.writeParticleData((SchemaParticle) elt);
         saver.writeString(elt.getSourceName());
         saver.writeEnd();
     }
 
-    public void saveGlobalAttribute(SchemaGlobalAttribute attr)
-    {
-        if (_incomplete)
+    public void saveGlobalAttribute(SchemaGlobalAttribute attr) {
+        if (_incomplete) {
             throw new IllegalStateException("This SchemaTypeSystem cannot be saved.");
+        }
         String handle = _localHandles.handleForAttribute(attr);
         XsbReader saver = new XsbReader(handle);
         saver.writeAttributeData(attr);
@@ -1446,10 +1319,10 @@
         saver.writeEnd();
     }
 
-    public void saveModelGroup(SchemaModelGroup grp)
-    {
-        if (_incomplete)
+    public void saveModelGroup(SchemaModelGroup grp) {
+        if (_incomplete) {
             throw new IllegalStateException("This SchemaTypeSystem cannot be saved.");
+        }
         String handle = _localHandles.handleForModelGroup(grp);
         XsbReader saver = new XsbReader(handle);
         saver.writeModelGroupData(grp);
@@ -1458,10 +1331,10 @@
         saver.writeEnd();
     }
 
-    public void saveAttributeGroup(SchemaAttributeGroup grp)
-    {
-        if (_incomplete)
+    public void saveAttributeGroup(SchemaAttributeGroup grp) {
+        if (_incomplete) {
             throw new IllegalStateException("This SchemaTypeSystem cannot be saved.");
+        }
         String handle = _localHandles.handleForAttributeGroup(grp);
         XsbReader saver = new XsbReader(handle);
         saver.writeAttributeGroupData(grp);
@@ -1470,10 +1343,10 @@
         saver.writeEnd();
     }
 
-    public void saveIdentityConstraint(SchemaIdentityConstraint idc)
-    {
-        if (_incomplete)
+    public void saveIdentityConstraint(SchemaIdentityConstraint idc) {
+        if (_incomplete) {
             throw new IllegalStateException("This SchemaTypeSystem cannot be saved.");
+        }
         String handle = _localHandles.handleForIdentityConstraint(idc);
         XsbReader saver = new XsbReader(handle);
         saver.writeIdConstraintData(idc);
@@ -1482,8 +1355,7 @@
         saver.writeEnd();
     }
 
-    void saveType(SchemaType type)
-    {
+    void saveType(SchemaType type) {
         String handle = _localHandles.handleForType(type);
         XsbReader saver = new XsbReader(handle);
         saver.writeTypeData(type);
@@ -1492,51 +1364,53 @@
         saver.writeEnd();
     }
 
-    public static String crackPointer(InputStream stream)
-    {
+    public static String crackPointer(InputStream stream) {
         DataInputStream input = null;
-        try
-        {
+        try {
             input = new DataInputStream(stream);
 
             int magic = input.readInt();
-            if (magic != DATA_BABE)
+            if (magic != DATA_BABE) {
                 return null;
+            }
 
             int majorver = input.readShort();
             int minorver = input.readShort();
 
-            if (majorver != MAJOR_VERSION)
+            if (majorver != MAJOR_VERSION) {
                 return null;
+            }
 
-            if (minorver > MINOR_VERSION)
+            if (minorver > MINOR_VERSION) {
                 return null;
+            }
 
-            if (majorver > 2 || majorver == 2 && minorver >= 18)
+            if (majorver > 2 || majorver == 2 && minorver >= 18) {
                 input.readShort(); // release number present in atLeast(2, 18, 0)
+            }
 
             int actualfiletype = input.readShort();
-            if (actualfiletype != FILETYPE_SCHEMAPOINTER)
+            if (actualfiletype != FILETYPE_SCHEMAPOINTER) {
                 return null;
+            }
 
             StringPool stringPool = new StringPool("pointer", "unk");
             stringPool.readFrom(input);
 
             return stringPool.stringForCode(input.readShort());
-        }
-        catch (IOException e)
-        {
+        } catch (IOException e) {
             return null;
-        }
-        finally
-        {
-            if (input != null)
-                try { input.close(); } catch (IOException e) {}
+        } finally {
+            if (input != null) {
+                try {
+                    input.close();
+                } catch (IOException e) {
+                }
+            }
         }
     }
 
-    private class XsbReader
-    {
+    private class XsbReader {
         DataInputStream _input;
         DataOutputStream _output;
         StringPool _stringPool;
@@ -1546,42 +1420,48 @@
         private int _releaseno;
         int _actualfiletype;
 
-        public XsbReader(String handle, int filetype)
-        {
+        public XsbReader(String handle, int filetype) {
             String resourcename = _basePackage + handle + ".xsb";
             InputStream rawinput = getLoaderStream(resourcename);
-            if (rawinput == null)
+            if (rawinput == null) {
                 throw new SchemaTypeLoaderException("XML-BEANS compiled schema: Could not locate compiled schema resource " + resourcename, _name, handle, SchemaTypeLoaderException.NO_RESOURCE);
+            }
 
             _input = new DataInputStream(rawinput);
             _handle = handle;
 
             int magic = readInt();
-            if (magic != DATA_BABE)
+            if (magic != DATA_BABE) {
                 throw new SchemaTypeLoaderException("XML-BEANS compiled schema: Wrong magic cookie", _name, handle, SchemaTypeLoaderException.WRONG_MAGIC_COOKIE);
+            }
 
             _majorver = readShort();
             _minorver = readShort();
 
-            if (_majorver != MAJOR_VERSION)
+            if (_majorver != MAJOR_VERSION) {
                 throw new SchemaTypeLoaderException("XML-BEANS compiled schema: Wrong major version - expecting " + MAJOR_VERSION + ", got " + _majorver, _name, handle, SchemaTypeLoaderException.WRONG_MAJOR_VERSION);
+            }
 
-            if (_minorver > MINOR_VERSION)
+            if (_minorver > MINOR_VERSION) {
                 throw new SchemaTypeLoaderException("XML-BEANS compiled schema: Incompatible minor version - expecting up to " + MINOR_VERSION + ", got " + _minorver, _name, handle, SchemaTypeLoaderException.WRONG_MINOR_VERSION);
+            }
 
             // Clip to 14 because we're not backward compatible with earlier
             // minor versions.  Remove this when upgrading to a new major
             // version
 
-            if (_minorver < 14)
+            if (_minorver < 14) {
                 throw new SchemaTypeLoaderException("XML-BEANS compiled schema: Incompatible minor version - expecting at least 14, got " + _minorver, _name, handle, SchemaTypeLoaderException.WRONG_MINOR_VERSION);
+            }
 
-            if (atLeast(2, 18, 0))
+            if (atLeast(2, 18, 0)) {
                 _releaseno = readShort();
+            }
 
             int actualfiletype = readShort();
-            if (actualfiletype != filetype && filetype != 0xFFFF)
+            if (actualfiletype != filetype && filetype != 0xFFFF) {
                 throw new SchemaTypeLoaderException("XML-BEANS compiled schema: File has the wrong type - expecting type " + filetype + ", got type " + actualfiletype, _name, handle, SchemaTypeLoaderException.WRONG_FILE_TYPE);
+            }
 
             _stringPool = new StringPool(_handle, _name);
             _stringPool.readFrom(_input);
@@ -1589,56 +1469,61 @@
             _actualfiletype = actualfiletype;
         }
 
-        protected boolean atLeast(int majorver, int minorver, int releaseno)
-        {
-            if (_majorver > majorver)
+        protected boolean atLeast(int majorver, int minorver, int releaseno) {
+            if (_majorver > majorver) {
                 return true;
-            if (_majorver < majorver)
+            }
+            if (_majorver < majorver) {
                 return false;
-            if (_minorver > minorver)
+            }
+            if (_minorver > minorver) {
                 return true;
-            if (_minorver < minorver)
+            }
+            if (_minorver < minorver) {
                 return false;
+            }
             return (_releaseno >= releaseno);
         }
 
-        protected boolean atMost(int majorver, int minorver, int releaseno)
-        {
-            if (_majorver > majorver)
+        protected boolean atMost(int majorver, int minorver, int releaseno) {
+            if (_majorver > majorver) {
                 return false;
-            if (_majorver < majorver)
+            }
+            if (_majorver < majorver) {
                 return true;
-            if (_minorver > minorver)
+            }
+            if (_minorver > minorver) {
                 return false;
-            if (_minorver < minorver)
+            }
+            if (_minorver < minorver) {
                 return true;
+            }
             return (_releaseno <= releaseno);
         }
 
-        int getActualFiletype()
-        {
+        int getActualFiletype() {
             return _actualfiletype;
         }
 
-        XsbReader(String handle)
-        {
+        XsbReader(String handle) {
             _handle = handle;
             _stringPool = new StringPool(_handle, _name);
         }
 
-        void writeRealHeader(String handle, int filetype)
-        {
+        void writeRealHeader(String handle, int filetype) {
             // hackeroo: if handle contains a "/" it's not relative.
             String resourcename;
 
-            if (handle.indexOf('/') >= 0)
+            if (handle.indexOf('/') >= 0) {
                 resourcename = handle + ".xsb";
-            else
+            } else {
                 resourcename = _basePackage + handle + ".xsb";
+            }
 
             OutputStream rawoutput = getSaverStream(resourcename);
-            if (rawoutput == null)
+            if (rawoutput == null) {
                 throw new SchemaTypeLoaderException("Could not write compiled schema resource " + resourcename, _name, handle, SchemaTypeLoaderException.NOT_WRITEABLE);
+            }
 
             _output = new DataOutputStream(rawoutput);
             _handle = handle;
@@ -1652,15 +1537,12 @@
             _stringPool.writeTo(_output);
         }
 
-        void readEnd()
-        {
-            try
-            {
-                if (_input != null)
+        void readEnd() {
+            try {
+                if (_input != null) {
                     _input.close();
-            }
-            catch (IOException e)
-            {
+                }
+            } catch (IOException e) {
                 // oh, well.
             }
             _input = null;
@@ -1668,29 +1550,22 @@
             _handle = null;
         }
 
-        void writeEnd()
-        {
-            try
-            {
-                if (_output != null)
-                {
+        void writeEnd() {
+            try {
+                if (_output != null) {
                     _output.flush();
                     _output.close();
                 }
-            }
-            catch (IOException e)
-            {
-                throw new SchemaTypeLoaderException(e.getMessage(), _name, _handle, SchemaTypeLoaderException.IO_EXCEPTION);
+            } catch (IOException e) {
+                throw new SchemaTypeLoaderException(e.getMessage(), _name, _handle, SchemaTypeLoaderException.IO_EXCEPTION, e);
             }
             _output = null;
             _stringPool = null;
             _handle = null;
         }
 
-        int fileTypeFromComponentType(int componentType)
-        {
-            switch (componentType)
-            {
+        int fileTypeFromComponentType(int componentType) {
+            switch (componentType) {
                 case SchemaComponent.TYPE:
                     return SchemaTypeSystemImpl.FILETYPE_SCHEMATYPE;
                 case SchemaComponent.ELEMENT:
@@ -1708,8 +1583,7 @@
             }
         }
 
-        void writeIndexData()
-        {
+        void writeIndexData() {
             // has a handle pool (count, handle/type, handle/type...)
             writeHandlePool(_localHandles);
 
@@ -1750,32 +1624,28 @@
             writeAnnotations(annotations());
         }
 
-        void writeHandlePool(HandlePool pool)
-        {
+        void writeHandlePool(HandlePool pool) {
             writeShort(pool._componentsToHandles.size());
-            for (Iterator i = pool._componentsToHandles.keySet().iterator(); i.hasNext(); )
-            {
-                SchemaComponent comp = (SchemaComponent)i.next();
-                String handle = (String)pool._componentsToHandles.get(comp);
+            for (Iterator i = pool._componentsToHandles.keySet().iterator(); i.hasNext(); ) {
+                SchemaComponent comp = (SchemaComponent) i.next();
+                String handle = (String) pool._componentsToHandles.get(comp);
                 int code = fileTypeFromComponentType(comp.getComponentType());
                 writeString(handle);
                 writeShort(code);
             }
         }
 
-        void readHandlePool(HandlePool pool)
-        {
-            if (pool._handlesToRefs.size() != 0 || pool._started)
+        void readHandlePool(HandlePool pool) {
+            if (pool._handlesToRefs.size() != 0 || pool._started) {
                 throw new IllegalStateException("Nonempty handle set before read");
+            }
 
             int size = readShort();
-            for (int i = 0; i < size; i++)
-            {
+            for (int i = 0; i < size; i++) {
                 String handle = readString();
                 int code = readShort();
                 Object result;
-                switch (code)
-                {
+                switch (code) {
                     case FILETYPE_SCHEMATYPE:
                         result = new SchemaType.Ref(getTypeSystem(), handle);
                         break;
@@ -1801,86 +1671,65 @@
             }
         }
 
-        int readShort()
-        {
-            try
-            {
+        int readShort() {
+            try {
                 return _input.readUnsignedShort();
-            }
-            catch (IOException e)
-            {
-                throw new SchemaTypeLoaderException(e.getMessage(), _name, _handle, SchemaTypeLoaderException.IO_EXCEPTION);
+            } catch (IOException e) {
+                throw new SchemaTypeLoaderException(e.getMessage(), _name, _handle, SchemaTypeLoaderException.IO_EXCEPTION, e);
             }
         }
 
-        void writeShort(int s)
-        {
-            if (s >= MAX_UNSIGNED_SHORT || s < -1)
+        void writeShort(int s) {
+            if (s >= MAX_UNSIGNED_SHORT || s < -1) {
                 throw new SchemaTypeLoaderException("Value " + s + " out of range: must fit in a 16-bit unsigned short.", _name, _handle, SchemaTypeLoaderException.INT_TOO_LARGE);
-            if (_output != null)
-            {
-                try
-                {
+            }
+            if (_output != null) {
+                try {
                     _output.writeShort(s);
-                }
-                catch (IOException e)
-                {
-                    throw new SchemaTypeLoaderException(e.getMessage(), _name, _handle, SchemaTypeLoaderException.IO_EXCEPTION);
+                } catch (IOException e) {
+                    throw new SchemaTypeLoaderException(e.getMessage(), _name, _handle, SchemaTypeLoaderException.IO_EXCEPTION, e);
                 }
             }
         }
 
-        int readInt()
-        {
-            try
-            {
+        int readInt() {
+            try {
                 return _input.readInt();
-            }
-            catch (IOException e)
-            {
-                throw new SchemaTypeLoaderException(e.getMessage(), _name, _handle, SchemaTypeLoaderException.IO_EXCEPTION);
+            } catch (IOException e) {
+                throw new SchemaTypeLoaderException(e.getMessage(), _name, _handle, SchemaTypeLoaderException.IO_EXCEPTION, e);
             }
         }
 
-        void writeInt(int i)
-        {
-            if (_output != null)
-            {
-                try
-                {
+        void writeInt(int i) {
+            if (_output != null) {
+                try {
                     _output.writeInt(i);
-                }
-                catch (IOException e)
-                {
-                    throw new SchemaTypeLoaderException(e.getMessage(), _name, _handle, SchemaTypeLoaderException.IO_EXCEPTION);
+                } catch (IOException e) {
+                    throw new SchemaTypeLoaderException(e.getMessage(), _name, _handle, SchemaTypeLoaderException.IO_EXCEPTION, e);
                 }
             }
         }
 
-        String readString()
-        {
+        String readString() {
             return _stringPool.stringForCode(readShort());
         }
 
-        void writeString(String str)
-        {
+        void writeString(String str) {
             int code = _stringPool.codeForString(str);
             writeShort(code);
         }
 
-        QName readQName()
-        {
+        QName readQName() {
             String namespace = readString();
             String localname = readString();
-            if (localname == null)
+            if (localname == null) {
                 return null;
+            }
             return new QName(namespace, localname);
         }
 
-        void writeQName(QName qname)
-        {
-            if (qname == null)
-            {
+        void writeQName(QName qname) {
+            if (qname == null) {
                 writeString(null);
                 writeString(null);
                 return;
@@ -1889,41 +1738,34 @@
             writeString(qname.getLocalPart());
         }
 
-        SOAPArrayType readSOAPArrayType()
-        {
+        SOAPArrayType readSOAPArrayType() {
             QName qName = readQName();
             String dimensions = readString();
-            if (qName == null)
+            if (qName == null) {
                 return null;
+            }
             return new SOAPArrayType(qName, dimensions);
         }
 
-        void writeSOAPArrayType(SOAPArrayType arrayType)
-        {
-            if (arrayType == null)
-            {
+        void writeSOAPArrayType(SOAPArrayType arrayType) {
+            if (arrayType == null) {
                 writeQName(null);
                 writeString(null);
-            }
-            else
-            {
+            } else {
                 writeQName(arrayType.getQName());
                 writeString(arrayType.soap11DimensionString());
             }
         }
 
-        void writeAnnotation(SchemaAnnotation a)
-        {
+        void writeAnnotation(SchemaAnnotation a) {
             // Write attributes
-            if (a == null)
-            {
+            if (a == null) {
                 writeInt(-1);
                 return;
             }
             SchemaAnnotation.Attribute[] attributes = a.getAttributes();
             writeInt(attributes.length);
-            for (int i = 0; i < attributes.length; i++)
-            {
+            for (int i = 0; i < attributes.length; i++) {
                 QName name = attributes[i].getName();
                 String value = attributes[i].getValue();
                 String valueURI = attributes[i].getValueUri();
@@ -1937,8 +1779,7 @@
             writeInt(documentationItems.length);
             XmlOptions opt = new XmlOptions().setSaveOuter().
                 setSaveAggressiveNamespaces();
-            for (int i = 0; i < documentationItems.length; i++)
-            {
+            for (int i = 0; i < documentationItems.length; i++) {
                 XmlObject doc = documentationItems[i];
                 writeString(doc.xmlText(opt));
             }
@@ -1946,46 +1787,44 @@
             // Write application info items
             XmlObject[] appInfoItems = a.getApplicationInformation();
             writeInt(appInfoItems.length);
-            for (int i = 0; i < appInfoItems.length; i++)
-            {
+            for (int i = 0; i < appInfoItems.length; i++) {
                 XmlObject doc = appInfoItems[i];
                 writeString(doc.xmlText(opt));
             }
         }
 
-        SchemaAnnotation readAnnotation(SchemaContainer c)
-        {
-            if (!atLeast(2, 19, 0))
+        SchemaAnnotation readAnnotation(SchemaContainer c) {
+            if (!atLeast(2, 19, 0)) {
                 return null; // no annotations for this version of the file
+            }
             // Read attributes
             int n = readInt();
-            if (n == -1)
+            if (n == -1) {
                 return null;
+            }
             SchemaAnnotation.Attribute[] attributes =
                 new SchemaAnnotation.Attribute[n];
-            for (int i = 0; i < n; i++)
-            {
+            for (int i = 0; i < n; i++) {
                 QName name = readQName();
                 String value = readString();
                 String valueUri = null;
-                if (atLeast(2, 24, 0))
+                if (atLeast(2, 24, 0)) {
                     valueUri = readString();
+                }
                 attributes[i] = new SchemaAnnotationImpl.AttributeImpl(name, value, valueUri);
             }
 
             // Read documentation items
             n = readInt();
             String[] docStrings = new String[n];
-            for (int i = 0; i <  n; i++)
-            {
+            for (int i = 0; i < n; i++) {
                 docStrings[i] = readString();
             }
 
             // Read application info items
             n = readInt();
             String[] appInfoStrings = new String[n];
-            for (int i = 0; i < n; i++)
-            {
+            for (int i = 0; i < n; i++) {
                 appInfoStrings[i] = readString();
             }
 
@@ -1993,39 +1832,40 @@
                 docStrings, attributes);
         }
 
-        void writeAnnotations(SchemaAnnotation[] anns)
-        {
+        void writeAnnotations(SchemaAnnotation[] anns) {
             writeInt(anns.length);
-            for (int i = 0; i < anns.length; i++)
+            for (int i = 0; i < anns.length; i++) {
                 writeAnnotation(anns[i]);
+            }
         }
 
-        List readAnnotations()
-        {
+        List readAnnotations() {
             int n = readInt();
             List result = new ArrayList(n);
             // BUGBUG(radup)
             SchemaContainer container = getContainerNonNull("");
-            for (int i = 0; i < n; i++)
+            for (int i = 0; i < n; i++) {
                 result.add(readAnnotation(container));
+            }
             return result;
         }
 
-        SchemaComponent.Ref readHandle()
-        {
+        SchemaComponent.Ref readHandle() {
             String handle = readString();
-            if (handle == null)
+            if (handle == null) {
                 return null;
+            }
 
-            if (handle.charAt(0) != '_')
+            if (handle.charAt(0) != '_') {
                 return _localHandles.refForHandle(handle);
+            }
 
-            switch (handle.charAt(2))
-            {
+            switch (handle.charAt(2)) {
                 case 'I': // _BI_ - built-in schema type system
                     SchemaType st = (SchemaType) BuiltinSchemaTypeSystem.get().resolveHandle(handle);
-                    if (st != null)
+                    if (st != null) {
                         return st.getRef();
+                    }
                     st = (SchemaType) XQuerySchemaTypeSystem.get().resolveHandle(handle);
                     return st.getRef();
                 case 'T': // _XT_ - external type
@@ -2043,37 +1883,37 @@
                 case 'R': // _XR_ - external ref to attribute's type
                     // deprecated: replaced by _XY_
                     SchemaGlobalAttribute attr = _linker.findAttribute(QNameHelper.forPretty(handle, 4));
-                    if (attr == null)
+                    if (attr == null) {
                         throw new SchemaTypeLoaderException("Cannot resolve attribute for handle " + handle, _name, _handle, SchemaTypeLoaderException.BAD_HANDLE);
+                    }
                     return attr.getType().getRef();
                 case 'S': // _XS_ - external ref to element's type
                     // deprecated: replaced by _XY_
                     SchemaGlobalElement elem = _linker.findElement(QNameHelper.forPretty(handle, 4));
-                    if (elem == null)
+                    if (elem == null) {
                         throw new SchemaTypeLoaderException("Cannot resolve element for handle " + handle, _name, _handle, SchemaTypeLoaderException.BAD_HANDLE);
+                    }
                     return elem.getType().getRef();
                 case 'O': // _XO_ - external ref to document type
                     return _linker.findDocumentTypeRef(QNameHelper.forPretty(handle, 4));
                 case 'Y': // _XY_ - external ref to any possible type
                     SchemaType type = _linker.typeForSignature(handle.substring(4));
-                    if (type == null)
+                    if (type == null) {
                         throw new SchemaTypeLoaderException("Cannot resolve type for handle " + handle, _name, _handle, SchemaTypeLoaderException.BAD_HANDLE);
+                    }
                     return type.getRef();
                 default:
                     throw new SchemaTypeLoaderException("Cannot resolve handle " + handle, _name, _handle, SchemaTypeLoaderException.BAD_HANDLE);
             }
         }
 
-        void writeHandle(SchemaComponent comp)
-        {
-            if (comp == null || comp.getTypeSystem() == getTypeSystem())
-            {
+        void writeHandle(SchemaComponent comp) {
+            if (comp == null || comp.getTypeSystem() == getTypeSystem()) {
                 writeString(_localHandles.handleForComponent(comp));
                 return;
             }
 
-            switch (comp.getComponentType())
-            {
+            switch (comp.getComponentType()) {
                 case SchemaComponent.ATTRIBUTE:
                     writeString("_XA_" + QNameHelper.pretty(comp.getName()));
                     return;
@@ -2090,9 +1930,8 @@
                     writeString("_XD_" + QNameHelper.pretty(comp.getName()));
                     return;
                 case SchemaComponent.TYPE:
-                    SchemaType type = (SchemaType)comp;
-                    if (type.isBuiltinType())
-                    {
+                    SchemaType type = (SchemaType) comp;
+                    if (type.isBuiltinType()) {
                         writeString("_BI_" + type.getName().getLocalPart());
                         return;
                     }
@@ -2103,19 +1942,14 @@
                     // schema and the type of that attribute or element
                     // is an anonymous (local) type
                     // kkrouse 02/1/2005: _XR_ and _XS_ refs are replaced by _XY_
-                    if (type.getName() != null)
-                    {
+                    if (type.getName() != null) {
                         writeString("_XT_" + QNameHelper.pretty(type.getName()));
-                    }
-                    else if (type.isDocumentType())
-                    {
+                    } else if (type.isDocumentType()) {
                         // Substitution groups will create document types that
                         // extend from other document types, possibly in
                         // different jars
                         writeString("_XO_" + QNameHelper.pretty(type.getDocumentElementName()));
-                    }
-                    else
-                    {
+                    } else {
                         // fix for XMLBEANS-105:
                         // save out the external type reference using the type's signature.
                         writeString("_XY_" + type.toString());
@@ -2124,27 +1958,23 @@
                     return;
 
                 default:
-                    assert(false);
+                    assert (false);
                     throw new SchemaTypeLoaderException("Cannot write handle for component " + comp, _name, _handle, SchemaTypeLoaderException.BAD_HANDLE);
             }
         }
 
-        SchemaType.Ref readTypeRef()
-        {
-            return (SchemaType.Ref)readHandle();
+        SchemaType.Ref readTypeRef() {
+            return (SchemaType.Ref) readHandle();
         }
 
-        void writeType(SchemaType type)
-        {
+        void writeType(SchemaType type) {
             writeHandle(type);
         }
 
-        Map readQNameRefMap()
-        {
+        Map readQNameRefMap() {
             Map result = new HashMap();
             int size = readShort();
-            for (int i = 0; i < size; i++)
-            {
+            for (int i = 0; i < size; i++) {
                 QName name = readQName();
                 SchemaComponent.Ref obj = readHandle();
                 result.put(name, obj);
@@ -2152,12 +1982,10 @@
             return result;
         }
 
-        List readQNameRefMapAsList(List names)
-        {
+        List readQNameRefMapAsList(List names) {
             int size = readShort();
             List result = new ArrayList(size);
-            for (int i = 0; i < size; i++)
-            {
+            for (int i = 0; i < size; i++) {
                 QName name = readQName();
                 SchemaComponent.Ref obj = readHandle();
                 result.add(obj);
@@ -2166,62 +1994,50 @@
             return result;
         }
 
-        void writeQNameMap(SchemaComponent[] components)
-        {
+        void writeQNameMap(SchemaComponent[] components) {
             writeShort(components.length);
-            for (int i = 0; i < components.length; i++)
-            {
+            for (int i = 0; i < components.length; i++) {
                 writeQName(components[i].getName());
                 writeHandle(components[i]);
             }
         }
 
-        void writeDocumentTypeMap(SchemaType[] doctypes)
-        {
+        void writeDocumentTypeMap(SchemaType[] doctypes) {
             writeShort(doctypes.length);
-            for (int i = 0; i < doctypes.length; i++)
-            {
+            for (int i = 0; i < doctypes.length; i++) {
                 writeQName(doctypes[i].getDocumentElementName());
                 writeHandle(doctypes[i]);
             }
         }
 
-        void writeAttributeTypeMap(SchemaType[] attrtypes)
-        {
+        void writeAttributeTypeMap(SchemaType[] attrtypes) {
             writeShort(attrtypes.length);
-            for (int i = 0; i < attrtypes.length; i++)
-            {
+            for (int i = 0; i < attrtypes.length; i++) {
                 writeQName(attrtypes[i].getAttributeTypeAttributeName());
                 writeHandle(attrtypes[i]);
             }
         }
 
-        SchemaType.Ref[] readTypeRefArray()
-        {
+        SchemaType.Ref[] readTypeRefArray() {
             int size = readShort();
             SchemaType.Ref[] result = new SchemaType.Ref[size];
-            for (int i = 0; i < size; i++)
-            {
+            for (int i = 0; i < size; i++) {
                 result[i] = readTypeRef();
             }
             return result;
         }
 
-        void writeTypeArray(SchemaType[] array)
-        {
+        void writeTypeArray(SchemaType[] array) {
             writeShort(array.length);
-            for (int i = 0; i < array.length; i++)
-            {
+            for (int i = 0; i < array.length; i++) {
                 writeHandle(array[i]);
             }
         }
 
-        Map readClassnameRefMap()
-        {
+        Map readClassnameRefMap() {
             Map result = new HashMap();
             int size = readShort();
-            for (int i = 0; i < size; i++)
-            {
+            for (int i = 0; i < size; i++) {
                 String name = readString();
                 SchemaComponent.Ref obj = readHandle();
                 result.put(name, obj);
@@ -2229,77 +2045,63 @@
             return result;
         }
 
-        void writeClassnameMap(Map typesByClass)
-        {
+        void writeClassnameMap(Map typesByClass) {
             writeShort(typesByClass.size());
-            for (Iterator i = typesByClass.keySet().iterator(); i.hasNext(); )
-            {
-                String className = (String)i.next();
+            for (Iterator i = typesByClass.keySet().iterator(); i.hasNext(); ) {
+                String className = (String) i.next();
                 writeString(className);
-                writeHandle(((SchemaType.Ref)typesByClass.get(className)).get());
+                writeHandle(((SchemaType.Ref) typesByClass.get(className)).get());
             }
         }
 
-        Set readNamespaces()
-        {
+        Set readNamespaces() {
             Set result = new HashSet();
             int size = readShort();
-            for (int i = 0; i < size; i++)
-            {
+            for (int i = 0; i < size; i++) {
                 String ns = readString();
                 result.add(ns);
             }
             return result;
         }
 
-        void writeNamespaces(Set namespaces)
-        {
+        void writeNamespaces(Set namespaces) {
             writeShort(namespaces.size());
-            for (Iterator i = namespaces.iterator(); i.hasNext(); )
-            {
-                String ns = (String)i.next();
+            for (Iterator i = namespaces.iterator(); i.hasNext(); ) {
+                String ns = (String) i.next();
                 writeString(ns);
             }
         }
 
-        OutputStream getSaverStream(String name)
-        {
-            try
-            {
+        OutputStream getSaverStream(String name) {
+            try {
                 return _filer.createBinaryFile(name);
-            }
-            catch (IOException e)
-            {
-                throw new SchemaTypeLoaderException(e.getMessage(), _name, _handle, SchemaTypeLoaderException.IO_EXCEPTION);
+            } catch (IOException e) {
+                throw new SchemaTypeLoaderException(e.getMessage(), _name, _handle, SchemaTypeLoaderException.IO_EXCEPTION, e);
             }
         }
 
-        InputStream getLoaderStream(String resourcename)
-        {
+        InputStream getLoaderStream(String resourcename) {
             return _resourceLoader.getResourceAsStream(resourcename);
         }
 
-        void checkContainerNotNull(SchemaContainer container, QName name)
-        {
-            if (container == null)
-            {
+        void checkContainerNotNull(SchemaContainer container, QName name) {
+            if (container == null) {
                 throw new LinkageError("Loading of resource " + _name + '.' + _handle +
-                    "failed, information from " + _name + ".index.xsb is " +
-                    " out of sync (or conflicting index files found)");
+                                       "failed, information from " + _name + ".index.xsb is " +
+                                       " out of sync (or conflicting index files found)");
             }
         }
 
         /**
          * Finishes loading an element after the header has already been loaded.
          */
-        public SchemaGlobalElement finishLoadingElement()
-        {
+        public SchemaGlobalElement finishLoadingElement() {
             String handle = null;
-            try
-            {
+            try {
                 int particleType = readShort();
-                if (particleType != SchemaParticle.ELEMENT)
+                if (particleType != SchemaParticle.ELEMENT) {
                     throw new SchemaTypeLoaderException("Wrong particle type ", _name, _handle, SchemaTypeLoaderException.BAD_PARTICLE_TYPE);
+                }
                 int particleFlags = readShort();
                 BigInteger minOccurs = readBigInteger();
                 BigInteger maxOccurs = readBigInteger();
@@ -2315,8 +2117,9 @@
                     (particleFlags & FLAG_PART_SKIPPABLE) != 0);
                 impl.setNameAndTypeRef(name, readTypeRef());
                 impl.setDefault(readString(), (particleFlags & FLAG_PART_FIXED) != 0, null);
-                if (atLeast(2, 16, 0))
+                if (atLeast(2, 16, 0)) {
                     impl.setDefaultValue(readXmlValueObject());
+                }
                 impl.setNillable((particleFlags & FLAG_PART_NILLABLE) != 0);
                 impl.setBlock((particleFlags & FLAG_PART_BLOCKEXT) != 0,
                     (particleFlags & FLAG_PART_BLOCKREST) != 0,
@@ -2325,44 +2128,37 @@
                 impl.setAbstract((particleFlags & FLAG_PART_ABSTRACT) != 0);
                 impl.setAnnotation(readAnnotation(container));
                 impl.setFinal(
-                              (particleFlags & FLAG_PART_FINALEXT) != 0,
-                              (particleFlags & FLAG_PART_FINALREST) != 0);
+                    (particleFlags & FLAG_PART_FINALEXT) != 0,
+                    (particleFlags & FLAG_PART_FINALREST) != 0);
 
-                if (atLeast(2, 17, 0))
-                    impl.setSubstitutionGroup((SchemaGlobalElement.Ref)readHandle());
+                if (atLeast(2, 17, 0)) {
+                    impl.setSubstitutionGroup((SchemaGlobalElement.Ref) readHandle());
+                }
 
                 int substGroupCount = readShort();
-                for (int i = 0; i < substGroupCount; i++)
-                {
+                for (int i = 0; i < substGroupCount; i++) {
                     impl.addSubstitutionGroupMember(readQName());
                 }
                 SchemaIdentityConstraint.Ref[] idcs = new SchemaIdentityConstraint.Ref[readShort()];
 
-                for (int i = 0 ; i < idcs.length ; i++)
-                    idcs[i] = (SchemaIdentityConstraint.Ref)readHandle();
+                for (int i = 0; i < idcs.length; i++) {
+                    idcs[i] = (SchemaIdentityConstraint.Ref) readHandle();
+                }
 
                 impl.setIdentityConstraints(idcs);
                 impl.setFilename(readString());
                 return impl;
-            }
-            catch (SchemaTypeLoaderException e)
-            {
+            } catch (SchemaTypeLoaderException e) {
                 throw e;
-            }
-            catch (Exception e)
-            {
+            } catch (Exception e) {
                 throw new SchemaTypeLoaderException("Cannot load type from typesystem", _name, handle, SchemaTypeLoaderException.NESTED_EXCEPTION, e);
-            }
-            finally
-            {
+            } finally {
                 readEnd();
             }
         }
 
-        public SchemaGlobalAttribute finishLoadingAttribute()
-        {
-            try
-            {
+        public SchemaGlobalAttribute finishLoadingAttribute() {
+            try {
                 QName name = readQName();
                 SchemaContainer container = getContainer(name.getNamespaceURI());
                 checkContainerNotNull(container, name);
@@ -2371,55 +2167,41 @@
                 impl.setFilename(readString());
 
                 return impl;
-            }
-            catch (SchemaTypeLoaderException e)
-            {
+            } catch (SchemaTypeLoaderException e) {
                 throw e;
-            }
-            catch (Exception e)
-            {
+            } catch (Exception e) {
                 throw new SchemaTypeLoaderException("Cannot load type from typesystem", _name, _handle, SchemaTypeLoaderException.NESTED_EXCEPTION, e);
-            }
-            finally
-            {
+            } finally {
                 readEnd();
             }
         }
 
-        SchemaModelGroup finishLoadingModelGroup()
-        {
+        SchemaModelGroup finishLoadingModelGroup() {
             QName name = readQName();
             SchemaContainer container = getContainer(name.getNamespaceURI());
             checkContainerNotNull(container, name);
             SchemaModelGroupImpl impl = new SchemaModelGroupImpl(container);
 
-            try
-            {
+            try {
                 impl.init(name, readString(), readShort() == 1,
                     atLeast(2, 22, 0) ? readString() : null,
                     atLeast(2, 22, 0) ? readString() : null,
                     atLeast(2, 15, 0) ? readShort() == 1 : false,
-                    GroupDocument.Factory.parse( readString() ).getGroup(), readAnnotation(container), null);
-                if (atLeast(2, 21, 0))
+                    GroupDocument.Factory.parse(readString()).getGroup(), readAnnotation(container), null);
+                if (atLeast(2, 21, 0)) {
                     impl.setFilename(readString());
+                }
                 return impl;
-            }
-            catch (SchemaTypeLoaderException e)
-            {
+            } catch (SchemaTypeLoaderException e) {
                 throw e;
-            }
-            catch (Exception e)
-            {
+            } catch (Exception e) {
                 throw new SchemaTypeLoaderException("Cannot load type from typesystem", _name, _handle, SchemaTypeLoaderException.NESTED_EXCEPTION, e);
-            }
-            finally
-            {
+            } finally {
                 readEnd();
             }
         }
 
-        SchemaIdentityConstraint finishLoadingIdentityConstraint()
-        {
+        SchemaIdentityConstraint finishLoadingIdentityConstraint() {
             try {
                 QName name = readQName();
                 SchemaContainer container = getContainer(name.getNamespaceURI());
@@ -2431,78 +2213,65 @@
                 impl.setAnnotation(readAnnotation(container));
 
                 String[] fields = new String[readShort()];
-                for (int i = 0 ; i < fields.length ; i++)
+                for (int i = 0; i < fields.length; i++) {
                     fields[i] = readString();
+                }
                 impl.setFields(fields);
 
-                if (impl.getConstraintCategory() == SchemaIdentityConstraint.CC_KEYREF)
-                    impl.setReferencedKey((SchemaIdentityConstraint.Ref)readHandle());
+                if (impl.getConstraintCategory() == SchemaIdentityConstraint.CC_KEYREF) {
+                    impl.setReferencedKey((SchemaIdentityConstraint.Ref) readHandle());
+                }
 
                 int mapCount = readShort();
                 Map nsMappings = new HashMap();
-                for (int i = 0 ; i < mapCount ; i++)
-                {
+                for (int i = 0; i < mapCount; i++) {
                     String prefix = readString();
                     String uri = readString();
                     nsMappings.put(prefix, uri);
                 }
                 impl.setNSMap(nsMappings);
 
-                if (atLeast(2, 21, 0))
+                if (atLeast(2, 21, 0)) {
                     impl.setFilename(readString());
+                }
 
                 return impl;
-            }
-            catch (SchemaTypeLoaderException e)
-            {
+            } catch (SchemaTypeLoaderException e) {
                 throw e;
-            }
-            catch (Exception e)
-            {
+            } catch (Exception e) {
                 throw new SchemaTypeLoaderException("Cannot load type from typesystem", _name, _handle, SchemaTypeLoaderException.NESTED_EXCEPTION, e);
-            }
-            finally
-            {
+            } finally {
                 readEnd();
             }
         }
 
-        SchemaAttributeGroup finishLoadingAttributeGroup()
-        {
+        SchemaAttributeGroup finishLoadingAttributeGroup() {
             QName name = readQName();
             SchemaContainer container = getContainer(name.getNamespaceURI());
             checkContainerNotNull(container, name);
             SchemaAttributeGroupImpl impl = new SchemaAttributeGroupImpl(container);
 
-            try
-            {
-                impl.init( name, readString(), readShort() == 1,
+            try {
+                impl.init(name, readString(), readShort() == 1,
                     atLeast(2, 22, 0) ? readString() : null,
                     atLeast(2, 15, 0) ? readShort() == 1 : false,
-                    AttributeGroupDocument.Factory.parse( readString() ).getAttributeGroup(),
+                    AttributeGroupDocument.Factory.parse(readString()).getAttributeGroup(),
                     readAnnotation(container), null);
-                if (atLeast(2, 21, 0))
+                if (atLeast(2, 21, 0)) {
                     impl.setFilename(readString());
+                }
                 return impl;
-            }
-            catch (SchemaTypeLoaderException e)
-            {
+            } catch (SchemaTypeLoaderException e) {
                 throw e;
-            }
-            catch (Exception e)
-            {
+            } catch (Exception e) {
                 throw new SchemaTypeLoaderException("Cannot load type from typesystem", _name, _handle, SchemaTypeLoaderException.NESTED_EXCEPTION, e);
-            }
-            finally
-            {
+            } finally {
                 readEnd();
             }
         }
 
-        public SchemaType finishLoadingType()
-        {
-            try
-            {
+        public SchemaType finishLoadingType() {
+            try {
                 SchemaContainer cNonNull = getContainerNonNull(""); //HACKHACK
                 SchemaTypeImpl impl = new SchemaTypeImpl(cNonNull, true);
                 impl.setName(readQName());
@@ -2512,23 +2281,22 @@
                 impl.setDerivationType(readShort());
                 impl.setAnnotation(readAnnotation(null));
 
-                switch (readShort())
-                {
+                switch (readShort()) {
                     case FIELD_GLOBAL:
                         impl.setContainerFieldRef(readHandle());
                         break;
                     case FIELD_LOCALATTR:
-                        impl.setContainerFieldIndex((short)1, readShort());
+                        impl.setContainerFieldIndex((short) 1, readShort());
                         break;
                     case FIELD_LOCALELT:
-                        impl.setContainerFieldIndex((short)2, readShort());
+                        impl.setContainerFieldIndex((short) 2, readShort());
                         break;
                 }
                 // TODO (radup) find the right solution here
                 String jn = readString();
                 impl.setFullJavaName(jn == null ? "" : jn);
                 jn = readString();
-                impl.setFullJavaImplName(jn == null? "" : jn);
+                impl.setFullJavaImplName(jn == null ? "" : jn);
 
                 impl.setAnonymousTypeRefs(readTypeRefArray());
 
@@ -2545,8 +2313,7 @@
                 impl.setSimpleType(!isComplexType);
 
                 int complexVariety = SchemaType.NOT_COMPLEX_TYPE;
-                if (isComplexType)
-                {
+                if (isComplexType) {
                     impl.setAbstractFinal((flags & FLAG_ABSTRACT) != 0,
                         (flags & FLAG_FINAL_EXT) != 0,
                         (flags & FLAG_FINAL_REST) != 0,
@@ -2559,15 +2326,17 @@
                     complexVariety = readShort();
                     impl.setComplexTypeVariety(complexVariety);
 
-                    if (atLeast(2, 23, 0))
+                    if (atLeast(2, 23, 0)) {
                         impl.setContentBasedOnTypeRef(readTypeRef());
+                    }
 
                     // Attribute Model Table
                     SchemaAttributeModelImpl attrModel = new SchemaAttributeModelImpl();
 
                     int attrCount = readShort();
-                    for (int i = 0; i < attrCount; i++)
+                    for (int i = 0; i < attrCount; i++) {
                         attrModel.addAttribute(readAttributeData());
+                    }
 
                     attrModel.setWildcardSet(readQNameSet());
                     attrModel.setWildcardProcess(readShort());
@@ -2575,11 +2344,11 @@
                     // Attribute Property Table
                     Map attrProperties = new LinkedHashMap();
                     int attrPropCount = readShort();
-                    for (int i = 0; i < attrPropCount; i++)
-                    {
+                    for (int i = 0; i < attrPropCount; i++) {
                         SchemaProperty prop = readPropertyData();
-                        if (!prop.isAttribute())
+                        if (!prop.isAttribute()) {
                             throw new SchemaTypeLoaderException("Attribute property " + i + " is not an attribute", _name, _handle, SchemaTypeLoaderException.WRONG_PROPERTY_TYPE);
+                        }
                         attrProperties.put(prop.getName(), prop);
                     }
 
@@ -2587,27 +2356,27 @@
                     Map elemProperties = null;
                     int isAll = 0;
 
-                    if (complexVariety == SchemaType.ELEMENT_CONTENT || complexVariety == SchemaType.MIXED_CONTENT)
-                    {
+                    if (complexVariety == SchemaType.ELEMENT_CONTENT || complexVariety == SchemaType.MIXED_CONTENT) {
                         // Content Model Tree
                         isAll = readShort();
                         SchemaParticle[] parts = readParticleArray();
-                        if (parts.length == 1)
+                        if (parts.length == 1) {
                             contentModel = parts[0];
-                        else if (parts.length == 0)
+                        } else if (parts.length == 0) {
                             contentModel = null;
-                        else
+                        } else {
                             throw new SchemaTypeLoaderException("Content model not well-formed", _name, _handle, SchemaTypeLoaderException.MALFORMED_CONTENT_MODEL);
+                        }
 
                         // Element Property Table
 
                         elemProperties = new LinkedHashMap();
                         int elemPropCount = readShort();
-                        for (int i = 0; i < elemPropCount; i++)
-                        {
+                        for (int i = 0; i < elemPropCount; i++) {
                             SchemaProperty prop = readPropertyData();
-                            if (prop.isAttribute())
+                            if (prop.isAttribute()) {
                                 throw new SchemaTypeLoaderException("Element property " + i + " is not an element", _name, _handle, SchemaTypeLoaderException.WRONG_PROPERTY_TYPE);
+                            }
                             elemProperties.put(prop.getName(), prop);
                         }
                     }
@@ -2618,8 +2387,7 @@
                     impl.setWildcardSummary(wcElt.typedWildcards, wcElt.hasWildcards, wcAttr.typedWildcards, wcAttr.hasWildcards);
                 }
 
-                if (!isComplexType || complexVariety == SchemaType.SIMPLE_CONTENT)
-                {
+                if (!isComplexType || complexVariety == SchemaType.SIMPLE_CONTENT) {
                     int simpleVariety = readShort();
                     impl.setSimpleTypeVariety(simpleVariety);
 
@@ -2637,8 +2405,7 @@
                     XmlValueRef[] facets = new XmlValueRef[SchemaType.LAST_FACET + 1];
                     boolean[] fixedFacets = new boolean[SchemaType.LAST_FACET + 1];
                     int facetCount = readShort();
-                    for (int i = 0; i < facetCount; i++)
-                    {
+                    for (int i = 0; i < facetCount; i++) {
                         int facetCode = readShort();
                         facets[facetCode] = readXmlValueObject();
                         fixedFacets[facetCode] = (readShort() == 1);
@@ -2651,34 +2418,29 @@
 
                     int patternCount = readShort();
                     org.apache.xmlbeans.impl.regex.RegularExpression[] patterns = new org.apache.xmlbeans.impl.regex.RegularExpression[patternCount];
-                    for (int i = 0; i < patternCount; i++)
-                    {
+                    for (int i = 0; i < patternCount; i++) {
                         patterns[i] = new org.apache.xmlbeans.impl.regex.RegularExpression(readString(), "X");
                     }
                     impl.setPatterns(patterns);
 
                     int enumCount = readShort();
                     XmlValueRef[] enumValues = new XmlValueRef[enumCount];
-                    for (int i = 0; i < enumCount; i++)
-                    {
+                    for (int i = 0; i < enumCount; i++) {
                         enumValues[i] = readXmlValueObject();
                     }
                     impl.setEnumerationValues(enumCount == 0 ? null : enumValues);
 
                     impl.setBaseEnumTypeRef(readTypeRef());
-                    if (isStringEnum)
-                    {
+                    if (isStringEnum) {
                         int seCount = readShort();
                         SchemaStringEnumEntry[] entries = new SchemaStringEnumEntry[seCount];
-                        for (int i = 0; i < seCount; i++)
-                        {
+                        for (int i = 0; i < seCount; i++) {
                             entries[i] = new SchemaStringEnumEntryImpl(readString(), readShort(), readString());
                         }
                         impl.setStringEnumEntries(entries);
                     }
 
-                    switch (simpleVariety)
-                    {
+                    switch (simpleVariety) {
                         case SchemaType.ATOMIC:
                             impl.setPrimitiveTypeRef(readTypeRef());
                             impl.setDecimalSize(readInt());
@@ -2701,27 +2463,20 @@
 
                 impl.setFilename(readString());
                 // Set the container for global, attribute or document types
-                if (impl.getName() != null)
-                {
+                if (impl.getName() != null) {
                     SchemaContainer container = getContainer(impl.getName().getNamespaceURI());
                     checkContainerNotNull(container, impl.getName());
                     impl.setContainer(container);
-                }
-                else if (impl.isDocumentType())
-                {
+                } else if (impl.isDocumentType()) {
                     QName name = impl.getDocumentElementName();
-                    if (name != null)
-                    {
+                    if (name != null) {
                         SchemaContainer container = getContainer(name.getNamespaceURI());
                         checkContainerNotNull(container, name);
                         impl.setContainer(container);
                     }
-                }
-                else if (impl.isAttributeType())
-                {
+                } else if (impl.isAttributeType()) {
                     QName name = impl.getAttributeTypeAttributeName();
-                    if (name != null)
-                    {
+                    if (name != null) {
                         SchemaContainer container = getContainer(name.getNamespaceURI());
                         checkContainerNotNull(container, name);
                         impl.setContainer(container);
@@ -2729,47 +2484,33 @@
                 }
 
                 return impl;
-            }
-            catch (SchemaTypeLoaderException e)
-            {
+            } catch (SchemaTypeLoaderException e) {
                 throw e;
-            }
-            catch (Exception e)
-            {
+            } catch (Exception e) {
                 throw new SchemaTypeLoaderException("Cannot load type from typesystem", _name, _handle, SchemaTypeLoaderException.NESTED_EXCEPTION, e);
-            }
-            finally
-            {
+            } finally {
                 readEnd();
             }
         }
 
-        void writeTypeData(SchemaType type)
-        {
+        void writeTypeData(SchemaType type) {
             writeQName(type.getName());
             writeType(type.getOuterType());
-            writeShort(((SchemaTypeImpl)type).getBaseDepth());
+            writeShort(((SchemaTypeImpl) type).getBaseDepth());
             writeType(type.getBaseType());
             writeShort(type.getDerivationType());
             writeAnnotation(type.getAnnotation());
-            if (type.getContainerField() == null)
-            {
+            if (type.getContainerField() == null) {
                 writeShort(FIELD_NONE);
-            }
-            else if (type.getOuterType().isAttributeType() || type.getOuterType().isDocumentType())
-            {
+            } else if (type.getOuterType().isAttributeType() || type.getOuterType().isDocumentType()) {
                 writeShort(FIELD_GLOBAL);
-                writeHandle((SchemaComponent)type.getContainerField());
-            }
-            else if (type.getContainerField().isAttribute())
-            {
+                writeHandle((SchemaComponent) type.getContainerField());
+            } else if (type.getContainerField().isAttribute()) {
                 writeShort(FIELD_LOCALATTR);
-                writeShort(((SchemaTypeImpl)type.getOuterType()).getIndexForLocalAttribute((SchemaLocalAttribute)type.getContainerField()));
-            }
-            else
-            {
+                writeShort(((SchemaTypeImpl) type.getOuterType()).getIndexForLocalAttribute((SchemaLocalAttribute) type.getContainerField()));
+            } else {
                 writeShort(FIELD_LOCALELT);
-                writeShort(((SchemaTypeImpl)type.getOuterType()).getIndexForLocalElement((SchemaLocalElement)type.getContainerField()));
+                writeShort(((SchemaTypeImpl) type.getOuterType()).getIndexForLocalElement((SchemaLocalElement) type.getContainerField()));
             }
             writeString(type.getFullJavaName());
             writeString(type.getFullJavaImplName());
@@ -2777,50 +2518,68 @@
             writeShort(type.getAnonymousUnionMemberOrdinal());
 
             int flags = 0;
-            if (type.isSimpleType())
+            if (type.isSimpleType()) {
                 flags |= FLAG_SIMPLE_TYPE;
-            if (type.isDocumentType())
+            }
+            if (type.isDocumentType()) {
                 flags |= FLAG_DOCUMENT_TYPE;
-            if (type.isAttributeType())
+            }
+            if (type.isAttributeType()) {
                 flags |= FLAG_ATTRIBUTE_TYPE;
-            if (type.ordered() != SchemaType.UNORDERED)
+            }
+            if (type.ordered() != SchemaType.UNORDERED) {
                 flags |= FLAG_ORDERED;
-            if (type.ordered() == SchemaType.TOTAL_ORDER)
+            }
+            if (type.ordered() == SchemaType.TOTAL_ORDER) {
                 flags |= FLAG_TOTAL_ORDER;
-            if (type.isBounded())
+            }
+            if (type.isBounded()) {
                 flags |= FLAG_BOUNDED;
-            if (type.isFinite())
+            }
+            if (type.isFinite()) {
                 flags |= FLAG_FINITE;
-            if (type.isNumeric())
+            }
+            if (type.isNumeric()) {
                 flags |= FLAG_NUMERIC;
-            if (type.hasStringEnumValues())
+            }
+            if (type.hasStringEnumValues()) {
                 flags |= FLAG_STRINGENUM;
-            if (((SchemaTypeImpl)type).isUnionOfLists())
+            }
+            if (((SchemaTypeImpl) type).isUnionOfLists()) {
                 flags |= FLAG_UNION_OF_LISTS;
-            if (type.hasPatternFacet())
+            }
+            if (type.hasPatternFacet()) {
                 flags |= FLAG_HAS_PATTERN;
-            if (type.isOrderSensitive())
+            }
+            if (type.isOrderSensitive()) {
                 flags |= FLAG_ORDER_SENSITIVE;
+            }
 
-            if (type.blockExtension())
+            if (type.blockExtension()) {
                 flags |= FLAG_BLOCK_EXT;
-            if (type.blockRestriction())
+            }
+            if (type.blockRestriction()) {
                 flags |= FLAG_BLOCK_REST;
-            if (type.finalExtension())
+            }
+            if (type.finalExtension()) {
                 flags |= FLAG_FINAL_EXT;
-            if (type.finalRestriction())
+            }
+            if (type.finalRestriction()) {
                 flags |= FLAG_FINAL_EXT;
-            if (type.finalList())
+            }
+            if (type.finalList()) {
                 flags |= FLAG_FINAL_LIST;
-            if (type.finalUnion())
+            }
+            if (type.finalUnion()) {
                 flags |= FLAG_FINAL_UNION;
-            if (type.isAbstract())
+            }
+            if (type.isAbstract()) {
                 flags |= FLAG_ABSTRACT;
+            }
 
             writeInt(flags);
 
-            if (!type.isSimpleType())
-            {
+            if (!type.isSimpleType()) {
                 writeShort(type.getContentType());
 
                 writeType(type.getContentBasedOnType());
@@ -2830,8 +2589,9 @@
                 SchemaLocalAttribute[] attrs = attrModel.getAttributes();
 
                 writeShort(attrs.length);
-                for (int i = 0; i < attrs.length; i++)
+                for (int i = 0; i < attrs.length; i++) {
                     writeAttributeData(attrs[i]);
+                }
 
                 writeQNameSet(attrModel.getWildcardSet());
                 writeShort(attrModel.getWildcardProcess());
@@ -2839,44 +2599,45 @@
                 // Attribute Property Table
                 SchemaProperty[] attrProperties = type.getAttributeProperties();
                 writeShort(attrProperties.length);
-                for (int i = 0; i < attrProperties.length; i++)
+                for (int i = 0; i < attrProperties.length; i++) {
                     writePropertyData(attrProperties[i]);
+                }
 
                 if (type.getContentType() == SchemaType.ELEMENT_CONTENT ||
-                    type.getContentType() == SchemaType.MIXED_CONTENT)
-                {
+                    type.getContentType() == SchemaType.MIXED_CONTENT) {
                     // Content Model Tree
                     writeShort(type.hasAllContent() ? 1 : 0);
                     SchemaParticle[] parts;
-                    if (type.getContentModel() != null)
-                        parts = new SchemaParticle[] { type.getContentModel() };
-                    else
+                    if (type.getContentModel() != null) {
+                        parts = new SchemaParticle[]{type.getContentModel()};
+                    } else {
                         parts = new SchemaParticle[0];
+                    }
 
                     writeParticleArray(parts);
 
                     // Element Property Table
                     SchemaProperty[] eltProperties = type.getElementProperties();
                     writeShort(eltProperties.length);
-                    for (int i = 0; i < eltProperties.length; i++)
+                    for (int i = 0; i < eltProperties.length; i++) {
                         writePropertyData(eltProperties[i]);
+                    }
                 }
             }
 
-            if (type.isSimpleType() || type.getContentType() == SchemaType.SIMPLE_CONTENT)
-            {
+            if (type.isSimpleType() || type.getContentType() == SchemaType.SIMPLE_CONTENT) {
                 writeShort(type.getSimpleVariety());
 
                 int facetCount = 0;
-                for (int i = 0; i <= SchemaType.LAST_FACET; i++)
-                    if (type.getFacet(i) != null)
+                for (int i = 0; i <= SchemaType.LAST_FACET; i++) {
+                    if (type.getFacet(i) != null) {
                         facetCount++;
+                    }
+                }
                 writeShort(facetCount);
-                for (int i = 0; i <= SchemaType.LAST_FACET; i++)
-                {
+                for (int i = 0; i <= SchemaType.LAST_FACET; i++) {
                     XmlAnySimpleType facet = type.getFacet(i);
-                    if (facet != null)
-                    {
+                    if (facet != null) {
                         writeShort(i);
                         writeXmlValueObject(facet);
                         writeShort(type.isFacetFixed(i) ? 1 : 0);
@@ -2885,37 +2646,35 @@
 
                 writeShort(type.getWhiteSpaceRule());
 
-                org.apache.xmlbeans.impl.regex.RegularExpression[] patterns = ((SchemaTypeImpl)type).getPatternExpressions();
+                org.apache.xmlbeans.impl.regex.RegularExpression[] patterns = ((SchemaTypeImpl) type).getPatternExpressions();
                 writeShort(patterns.length);
-                for (int i = 0; i < patterns.length; i++)
+                for (int i = 0; i < patterns.length; i++) {
                     writeString(patterns[i].getPattern());
+                }
 
                 XmlAnySimpleType[] enumValues = type.getEnumerationValues();
-                if (enumValues == null)
+                if (enumValues == null) {
                     writeShort(0);
-                else
-                {
+                } else {
                     writeShort(enumValues.length);
-                    for (int i = 0; i < enumValues.length; i++)
+                    for (int i = 0; i < enumValues.length; i++) {
                         writeXmlValueObject(enumValues[i]);
+                    }
                 }
 
                 // new for version 2.3
                 writeType(type.getBaseEnumType());
-                if (type.hasStringEnumValues())
-                {
+                if (type.hasStringEnumValues()) {
                     SchemaStringEnumEntry[] entries = type.getStringEnumEntries();
                     writeShort(entries.length);
-                    for (int i = 0; i < entries.length; i++)
-                    {
-                        writeString(entries[i].getString());
-                        writeShort(entries[i].getIntValue());
-                        writeString(entries[i].getEnumName());
+                    for (SchemaStringEnumEntry entry : entries) {
+                        writeString(entry.getString());
+                        writeShort(entry.getIntValue());
+                        writeString(entry.getEnumName());
                     }
                 }
 
-                switch (type.getSimpleVariety())
-                {
+                switch (type.getSimpleVariety()) {
                     case SchemaType.ATOMIC:
                         writeType(type.getPrimitiveType());
                         writeInt(type.getDecimalSize());
@@ -2934,47 +2693,41 @@
             writeString(type.getSourceName());
         }
 
-        void readExtensionsList()
-        {
+        void readExtensionsList() {
             int count = readShort();
             assert count == 0;
 
-            for (int i = 0; i < count; i++)
-            {
+            for (int i = 0; i < count; i++) {
                 readString();
                 readString();
                 readString();
             }
         }
 
-        SchemaLocalAttribute readAttributeData()
-        {
+        SchemaLocalAttribute readAttributeData() {
             SchemaLocalAttributeImpl result = new SchemaLocalAttributeImpl();
             loadAttribute(result, readQName(), null);
             return result;
         }
 
 
-        void loadAttribute(SchemaLocalAttributeImpl result, QName name, SchemaContainer container)
-        {
+        void loadAttribute(SchemaLocalAttributeImpl result, QName name, SchemaContainer container) {
             // name, type, use, deftext, defval, fixed, soaparraytype, annotation
             result.init(name, readTypeRef(), readShort(), readString(), null, atLeast(2, 16, 0) ? readXmlValueObject() : null, readShort() == 1, readSOAPArrayType(), readAnnotation(container), null);
         }
 
-        void writeAttributeData(SchemaLocalAttribute attr)
-        {
+        void writeAttributeData(SchemaLocalAttribute attr) {
             writeQName(attr.getName());
             writeType(attr.getType());
             writeShort(attr.getUse());
             writeString(attr.getDefaultText());
             writeXmlValueObject(attr.getDefaultValue());
             writeShort(attr.isFixed() ? 1 : 0);
-            writeSOAPArrayType(((SchemaWSDLArrayType)attr).getWSDLArrayType());
+            writeSOAPArrayType(((SchemaWSDLArrayType) attr).getWSDLArrayType());
             writeAnnotation(attr.getAnnotation());
         }
 
-        void writeIdConstraintData(SchemaIdentityConstraint idc)
-        {
+        void writeIdConstraintData(SchemaIdentityConstraint idc) {
             writeQName(idc.getName());
             writeShort(idc.getConstraintCategory());
             writeString(idc.getSelector());
@@ -2982,19 +2735,21 @@
 
             String[] fields = idc.getFields();
             writeShort(fields.length);
-            for (int i = 0 ; i < fields.length ; i++)
+            for (int i = 0; i < fields.length; i++) {
                 writeString(fields[i]);
+            }
 
 
-            if (idc.getConstraintCategory() == SchemaIdentityConstraint.CC_KEYREF)
+            if (idc.getConstraintCategory() == SchemaIdentityConstraint.CC_KEYREF) {
                 writeHandle(idc.getReferencedKey());
+            }
 
             Set mappings = idc.getNSMap().entrySet();
             writeShort(mappings.size());
-            for (Iterator it = mappings.iterator() ; it.hasNext() ; ) {
-                Map.Entry e = (Map.Entry)it.next();
-                String prefix = (String)e.getKey();
-                String uri = (String)e.getValue();
+            for (Iterator it = mappings.iterator(); it.hasNext(); ) {
+                Map.Entry e = (Map.Entry) it.next();
+                String prefix = (String) e.getKey();
+                String uri = (String) e.getValue();
 
                 writeString(prefix);
                 writeString(uri);
@@ -3002,35 +2757,34 @@
             writeString(idc.getSourceName());
         }
 
-        SchemaParticle[] readParticleArray()
-        {
+        SchemaParticle[] readParticleArray() {
             SchemaParticle[] result = new SchemaParticle[readShort()];
-            for (int i = 0; i < result.length; i++)
+            for (int i = 0; i < result.length; i++) {
                 result[i] = readParticleData();
+            }
             return result;
         }
 
-        void writeParticleArray(SchemaParticle[] spa)
-        {
+        void writeParticleArray(SchemaParticle[] spa) {
             writeShort(spa.length);
-            for (int i = 0; i < spa.length; i++)
+            for (int i = 0; i < spa.length; i++) {
                 writeParticleData(spa[i]);
+            }
         }
 
-        SchemaParticle readParticleData()
-        {
+        SchemaParticle readParticleData() {
             int particleType = readShort();
             SchemaParticleImpl result;
-            if (particleType != SchemaParticle.ELEMENT)
+            if (particleType != SchemaParticle.ELEMENT) {
                 result = new SchemaParticleImpl();
-            else
+            } else {
                 result = new SchemaLocalElementImpl();
+            }
             loadParticle(result, particleType);
             return result;
         }
 
-        void loadParticle(SchemaParticleImpl result, int particleType)
-        {
+        void loadParticle(SchemaParticleImpl result, int particleType) {
             int particleFlags = readShort();
 
             result.setParticleType(particleType);
@@ -3038,33 +2792,34 @@
             result.setMaxOccurs(readBigInteger());
 
             result.setTransitionRules(readQNameSet(),
-                                      (particleFlags & FLAG_PART_SKIPPABLE) != 0);
+                (particleFlags & FLAG_PART_SKIPPABLE) != 0);
 
-            switch (particleType)
-            {
+            switch (particleType) {
                 case SchemaParticle.WILDCARD:
                     result.setWildcardSet(readQNameSet());
                     result.setWildcardProcess(readShort());
                     break;
 
                 case SchemaParticle.ELEMENT:
-                    SchemaLocalElementImpl lresult = (SchemaLocalElementImpl)result;
+                    SchemaLocalElementImpl lresult = (SchemaLocalElementImpl) result;
                     lresult.setNameAndTypeRef(readQName(), readTypeRef());
                     lresult.setDefault(readString(), (particleFlags & FLAG_PART_FIXED) != 0, null);
-                    if (atLeast(2, 16, 0))
+                    if (atLeast(2, 16, 0)) {
                         lresult.setDefaultValue(readXmlValueObject());
+                    }
                     lresult.setNillable((particleFlags & FLAG_PART_NILLABLE) != 0);
                     lresult.setBlock((particleFlags & FLAG_PART_BLOCKEXT) != 0,
-                                     (particleFlags & FLAG_PART_BLOCKREST) != 0,
-                                     (particleFlags & FLAG_PART_BLOCKSUBST) != 0);
+                        (particleFlags & FLAG_PART_BLOCKREST) != 0,
+                        (particleFlags & FLAG_PART_BLOCKSUBST) != 0);
                     lresult.setWsdlArrayType(readSOAPArrayType());
                     lresult.setAbstract((particleFlags & FLAG_PART_ABSTRACT) != 0);
                     lresult.setAnnotation(readAnnotation(null));
 
                     SchemaIdentityConstraint.Ref[] idcs = new SchemaIdentityConstraint.Ref[readShort()];
 
-                    for (int i = 0 ; i < idcs.length ; i++)
-                        idcs[i] = (SchemaIdentityConstraint.Ref)readHandle();
+                    for (int i = 0; i < idcs.length; i++) {
+                        idcs[i] = (SchemaIdentityConstraint.Ref) readHandle();
+                    }
 
                     lresult.setIdentityConstraints(idcs);
 
@@ -3081,35 +2836,41 @@
             }
         }
 
-        void writeParticleData(SchemaParticle part)
-        {
+        void writeParticleData(SchemaParticle part) {
             writeShort(part.getParticleType());
             short flags = 0;
-            if (part.isSkippable())
+            if (part.isSkippable()) {
                 flags |= FLAG_PART_SKIPPABLE;
-            if (part.getParticleType() == SchemaParticle.ELEMENT)
-            {
-                SchemaLocalElement lpart = (SchemaLocalElement)part;
-                if (lpart.isFixed())
+            }
+            if (part.getParticleType() == SchemaParticle.ELEMENT) {
+                SchemaLocalElement lpart = (SchemaLocalElement) part;
+                if (lpart.isFixed()) {
                     flags |= FLAG_PART_FIXED;
-                if (lpart.isNillable())
+                }
+                if (lpart.isNillable()) {
                     flags |= FLAG_PART_NILLABLE;
-                if (lpart.blockExtension())
+                }
+                if (lpart.blockExtension()) {
                     flags |= FLAG_PART_BLOCKEXT;
-                if (lpart.blockRestriction())
+                }
+                if (lpart.blockRestriction()) {
                     flags |= FLAG_PART_BLOCKREST;
-                if (lpart.blockSubstitution())
+                }
+                if (lpart.blockSubstitution()) {
                     flags |= FLAG_PART_BLOCKSUBST;
-                if (lpart.isAbstract())
+                }
+                if (lpart.isAbstract()) {
                     flags |= FLAG_PART_ABSTRACT;
+                }
 
-                if (lpart instanceof SchemaGlobalElement)
-                {
-                    SchemaGlobalElement gpart = (SchemaGlobalElement)lpart;
-                    if (gpart.finalExtension())
+                if (lpart instanceof SchemaGlobalElement) {
+                    SchemaGlobalElement gpart = (SchemaGlobalElement) lpart;
+                    if (gpart.finalExtension()) {
                         flags |= FLAG_PART_FINALEXT;
-                    if (gpart.finalRestriction())
+                    }
+                    if (gpart.finalRestriction()) {
                         flags |= FLAG_PART_FINALREST;
+                    }
                 }
             }
             writeShort(flags);
@@ -3117,38 +2878,38 @@
             writeBigInteger(part.getMaxOccurs());
             writeQNameSet(part.acceptedStartNames());
 
-            switch (part.getParticleType())
-            {
+            switch (part.getParticleType()) {
                 case SchemaParticle.WILDCARD:
                     writeQNameSet(part.getWildcardSet());
                     writeShort(part.getWildcardProcess());
                     break;
 
                 case SchemaParticle.ELEMENT:
-                    SchemaLocalElement lpart = (SchemaLocalElement)part;
+                    SchemaLocalElement lpart = (SchemaLocalElement) part;
                     writeQName(lpart.getName());
                     writeType(lpart.getType());
                     writeString(lpart.getDefaultText());
                     writeXmlValueObject(lpart.getDefaultValue());
-                    writeSOAPArrayType(((SchemaWSDLArrayType)lpart).getWSDLArrayType());
+                    writeSOAPArrayType(((SchemaWSDLArrayType) lpart).getWSDLArrayType());
                     writeAnnotation(lpart.getAnnotation());
-                    if (lpart instanceof SchemaGlobalElement)
-                    {
-                        SchemaGlobalElement gpart = (SchemaGlobalElement)lpart;
+                    if (lpart instanceof SchemaGlobalElement) {
+                        SchemaGlobalElement gpart = (SchemaGlobalElement) lpart;
 
                         writeHandle(gpart.substitutionGroup());
 
                         QName[] substGroupMembers = gpart.substitutionGroupMembers();
                         writeShort(substGroupMembers.length);
-                        for (int i = 0; i < substGroupMembers.length; i++)
+                        for (int i = 0; i < substGroupMembers.length; i++) {
                             writeQName(substGroupMembers[i]);
+                        }
                     }
 
                     SchemaIdentityConstraint[] idcs = lpart.getIdentityConstraints();
 
                     writeShort(idcs.length);
-                    for (int i = 0 ; i < idcs.length ; i++)
+                    for (int i = 0; i < idcs.length; i++) {
                         writeHandle(idcs[i]);
+                    }
 
                     break;
 
@@ -3163,8 +2924,7 @@
             }
         }
 
-        SchemaProperty readPropertyData()
-        {
+        SchemaProperty readPropertyData() {
             SchemaPropertyImpl prop = new SchemaPropertyImpl();
             prop.setName(readQName());
             prop.setTypeRef(readTypeRef());
@@ -3181,28 +2941,29 @@
             prop.setJavaPropertyName(readString());
             prop.setJavaTypeCode(readShort());
             prop.setExtendsJava(readTypeRef(),
-                    (propflags & FLAG_PROP_JAVASINGLETON) != 0,
-                    (propflags & FLAG_PROP_JAVAOPTIONAL) != 0,
-                    (propflags & FLAG_PROP_JAVAARRAY) != 0);
-            if (atMost(2, 19, 0))
+                (propflags & FLAG_PROP_JAVASINGLETON) != 0,
+                (propflags & FLAG_PROP_JAVAOPTIONAL) != 0,
+                (propflags & FLAG_PROP_JAVAARRAY) != 0);
+            if (atMost(2, 19, 0)) {
                 prop.setJavaSetterDelimiter(readQNameSet());
-            if (atLeast(2, 16, 0))
+            }
+            if (atLeast(2, 16, 0)) {
                 prop.setDefaultValue(readXmlValueObject());
+            }
 
-            if (!prop.isAttribute() && atLeast(2, 17, 0))
-            {
+            if (!prop.isAttribute() && atLeast(2, 17, 0)) {
                 int size = readShort();
                 LinkedHashSet qnames = new LinkedHashSet(size);
-                for (int i = 0 ; i < size ; i++)
+                for (int i = 0; i < size; i++) {
                     qnames.add(readQName());
+                }
                 prop.setAcceptedNames(qnames);
             }
             prop.setImmutable();
             return prop;
         }
 
-        void writePropertyData(SchemaProperty prop)
-        {
+        void writePropertyData(SchemaProperty prop) {
             writeQName(prop.getName());
             writeType(prop.getType());
             writeShort((prop.isAttribute() ? FLAG_PROP_ISATTR : 0) |
@@ -3222,18 +2983,17 @@
             writeType(prop.javaBasedOnType());
             writeXmlValueObject(prop.getDefaultValue());
 
-            if (! prop.isAttribute())
-            {
+            if (!prop.isAttribute()) {
                 QName[] names = prop.acceptedNames();
                 writeShort(names.length);
-                for (int i = 0 ; i < names.length ; i++)
+                for (int i = 0; i < names.length; i++) {
                     writeQName(names[i]);
+                }
             }
         }
 
-        void writeModelGroupData(SchemaModelGroup grp)
-        {
-            SchemaModelGroupImpl impl = (SchemaModelGroupImpl)grp;
+        void writeModelGroupData(SchemaModelGroup grp) {
+            SchemaModelGroupImpl impl = (SchemaModelGroupImpl) grp;
             writeQName(impl.getName());
             writeString(impl.getTargetNamespace());
             writeShort(impl.getChameleonNamespace() != null ? 1 : 0);
@@ -3245,9 +3005,8 @@
             writeString(impl.getSourceName());
         }
 
-        void writeAttributeGroupData(SchemaAttributeGroup grp)
-        {
-            SchemaAttributeGroupImpl impl = (SchemaAttributeGroupImpl)grp;
+        void writeAttributeGroupData(SchemaAttributeGroup grp) {
+            SchemaAttributeGroupImpl impl = (SchemaAttributeGroupImpl) grp;
             writeQName(impl.getName());
             writeString(impl.getTargetNamespace());
             writeShort(impl.getChameleonNamespace() != null ? 1 : 0);
@@ -3258,29 +3017,26 @@
             writeString(impl.getSourceName());
         }
 
-        XmlValueRef readXmlValueObject()
-        {
+        XmlValueRef readXmlValueObject() {
             SchemaType.Ref typeref = readTypeRef();
-            if (typeref == null)
+            if (typeref == null) {
                 return null;
+            }
             int btc = readShort();
-            switch (btc)
-            {
+            switch (btc) {
                 default:
-                    assert(false);
+                    assert (false);
                 case 0:
                     return new XmlValueRef(typeref, null);
-                case 0xFFFF:
-                    {
-                        int size = readShort();
-                        List values = new ArrayList();
-                        writeShort(values.size());
-                        for (int i = 0; i < size; i++)
-                        {
-                            values.add(readXmlValueObject());
-                        }
-                        return new XmlValueRef(typeref, values);
+                case 0xFFFF: {
+                    int size = readShort();
+                    List values = new ArrayList();
+                    writeShort(values.size());
+                    for (int i = 0; i < size; i++) {
+                        values.add(readXmlValueObject());
                     }
+                    return new XmlValueRef(typeref, values);
+                }
 
 
                 case SchemaType.BTC_ANY_SIMPLE:
@@ -3313,34 +3069,27 @@
             }
         }
 
-        void writeXmlValueObject(XmlAnySimpleType value)
-        {
+        void writeXmlValueObject(XmlAnySimpleType value) {
             SchemaType type = value == null ? null : value.schemaType();
             writeType(type);
-            if (type == null)
+            if (type == null) {
                 return;
+            }
 
-            SchemaType iType = ((SimpleValue)value).instanceType();
-            if (iType == null)
-            {
+            SchemaType iType = ((SimpleValue) value).instanceType();
+            if (iType == null) {
                 writeShort(0);
-            }
-            else if (iType.getSimpleVariety() == SchemaType.LIST)
-            {
+            } else if (iType.getSimpleVariety() == SchemaType.LIST) {
                 writeShort(-1);
-                List values = ((XmlObjectBase)value).xgetListValue();
+                List values = ((XmlObjectBase) value).xgetListValue();
                 writeShort(values.size());
-                for (Iterator i = values.iterator(); i.hasNext(); )
-                {
-                    writeXmlValueObject((XmlAnySimpleType)i.next());
+                for (Iterator i = values.iterator(); i.hasNext(); ) {
+                    writeXmlValueObject((XmlAnySimpleType) i.next());
                 }
-            }
-            else
-            {
+            } else {
                 int btc = iType.getPrimitiveType().getBuiltinTypeCode();
                 writeShort(btc);
-                switch (btc)
-                {
+                switch (btc) {
                     case SchemaType.BTC_ANY_SIMPLE:
                     case SchemaType.BTC_ANY_URI:
                     case SchemaType.BTC_STRING:
@@ -3360,187 +3109,165 @@
 
                     case SchemaType.BTC_BASE_64_BINARY:
                     case SchemaType.BTC_HEX_BINARY:
-                        writeByteArray(((SimpleValue)value).getByteArrayValue());
+                        writeByteArray(((SimpleValue) value).getByteArrayValue());
                         break;
 
                     case SchemaType.BTC_QNAME:
                     case SchemaType.BTC_NOTATION:
-                        writeQName(((SimpleValue)value).getQNameValue());
+                        writeQName(((SimpleValue) value).getQNameValue());
                         break;
 
                     case SchemaType.BTC_FLOAT:
-                        writeDouble(((SimpleValue)value).getFloatValue());
+                        writeDouble(((SimpleValue) value).getFloatValue());
                         break;
 
                     case SchemaType.BTC_DOUBLE:
-                        writeDouble(((SimpleValue)value).getDoubleValue());
+                        writeDouble(((SimpleValue) value).getDoubleValue());
                         break;
                 }
             }
         }
 
-        double readDouble()
-        {
-            try
-            {
+        double readDouble() {
+            try {
                 return _input.readDouble();
-            }
-            catch (IOException e)
-            {
-                throw new SchemaTypeLoaderException(e.getMessage(), _name, _handle, SchemaTypeLoaderException.IO_EXCEPTION);
+            } catch (IOException e) {
+                throw new SchemaTypeLoaderException(e.getMessage(), _name, _handle, SchemaTypeLoaderException.IO_EXCEPTION, e);
             }
         }
 
-        void writeDouble(double d)
-        {
-            if (_output != null)
-            {
-                try
-                {
+        void writeDouble(double d) {
+            if (_output != null) {
+                try {
                     _output.writeDouble(d);
-                }
-                catch (IOException e)
-                {
-                    throw new SchemaTypeLoaderException(e.getMessage(), _name, _handle, SchemaTypeLoaderException.IO_EXCEPTION);
+                } catch (IOException e) {
+                    throw new SchemaTypeLoaderException(e.getMessage(), _name, _handle, SchemaTypeLoaderException.IO_EXCEPTION, e);
                 }
             }
         }
 
-        QNameSet readQNameSet()
-        {
+        QNameSet readQNameSet() {
             int flag = readShort();
 
             Set uriSet = new HashSet();
             int uriCount = readShort();
-            for (int i = 0; i < uriCount; i++)
+            for (int i = 0; i < uriCount; i++) {
                 uriSet.add(readString());
+            }
 
             Set qnameSet1 = new HashSet();
             int qncount1 = readShort();
-            for (int i = 0; i < qncount1; i++)
+            for (int i = 0; i < qncount1; i++) {
                 qnameSet1.add(readQName());
+            }
 
             Set qnameSet2 = new HashSet();
             int qncount2 = readShort();
-            for (int i = 0; i < qncount2; i++)
+            for (int i = 0; i < qncount2; i++) {
                 qnameSet2.add(readQName());
+            }
 
-            if (flag == 1)
+            if (flag == 1) {
                 return QNameSet.forSets(uriSet, null, qnameSet1, qnameSet2);
-            else
+            } else {
                 return QNameSet.forSets(null, uriSet, qnameSet2, qnameSet1);
+            }
         }
 
-        void writeQNameSet(QNameSet set)
-        {
+        void writeQNameSet(QNameSet set) {
             boolean invert = (set.excludedURIs() != null);
             writeShort(invert ? 1 : 0);
 
             Set uriSet = invert ? set.excludedURIs() : set.includedURIs();
             writeShort(uriSet.size());
-            for (Iterator i = uriSet.iterator(); i.hasNext(); )
-                writeString((String)i.next());
+            for (Iterator i = uriSet.iterator(); i.hasNext(); ) {
+                writeString((String) i.next());
+            }
 
             Set qnameSet1 = invert ? set.excludedQNamesInIncludedURIs() : set.includedQNamesInExcludedURIs();
             writeShort(qnameSet1.size());
-            for (Iterator i = qnameSet1.iterator(); i.hasNext(); )
-                writeQName((QName)i.next());
+            for (Iterator i = qnameSet1.iterator(); i.hasNext(); ) {
+                writeQName((QName) i.next());
+            }
 
             Set qnameSet2 = invert ? set.includedQNamesInExcludedURIs() : set.excludedQNamesInIncludedURIs();
             writeShort(qnameSet2.size());
-            for (Iterator i = qnameSet2.iterator(); i.hasNext(); )
-                writeQName((QName)i.next());
+            for (Iterator i = qnameSet2.iterator(); i.hasNext(); ) {
+                writeQName((QName) i.next());
+            }
         }
 
-        byte[] readByteArray()
-        {
-            try
-            {
+        byte[] readByteArray() {
+            try {
                 int len = _input.readShort();
                 byte[] result = new byte[len];
                 _input.readFully(result);
                 return result;
-            }
-            catch (IOException e)
-            {
-                throw new SchemaTypeLoaderException(e.getMessage(), _name, _handle, SchemaTypeLoaderException.IO_EXCEPTION);
+            } catch (IOException e) {
+                throw new SchemaTypeLoaderException(e.getMessage(), _name, _handle, SchemaTypeLoaderException.IO_EXCEPTION, e);
             }
         }
 
-        void writeByteArray(byte[] ba)
-        {
-            try
-            {
+        void writeByteArray(byte[] ba) {
+            try {
                 writeShort(ba.length);
-                if (_output != null)
+                if (_output != null) {
                     _output.write(ba);
-            }
-            catch (IOException e)
-            {
-                throw new SchemaTypeLoaderException(e.getMessage(), _name, _handle, SchemaTypeLoaderException.IO_EXCEPTION);
+                }
+            } catch (IOException e) {
+                throw new SchemaTypeLoaderException(e.getMessage(), _name, _handle, SchemaTypeLoaderException.IO_EXCEPTION, e);
             }
         }
 
-        BigInteger readBigInteger()
-        {
+        BigInteger readBigInteger() {
             byte[] result = readByteArray();
-            if (result.length == 0)
+            if (result.length == 0) {
                 return null;
-            if (result.length == 1 && result[0] == 0)
+            }
+            if (result.length == 1 && result[0] == 0) {
                 return BigInteger.ZERO;
-            if (result.length == 1 && result[0] == 1)
+            }
+            if (result.length == 1 && result[0] == 1) {
                 return BigInteger.ONE;
+            }
             return new BigInteger(result);
         }
 
-        void writeBigInteger(BigInteger bi)
-        {
-            if (bi == null)
-            {
+        void writeBigInteger(BigInteger bi) {
+            if (bi == null) {
                 writeShort(0);
-            }
-            else if (bi.signum() == 0)
-            {
+            } else if (bi.signum() == 0) {
                 writeByteArray(SINGLE_ZERO_BYTE);
-            }
-            else
-            {
+            } else {
                 writeByteArray(bi.toByteArray());
             }
         }
 
     }
 
-    static final byte[] SINGLE_ZERO_BYTE = new byte[] { (byte)0 };
+    static final byte[] SINGLE_ZERO_BYTE = new byte[]{(byte) 0};
 
-    public SchemaType typeForHandle(String handle)
-    {
-        synchronized (_resolvedHandles)
-        {
-            return (SchemaType)_resolvedHandles.get(handle);
+    public SchemaType typeForHandle(String handle) {
+        synchronized (_resolvedHandles) {
+            return (SchemaType) _resolvedHandles.get(handle);
         }
     }
 
-    public SchemaType typeForClassname(String classname)
-    {
-        SchemaType.Ref ref = (SchemaType.Ref)_typeRefsByClassname.get(classname);
+    public SchemaType typeForClassname(String classname) {
+        SchemaType.Ref ref = (SchemaType.Ref) _typeRefsByClassname.get(classname);
         return (ref != null) ? ref.get() : null;
     }
 
-    public SchemaComponent resolveHandle(String handle)
-    {
+    public SchemaComponent resolveHandle(String handle) {
         SchemaComponent result;
 
-        synchronized (_resolvedHandles)
-        {
-            result = (SchemaComponent)_resolvedHandles.get(handle);
+        synchronized (_resolvedHandles) {
+            result = (SchemaComponent) _resolvedHandles.get(handle);
         }
-        if (result == null)
-        {
+        if (result == null) {
             XsbReader reader = new XsbReader(handle, 0xFFFF);
             int filetype = reader.getActualFiletype();
-            switch (filetype)
-            {
+            switch (filetype) {
                 case FILETYPE_SCHEMATYPE:
                     XBeanDebug.trace(XBeanDebug.TRACE_SCHEMA_LOADING, "Resolving type for handle " + handle, 0);
                     result = reader.finishLoadingType();
@@ -3569,12 +3296,12 @@
                     throw new IllegalStateException("Illegal handle type");
             }
 
-            synchronized (_resolvedHandles)
-            {
-                if (!_resolvedHandles.containsKey(handle))
+            synchronized (_resolvedHandles) {
+                if (!_resolvedHandles.containsKey(handle)) {
                     _resolvedHandles.put(handle, result);
-                else
-                    result = (SchemaComponent)_resolvedHandles.get(handle);
+                } else {
+                    result = (SchemaComponent) _resolvedHandles.get(handle);
+                }
             }
         }
         return result;
@@ -3583,11 +3310,11 @@
     private final Map _resolvedHandles = new HashMap();
     private boolean _allNonGroupHandlesResolved = false;
 
-    public void resolve()
-    {
+    public void resolve() {
         XBeanDebug.trace(XBeanDebug.TRACE_SCHEMA_LOADING, "Resolve called type system " + _name, 0);
-        if (_allNonGroupHandlesResolved)
+        if (_allNonGroupHandlesResolved) {
             return;
+        }
 
         XBeanDebug.trace(XBeanDebug.TRACE_SCHEMA_LOADING, "Resolving all handles for type system " + _name, 1);
 
@@ -3599,9 +3326,8 @@
         refs.addAll(_attributeTypes.values());
         refs.addAll(_identityConstraints.values());
 
-        for (Iterator i = refs.iterator(); i.hasNext(); )
-        {
-            SchemaComponent.Ref ref = (SchemaComponent.Ref)i.next();
+        for (Iterator i = refs.iterator(); i.hasNext(); ) {
+            SchemaComponent.Ref ref = (SchemaComponent.Ref) i.next();
             ref.getComponent(); // Forces ref to be resolved
         }
 
@@ -3610,212 +3336,213 @@
     }
 
 
-    public boolean isNamespaceDefined(String namespace)
-    {
+    public boolean isNamespaceDefined(String namespace) {
         return _namespaces.contains(namespace);
     }
 
-    public SchemaType.Ref findTypeRef(QName name)
-    {
-        return (SchemaType.Ref)_globalTypes.get(name);
+    public SchemaType.Ref findTypeRef(QName name) {
+        return (SchemaType.Ref) _globalTypes.get(name);
     }
 
-    public SchemaType.Ref findDocumentTypeRef(QName name)
-    {
-        return (SchemaType.Ref)_documentTypes.get(name);
+    public SchemaType.Ref findDocumentTypeRef(QName name) {
+        return (SchemaType.Ref) _documentTypes.get(name);
     }
 
-    public SchemaType.Ref findAttributeTypeRef(QName name)
-    {
-        return (SchemaType.Ref)_attributeTypes.get(name);
+    public SchemaType.Ref findAttributeTypeRef(QName name) {
+        return (SchemaType.Ref) _attributeTypes.get(name);
     }
 
-    public SchemaGlobalElement.Ref findElementRef(QName name)
-    {
-        return (SchemaGlobalElement.Ref)_globalElements.get(name);
+    public SchemaGlobalElement.Ref findElementRef(QName name) {
+        return (SchemaGlobalElement.Ref) _globalElements.get(name);
     }
 
-    public SchemaGlobalAttribute.Ref findAttributeRef(QName name)
-    {
-        return (SchemaGlobalAttribute.Ref)_globalAttributes.get(name);
+    public SchemaGlobalAttribute.Ref findAttributeRef(QName name) {
+        return (SchemaGlobalAttribute.Ref) _globalAttributes.get(name);
     }
 
-    public SchemaModelGroup.Ref findModelGroupRef(QName name)
-    {
-        return (SchemaModelGroup.Ref)_modelGroups.get(name);
+    public SchemaModelGroup.Ref findModelGroupRef(QName name) {
+        return (SchemaModelGroup.Ref) _modelGroups.get(name);
     }
 
-    public SchemaAttributeGroup.Ref findAttributeGroupRef(QName name)
-    {
-        return (SchemaAttributeGroup.Ref)_attributeGroups.get(name);
+    public SchemaAttributeGroup.Ref findAttributeGroupRef(QName name) {
+        return (SchemaAttributeGroup.Ref) _attributeGroups.get(name);
     }
 
-    public SchemaIdentityConstraint.Ref findIdentityConstraintRef(QName name)
-    {
-        return (SchemaIdentityConstraint.Ref)_identityConstraints.get(name);
+    public SchemaIdentityConstraint.Ref findIdentityConstraintRef(QName name) {
+        return (SchemaIdentityConstraint.Ref) _identityConstraints.get(name);
     }
 
-    public SchemaType[] globalTypes()
-    {
-        if (_globalTypes.isEmpty())
+    public SchemaType[] globalTypes() {
+        if (_globalTypes.isEmpty()) {
             return EMPTY_ST_ARRAY;
+        }
 
         SchemaType[] result = new SchemaType[_globalTypes.size()];
         int j = 0;
-        for (Iterator i = _globalTypes.values().iterator(); i.hasNext(); j++)
-            result[j] = ((SchemaType.Ref)i.next()).get();
+        for (Iterator i = _globalTypes.values().iterator(); i.hasNext(); j++) {
+            result[j] = ((SchemaType.Ref) i.next()).get();
+        }
         return result;
     }
 
-    public SchemaType[] redefinedGlobalTypes()
-    {
-        if (_redefinedGlobalTypes == null || _redefinedGlobalTypes.isEmpty())
+    public SchemaType[] redefinedGlobalTypes() {
+        if (_redefinedGlobalTypes == null || _redefinedGlobalTypes.isEmpty()) {
             return EMPTY_ST_ARRAY;
+        }
 
         SchemaType[] result = new SchemaType[_redefinedGlobalTypes.size()];
         int j = 0;
-        for (Iterator i = _redefinedGlobalTypes.iterator(); i.hasNext(); j++)
-            result[j] = ((SchemaType.Ref)i.next()).get();
+        for (Iterator i = _redefinedGlobalTypes.iterator(); i.hasNext(); j++) {
+            result[j] = ((SchemaType.Ref) i.next()).get();
+        }
         return result;
     }
 
-    public InputStream getSourceAsStream(String sourceName)
-    {
-        if (!sourceName.startsWith("/"))
+    public InputStream getSourceAsStream(String sourceName) {
+        if (!sourceName.startsWith("/")) {
             sourceName = "/" + sourceName;
+        }
 
         return _resourceLoader.getResourceAsStream(getMetadataPath() + "/src" + sourceName);
     }
 
-    SchemaContainer[] containers()
-    {
+    SchemaContainer[] containers() {
         SchemaContainer[] result = new SchemaContainer[_containers.size()];
         int j = 0;
-        for (Iterator i = _containers.values().iterator(); i.hasNext(); j++)
+        for (Iterator i = _containers.values().iterator(); i.hasNext(); j++) {
             result[j] = (SchemaContainer) i.next();
+        }
         return result;
     }
 
-    public SchemaType[] documentTypes()
-    {
-        if (_documentTypes.isEmpty())
+    public SchemaType[] documentTypes() {
+        if (_documentTypes.isEmpty()) {
             return EMPTY_ST_ARRAY;
+        }
 
         SchemaType[] result = new SchemaType[_documentTypes.size()];
         int j = 0;
-        for (Iterator i = _documentTypes.values().iterator(); i.hasNext(); j++)
-            result[j] = ((SchemaType.Ref)i.next()).get();
+        for (Iterator i = _documentTypes.values().iterator(); i.hasNext(); j++) {
+            result[j] = ((SchemaType.Ref) i.next()).get();
+        }
         return result;
     }
 
-    public SchemaType[] attributeTypes()
-    {
-        if (_attributeTypes.isEmpty())
+    public SchemaType[] attributeTypes() {
+        if (_attributeTypes.isEmpty()) {
             return EMPTY_ST_ARRAY;
+        }
 
         SchemaType[] result = new SchemaType[_attributeTypes.size()];
         int j = 0;
-        for (Iterator i = _attributeTypes.values().iterator(); i.hasNext(); j++)
-            result[j] = ((SchemaType.Ref)i.next()).get();
+        for (Iterator i = _attributeTypes.values().iterator(); i.hasNext(); j++) {
+            result[j] = ((SchemaType.Ref) i.next()).get();
+        }
         return result;
     }
 
-    public SchemaGlobalElement[] globalElements()
-    {
-        if (_globalElements.isEmpty())
+    public SchemaGlobalElement[] globalElements() {
+        if (_globalElements.isEmpty()) {
             return EMPTY_GE_ARRAY;
+        }
 
         SchemaGlobalElement[] result = new SchemaGlobalElement[_globalElements.size()];
         int j = 0;
-        for (Iterator i = _globalElements.values().iterator(); i.hasNext(); j++)
-            result[j] = ((SchemaGlobalElement.Ref)i.next()).get();
+        for (Iterator i = _globalElements.values().iterator(); i.hasNext(); j++) {
+            result[j] = ((SchemaGlobalElement.Ref) i.next()).get();
+        }
         return result;
     }
 
-    public SchemaGlobalAttribute[] globalAttributes()
-    {
-        if (_globalAttributes.isEmpty())
+    public SchemaGlobalAttribute[] globalAttributes() {
+        if (_globalAttributes.isEmpty()) {
             return EMPTY_GA_ARRAY;
+        }
 
         SchemaGlobalAttribute[] result = new SchemaGlobalAttribute[_globalAttributes.size()];
         int j = 0;
-        for (Iterator i = _globalAttributes.values().iterator(); i.hasNext(); j++)
-            result[j] = ((SchemaGlobalAttribute.Ref)i.next()).get();
+        for (Iterator i = _globalAttributes.values().iterator(); i.hasNext(); j++) {
+            result[j] = ((SchemaGlobalAttribute.Ref) i.next()).get();
+        }
         return result;
     }
 
-    public SchemaModelGroup[] modelGroups()
-    {
-        if (_modelGroups.isEmpty())
+    public SchemaModelGroup[] modelGroups() {
+        if (_modelGroups.isEmpty()) {
             return EMPTY_MG_ARRAY;
+        }
 
         SchemaModelGroup[] result = new SchemaModelGroup[_modelGroups.size()];
         int j = 0;
-        for (Iterator i = _modelGroups.values().iterator(); i.hasNext(); j++)
-            result[j] = ((SchemaModelGroup.Ref)i.next()).get();
+        for (Iterator i = _modelGroups.values().iterator(); i.hasNext(); j++) {
+            result[j] = ((SchemaModelGroup.Ref) i.next()).get();
+        }
         return result;
     }
 
-    public SchemaModelGroup[] redefinedModelGroups()
-    {
-        if (_redefinedModelGroups == null || _redefinedModelGroups.isEmpty())
+    public SchemaModelGroup[] redefinedModelGroups() {
+        if (_redefinedModelGroups == null || _redefinedModelGroups.isEmpty()) {
             return EMPTY_MG_ARRAY;
+        }
 
         SchemaModelGroup[] result = new SchemaModelGroup[_redefinedModelGroups.size()];
         int j = 0;
-        for (Iterator i = _redefinedModelGroups.iterator(); i.hasNext(); j++)
-            result[j] = ((SchemaModelGroup.Ref)i.next()).get();
+        for (Iterator i = _redefinedModelGroups.iterator(); i.hasNext(); j++) {
+            result[j] = ((SchemaModelGroup.Ref) i.next()).get();
+        }
         return result;
     }
 
-    public SchemaAttributeGroup[] attributeGroups()
-    {
-        if (_attributeGroups.isEmpty())
+    public SchemaAttributeGroup[] attributeGroups() {
+        if (_attributeGroups.isEmpty()) {
             return EMPTY_AG_ARRAY;
+        }
 
         SchemaAttributeGroup[] result = new SchemaAttributeGroup[_attributeGroups.size()];
         int j = 0;
-        for (Iterator i = _attributeGroups.values().iterator(); i.hasNext(); j++)
-            result[j] = ((SchemaAttributeGroup.Ref)i.next()).get();
+        for (Iterator i = _attributeGroups.values().iterator(); i.hasNext(); j++) {
+            result[j] = ((SchemaAttributeGroup.Ref) i.next()).get();
+        }
         return result;
     }
 
-    public SchemaAttributeGroup[] redefinedAttributeGroups()
-    {
-        if (_redefinedAttributeGroups == null || _redefinedAttributeGroups.isEmpty())
+    public SchemaAttributeGroup[] redefinedAttributeGroups() {
+        if (_redefinedAttributeGroups == null || _redefinedAttributeGroups.isEmpty()) {
             return EMPTY_AG_ARRAY;
+        }
 
         SchemaAttributeGroup[] result = new SchemaAttributeGroup[_redefinedAttributeGroups.size()];
         int j = 0;
-        for (Iterator i = _redefinedAttributeGroups.iterator(); i.hasNext(); j++)
-            result[j] = ((SchemaAttributeGroup.Ref)i.next()).get();
+        for (Iterator i = _redefinedAttributeGroups.iterator(); i.hasNext(); j++) {
+            result[j] = ((SchemaAttributeGroup.Ref) i.next()).get();
+        }
         return result;
     }
 
-    public SchemaAnnotation[] annotations()
-    {
-        if (_annotations == null || _annotations.isEmpty())
+    public SchemaAnnotation[] annotations() {
+        if (_annotations == null || _annotations.isEmpty()) {
             return EMPTY_ANN_ARRAY;
+        }
 
         SchemaAnnotation[] result = new SchemaAnnotation[_annotations.size()];
         result = (SchemaAnnotation[]) _annotations.toArray(result);
         return result;
     }
 
-    public SchemaIdentityConstraint[] identityConstraints()
-    {
-        if (_identityConstraints.isEmpty())
+    public SchemaIdentityConstraint[] identityConstraints() {
+        if (_identityConstraints.isEmpty()) {
             return EMPTY_IC_ARRAY;
+        }
 
         SchemaIdentityConstraint[] result = new SchemaIdentityConstraint[_identityConstraints.size()];
         int j = 0;
-        for (Iterator i = _identityConstraints.values().iterator(); i.hasNext(); j++)
-            result[j] = ((SchemaIdentityConstraint.Ref)i.next()).get();
+        for (Iterator i = _identityConstraints.values().iterator(); i.hasNext(); j++) {
+            result[j] = ((SchemaIdentityConstraint.Ref) i.next()).get();
+        }
         return result;
     }
 
-    public ClassLoader getClassLoader()
-    {
+    public ClassLoader getClassLoader() {
         return _classloader;
     }
 
@@ -3823,20 +3550,18 @@
      * Used INTERNALLY ONLY by the code output AFTER the type system has
      * been saved and a handle has been established for each type.
      */
-    public String handleForType(SchemaType type)
-    {
+    public String handleForType(SchemaType type) {
         return _localHandles.handleForType(type);
     }
 
-    public String getName()
-    {
+    public String getName() {
         return _name;
     }
 
-    public SchemaTypeSystem typeSystemForName(String name)
-    {
-        if (_name != null && name.equals(_name))
+    public SchemaTypeSystem typeSystemForName(String name) {
+        if (_name != null && name.equals(_name)) {
             return this;
+        }
         return null;
     }
 
@@ -3845,12 +3570,11 @@
      * Provide method to be overriden by user typesystems using a different metadata path
      *
      * @return the metadata directory
-     *
      * @since XmlBeans 3.1.0
      */
     public String getMetadataPath() {
         Matcher m = packPat.matcher(_name);
         m.find();
-        return m.group(1).replace('.','/');
+        return m.group(1).replace('.', '/');
     }
 }
diff --git a/src/main/java/org/apache/xmlbeans/impl/store/Path.java b/src/main/java/org/apache/xmlbeans/impl/store/Path.java
index 53863f5..505cdc4 100755
--- a/src/main/java/org/apache/xmlbeans/impl/store/Path.java
+++ b/src/main/java/org/apache/xmlbeans/impl/store/Path.java
@@ -15,30 +15,29 @@
 
 package org.apache.xmlbeans.impl.store;
 
-import java.io.*;
+import org.apache.xmlbeans.*;
+import org.apache.xmlbeans.impl.common.DefaultClassLoaderResourceLoader;
+import org.apache.xmlbeans.impl.common.XPath;
+import org.apache.xmlbeans.impl.common.XPathExecutionContext;
+import org.apache.xmlbeans.impl.common.XPath.XPathCompileException;
+import org.w3c.dom.Node;
+
+import java.io.BufferedReader;
+import java.io.InputStream;
+import java.io.InputStreamReader;
+import java.lang.ref.WeakReference;
+import java.lang.reflect.InvocationTargetException;
+import java.lang.reflect.Method;
+import java.math.BigDecimal;
 import java.text.DateFormat;
 import java.text.SimpleDateFormat;
 import java.util.*;
-
-import java.lang.reflect.Method;
-import java.lang.reflect.InvocationTargetException;
-import java.lang.ref.WeakReference;
-import java.math.BigDecimal;
 import java.util.concurrent.locks.ReentrantReadWriteLock;
 
-import org.apache.xmlbeans.impl.common.DefaultClassLoaderResourceLoader;
-import org.apache.xmlbeans.impl.common.XPath;
-import org.apache.xmlbeans.impl.common.XPath.XPathCompileException;
-import org.apache.xmlbeans.impl.common.XPath.ExecutionContext;
-
-import org.apache.xmlbeans.*;
-import org.w3c.dom.Node;
-
 
 // TODO - This class handled query *and* path ... rename it?
 
-public abstract class Path
-{
+public abstract class Path {
     public static final String PATH_DELEGATE_INTERFACE = "PATH_DELEGATE_INTERFACE";
     public static String _useDelegateForXpath = "use delegate for xpath";
     public static String _useXdkForXpath = "use xdk for xpath";
@@ -46,16 +45,16 @@
     public static String _useXbeanForXpath = "use xbean for xpath";
     public static String _forceXqrl2002ForXpathXQuery = "use xqrl-2002 for xpath";
 
-    private static final int USE_XBEAN    = 0x01;
-    private static final int USE_XQRL     = 0x02;
+    private static final int USE_XBEAN = 0x01;
+    private static final int USE_XQRL = 0x02;
     private static final int USE_DELEGATE = 0x04;
     private static final int USE_XQRL2002 = 0x08;
-    private static final int USE_XDK      = 0x10;
+    private static final int USE_XDK = 0x10;
 
-    private static Map _xbeanPathCache = new WeakHashMap();
-    private static Map _xdkPathCache = new WeakHashMap();
-    private static Map _xqrlPathCache = new WeakHashMap();
-    private static Map _xqrl2002PathCache = new WeakHashMap();
+    private static final Map<String,WeakReference<Path>> _xbeanPathCache = new WeakHashMap<>();
+    private static final Map<String,WeakReference<Path>> _xdkPathCache = new WeakHashMap<>();
+    private static final Map<String,WeakReference<Path>> _xqrlPathCache = new WeakHashMap<>();
+    private static final Map<String,WeakReference<Path>> _xqrl2002PathCache = new WeakHashMap<>();
 
     private static Method _xdkCompilePath;
     private static Method _xqrlCompilePath;
@@ -68,13 +67,12 @@
     private static final String _delIntfName;
     private static final ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
 
-    static
-    {
+    static {
         String id = "META-INF/services/org.apache.xmlbeans.impl.store.PathDelegate.SelectPathInterface";
         InputStream in = new DefaultClassLoaderResourceLoader().getResourceAsStream(id);
 
         String name = null;
-        if(in != null) {
+        if (in != null) {
             try {
                 BufferedReader br = new BufferedReader(new InputStreamReader(in));
                 name = br.readLine().trim();
@@ -89,14 +87,12 @@
 
     protected final String _pathKey;
 
-    Path(String key)
-    {
+    Path(String key) {
         _pathKey = key;
     }
 
 
-    interface PathEngine
-    {
+    interface PathEngine {
         void release();
 
         boolean next(Cur c);
@@ -108,8 +104,7 @@
     //
     //
 
-    static String getCurrentNodeVar(XmlOptions options)
-    {
+    static String getCurrentNodeVar(XmlOptions options) {
         String currentNodeVar = "this";
 
         options = XmlOptions.maskNull(options);
@@ -125,171 +120,179 @@
         return currentNodeVar;
     }
 
-    public static Path getCompiledPath(String pathExpr, XmlOptions options)
-    {
+    public static Path getCompiledPath(String pathExpr, XmlOptions options) {
         options = XmlOptions.maskNull(options);
 
         int force =
-                options.hasOption(_useDelegateForXpath) ? USE_DELEGATE
+            options.hasOption(_useDelegateForXpath) ? USE_DELEGATE
                 : options.hasOption(_useXqrlForXpath) ? USE_XQRL
                 : options.hasOption(_useXdkForXpath) ? USE_XDK
                 : options.hasOption(_useXbeanForXpath) ? USE_XBEAN
                 : options.hasOption(_forceXqrl2002ForXpathXQuery) ? USE_XQRL2002
-                : USE_XBEAN|USE_XQRL|USE_XDK|USE_DELEGATE; //set all bits except XQRL2002
-        String delIntfName = 
-            options.hasOption(PATH_DELEGATE_INTERFACE) ? 
-                (String)options.get(PATH_DELEGATE_INTERFACE) : _delIntfName;
+                : USE_XBEAN | USE_XQRL | USE_XDK | USE_DELEGATE; //set all bits except XQRL2002
+        String delIntfName =
+            options.hasOption(PATH_DELEGATE_INTERFACE) ?
+                (String) options.get(PATH_DELEGATE_INTERFACE) : _delIntfName;
 
         return getCompiledPath(pathExpr, force, getCurrentNodeVar(options), delIntfName);
     }
 
     static Path getCompiledPath(String pathExpr, int force,
-        String currentVar, String delIntfName)
-    {
+                                String currentVar, String delIntfName) {
         Path path = null;
-        WeakReference pathWeakRef = null;
-        Map namespaces = (force & USE_DELEGATE) != 0 ? new HashMap() : null;
+        WeakReference<Path> pathWeakRef = null;
+        Map<String,String> namespaces = (force & USE_DELEGATE) != 0 ? new HashMap<>() : null;
         lock.readLock().lock();
         try {
-        if ((force & USE_XBEAN) != 0)
-            pathWeakRef = (WeakReference)_xbeanPathCache.get(pathExpr);
-        if (pathWeakRef == null && (force & USE_XQRL) != 0)
-            pathWeakRef = (WeakReference)_xqrlPathCache.get(pathExpr);
-        if (pathWeakRef == null && (force & USE_XDK) != 0)
-            pathWeakRef = (WeakReference)_xdkPathCache.get(pathExpr);
-        if (pathWeakRef == null && (force & USE_XQRL2002) != 0)
-            pathWeakRef = (WeakReference)_xqrl2002PathCache.get(pathExpr);
+            if ((force & USE_XBEAN) != 0) {
+                pathWeakRef = _xbeanPathCache.get(pathExpr);
+            }
+            if (pathWeakRef == null && (force & USE_XQRL) != 0) {
+                pathWeakRef = _xqrlPathCache.get(pathExpr);
+            }
+            if (pathWeakRef == null && (force & USE_XDK) != 0) {
+                pathWeakRef = _xdkPathCache.get(pathExpr);
+            }
+            if (pathWeakRef == null && (force & USE_XQRL2002) != 0) {
+                pathWeakRef = _xqrl2002PathCache.get(pathExpr);
+            }
 
-        if (pathWeakRef!=null)
-            path = (Path)pathWeakRef.get();
-        if (path != null)
-            return path;
+            if (pathWeakRef != null) {
+                path = pathWeakRef.get();
+            }
+            if (path != null) {
+                return path;
+            }
         } finally {
             lock.readLock().unlock();
         }
         lock.writeLock().lock();
         try {
-        if ((force & USE_XBEAN) != 0) {
-            pathWeakRef = (WeakReference)_xbeanPathCache.get(pathExpr);
-            if (pathWeakRef != null)
-                path = (Path)pathWeakRef.get();
-            if (path==null)
-            path = getCompiledPathXbean(pathExpr, currentVar, namespaces);
-        }
-        if (path == null && (force & USE_XQRL) != 0) {
-            pathWeakRef = (WeakReference)_xqrlPathCache.get(pathExpr);
-            if (pathWeakRef != null)
-                path = (Path)pathWeakRef.get();
-            if (path==null)
-            path = getCompiledPathXqrl(pathExpr, currentVar);
-        }
-        if (path == null && (force & USE_XDK) != 0) {
-            pathWeakRef = (WeakReference)_xdkPathCache.get(pathExpr);
-            if (pathWeakRef != null)
-                path = (Path)pathWeakRef.get();
-            if (path==null)
-            path = getCompiledPathXdk(pathExpr, currentVar);
-        }
-        if (path == null && (force & USE_DELEGATE) != 0) {
-            path = getCompiledPathDelegate(pathExpr, currentVar, namespaces, delIntfName);
-        }
-        if (path == null && (force & USE_XQRL2002) != 0) {
-            pathWeakRef = (WeakReference)_xqrl2002PathCache.get(pathExpr);
-            if (pathWeakRef != null)
-                path = (Path)pathWeakRef.get();
-            if (path==null)
-            path = getCompiledPathXqrl2002(pathExpr, currentVar);
-        }
-        if (path == null)
-        {
-            StringBuilder errMessage = new StringBuilder();
-            if ((force & USE_XBEAN) != 0)
-                errMessage.append(" Trying XBeans path engine...");
-            if ((force & USE_XQRL) != 0)
-                errMessage.append(" Trying XQRL...");
-            if ((force & USE_XDK) != 0)
-                errMessage.append(" Trying XDK...");
-            if ((force & USE_DELEGATE) != 0)
-                errMessage.append(" Trying delegated path engine...");
-            if ((force & USE_XQRL2002) != 0)
-                errMessage.append(" Trying XQRL2002...");
+            if ((force & USE_XBEAN) != 0) {
+                pathWeakRef = _xbeanPathCache.get(pathExpr);
+                if (pathWeakRef != null) {
+                    path = pathWeakRef.get();
+                }
+                if (path == null) {
+                    path = getCompiledPathXbean(pathExpr, currentVar, namespaces);
+                }
+            }
+            if (path == null && (force & USE_XQRL) != 0) {
+                pathWeakRef = _xqrlPathCache.get(pathExpr);
+                if (pathWeakRef != null) {
+                    path = pathWeakRef.get();
+                }
+                if (path == null) {
+                    path = getCompiledPathXqrl(pathExpr, currentVar);
+                }
+            }
+            if (path == null && (force & USE_XDK) != 0) {
+                pathWeakRef = _xdkPathCache.get(pathExpr);
+                if (pathWeakRef != null) {
+                    path = pathWeakRef.get();
+                }
+                if (path == null) {
+                    path = getCompiledPathXdk(pathExpr, currentVar);
+                }
+            }
+            if (path == null && (force & USE_DELEGATE) != 0) {
+                path = getCompiledPathDelegate(pathExpr, currentVar, namespaces, delIntfName);
+            }
+            if (path == null && (force & USE_XQRL2002) != 0) {
+                pathWeakRef = _xqrl2002PathCache.get(pathExpr);
+                if (pathWeakRef != null) {
+                    path = pathWeakRef.get();
+                }
+                if (path == null) {
+                    path = getCompiledPathXqrl2002(pathExpr, currentVar);
+                }
+            }
+            if (path == null) {
+                StringBuilder errMessage = new StringBuilder();
+                if ((force & USE_XBEAN) != 0) {
+                    errMessage.append(" Trying XBeans path engine...");
+                }
+                if ((force & USE_XQRL) != 0) {
+                    errMessage.append(" Trying XQRL...");
+                }
+                if ((force & USE_XDK) != 0) {
+                    errMessage.append(" Trying XDK...");
+                }
+                if ((force & USE_DELEGATE) != 0) {
+                    errMessage.append(" Trying delegated path engine...");
+                }
+                if ((force & USE_XQRL2002) != 0) {
+                    errMessage.append(" Trying XQRL2002...");
+                }
 
-            throw new RuntimeException(errMessage.toString() + " FAILED on " + pathExpr);
-        }
+                throw new RuntimeException(errMessage.toString() + " FAILED on " + pathExpr);
+            }
         } finally {
             lock.writeLock().unlock();
         }
         return path;
     }
 
-    static private Path getCompiledPathXdk(String pathExpr, String currentVar)
-    {
+    static private Path getCompiledPathXdk(String pathExpr, String currentVar) {
         Path path = createXdkCompiledPath(pathExpr, currentVar);
-        if (path != null)
-            _xdkPathCache.put(path._pathKey, new WeakReference(path));
+        if (path != null) {
+            _xdkPathCache.put(path._pathKey, new WeakReference<>(path));
+        }
 
         return path;
     }
 
-    static private Path getCompiledPathXqrl(String pathExpr, String currentVar)
-    {
+    static private Path getCompiledPathXqrl(String pathExpr, String currentVar) {
         Path path = createXqrlCompiledPath(pathExpr, currentVar);
-        if (path != null)
-            _xqrlPathCache.put(path._pathKey, new WeakReference(path));
+        if (path != null) {
+            _xqrlPathCache.put(path._pathKey, new WeakReference<>(path));
+        }
 
         return path;
     }
 
-    static private Path getCompiledPathXqrl2002(String pathExpr, String currentVar)
-    {
+    static private Path getCompiledPathXqrl2002(String pathExpr, String currentVar) {
         Path path = createXqrl2002CompiledPath(pathExpr, currentVar);
-        if (path != null)
-            _xqrl2002PathCache.put(path._pathKey, new WeakReference(path));
+        if (path != null) {
+            _xqrl2002PathCache.put(path._pathKey, new WeakReference<>(path));
+        }
 
         return path;
     }
 
     static private Path getCompiledPathXbean(String pathExpr,
-        String currentVar, Map namespaces)
-    {
+                                             String currentVar, Map<String,String> namespaces) {
         Path path = XbeanPath.create(pathExpr, currentVar, namespaces);
-        if (path != null)
-            _xbeanPathCache.put(path._pathKey, new WeakReference(path));
+        if (path != null) {
+            _xbeanPathCache.put(path._pathKey, new WeakReference<>(path));
+        }
 
         return path;
     }
 
-    static private Path getCompiledPathDelegate(String pathExpr, String currentVar, Map namespaces, String delIntfName)
-    {
-        Path path = null;
-        if ( namespaces == null )
-            namespaces = new HashMap();
-
-        try
-        {
-            XPath.compileXPath(pathExpr, currentVar, namespaces);
+    static private Path getCompiledPathDelegate(String pathExpr, String currentVar, Map<String,String> namespaces, String delIntfName) {
+        if (namespaces == null) {
+            namespaces = new HashMap<>();
         }
-        catch (XPath.XPathCompileException e)
-        {
+
+        try {
+            XPath.compileXPath(pathExpr, currentVar, namespaces);
+        } catch (XPath.XPathCompileException e) {
             //do nothing, this function is only called to populate the namespaces map
         }
 
-        int offset =
-            namespaces.get(XPath._NS_BOUNDARY) == null ?
-            0 :
-            ((Integer) namespaces.get(XPath._NS_BOUNDARY)).intValue();
+
+        int offset = Integer.parseInt(namespaces.getOrDefault(XPath._NS_BOUNDARY, "0"));
         namespaces.remove(XPath._NS_BOUNDARY);
-        path = DelegatePathImpl.create(delIntfName,
+
+        return DelegatePathImpl.create(delIntfName,
             pathExpr.substring(offset),
             currentVar,
             namespaces);
-
-        return path;
     }
 
 
-    public static String compilePath(String pathExpr, XmlOptions options)
-    {
+    public static String compilePath(String pathExpr, XmlOptions options) {
         return getCompiledPath(pathExpr, options)._pathKey;
     }
 
@@ -297,42 +300,35 @@
     // Xbean store specific implementation of compiled path
     //
 
-    private static final class XbeanPath extends Path
-    {
-        static Path create(String pathExpr, String currentVar, Map namespaces)
-        {
-            try
-            {
+    private static final class XbeanPath extends Path {
+        static Path create(String pathExpr, String currentVar, Map<String,String> namespaces) {
+            try {
                 return new XbeanPath(pathExpr, currentVar,
-                                XPath.compileXPath(pathExpr, currentVar, namespaces));
-            }
-            catch (XPathCompileException e) {
+                    XPath.compileXPath(pathExpr, currentVar, namespaces));
+            } catch (XPathCompileException e) {
                 return null;
             }
         }
 
-        private XbeanPath(String pathExpr, String currentVar, XPath xpath)
-        {
+        private XbeanPath(String pathExpr, String currentVar, XPath xpath) {
             super(pathExpr);
 
             _currentVar = currentVar;
             _compiledPath = xpath;
         }
 
-        PathEngine execute(Cur c, XmlOptions options)
-        {
+        PathEngine execute(Cur c, XmlOptions options) {
             options = XmlOptions.maskNull(options);
-            String delIntfName = 
-                options.hasOption(PATH_DELEGATE_INTERFACE) ? 
-                    (String)options.get(PATH_DELEGATE_INTERFACE) : _delIntfName;
+            String delIntfName =
+                options.hasOption(PATH_DELEGATE_INTERFACE) ?
+                    (String) options.get(PATH_DELEGATE_INTERFACE) : _delIntfName;
 
             // The builtin XPath engine works only on containers.  Delegate to
             // xqrl otherwise.  Also, if the path had a //. at the end, the
             // simple xpath engine can't do the generate case, it only handles
             // attrs and elements.
 
-            if (!c.isContainer() || _compiledPath.sawDeepDot())
-            {
+            if (!c.isContainer() || _compiledPath.sawDeepDot()) {
                 int force = USE_DELEGATE | USE_XQRL | USE_XDK;
                 return getCompiledPath(_pathKey, force, _currentVar, delIntfName).execute(c, options);
             }
@@ -341,141 +337,112 @@
 
         private final String _currentVar;
         private final XPath _compiledPath;
-        public Map namespaces;
+        public Map<String,String> namespaces;
     }
 
-    private static Path createXdkCompiledPath(String pathExpr, String currentVar)
-    {
-        if (!_xdkAvailable)
+    private static Path createXdkCompiledPath(String pathExpr, String currentVar) {
+        if (!_xdkAvailable) {
             return null;
+        }
 
-        if (_xdkCompilePath == null)
-        {
-            try
-            {
+        if (_xdkCompilePath == null) {
+            try {
                 Class xdkImpl = Class.forName("org.apache.xmlbeans.impl.store.OXQXBXqrlImpl");
 
                 _xdkCompilePath =
                     xdkImpl.getDeclaredMethod("compilePath",
                         new Class[]{String.class, String.class, Boolean.class});
-            }
-            catch (ClassNotFoundException e)
-            {
+            } catch (ClassNotFoundException e) {
                 _xdkAvailable = false;
                 return null;
-            }
-            catch (Exception e)
-            {
+            } catch (Exception e) {
                 _xdkAvailable = false;
                 throw new RuntimeException(e.getMessage(), e);
             }
         }
 
-        Object[] args = new Object[]{pathExpr, currentVar, new Boolean(true)};
+        Object[] args = new Object[]{pathExpr, currentVar, Boolean.TRUE};
 
         try {
             return (Path) _xdkCompilePath.invoke(null, args);
-        }
-        catch (InvocationTargetException e) {
+        } catch (InvocationTargetException e) {
             Throwable t = e.getCause();
             throw new RuntimeException(t.getMessage(), t);
-        }
-        catch (IllegalAccessException e) {
+        } catch (IllegalAccessException e) {
             throw new RuntimeException(e.getMessage(), e);
         }
     }
 
-    private static Path createXqrlCompiledPath(String pathExpr, String currentVar)
-    {
-        if (!_xqrlAvailable)
+    private static Path createXqrlCompiledPath(String pathExpr, String currentVar) {
+        if (!_xqrlAvailable) {
             return null;
+        }
 
-        if (_xqrlCompilePath == null)
-        {
-            try
-            {
+        if (_xqrlCompilePath == null) {
+            try {
                 Class xqrlImpl = Class.forName("org.apache.xmlbeans.impl.store.XqrlImpl");
 
                 _xqrlCompilePath =
-                        xqrlImpl.getDeclaredMethod("compilePath",
-                                new Class[]{String.class, String.class, Boolean.class});
-            }
-            catch (ClassNotFoundException e)
-            {
+                    xqrlImpl.getDeclaredMethod("compilePath",
+                        new Class[]{String.class, String.class, Boolean.class});
+            } catch (ClassNotFoundException e) {
                 _xqrlAvailable = false;
                 return null;
-            }
-            catch (Exception e)
-            {
+            } catch (Exception e) {
                 _xqrlAvailable = false;
                 throw new RuntimeException(e.getMessage(), e);
             }
         }
 
-        Object[] args = new Object[]{pathExpr, currentVar, new Boolean(true)};
+        Object[] args = new Object[]{pathExpr, currentVar, Boolean.TRUE};
 
         try {
             return (Path) _xqrlCompilePath.invoke(null, args);
-        }
-        catch (InvocationTargetException e) {
+        } catch (InvocationTargetException e) {
             Throwable t = e.getCause();
             throw new RuntimeException(t.getMessage(), t);
-        }
-        catch (IllegalAccessException e) {
+        } catch (IllegalAccessException e) {
             throw new RuntimeException(e.getMessage(), e);
         }
     }
 
-    private static Path createXqrl2002CompiledPath(String pathExpr, String currentVar)
-    {
-        if (!_xqrl2002Available)
+    private static Path createXqrl2002CompiledPath(String pathExpr, String currentVar) {
+        if (!_xqrl2002Available) {
             return null;
+        }
 
-        if (_xqrl2002CompilePath == null)
-        {
-            try
-            {
+        if (_xqrl2002CompilePath == null) {
+            try {
                 Class xqrlImpl = Class.forName("org.apache.xmlbeans.impl.store.Xqrl2002Impl");
 
                 _xqrl2002CompilePath =
                     xqrlImpl.getDeclaredMethod("compilePath",
                         new Class[]{String.class, String.class, Boolean.class});
-            }
-            catch (ClassNotFoundException e)
-            {
+            } catch (ClassNotFoundException e) {
                 _xqrl2002Available = false;
                 return null;
-            }
-            catch (Exception e)
-            {
+            } catch (Exception e) {
                 _xqrl2002Available = false;
                 throw new RuntimeException(e.getMessage(), e);
             }
         }
 
-        Object[] args = new Object[]{pathExpr, currentVar, new Boolean(true)};
+        Object[] args = new Object[]{pathExpr, currentVar, Boolean.TRUE};
 
-        try
-        {
+        try {
             return (Path) _xqrl2002CompilePath.invoke(null, args);
-        }
-        catch (InvocationTargetException e)
-        {
+        } catch (InvocationTargetException e) {
             Throwable t = e.getCause();
             throw new RuntimeException(t.getMessage(), t);
-        }
-        catch (IllegalAccessException e)
-        {
+        } catch (IllegalAccessException e) {
             throw new RuntimeException(e.getMessage(), e);
         }
     }
 
     private static final class XbeanPathEngine
-        extends ExecutionContext
-        implements PathEngine
-    {
-        XbeanPathEngine(XPath xpath, Cur c)
-        {
+        extends XPathExecutionContext
+        implements PathEngine {
+        XbeanPathEngine(XPath xpath, Cur c) {
             assert c.isContainer();
 
             _version = c._locale.version();
@@ -487,62 +454,57 @@
 
             int ret = start();
 
-            if ((ret & HIT) != 0)
+            if ((ret & HIT) != 0) {
                 c.addToSelection();
+            }
 
             doAttrs(ret, c);
 
-            if ((ret & DESCEND) == 0 || !Locale.toFirstChildElement(_cur))
+            if ((ret & DESCEND) == 0 || !Locale.toFirstChildElement(_cur)) {
                 release();
+            }
         }
 
-        private void advance(Cur c)
-        {
+        private void advance(Cur c) {
             assert _cur != null;
 
-            if (_cur.isFinish())
-            {
-                if (_cur.isAtEndOfLastPush())
+            if (_cur.isFinish()) {
+                if (_cur.isAtEndOfLastPush()) {
                     release();
-                else {
+                } else {
                     end();
                     _cur.next();
                 }
-            }
-            else if (_cur.isElem())
-            {
+            } else if (_cur.isElem()) {
                 int ret = element(_cur.getName());
 
-                if ((ret & HIT) != 0)
+                if ((ret & HIT) != 0) {
                     c.addToSelection(_cur);
+                }
 
                 doAttrs(ret, c);
 
-                if ((ret & DESCEND) == 0 || !Locale.toFirstChildElement(_cur))
-                {
+                if ((ret & DESCEND) == 0 || !Locale.toFirstChildElement(_cur)) {
                     end();
                     _cur.skip();
                 }
-            }
-            else
-            {
-                do
-                {
+            } else {
+                do {
                     _cur.next();
                 }
-                while(!_cur.isContainerOrFinish());
+                while (!_cur.isContainerOrFinish());
             }
         }
 
-        private void doAttrs(int ret, Cur c)
-        {
+        private void doAttrs(int ret, Cur c) {
             assert _cur.isContainer();
 
             if ((ret & ATTRS) != 0) {
                 if (_cur.toFirstAttr()) {
                     do {
-                        if (attr(_cur.getName()))
+                        if (attr(_cur.getName())) {
                             c.addToSelection(_cur);
+                        }
                     }
                     while (_cur.toNextAttr());
 
@@ -551,25 +513,25 @@
             }
         }
 
-        public boolean next(Cur c)
-        {
-            if (_cur != null && _version != _cur._locale.version())
+        public boolean next(Cur c) {
+            if (_cur != null && _version != _cur._locale.version()) {
                 throw new ConcurrentModificationException("Document changed during select");
+            }
 
             int startCount = c.selectionCount();
 
             while (_cur != null) {
                 advance(c);
 
-                if (startCount != c.selectionCount())
+                if (startCount != c.selectionCount()) {
                     return true;
+                }
             }
 
             return false;
         }
 
-        public void release()
-        {
+        public void release() {
             if (_cur != null) {
                 _cur.release();
                 _cur = null;
@@ -581,64 +543,59 @@
     }
 
     private static final class DelegatePathImpl
-        extends Path
-    {
+        extends Path {
         private PathDelegate.SelectPathInterface _xpathImpl;
 
-        static Path create(String implClassName, String pathExpr, String currentNodeVar, Map namespaceMap)
-        {
+        static Path create(String implClassName, String pathExpr, String currentNodeVar, Map namespaceMap) {
             assert !currentNodeVar.startsWith("$"); // cezar review with ericvas
 
             PathDelegate.SelectPathInterface impl =
-                    PathDelegate.createInstance(implClassName, pathExpr, currentNodeVar, namespaceMap);
-            if (impl == null)
+                PathDelegate.createInstance(implClassName, pathExpr, currentNodeVar, namespaceMap);
+            if (impl == null) {
                 return null;
+            }
 
             return new DelegatePathImpl(impl, pathExpr);
         }
 
 
         private DelegatePathImpl(PathDelegate.SelectPathInterface xpathImpl,
-                              String pathExpr)
-        {
+                                 String pathExpr) {
             super(pathExpr);
             _xpathImpl = xpathImpl;
         }
 
-        protected PathEngine execute(Cur c, XmlOptions options)
-        {
+        protected PathEngine execute(Cur c, XmlOptions options) {
             return new DelegatePathEngine(_xpathImpl, c);
         }
 
         private static class DelegatePathEngine
-                extends XPath.ExecutionContext
-                implements PathEngine
-        {
+            extends XPathExecutionContext
+            implements PathEngine {
             // full datetime format: yyyy-MM-dd'T'HH:mm:ss'Z'
             private final DateFormat xmlDateFormat = new SimpleDateFormat("yyyy-MM-dd");
 
             DelegatePathEngine(PathDelegate.SelectPathInterface xpathImpl,
-                               Cur c)
-            {
+                               Cur c) {
                 _engine = xpathImpl;
                 _version = c._locale.version();
                 _cur = c.weakCur(this);
             }
 
-            public boolean next(Cur c)
-            {
-                if (!_firstCall)
+            public boolean next(Cur c) {
+                if (!_firstCall) {
                     return false;
+                }
 
                 _firstCall = false;
 
-                if (_cur != null && _version != _cur._locale.version())
+                if (_cur != null && _version != _cur._locale.version()) {
                     throw new ConcurrentModificationException("Document changed during select");
+                }
 
                 List resultsList;
-                Object context_node;
 
-                context_node = _cur.getDom();
+                Object context_node = _cur.getDom();
                 resultsList = _engine.selectPath(context_node);
 
                 int i;
@@ -652,7 +609,7 @@
                         if (obj instanceof Date) {
                             value = xmlDateFormat.format((Date) obj);
                         } else if (obj instanceof BigDecimal) {
-                            value = ((BigDecimal)obj).toPlainString();
+                            value = ((BigDecimal) obj).toPlainString();
                         } else {
                             value = obj.toString();
                         }
@@ -663,19 +620,17 @@
                         Locale l = c._locale;
                         try {
                             pos = l.load("<xml-fragment/>").tempCur();
-                            pos.setValue(value);     
+                            pos.setValue(value);
                             SchemaType type = getType(node);
                             Locale.autoTypeDocument(pos, type, null);
                             //move the cur to the actual text
                             pos.next();
-                        }
-                        catch (Exception e) {
+                        } catch (Exception e) {
                             throw new RuntimeException(e);
                         }
-                    }
-                    else {
-                        assert (node instanceof DomImpl.Dom):
-                                "New object created in XPATH!";
+                    } else {
+                        assert (node instanceof DomImpl.Dom) :
+                            "New object created in XPATH!";
                         pos = ((DomImpl.Dom) node).tempCur();
 
                     }
@@ -687,32 +642,31 @@
                 return true;
             }
 
-            private SchemaType getType(Object node)
-            {
+            private SchemaType getType(Object node) {
                 SchemaType type;
-                if (node instanceof Integer)
+                if (node instanceof Integer) {
                     type = XmlInteger.type;
-                else if (node instanceof Double)
+                } else if (node instanceof Double) {
                     type = XmlDouble.type;
-                else if (node instanceof Long)
+                } else if (node instanceof Long) {
                     type = XmlLong.type;
-                else if (node instanceof Float)
+                } else if (node instanceof Float) {
                     type = XmlFloat.type;
-                else if (node instanceof BigDecimal)
+                } else if (node instanceof BigDecimal) {
                     type = XmlDecimal.type;
-                else if (node instanceof Boolean)
+                } else if (node instanceof Boolean) {
                     type = XmlBoolean.type;
-                else if (node instanceof String)
+                } else if (node instanceof String) {
                     type = XmlString.type;
-                else if (node instanceof Date)
+                } else if (node instanceof Date) {
                     type = XmlDate.type;
-                else
+                } else {
                     type = XmlAnySimpleType.type;
+                }
                 return type;
             }
 
-            public void release()
-            {
+            public void release() {
                 if (_cur != null) {
                     _cur.release();
                     _cur = null;
diff --git a/src/main/java/org/apache/xmlbeans/impl/store/Query.java b/src/main/java/org/apache/xmlbeans/impl/store/Query.java
index 5644ab6..7fc8643 100644
--- a/src/main/java/org/apache/xmlbeans/impl/store/Query.java
+++ b/src/main/java/org/apache/xmlbeans/impl/store/Query.java
@@ -18,20 +18,21 @@
 import org.apache.xmlbeans.*;
 import org.apache.xmlbeans.impl.common.DefaultClassLoaderResourceLoader;
 import org.apache.xmlbeans.impl.common.XPath;
-import org.w3c.dom.*;
+import org.w3c.dom.Node;
 
 import javax.xml.namespace.QName;
-import java.io.*;
+import java.io.BufferedReader;
+import java.io.InputStream;
+import java.io.InputStreamReader;
+import java.lang.reflect.InvocationTargetException;
+import java.lang.reflect.Method;
+import java.math.BigDecimal;
+import java.util.Date;
 import java.util.HashMap;
 import java.util.List;
 import java.util.Map;
-import java.util.Date;
-import java.lang.reflect.Method;
-import java.lang.reflect.InvocationTargetException;
-import java.math.BigDecimal;
 
-public abstract class Query
-{
+public abstract class Query {
     public static final String QUERY_DELEGATE_INTERFACE = "QUERY_DELEGATE_INTERFACE";
     public static String _useDelegateForXQuery = "use delegate for xquery";
     public static String _useXdkForXQuery = "use xdk for xquery";
@@ -48,21 +49,17 @@
     private static boolean _xqrlAvailable = true;  // at the beginning assume is available
 
     private static HashMap _xqrl2002QueryCache = new HashMap();
-    private static Method  _xqrl2002CompileQuery;
+    private static Method _xqrl2002CompileQuery;
     private static boolean _xqrl2002Available = true;  // at the beginning assume is available
 
-    static
-    {
+    static {
         String id = "META-INF/services/org.apache.xmlbeans.impl.store.QueryDelegate.QueryInterface";
         InputStream in = new DefaultClassLoaderResourceLoader().getResourceAsStream(id);
-        try
-        {
+        try {
             BufferedReader br = new BufferedReader(new InputStreamReader(in));
             _delIntfName = br.readLine().trim();
             br.close();
-        }
-        catch (Exception e)
-        {
+        } catch (Exception e) {
             _delIntfName = null;
         }
     }
@@ -75,36 +72,31 @@
     // Xqrl store specific implementation of compiled path/query
     //
 
-    static XmlObject[] objectExecQuery(Cur c, String queryExpr, XmlOptions options)
-    {
+    static XmlObject[] objectExecQuery(Cur c, String queryExpr, XmlOptions options) {
         return getCompiledQuery(queryExpr, options).objectExecute(c, options);
     }
 
-    static XmlCursor cursorExecQuery(Cur c, String queryExpr, XmlOptions options)
-    {
+    static XmlCursor cursorExecQuery(Cur c, String queryExpr, XmlOptions options) {
         return getCompiledQuery(queryExpr, options).cursorExecute(c, options);
     }
 
-    public static synchronized Query getCompiledQuery(String queryExpr, XmlOptions options)
-    {
+    public static synchronized Query getCompiledQuery(String queryExpr, XmlOptions options) {
         return getCompiledQuery(queryExpr, Path.getCurrentNodeVar(options), options);
     }
 
-    static synchronized Query getCompiledQuery(String queryExpr, String currentVar, XmlOptions options)
-    {
+    static synchronized Query getCompiledQuery(String queryExpr, String currentVar, XmlOptions options) {
         assert queryExpr != null;
         options = XmlOptions.maskNull(options);
         Query query;
 
-        if (options.hasOption(Path._forceXqrl2002ForXpathXQuery))
-        {
-            query = (Query)_xqrl2002QueryCache.get(queryExpr);
-            if (query!=null)
+        if (options.hasOption(Path._forceXqrl2002ForXpathXQuery)) {
+            query = (Query) _xqrl2002QueryCache.get(queryExpr);
+            if (query != null) {
                 return query;
+            }
 
             query = getXqrl2002CompiledQuery(queryExpr, currentVar);
-            if (query!=null)
-            {
+            if (query != null) {
                 _xqrl2002QueryCache.put(queryExpr, query);
                 return query;
             }
@@ -113,66 +105,57 @@
 
         //Parse the query via XBeans: need to figure out end of prolog
         //in order to bind $this...not good but...
-        Map boundary = new HashMap();
-        int boundaryVal = 0;
-        try
-        {
+        Map<String, String> boundary = new HashMap<>();
+        int boundaryVal;
+        try {
             XPath.compileXPath(queryExpr, currentVar, boundary);
-        }
-        catch (XPath.XPathCompileException e)
-        {
+        } catch (XPath.XPathCompileException e) {
             //don't care if it fails, just care about boundary
-        }
-        finally
-        {
-            boundaryVal = boundary.get(XPath._NS_BOUNDARY) == null ? 0 :
-                ((Integer) boundary.get(XPath._NS_BOUNDARY)).intValue();
+        } finally {
+            boundaryVal = Integer.parseInt(boundary.getOrDefault(XPath._NS_BOUNDARY, "0"));
         }
 
-        if (options.hasOption(_useXdkForXQuery))
-        {
+        if (options.hasOption(_useXdkForXQuery)) {
             //try XDK
             query = (Query) _xdkQueryCache.get(queryExpr);
-            if (query != null)
+            if (query != null) {
                 return query;
+            }
 
             query = createXdkCompiledQuery(queryExpr, currentVar);
-            if (query != null)
-            {
+            if (query != null) {
                 _xdkQueryCache.put(queryExpr, query);
                 return query;
             }
         }
 
-        if (!options.hasOption(_useDelegateForXQuery))
-        {
-        //try XQRL
-        query = (Query) _xqrlQueryCache.get(queryExpr);
-        if (query != null)
-            return query;
+        if (!options.hasOption(_useDelegateForXQuery)) {
+            //try XQRL
+            query = (Query) _xqrlQueryCache.get(queryExpr);
+            if (query != null) {
+                return query;
+            }
 
-        query = createXqrlCompiledQuery(queryExpr, currentVar);
-        if (query != null)
-        {
-            _xqrlQueryCache.put(queryExpr, query);
-            return query;
-        }
+            query = createXqrlCompiledQuery(queryExpr, currentVar);
+            if (query != null) {
+                _xqrlQueryCache.put(queryExpr, query);
+                return query;
+            }
         }
 
-        //otherwise (if _useDelegateForXQuery option is set), 
+        //otherwise (if _useDelegateForXQuery option is set),
         //or if xqrl is not found, try delegate
         //query = (Query) _delegateQueryCache.get(queryExpr);
 
         //if (query != null)
         //    return query;
 
-        String delIntfName = 
-            options.hasOption(QUERY_DELEGATE_INTERFACE) ? 
-                (String)options.get(QUERY_DELEGATE_INTERFACE) : _delIntfName;
+        String delIntfName =
+            options.hasOption(QUERY_DELEGATE_INTERFACE) ?
+                (String) options.get(QUERY_DELEGATE_INTERFACE) : _delIntfName;
         query = DelegateQueryImpl.createDelegateCompiledQuery(delIntfName, queryExpr, currentVar, boundaryVal, options);
 
-        if (query != null)
-        {
+        if (query != null) {
             //_delegateQueryCache.put(queryExpr, query);
             return query;
         }
@@ -180,33 +163,27 @@
         throw new RuntimeException("No query engine found");
     }
 
-    public static synchronized String compileQuery(String queryExpr, XmlOptions options)
-    {
+    public static synchronized String compileQuery(String queryExpr, XmlOptions options) {
         getCompiledQuery(queryExpr, options);
         return queryExpr;
     }
 
-    private static Query createXdkCompiledQuery(String queryExpr, String currentVar)
-    {
+    private static Query createXdkCompiledQuery(String queryExpr, String currentVar) {
         //if the XDK engine has been determined unavailable, return null
-        if ( !_xdkAvailable ) return null;
-        if ( _xdkCompileQuery == null)
-        {
-            try
-            {
+        if (!_xdkAvailable) {
+            return null;
+        }
+        if (_xdkCompileQuery == null) {
+            try {
                 Class xdkImpl = Class.forName("org.apache.xmlbeans.impl.store.OXQXBXqrlImpl");
 
                 _xdkCompileQuery =
                     xdkImpl.getDeclaredMethod("compileQuery",
                         new Class[]{String.class, String.class, Boolean.class});
-            }
-            catch (ClassNotFoundException e)
-            {
+            } catch (ClassNotFoundException e) {
                 _xdkAvailable = false;
                 return null;
-            }
-            catch (Exception e)
-            {
+            } catch (Exception e) {
                 _xdkAvailable = false;
                 throw new RuntimeException(e.getMessage(), e);
             }
@@ -214,42 +191,32 @@
 
         Object[] args = new Object[]{queryExpr, currentVar, new Boolean(true)};
 
-        try
-        {
+        try {
             return (Query) _xdkCompileQuery.invoke(null, args);
-        }
-        catch (InvocationTargetException e)
-        {
+        } catch (InvocationTargetException e) {
             Throwable t = e.getCause();
             throw new RuntimeException(t.getMessage(), t);
-        }
-        catch (IllegalAccessException e)
-        {
+        } catch (IllegalAccessException e) {
             throw new RuntimeException(e.getMessage(), e);
         }
     }
 
-    private static Query createXqrlCompiledQuery(String queryExpr, String currentVar)
-    {
+    private static Query createXqrlCompiledQuery(String queryExpr, String currentVar) {
         //if the XQRL engine has been determined unavailable, return null
-        if ( !_xqrlAvailable ) return null;
-        if ( _xqrlCompileQuery == null)
-        {
-            try
-            {
+        if (!_xqrlAvailable) {
+            return null;
+        }
+        if (_xqrlCompileQuery == null) {
+            try {
                 Class xqrlImpl = Class.forName("org.apache.xmlbeans.impl.store.XqrlImpl");
 
                 _xqrlCompileQuery =
-                        xqrlImpl.getDeclaredMethod("compileQuery",
-                                new Class[]{String.class, String.class, Boolean.class});
-            }
-            catch (ClassNotFoundException e)
-            {
+                    xqrlImpl.getDeclaredMethod("compileQuery",
+                        new Class[]{String.class, String.class, Boolean.class});
+            } catch (ClassNotFoundException e) {
                 _xqrlAvailable = false;
                 return null;
-            }
-            catch (Exception e)
-            {
+            } catch (Exception e) {
                 _xqrlAvailable = false;
                 throw new RuntimeException(e.getMessage(), e);
             }
@@ -257,40 +224,28 @@
 
         Object[] args = new Object[]{queryExpr, currentVar, new Boolean(true)};
 
-        try
-        {
+        try {
             return (Query) _xqrlCompileQuery.invoke(null, args);
-        }
-        catch (InvocationTargetException e)
-        {
+        } catch (InvocationTargetException e) {
             Throwable t = e.getCause();
             throw new RuntimeException(t.getMessage(), t);
-        }
-        catch (IllegalAccessException e)
-        {
+        } catch (IllegalAccessException e) {
             throw new RuntimeException(e.getMessage(), e);
         }
     }
 
-    private static Query getXqrl2002CompiledQuery(String queryExpr, String currentVar)
-    {
-        if (_xqrl2002Available && _xqrl2002CompileQuery == null)
-        {
-            try
-            {
+    private static Query getXqrl2002CompiledQuery(String queryExpr, String currentVar) {
+        if (_xqrl2002Available && _xqrl2002CompileQuery == null) {
+            try {
                 Class xqrlImpl = Class.forName("org.apache.xmlbeans.impl.store.Xqrl2002Impl");
 
                 _xqrl2002CompileQuery =
-                        xqrlImpl.getDeclaredMethod("compileQuery",
-                                new Class[]{String.class, String.class, Boolean.class});
-            }
-            catch (ClassNotFoundException e)
-            {
+                    xqrlImpl.getDeclaredMethod("compileQuery",
+                        new Class[]{String.class, String.class, Boolean.class});
+            } catch (ClassNotFoundException e) {
                 _xqrl2002Available = false;
                 return null;
-            }
-            catch (Exception e)
-            {
+            } catch (Exception e) {
                 _xqrl2002Available = false;
                 throw new RuntimeException(e.getMessage(), e);
             }
@@ -298,25 +253,18 @@
 
         Object[] args = new Object[]{queryExpr, currentVar, new Boolean(true)};
 
-        try
-        {
+        try {
             return (Query) _xqrl2002CompileQuery.invoke(null, args);
-        }
-        catch (InvocationTargetException e)
-        {
+        } catch (InvocationTargetException e) {
             Throwable t = e.getCause();
             throw new RuntimeException(t.getMessage(), t);
-        }
-        catch (IllegalAccessException e)
-        {
+        } catch (IllegalAccessException e) {
             throw new RuntimeException(e.getMessage(), e);
         }
     }
 
-    private static final class DelegateQueryImpl extends Query
-    {
-        private DelegateQueryImpl(QueryDelegate.QueryInterface xqueryImpl)
-        {
+    private static final class DelegateQueryImpl extends Query {
+        private DelegateQueryImpl(QueryDelegate.QueryInterface xqueryImpl) {
             _xqueryImpl = xqueryImpl;
         }
 
@@ -324,34 +272,30 @@
                                                  String queryExpr,
                                                  String currentVar,
                                                  int boundary,
-                                                 XmlOptions xmlOptions)
-        {
+                                                 XmlOptions xmlOptions) {
             assert !(currentVar.startsWith(".") || currentVar.startsWith(".."));
             QueryDelegate.QueryInterface impl =
                 QueryDelegate.createInstance(delIntfName, queryExpr,
-                                             currentVar, boundary, xmlOptions);
-            if (impl == null)
+                    currentVar, boundary, xmlOptions);
+            if (impl == null) {
                 return null;
+            }
 
             return new DelegateQueryImpl(impl);
         }
 
-        XmlObject[] objectExecute(Cur c, XmlOptions options)
-        {
+        XmlObject[] objectExecute(Cur c, XmlOptions options) {
             return new DelegateQueryEngine(_xqueryImpl, c, options).objectExecute();
         }
 
-        XmlCursor cursorExecute(Cur c, XmlOptions options)
-        {
+        XmlCursor cursorExecute(Cur c, XmlOptions options) {
             return new DelegateQueryEngine(_xqueryImpl, c, options).cursorExecute();
         }
 
 
-        private static class DelegateQueryEngine
-        {
+        private static class DelegateQueryEngine {
             public DelegateQueryEngine(QueryDelegate.QueryInterface xqImpl,
-                                    Cur c, XmlOptions opt)
-            {
+                                       Cur c, XmlOptions opt) {
 
                 _engine = xqImpl;
                 _version = c._locale.version();
@@ -360,12 +304,13 @@
 
             }
 
-            public XmlObject[] objectExecute()
-            {
+            public XmlObject[] objectExecute() {
                 if (_cur != null && _version != _cur._locale.version())
                 //throw new ConcurrentModificationException
                 // ("Document changed during select")
+                {
                     ;
+                }
 
                 Map bindings = (Map) XmlOptions.maskNull(_options).
                     get(XmlOptions.XQUERY_VARIABLE_MAP);
@@ -379,7 +324,7 @@
                 for (i = 0; i < resultsList.size(); i++) {
                     //copy objects into the locale
                     Locale l = Locale.getLocale(_cur._locale._schemaTypeLoader,
-                            _options);
+                        _options);
 
                     l.enter();
                     Object node = resultsList.get(i);
@@ -392,18 +337,16 @@
                             //superclass???
                             res = l.load("<xml-fragment/>").tempCur();
                             res.setValue(node.toString());
-                            SchemaType type=getType(node);
+                            SchemaType type = getType(node);
                             Locale.autoTypeDocument(res, type, null);
                             result[i] = res.getObject();
-                        }
-                        else
+                        } else {
                             res = loadNode(l, (Node) node);
+                        }
                         result[i] = res.getObject();
-                    }
-                    catch (XmlException e) {
+                    } catch (XmlException e) {
                         throw new RuntimeException(e);
-                    }
-                    finally {
+                    } finally {
                         l.exit();
                     }
                     res.release();
@@ -412,35 +355,38 @@
                 _engine = null;
                 return result;
             }
-            private SchemaType getType(Object node)
-            {
+
+            private SchemaType getType(Object node) {
                 SchemaType type;
-                if (node instanceof Integer)
+                if (node instanceof Integer) {
                     type = XmlInteger.type;
-                else if (node instanceof Double)
+                } else if (node instanceof Double) {
                     type = XmlDouble.type;
-                else if (node instanceof Long)
+                } else if (node instanceof Long) {
                     type = XmlLong.type;
-                else if (node instanceof Float)
+                } else if (node instanceof Float) {
                     type = XmlFloat.type;
-                else if (node instanceof BigDecimal)
+                } else if (node instanceof BigDecimal) {
                     type = XmlDecimal.type;
-                else if (node instanceof Boolean)
+                } else if (node instanceof Boolean) {
                     type = XmlBoolean.type;
-                else if (node instanceof String)
+                } else if (node instanceof String) {
                     type = XmlString.type;
-                else if (node instanceof Date)
+                } else if (node instanceof Date) {
                     type = XmlDate.type;
-                else
+                } else {
                     type = XmlAnySimpleType.type;
+                }
                 return type;
             }
-            public XmlCursor cursorExecute()
-            {
+
+            public XmlCursor cursorExecute() {
                 if (_cur != null && _version != _cur._locale.version())
                 //throw new ConcurrentModificationException
                 // ("Document changed during select")
+                {
                     ;
+                }
 
                 Map bindings = (Map) XmlOptions.maskNull(_options).
                     get(XmlOptions.XQUERY_VARIABLE_MAP);
@@ -464,10 +410,8 @@
                     Locale.associateSourceName(c, _options);
                     Locale.autoTypeDocument(c, null, _options);
                     resultCur = new Cursor(c);
-                }
-                catch (Exception e) {
-                }
-                finally {
+                } catch (Exception e) {
+                } finally {
                     locale.exit();
                 }
                 release();
@@ -475,8 +419,7 @@
             }
 
 
-            public void release()
-            {
+            public void release() {
                 if (_cur != null) {
                     _cur.release();
                     _cur = null;
@@ -484,8 +427,7 @@
             }
 
 
-            private Cur loadNode(Locale locale, Node node)
-            {
+            private Cur loadNode(Locale locale, Node node) {
                 Locale.LoadContext context = new Cur.CurLoadContext(locale, _options);
 
                 try {
@@ -494,22 +436,20 @@
                     Locale.associateSourceName(c, _options);
                     Locale.autoTypeDocument(c, null, _options);
                     return c;
-                }
-                catch (Exception e) {
+                } catch (Exception e) {
                     throw new XmlRuntimeException(e.getMessage(), e);
                 }
             }
 
-            private void loadNodeHelper(Locale locale, Node node, Locale.LoadContext context)
-            {
+            private void loadNodeHelper(Locale locale, Node node, Locale.LoadContext context) {
                 if (node.getNodeType() == Node.ATTRIBUTE_NODE) {
-                        QName attName = new QName(node.getNamespaceURI(),
-                            node.getLocalName(),
-                            node.getPrefix());
-                        context.attr(attName, node.getNodeValue());
-                        }
-                else
-                        locale.loadNode(node, context);
+                    QName attName = new QName(node.getNamespaceURI(),
+                        node.getLocalName(),
+                        node.getPrefix());
+                    context.attr(attName, node.getNodeValue());
+                } else {
+                    locale.loadNode(node, context);
+                }
 
             }