You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@jena.apache.org by an...@apache.org on 2018/05/04 09:03:02 UTC

[01/24] jena git commit: JENA-1537: Remove dependency on Xerces. Import needed code

Repository: jena
Updated Branches:
  refs/heads/master 88cd917f2 -> 2e917bd07


http://git-wip-us.apache.org/repos/asf/jena/blob/c9a7e646/jena-core/src/test/java/org/apache/jena/rdfxml/xmloutput/TestPackage.java
----------------------------------------------------------------------
diff --git a/jena-core/src/test/java/org/apache/jena/rdfxml/xmloutput/TestPackage.java b/jena-core/src/test/java/org/apache/jena/rdfxml/xmloutput/TestPackage.java
index f77a351..65d6c6e 100644
--- a/jena-core/src/test/java/org/apache/jena/rdfxml/xmloutput/TestPackage.java
+++ b/jena-core/src/test/java/org/apache/jena/rdfxml/xmloutput/TestPackage.java
@@ -38,9 +38,12 @@ public class TestPackage extends TestCase{
      */
     public static TestSuite suite() {
         TestSuite suite = new TestSuite();
-        suite.addTest( TestMacEncodings.suite() );
+        
+        // JENA-1537
+        // Character encoding checks removed due to lack of support in JDK XML parser APIs.  
+        //suite.addTest( TestMacEncodings.suite() );
+        
         // add all the tests defined in this class to the suite
-        /* */
         suite.addTestSuite( PrettyWriterTest.class );
         suite.addTest(new TestWriterInterface("testInterface", null)); 
         suite.addTest( testWriterAndReader.suiteXML() );

http://git-wip-us.apache.org/repos/asf/jena/blob/c9a7e646/jena-db/jena-tdb2/src/main/java/org/apache/jena/tdb2/store/value/DateTimeNode.java
----------------------------------------------------------------------
diff --git a/jena-db/jena-tdb2/src/main/java/org/apache/jena/tdb2/store/value/DateTimeNode.java b/jena-db/jena-tdb2/src/main/java/org/apache/jena/tdb2/store/value/DateTimeNode.java
index 9989414..256ac13 100644
--- a/jena-db/jena-tdb2/src/main/java/org/apache/jena/tdb2/store/value/DateTimeNode.java
+++ b/jena-db/jena-tdb2/src/main/java/org/apache/jena/tdb2/store/value/DateTimeNode.java
@@ -20,7 +20,6 @@ package org.apache.jena.tdb2.store.value;
 
 import java.math.BigDecimal ;
 
-import javax.xml.datatype.DatatypeConfigurationException ;
 import javax.xml.datatype.DatatypeConstants ;
 import javax.xml.datatype.DatatypeFactory ;
 import javax.xml.datatype.XMLGregorianCalendar ;
@@ -28,7 +27,7 @@ import javax.xml.datatype.XMLGregorianCalendar ;
 import org.apache.jena.atlas.lib.BitsInt ;
 import org.apache.jena.atlas.lib.BitsLong ;
 import org.apache.jena.atlas.lib.NumberUtils ;
-import org.apache.jena.tdb2.TDBException;
+import org.apache.jena.ext.xerces.DatatypeFactoryInst;
 
 public class DateTimeNode
 {
@@ -77,15 +76,8 @@ public class DateTimeNode
     // Value for no timezone.
     static final int       TZ_NONE         = 0x7E;
     
-    static DatatypeFactory datatypeFactory = null;
-    static {
-        try {
-            datatypeFactory = DatatypeFactory.newInstance();
-        }
-        catch (DatatypeConfigurationException ex) {
-            throw new TDBException("DateTimeNode", ex);
-        }
-    }
+    // JENA-1537: The Xerces 2.11.0 DatatypeFactory gets T24:00:00 right.
+    static DatatypeFactory datatypeFactory = DatatypeFactoryInst.newDatatypeFactory();
 
     // Packed in correct place.
     static long time(long v, int hour, int mins, int millisec) {

http://git-wip-us.apache.org/repos/asf/jena/blob/c9a7e646/jena-db/jena-tdb2/src/test/java/org/apache/jena/tdb2/store/value/TestNodeIdInline.java
----------------------------------------------------------------------
diff --git a/jena-db/jena-tdb2/src/test/java/org/apache/jena/tdb2/store/value/TestNodeIdInline.java b/jena-db/jena-tdb2/src/test/java/org/apache/jena/tdb2/store/value/TestNodeIdInline.java
index 480e5ff..519d635 100644
--- a/jena-db/jena-tdb2/src/test/java/org/apache/jena/tdb2/store/value/TestNodeIdInline.java
+++ b/jena-db/jena-tdb2/src/test/java/org/apache/jena/tdb2/store/value/TestNodeIdInline.java
@@ -135,7 +135,7 @@ public class TestNodeIdInline
     @Test public void nodeId_dateTime_06()
     { test("'2008-04-28T15:36:05.450'^^xsd:dateTime", "'2008-04-28T15:36:05.45'^^xsd:dateTime") ; }
 
-    // Old Java bug, now fixed: T24:00:00 not accepted by DatatypeFactory.newXMLGregorianCalendar(lex)
+    // Old Java bug, now fixed: T24:00:00 not accepted by JDK DatatypeFactory.newXMLGregorianCalendar(lex)
     // Note the Jena value is an XSDDateTime so it retains the "24"/"00" next day distinction. 
     @Test public void nodeId_dateTime_07()
     { test("'2008-04-28T24:00:00'^^xsd:dateTime") ; }

http://git-wip-us.apache.org/repos/asf/jena/blob/c9a7e646/jena-tdb/src/main/java/org/apache/jena/tdb/store/DateTimeNode.java
----------------------------------------------------------------------
diff --git a/jena-tdb/src/main/java/org/apache/jena/tdb/store/DateTimeNode.java b/jena-tdb/src/main/java/org/apache/jena/tdb/store/DateTimeNode.java
index 1ce79c9..1d9770d 100644
--- a/jena-tdb/src/main/java/org/apache/jena/tdb/store/DateTimeNode.java
+++ b/jena-tdb/src/main/java/org/apache/jena/tdb/store/DateTimeNode.java
@@ -20,7 +20,6 @@ package org.apache.jena.tdb.store;
 
 import java.math.BigDecimal ;
 
-import javax.xml.datatype.DatatypeConfigurationException ;
 import javax.xml.datatype.DatatypeConstants ;
 import javax.xml.datatype.DatatypeFactory ;
 import javax.xml.datatype.XMLGregorianCalendar ;
@@ -28,7 +27,7 @@ import javax.xml.datatype.XMLGregorianCalendar ;
 import org.apache.jena.atlas.lib.BitsInt ;
 import org.apache.jena.atlas.lib.BitsLong ;
 import org.apache.jena.atlas.lib.NumberUtils ;
-import org.apache.jena.tdb.TDBException ;
+import org.apache.jena.ext.xerces.DatatypeFactoryInst;
 
 public class DateTimeNode
 {
@@ -74,15 +73,9 @@ public class DateTimeNode
     static final int TZ_LEN = 7 ;
     static final int TZ_Z = 0x7F ;      // Value for Z
     static final int TZ_NONE = 0x7E ;   // Value for no timezone.
-    
-    static DatatypeFactory datatypeFactory = null ;
-    static
-    { 
-        try 
-        { datatypeFactory = DatatypeFactory.newInstance() ; }
-        catch (DatatypeConfigurationException ex)
-        { throw new TDBException("DateTimeNode", ex) ; }
-    }
+
+    // JENA-1537: The Xerces 2.11.0 DatatypeFactory gets T24:00:00 right.
+    static DatatypeFactory datatypeFactory = DatatypeFactoryInst.newDatatypeFactory();
     
     // Packed in correct place.
     static long time(long v, int hour, int mins, int millisec)

http://git-wip-us.apache.org/repos/asf/jena/blob/c9a7e646/jena-tdb/src/main/java/org/apache/jena/tdb/store/NodeId.java
----------------------------------------------------------------------
diff --git a/jena-tdb/src/main/java/org/apache/jena/tdb/store/NodeId.java b/jena-tdb/src/main/java/org/apache/jena/tdb/store/NodeId.java
index 92cebd6..8fecb72 100644
--- a/jena-tdb/src/main/java/org/apache/jena/tdb/store/NodeId.java
+++ b/jena-tdb/src/main/java/org/apache/jena/tdb/store/NodeId.java
@@ -245,9 +245,6 @@ public class NodeId
         }
         
         if ( XSDDatatype.XSDdateTime.isValidLiteral(lit) ) {
-            // Could use the Jena/XSDDateTime object here rather than reparse the lexical
-            // form.
-            // But this works and it's close to a release ...
             long v = DateTimeNode.packDateTime(lit.getLexicalForm());
             if ( v == -1 )
                 return null;

http://git-wip-us.apache.org/repos/asf/jena/blob/c9a7e646/jena-tdb/src/test/java/org/apache/jena/tdb/store/TestNodeId.java
----------------------------------------------------------------------
diff --git a/jena-tdb/src/test/java/org/apache/jena/tdb/store/TestNodeId.java b/jena-tdb/src/test/java/org/apache/jena/tdb/store/TestNodeId.java
index be1b64b..ea5d95b 100644
--- a/jena-tdb/src/test/java/org/apache/jena/tdb/store/TestNodeId.java
+++ b/jena-tdb/src/test/java/org/apache/jena/tdb/store/TestNodeId.java
@@ -152,7 +152,7 @@ public class TestNodeId extends BaseTest
     @Test public void nodeId_dateTime_06()
     { test("'2008-04-28T15:36:05.450'^^xsd:dateTime", "'2008-04-28T15:36:05.45'^^xsd:dateTime") ; }
 
-    // Old Java bug, now fixed: T24:00:00 not accepted by DatatypeFactory.newXMLGregorianCalendar(lex)
+    // Old Java bug, now fixed: T24:00:00 not accepted by JDK DatatypeFactory.newXMLGregorianCalendar(lex)
     // Note the Jena value is an XSDDateTime so it retains the "24"/"00" next day distinction. 
     @Test public void nodeId_dateTime_07()
     { test("'2008-04-28T24:00:00'^^xsd:dateTime") ; }

http://git-wip-us.apache.org/repos/asf/jena/blob/c9a7e646/pom.xml
----------------------------------------------------------------------
diff --git a/pom.xml b/pom.xml
index c58cb5c..750ddb8 100644
--- a/pom.xml
+++ b/pom.xml
@@ -54,7 +54,6 @@
     <ver.slf4j>1.7.25</ver.slf4j>
     <ver.log4j>1.2.17</ver.log4j>
     <ver.junit>4.12</ver.junit>
-    <ver.xerces>2.11.0</ver.xerces>
     <ver.libthrift>0.10.0</ver.libthrift>
 
     <!-- jsonld-java depends on depends on Jackson core
@@ -281,12 +280,6 @@
       </dependency>
 
       <dependency>
-        <groupId>xerces</groupId>
-        <artifactId>xercesImpl</artifactId>
-        <version>${ver.xerces}</version>
-      </dependency>
-
-      <dependency>
         <groupId>org.apache.httpcomponents</groupId>
         <artifactId>httpclient-cache</artifactId>
         <version>${ver.httpclient}</version>


[19/24] jena git commit: JENA-1537: Remove dependency on Xerces. Import needed code

Posted by an...@apache.org.
http://git-wip-us.apache.org/repos/asf/jena/blob/c9a7e646/jena-core/src/main/java/org/apache/jena/ext/xerces/impl/dv/xs/DateDV.java
----------------------------------------------------------------------
diff --git a/jena-core/src/main/java/org/apache/jena/ext/xerces/impl/dv/xs/DateDV.java b/jena-core/src/main/java/org/apache/jena/ext/xerces/impl/dv/xs/DateDV.java
new file mode 100644
index 0000000..66bb727
--- /dev/null
+++ b/jena-core/src/main/java/org/apache/jena/ext/xerces/impl/dv/xs/DateDV.java
@@ -0,0 +1,96 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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.jena.ext.xerces.impl.dv.xs;
+
+import javax.xml.datatype.DatatypeConstants;
+import javax.xml.datatype.XMLGregorianCalendar;
+
+import org.apache.jena.ext.xerces.impl.dv.InvalidDatatypeValueException;
+import org.apache.jena.ext.xerces.impl.dv.ValidationContext;
+
+/**
+ * Validator for <date> datatype (W3C Schema datatypes)
+ *
+ * @xerces.internal 
+ *
+ * @author Elena Litani
+ * @author Gopal Sharma, SUN Microsystems Inc.
+ *
+ * @version $Id: DateDV.java 937741 2010-04-25 04:25:46Z mrglavas $
+ */
+public class DateDV extends DateTimeDV {
+
+    @Override
+    public Object getActualValue(String content, ValidationContext context) throws InvalidDatatypeValueException {
+        try{
+            return parse(content);
+        } catch(Exception ex){
+            throw new InvalidDatatypeValueException("cvc-datatype-valid.1.2.1", new Object[]{content, "date"});
+        }
+    }
+
+    /**
+     * Parses, validates and computes normalized version of dateTime object
+     *
+     * @param str    The lexical representation of dateTime object CCYY-MM-DD
+     *               with possible time zone Z or (-),(+)hh:mm
+     * @return normalized dateTime representation
+     * @exception SchemaDateTimeException Invalid lexical representation
+     */
+    @Override
+    protected DateTimeData parse(String str) throws SchemaDateTimeException {
+        DateTimeData date = new DateTimeData(str, this);
+        int len = str.length();
+
+        int end = getDate(str, 0, len, date);
+        parseTimeZone (str, end, len, date);
+
+        //validate and normalize
+        //REVISIT: do we need SchemaDateTimeException?
+        validateDateTime(date);
+
+        //save unnormalized values
+        saveUnnormalized(date);
+        
+        if (date.utc!=0 && date.utc!='Z') {
+            normalize(date);
+        }
+        return date;
+    }
+
+    @Override
+    protected String dateToString(DateTimeData date) {
+        StringBuffer message = new StringBuffer(25);
+        append(message, date.year, 4);
+        message.append('-');
+        append(message, date.month, 2);
+        message.append('-');
+        append(message, date.day, 2);
+        append(message, (char)date.utc, 0);
+        return message.toString();
+    }
+    
+    @Override
+    protected XMLGregorianCalendar getXMLGregorianCalendar(DateTimeData date) {
+        return datatypeFactory.newXMLGregorianCalendar(date.unNormYear, date.unNormMonth, 
+                date.unNormDay, DatatypeConstants.FIELD_UNDEFINED, DatatypeConstants.FIELD_UNDEFINED, 
+                DatatypeConstants.FIELD_UNDEFINED, DatatypeConstants.FIELD_UNDEFINED, 
+                date.hasTimeZone() ? (date.timezoneHr * 60 + date.timezoneMin) : DatatypeConstants.FIELD_UNDEFINED);
+    }
+
+}

http://git-wip-us.apache.org/repos/asf/jena/blob/c9a7e646/jena-core/src/main/java/org/apache/jena/ext/xerces/impl/dv/xs/DateTimeDV.java
----------------------------------------------------------------------
diff --git a/jena-core/src/main/java/org/apache/jena/ext/xerces/impl/dv/xs/DateTimeDV.java b/jena-core/src/main/java/org/apache/jena/ext/xerces/impl/dv/xs/DateTimeDV.java
new file mode 100644
index 0000000..a91d578
--- /dev/null
+++ b/jena-core/src/main/java/org/apache/jena/ext/xerces/impl/dv/xs/DateTimeDV.java
@@ -0,0 +1,95 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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.jena.ext.xerces.impl.dv.xs;
+
+import java.math.BigInteger;
+
+import javax.xml.datatype.DatatypeConstants;
+import javax.xml.datatype.XMLGregorianCalendar;
+
+import org.apache.jena.ext.xerces.impl.dv.InvalidDatatypeValueException;
+import org.apache.jena.ext.xerces.impl.dv.ValidationContext;
+
+/**
+ * Validator for &lt;dateTime&gt; datatype (W3C Schema Datatypes)
+ *
+ * @xerces.internal 
+ *
+ * @author Elena Litani
+ * @author Gopal Sharma, SUN Microsystem Inc.
+ *
+ * @version $Id: DateTimeDV.java 937741 2010-04-25 04:25:46Z mrglavas $
+ */
+public class DateTimeDV extends AbstractDateTimeDV {
+
+    @Override
+    public Object getActualValue(String content, ValidationContext context) throws InvalidDatatypeValueException {
+        try{
+            return parse(content);
+        } catch(Exception ex){
+            throw new InvalidDatatypeValueException("cvc-datatype-valid.1.2.1", new Object[]{content, "dateTime"});
+        }
+    }
+
+    /**
+     * Parses, validates and computes normalized version of dateTime object
+     *
+     * @param str    The lexical representation of dateTime object CCYY-MM-DDThh:mm:ss.sss
+     *               with possible time zone Z or (-),(+)hh:mm
+     * @return normalized dateTime representation
+     * @exception SchemaDateTimeException Invalid lexical representation
+     */
+    protected DateTimeData parse(String str) throws SchemaDateTimeException {
+        DateTimeData date = new DateTimeData(str, this);
+        int len = str.length();
+
+        int end = indexOf (str, 0, len, 'T');
+
+        // both time and date
+        int dateEnd = getDate(str, 0, end, date);
+        getTime(str, end+1, len, date);
+
+        //Check the separator character between Date and Time
+        if (dateEnd != end) {
+            throw new RuntimeException(str
+                    + " is an invalid dateTime dataype value. "
+                    + "Invalid character(s) seprating date and time values.");
+        }
+
+        //validate and normalize
+
+        //REVISIT: do we need SchemaDateTimeException?
+        validateDateTime(date);
+
+        //save unnormalized values
+        saveUnnormalized(date);
+        
+        if (date.utc!=0 && date.utc!='Z') {
+            normalize(date);
+        }
+        return date;
+    }
+    
+    @Override
+    protected XMLGregorianCalendar getXMLGregorianCalendar(DateTimeData date) {
+        return datatypeFactory.newXMLGregorianCalendar(BigInteger.valueOf(date.unNormYear), date.unNormMonth, 
+                date.unNormDay, date.unNormHour, date.unNormMinute, 
+                (int)date.unNormSecond, date.unNormSecond != 0 ? getFractionalSecondsAsBigDecimal(date) : null, 
+                date.hasTimeZone() ? (date.timezoneHr * 60 + date.timezoneMin) : DatatypeConstants.FIELD_UNDEFINED);
+    }
+}

http://git-wip-us.apache.org/repos/asf/jena/blob/c9a7e646/jena-core/src/main/java/org/apache/jena/ext/xerces/impl/dv/xs/DayDV.java
----------------------------------------------------------------------
diff --git a/jena-core/src/main/java/org/apache/jena/ext/xerces/impl/dv/xs/DayDV.java b/jena-core/src/main/java/org/apache/jena/ext/xerces/impl/dv/xs/DayDV.java
new file mode 100644
index 0000000..9bee88a
--- /dev/null
+++ b/jena-core/src/main/java/org/apache/jena/ext/xerces/impl/dv/xs/DayDV.java
@@ -0,0 +1,120 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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.jena.ext.xerces.impl.dv.xs;
+
+import javax.xml.datatype.DatatypeConstants;
+import javax.xml.datatype.XMLGregorianCalendar;
+
+import org.apache.jena.ext.xerces.impl.dv.InvalidDatatypeValueException;
+import org.apache.jena.ext.xerces.impl.dv.ValidationContext;
+
+/**
+ * Validator for &lt;gDay&gt; datatype (W3C Schema datatypes)
+ *
+ * @xerces.internal 
+ *
+ * @author Elena Litani
+ * @author Gopal Sharma, SUN Microsystem Inc.
+ * @version $Id: DayDV.java 937741 2010-04-25 04:25:46Z mrglavas $
+ */
+public class DayDV extends AbstractDateTimeDV {
+
+    //size without time zone: ---09
+    private final static int DAY_SIZE=5;
+
+    @Override
+    public Object getActualValue(String content, ValidationContext context) throws InvalidDatatypeValueException {
+        try{
+            return parse(content);
+        } catch(Exception ex){
+            throw new InvalidDatatypeValueException("cvc-datatype-valid.1.2.1", new Object[]{content, "gDay"});
+        }
+    }
+
+    /**
+     * Parses, validates and computes normalized version of gDay object
+     *
+     * @param str    The lexical representation of gDay object ---DD
+     *               with possible time zone Z or (-),(+)hh:mm
+     *               Pattern: ---(\\d\\d)(Z|(([-+])(\\d\\d)(:(\\d\\d))?
+     * @return normalized date representation
+     * @exception SchemaDateTimeException Invalid lexical representation
+     */
+    protected DateTimeData parse(String str) throws SchemaDateTimeException {
+        DateTimeData date = new DateTimeData(str, this);
+        int len = str.length();
+
+        if (str.charAt(0)!='-' || str.charAt(1)!='-' || str.charAt(2)!='-') {
+            throw new SchemaDateTimeException ("Error in day parsing");
+        }
+
+        //initialize values
+        date.year=YEAR;
+        date.month=MONTH;
+
+        date.day=parseInt(str, 3,5);
+
+        if ( DAY_SIZE<len ) {
+            if (!isNextCharUTCSign(str, DAY_SIZE, len)) {
+                throw new SchemaDateTimeException ("Error in day parsing");
+            }
+            else {
+                getTimeZone(str, date, DAY_SIZE, len);
+            }
+        }
+
+       //validate and normalize
+        validateDateTime(date);
+
+        //save unnormalized values
+        saveUnnormalized(date);
+        
+        if ( date.utc!=0 && date.utc!='Z' ) {
+            normalize(date);
+        }
+        date.position = 2;
+        return date;
+    }
+
+    /**
+     * Converts gDay object representation to String
+     *
+     * @param date   gDay object
+     * @return lexical representation of gDay: ---DD with an optional time zone sign
+     */
+    @Override
+    protected String dateToString(DateTimeData date) {
+        StringBuffer message = new StringBuffer(6);
+        message.append('-');
+        message.append('-');
+        message.append('-');
+        append(message, date.day, 2);
+        append(message, (char)date.utc, 0);
+        return message.toString();
+    }
+    
+    @Override
+    protected XMLGregorianCalendar getXMLGregorianCalendar(DateTimeData date) {
+        return datatypeFactory.newXMLGregorianCalendar(DatatypeConstants.FIELD_UNDEFINED, DatatypeConstants.FIELD_UNDEFINED, 
+                date.unNormDay, DatatypeConstants.FIELD_UNDEFINED, DatatypeConstants.FIELD_UNDEFINED, 
+                DatatypeConstants.FIELD_UNDEFINED, DatatypeConstants.FIELD_UNDEFINED, 
+                date.hasTimeZone() ? date.timezoneHr * 60 + date.timezoneMin : DatatypeConstants.FIELD_UNDEFINED);
+    }
+
+}
+

http://git-wip-us.apache.org/repos/asf/jena/blob/c9a7e646/jena-core/src/main/java/org/apache/jena/ext/xerces/impl/dv/xs/DayTimeDurationDV.java
----------------------------------------------------------------------
diff --git a/jena-core/src/main/java/org/apache/jena/ext/xerces/impl/dv/xs/DayTimeDurationDV.java b/jena-core/src/main/java/org/apache/jena/ext/xerces/impl/dv/xs/DayTimeDurationDV.java
new file mode 100644
index 0000000..89c0eea
--- /dev/null
+++ b/jena-core/src/main/java/org/apache/jena/ext/xerces/impl/dv/xs/DayTimeDurationDV.java
@@ -0,0 +1,62 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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.jena.ext.xerces.impl.dv.xs;
+
+import java.math.BigDecimal;
+import java.math.BigInteger;
+
+import javax.xml.datatype.DatatypeConstants;
+import javax.xml.datatype.Duration;
+
+import org.apache.jena.ext.xerces.impl.dv.InvalidDatatypeValueException;
+import org.apache.jena.ext.xerces.impl.dv.ValidationContext;
+
+/**
+ * Used to validate the <dayTimeDuration> type
+ *
+ * @xerces.internal 
+ * 
+ * @author Ankit Pasricha, IBM
+ * 
+ * @version $Id: DayTimeDurationDV.java 937741 2010-04-25 04:25:46Z mrglavas $
+ */
+class DayTimeDurationDV extends DurationDV {
+    
+    @Override
+    public Object getActualValue(String content, ValidationContext context)
+        throws InvalidDatatypeValueException {
+        try {
+            return parse(content, DurationDV.DAYTIMEDURATION_TYPE);
+        } 
+        catch (Exception ex) {
+            throw new InvalidDatatypeValueException("cvc-datatype-valid.1.2.1", new Object[]{content, "dayTimeDuration"});
+        }
+    }
+    
+    @Override
+    protected Duration getDuration(DateTimeData date) {
+        int sign = 1;
+        if (date.day<0 || date.hour<0 || date.minute<0 || date.second<0) {
+            sign = -1;
+        }
+        return datatypeFactory.newDuration(sign == 1, null, null, 
+                date.day != DatatypeConstants.FIELD_UNDEFINED?BigInteger.valueOf(sign*date.day):null, 
+                date.hour != DatatypeConstants.FIELD_UNDEFINED?BigInteger.valueOf(sign*date.hour):null, 
+                date.minute != DatatypeConstants.FIELD_UNDEFINED?BigInteger.valueOf(sign*date.minute):null, 
+                date.second != DatatypeConstants.FIELD_UNDEFINED?new BigDecimal(String.valueOf(sign*date.second)):null);
+    }
+}

http://git-wip-us.apache.org/repos/asf/jena/blob/c9a7e646/jena-core/src/main/java/org/apache/jena/ext/xerces/impl/dv/xs/DecimalDV.java
----------------------------------------------------------------------
diff --git a/jena-core/src/main/java/org/apache/jena/ext/xerces/impl/dv/xs/DecimalDV.java b/jena-core/src/main/java/org/apache/jena/ext/xerces/impl/dv/xs/DecimalDV.java
new file mode 100644
index 0000000..6acadd2
--- /dev/null
+++ b/jena-core/src/main/java/org/apache/jena/ext/xerces/impl/dv/xs/DecimalDV.java
@@ -0,0 +1,375 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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.jena.ext.xerces.impl.dv.xs;
+
+import java.math.BigDecimal;
+import java.math.BigInteger;
+
+import org.apache.jena.ext.xerces.impl.dv.InvalidDatatypeValueException;
+import org.apache.jena.ext.xerces.impl.dv.ValidationContext;
+import org.apache.jena.ext.xerces.xs.datatypes.XSDecimal;
+
+/**
+ * Represent the schema type "decimal"
+ *
+ * @xerces.internal 
+ *
+ * @author Neeraj Bajaj, Sun Microsystems, inc.
+ * @author Sandy Gao, IBM
+ *
+ * @version $Id: DecimalDV.java 446745 2006-09-15 21:43:58Z mrglavas $
+ */
+public class DecimalDV extends TypeValidator {
+
+    @Override
+    public final short getAllowedFacets(){
+        return ( XSSimpleTypeDecl.FACET_PATTERN | XSSimpleTypeDecl.FACET_WHITESPACE | XSSimpleTypeDecl.FACET_ENUMERATION |XSSimpleTypeDecl.FACET_MAXINCLUSIVE |XSSimpleTypeDecl.FACET_MININCLUSIVE | XSSimpleTypeDecl.FACET_MAXEXCLUSIVE  | XSSimpleTypeDecl.FACET_MINEXCLUSIVE | XSSimpleTypeDecl.FACET_TOTALDIGITS | XSSimpleTypeDecl.FACET_FRACTIONDIGITS);
+    }
+
+    @Override
+    public Object getActualValue(String content, ValidationContext context) throws InvalidDatatypeValueException {
+        try {
+            return new XDecimal(content);
+        } catch (NumberFormatException nfe) {
+            throw new InvalidDatatypeValueException("cvc-datatype-valid.1.2.1", new Object[]{content, "decimal"});
+        }
+    }
+
+    @Override
+    public final int compare(Object value1, Object value2){
+        return ((XDecimal)value1).compareTo((XDecimal)value2);
+    }
+
+    @Override
+    public final int getTotalDigits(Object value){
+        return ((XDecimal)value).totalDigits;
+    }
+
+    @Override
+    public final int getFractionDigits(Object value){
+        return ((XDecimal)value).fracDigits;
+    }
+    
+    // Avoid using the heavy-weight java.math.BigDecimal
+    static class XDecimal implements XSDecimal {
+        // sign: 0 for vlaue 0; 1 for positive values; -1 for negative values
+        int sign = 1;
+        // total digits. >= 1
+        int totalDigits = 0;
+        // integer digits when sign != 0
+        int intDigits = 0;
+        // fraction digits when sign != 0
+        int fracDigits = 0;
+        // the string representing the integer part
+        String ivalue = "";
+        // the string representing the fraction part
+        String fvalue = "";
+        // whether the canonical form contains decimal point
+        boolean integer = false;
+        
+        XDecimal(String content) throws NumberFormatException {
+            initD(content);
+        }
+        XDecimal(String content, boolean integer) throws NumberFormatException {
+            if (integer)
+                initI(content);
+            else
+                initD(content);
+        }
+        void initD(String content) throws NumberFormatException {
+            int len = content.length();
+            if (len == 0)
+                throw new NumberFormatException();
+    
+            // these 4 variables are used to indicate where the integre/fraction
+            // parts start/end.
+            int intStart = 0, intEnd = 0, fracStart = 0, fracEnd = 0;
+            
+            // Deal with leading sign symbol if present
+            if (content.charAt(0) == '+') {
+                // skip '+', so intStart should be 1
+                intStart = 1;
+            }
+            else if (content.charAt(0) == '-') {
+                // keep '-', so intStart is stil 0
+                intStart = 1;
+                sign = -1;
+            }
+    
+            // skip leading zeroes in integer part
+            int actualIntStart = intStart;
+            while (actualIntStart < len && content.charAt(actualIntStart) == '0') {
+                actualIntStart++;
+            }
+    
+            // Find the ending position of the integer part
+            for (intEnd = actualIntStart;
+                 intEnd < len && TypeValidator.isDigit(content.charAt(intEnd));
+                 intEnd++);
+    
+            // Not reached the end yet
+            if (intEnd < len) {
+                // the remaining part is not ".DDD", error
+                if (content.charAt(intEnd) != '.')
+                    throw new NumberFormatException();
+    
+                // fraction part starts after '.', and ends at the end of the input
+                fracStart = intEnd + 1;
+                fracEnd = len;
+            }
+    
+            // no integer part, no fraction part, error.
+            if (intStart == intEnd && fracStart == fracEnd)
+                throw new NumberFormatException();
+    
+            // ignore trailing zeroes in fraction part
+            while (fracEnd > fracStart && content.charAt(fracEnd-1) == '0') {
+                fracEnd--;
+            }
+    
+            // check whether there is non-digit characters in the fraction part
+            for (int fracPos = fracStart; fracPos < fracEnd; fracPos++) {
+                if (!TypeValidator.isDigit(content.charAt(fracPos)))
+                    throw new NumberFormatException();
+            }
+    
+            intDigits = intEnd - actualIntStart;
+            fracDigits = fracEnd - fracStart;
+            totalDigits = intDigits + fracDigits;
+    
+            if (intDigits > 0) {
+                ivalue = content.substring(actualIntStart, intEnd);
+                if (fracDigits > 0)
+                    fvalue = content.substring(fracStart, fracEnd);
+            }
+            else {
+                if (fracDigits > 0) {
+                    fvalue = content.substring(fracStart, fracEnd);
+                }
+                else {
+                    // ".00", treat it as "0"
+                    sign = 0;
+                }
+            }
+        }
+        void initI(String content) throws NumberFormatException {
+            int len = content.length();
+            if (len == 0)
+                throw new NumberFormatException();
+    
+            // these 2 variables are used to indicate where the integre start/end.
+            int intStart = 0, intEnd = 0;
+    
+            // Deal with leading sign symbol if present
+            if (content.charAt(0) == '+') {
+                // skip '+', so intStart should be 1
+                intStart = 1;
+            }
+            else if (content.charAt(0) == '-') {
+                // keep '-', so intStart is stil 0
+                intStart = 1;
+                sign = -1;
+            }
+    
+            // skip leading zeroes in integer part
+            int actualIntStart = intStart;
+            while (actualIntStart < len && content.charAt(actualIntStart) == '0') {
+                actualIntStart++;
+            }
+    
+            // Find the ending position of the integer part
+            for (intEnd = actualIntStart;
+                 intEnd < len && TypeValidator.isDigit(content.charAt(intEnd));
+                 intEnd++);
+    
+            // Not reached the end yet, error
+            if (intEnd < len)
+                throw new NumberFormatException();
+    
+            // no integer part, error.
+            if (intStart == intEnd)
+                throw new NumberFormatException();
+    
+            intDigits = intEnd - actualIntStart;
+            fracDigits = 0;
+            totalDigits = intDigits;
+    
+            if (intDigits > 0) {
+                ivalue = content.substring(actualIntStart, intEnd);
+            }
+            else {
+                // "00", treat it as "0"
+                sign = 0;
+            }
+            
+            integer = true;
+        }
+        @Override
+        public boolean equals(Object val) {
+            if (val == this)
+                return true;
+    
+            if (!(val instanceof XDecimal))
+                return false;
+            XDecimal oval = (XDecimal)val;
+            
+            if (sign != oval.sign)
+               return false;
+            if (sign == 0)
+                return true;
+            
+            return intDigits == oval.intDigits && fracDigits == oval.fracDigits &&
+                   ivalue.equals(oval.ivalue) && fvalue.equals(oval.fvalue);
+        }
+        public int compareTo(XDecimal val) {
+            if (sign != val.sign)
+                return sign > val.sign ? 1 : -1;
+            if (sign == 0)
+                return 0;
+            return sign * intComp(val);
+        }
+        private int intComp(XDecimal val) {
+            if (intDigits != val.intDigits)
+                return intDigits > val.intDigits ? 1 : -1;
+            int ret = ivalue.compareTo(val.ivalue);
+            if (ret != 0)
+                return ret > 0 ? 1 : -1;;
+            ret = fvalue.compareTo(val.fvalue);
+            return ret == 0 ? 0 : (ret > 0 ? 1 : -1);
+        }
+        private String canonical;
+        @Override
+        public synchronized String toString() {
+            if (canonical == null) {
+                makeCanonical();
+            }
+            return canonical;
+        }
+        
+        private void makeCanonical() {
+            if (sign == 0) {
+                if (integer)
+                    canonical = "0";
+                else
+                    canonical = "0.0";
+                return;
+            }
+            if (integer && sign > 0) {
+                canonical = ivalue;
+                return;
+            }
+            // for -0.1, total digits is 1, so we need 3 extra spots
+            StringBuffer buffer = new StringBuffer(totalDigits+3);
+            if (sign == -1)
+                buffer.append('-');
+            if (intDigits != 0)
+                buffer.append(ivalue);
+            else
+                buffer.append('0');
+            if (!integer) {
+                buffer.append('.');
+                if (fracDigits != 0) {
+                    buffer.append(fvalue);
+                }
+                else {
+                    buffer.append('0');
+                }
+            }
+            canonical = buffer.toString();
+        }
+        
+        @Override
+        public BigDecimal getBigDecimal() {
+            if (sign == 0) {
+                return new BigDecimal(BigInteger.ZERO);
+            }
+            return new BigDecimal(toString());
+        }
+        
+        @Override
+        public BigInteger getBigInteger() throws NumberFormatException {
+            if (fracDigits != 0) {
+                throw new NumberFormatException();
+            }
+            if (sign == 0) {
+                return BigInteger.ZERO;
+            }
+            if (sign == 1) {
+                return new BigInteger(ivalue);
+            }
+            return new BigInteger("-" + ivalue);
+        }
+        
+        @Override
+        public long getLong() throws NumberFormatException {
+            if (fracDigits != 0) {
+                throw new NumberFormatException();
+            }
+            if (sign == 0) {
+                return 0L;
+            }
+            if (sign == 1) {
+                return Long.parseLong(ivalue);
+            }
+            return Long.parseLong("-" + ivalue);
+        }
+        
+        @Override
+        public int getInt() throws NumberFormatException {
+            if (fracDigits != 0) {
+                throw new NumberFormatException();
+            }
+            if (sign == 0) {
+                return 0;
+            }
+            if (sign == 1) {
+                return Integer.parseInt(ivalue);
+            }
+            return Integer.parseInt("-" + ivalue);
+        }
+        
+        @Override
+        public short getShort() throws NumberFormatException {
+            if (fracDigits != 0) {
+                throw new NumberFormatException();
+            }
+            if (sign == 0) {
+                return 0;
+            }
+            if (sign == 1) {
+                return Short.parseShort(ivalue);
+            }
+            return Short.parseShort("-" + ivalue);
+        }
+        
+        @Override
+        public byte getByte() throws NumberFormatException {
+            if (fracDigits != 0) {
+                throw new NumberFormatException();
+            }
+            if (sign == 0) {
+                return 0;
+            }
+            if (sign == 1) {
+                return Byte.parseByte(ivalue);
+            }
+            return Byte.parseByte("-" + ivalue);
+        }
+    }
+} // class DecimalDV
+

http://git-wip-us.apache.org/repos/asf/jena/blob/c9a7e646/jena-core/src/main/java/org/apache/jena/ext/xerces/impl/dv/xs/DoubleDV.java
----------------------------------------------------------------------
diff --git a/jena-core/src/main/java/org/apache/jena/ext/xerces/impl/dv/xs/DoubleDV.java b/jena-core/src/main/java/org/apache/jena/ext/xerces/impl/dv/xs/DoubleDV.java
new file mode 100644
index 0000000..735f79c
--- /dev/null
+++ b/jena-core/src/main/java/org/apache/jena/ext/xerces/impl/dv/xs/DoubleDV.java
@@ -0,0 +1,265 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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.jena.ext.xerces.impl.dv.xs;
+
+import org.apache.jena.ext.xerces.impl.dv.InvalidDatatypeValueException;
+import org.apache.jena.ext.xerces.impl.dv.ValidationContext;
+import org.apache.jena.ext.xerces.xs.datatypes.XSDouble;
+
+/**
+ * Represent the schema type "double"
+ *
+ * @xerces.internal 
+ *
+ * @author Neeraj Bajaj, Sun Microsystems, inc.
+ * @author Sandy Gao, IBM
+ *
+ * @version $Id: DoubleDV.java 572095 2007-09-02 18:32:43Z mrglavas $
+ */
+public class DoubleDV extends TypeValidator {
+
+    @Override
+    public short getAllowedFacets(){
+        return ( XSSimpleTypeDecl.FACET_PATTERN | XSSimpleTypeDecl.FACET_WHITESPACE | XSSimpleTypeDecl.FACET_ENUMERATION |XSSimpleTypeDecl.FACET_MAXINCLUSIVE |XSSimpleTypeDecl.FACET_MININCLUSIVE | XSSimpleTypeDecl.FACET_MAXEXCLUSIVE  | XSSimpleTypeDecl.FACET_MINEXCLUSIVE  );
+    }//getAllowedFacets()
+
+    //convert a String to Double form, we have to take care of cases specified in spec like INF, -INF and NaN
+    @Override
+    public Object getActualValue(String content, ValidationContext context) throws InvalidDatatypeValueException {
+        try{
+            return new XDouble(content);
+        } catch (NumberFormatException ex){
+            throw new InvalidDatatypeValueException("cvc-datatype-valid.1.2.1", new Object[]{content, "double"});
+        }
+    }//getActualValue()
+
+    // Can't call Double#compareTo method, because it's introduced in jdk 1.2
+    @Override
+    public int compare(Object value1, Object value2) {
+        return ((XDouble)value1).compareTo((XDouble)value2);
+    }//compare()
+    
+    //distinguishes between identity and equality for double datatype
+    //0.0 is equal but not identical to -0.0
+    @Override
+    public boolean isIdentical (Object value1, Object value2) {
+        if (value2 instanceof XDouble) {
+            return ((XDouble)value1).isIdentical((XDouble)value2);
+        }
+        return false;
+    }//isIdentical()
+    
+    /** 
+     * Returns true if it's possible that the given
+     * string represents a valid floating point value
+     * (excluding NaN, INF and -INF).
+     */
+    static boolean isPossibleFP(String val) {
+        final int length = val.length();
+        for (int i = 0; i < length; ++i) {
+            char c = val.charAt(i);
+            if (!(c >= '0' && c <= '9' || c == '.' || 
+                c == '-' || c == '+' || c == 'E' || c == 'e')) {
+                return false;
+            }
+        }
+        return true;
+    }
+
+    private static final class XDouble implements XSDouble {
+        private final double value;
+        public XDouble(String s) throws NumberFormatException {
+            if (isPossibleFP(s)) {
+                value = Double.parseDouble(s);
+            }
+            else if ( s.equals("INF") ) {
+                value = Double.POSITIVE_INFINITY;
+            }
+            else if ( s.equals("-INF") ) {
+                value = Double.NEGATIVE_INFINITY;
+            }
+            else if ( s.equals("NaN" ) ) {
+                value = Double.NaN;
+            }
+            else {
+                throw new NumberFormatException(s);
+            }
+        }
+
+        @Override
+        public boolean equals(Object val) {
+            if (val == this)
+                return true;
+    
+            if (!(val instanceof XDouble))
+                return false;
+            XDouble oval = (XDouble)val;
+
+            // NOTE: we don't distinguish 0.0 from -0.0
+            if (value == oval.value)
+                return true;
+            
+            if (value != value && oval.value != oval.value)
+                return true;
+
+            return false;
+        }
+        
+        @Override
+        public int hashCode() {
+            // This check is necessary because doubleToLongBits(+0) != doubleToLongBits(-0)
+            if (value == 0d) {
+                return 0;
+            }
+            long v = Double.doubleToLongBits(value);
+            return (int) (v ^ (v >>> 32));
+        }
+        
+        // NOTE: 0.0 is equal but not identical to -0.0
+        public boolean isIdentical (XDouble val) {
+            if (val == this) {
+                return true;
+            }
+            
+            if (value == val.value) {
+                return (value != 0.0d || 
+                    (Double.doubleToLongBits(value) == Double.doubleToLongBits(val.value)));
+            }
+            
+            if (value != value && val.value != val.value)
+                return true;
+
+            return false; 
+        }
+
+        private int compareTo(XDouble val) {
+            double oval = val.value;
+
+            // this < other
+            if (value < oval)
+                return -1;
+            // this > other
+            if (value > oval)
+                return 1;
+            // this == other
+            // NOTE: we don't distinguish 0.0 from -0.0
+            if (value == oval)
+                return 0;
+
+            // one of the 2 values or both is/are NaN(s)
+
+            if (value != value) {
+                // this = NaN = other
+                if (oval != oval)
+                    return 0;
+                // this is NaN <> other
+                return INDETERMINATE;
+            }
+
+            // other is NaN <> this
+            return INDETERMINATE;
+        }
+
+        private String canonical;
+        @Override
+        public synchronized String toString() {
+            if (canonical == null) {
+                if (value == Double.POSITIVE_INFINITY)
+                    canonical = "INF";
+                else if (value == Double.NEGATIVE_INFINITY)
+                    canonical = "-INF";
+                else if (value != value)
+                    canonical = "NaN";
+                // NOTE: we don't distinguish 0.0 from -0.0
+                else if (value == 0)
+                    canonical = "0.0E1";
+                else {
+                    // REVISIT: use the java algorithm for now, because we
+                    // don't know what to output for 1.1d (which is no
+                    // actually 1.1)
+                    canonical = Double.toString(value);
+                    // if it contains 'E', then it should be a valid schema
+                    // canonical representation
+                    if (canonical.indexOf('E') == -1) {
+                        int len = canonical.length();
+                        // at most 3 longer: E, -, 9
+                        char[] chars = new char[len+3];
+                        canonical.getChars(0, len, chars, 0);
+                        // expected decimal point position
+                        int edp = chars[0] == '-' ? 2 : 1;
+                        // for non-zero integer part
+                        if (value >= 1 || value <= -1) {
+                            // decimal point position
+                            int dp = canonical.indexOf('.');
+                            // move the digits: ddd.d --> d.ddd
+                            for (int i = dp; i > edp; i--) {
+                                chars[i] = chars[i-1];
+                            }
+                            chars[edp] = '.';
+                            // trim trailing zeros: d00.0 --> d.000 --> d.
+                            while (chars[len-1] == '0')
+                                len--;
+                            // add the last zero if necessary: d. --> d.0
+                            if (chars[len-1] == '.')
+                                len++;
+                            // append E: d.dd --> d.ddE
+                            chars[len++] = 'E';
+                            // how far we shifted the decimal point
+                            int shift = dp - edp;
+                            // append the exponent --> d.ddEd
+                            // the exponent is at most 7
+                            chars[len++] = (char)(shift + '0');
+                        }
+                        else {
+                            // non-zero digit point
+                            int nzp = edp + 1;
+                            // skip zeros: 0.003
+                            while (chars[nzp] == '0')
+                                nzp++;
+                            // put the first non-zero digit to the left of '.'
+                            chars[edp-1] = chars[nzp];
+                            chars[edp] = '.';
+                            // move other digits (non-zero) to the right of '.'
+                            for (int i = nzp+1, j = edp+1; i < len; i++, j++)
+                                chars[j] = chars[i];
+                            // adjust the length
+                            len -= nzp - edp;
+                            // append 0 if nessary: 0.03 --> 3. --> 3.0
+                            if (len == edp + 1)
+                                chars[len++] = '0';
+                            // append E-: d.dd --> d.ddE-
+                            chars[len++] = 'E';
+                            chars[len++] = '-';
+                            // how far we shifted the decimal point
+                            int shift = nzp - edp;
+                            // append the exponent --> d.ddEd
+                            // the exponent is at most 3
+                            chars[len++] = (char)(shift + '0');
+                        }
+                        canonical = new String(chars, 0, len);
+                    }
+                }
+            }
+            return canonical;
+        }
+        @Override
+        public double getValue() {
+            return value;
+        }
+    }
+} // class DoubleDV

http://git-wip-us.apache.org/repos/asf/jena/blob/c9a7e646/jena-core/src/main/java/org/apache/jena/ext/xerces/impl/dv/xs/DurationDV.java
----------------------------------------------------------------------
diff --git a/jena-core/src/main/java/org/apache/jena/ext/xerces/impl/dv/xs/DurationDV.java b/jena-core/src/main/java/org/apache/jena/ext/xerces/impl/dv/xs/DurationDV.java
new file mode 100644
index 0000000..4519e4f
--- /dev/null
+++ b/jena-core/src/main/java/org/apache/jena/ext/xerces/impl/dv/xs/DurationDV.java
@@ -0,0 +1,392 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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.jena.ext.xerces.impl.dv.xs;
+
+import java.math.BigDecimal;
+import java.math.BigInteger;
+
+import javax.xml.datatype.DatatypeConstants;
+import javax.xml.datatype.Duration;
+
+import org.apache.jena.ext.xerces.impl.dv.InvalidDatatypeValueException;
+import org.apache.jena.ext.xerces.impl.dv.ValidationContext;
+
+/**
+ * Validator for &lt;duration&gt; datatype (W3C Schema Datatypes)
+ *
+ * @xerces.internal 
+ *
+ * @author Elena Litani
+ * @author Gopal Sharma, SUN Microsystem Inc.
+ * @version $Id: DurationDV.java 937741 2010-04-25 04:25:46Z mrglavas $
+ */
+public class DurationDV extends AbstractDateTimeDV {
+
+	public static final int DURATION_TYPE = 0;
+	public static final int YEARMONTHDURATION_TYPE = 1;
+	public static final int DAYTIMEDURATION_TYPE = 2;
+    // order-relation on duration is a partial order. The dates below are used to
+    // for comparison of 2 durations, based on the fact that
+    // duration x and y is x<=y iff s+x<=s+y
+    // see 3.2.6 duration W3C schema datatype specs
+    //
+    // the dates are in format: {CCYY,MM,DD, H, S, M, MS, timezone}
+    private final static DateTimeData[] DATETIMES= {
+        new DateTimeData(1696, 9, 1, 0, 0, 0, 'Z', null, true, null),
+        new DateTimeData(1697, 2, 1, 0, 0, 0, 'Z', null, true, null),
+        new DateTimeData(1903, 3, 1, 0, 0, 0, 'Z', null, true, null),
+        new DateTimeData(1903, 7, 1, 0, 0, 0, 'Z', null, true, null)};
+
+    @Override
+    public Object getActualValue(String content, ValidationContext context) throws InvalidDatatypeValueException{
+        try{
+            return parse(content, DURATION_TYPE);
+        } catch (Exception ex) {
+            throw new InvalidDatatypeValueException("cvc-datatype-valid.1.2.1", new Object[]{content, "duration"});
+        }
+    }
+
+    /**
+     * Parses, validates and computes normalized version of duration object
+     *
+     * @param str    The lexical representation of duration object PnYn MnDTnH nMnS
+     * @param durationType
+     * @return normalized date representation
+     * @exception SchemaDateTimeException Invalid lexical representation
+     */
+    protected DateTimeData parse(String str, int durationType) throws SchemaDateTimeException{
+        int len = str.length();
+        DateTimeData date= new DateTimeData(str, this);
+        
+        int start = 0;
+        char c=str.charAt(start++);
+        if ( c!='P' && c!='-' ) {
+            throw new SchemaDateTimeException();
+        }
+        else {
+            date.utc=(c=='-')?'-':0;
+            if ( c=='-' && str.charAt(start++)!='P' ) {
+                throw new SchemaDateTimeException();
+            }
+        }
+        
+        int negate = 1;
+        //negative duration
+        if ( date.utc=='-' ) {
+            negate = -1;
+            
+        }
+        //at least one number and designator must be seen after P
+        boolean designator = false;
+        
+        int endDate = indexOf (str, start, len, 'T');
+        if ( endDate == -1 ) {
+            endDate = len;
+        }
+        else if (durationType == YEARMONTHDURATION_TYPE) {
+            throw new SchemaDateTimeException();
+        }
+        
+        //find 'Y'
+        int end = indexOf (str, start, endDate, 'Y');
+        if ( end!=-1 ) {
+            
+            if (durationType == DAYTIMEDURATION_TYPE) {
+                throw new SchemaDateTimeException();
+            }
+            
+            //scan year
+            date.year=negate * parseInt(str,start,end);
+            start = end+1;
+            designator = true;
+        }
+        
+        end = indexOf (str, start, endDate, 'M');
+        if ( end!=-1 ) {
+            
+            if (durationType == DAYTIMEDURATION_TYPE) {
+                throw new SchemaDateTimeException();
+            }
+            
+            //scan month
+            date.month=negate * parseInt(str,start,end);
+            start = end+1;
+            designator = true;
+        }
+        
+        end = indexOf (str, start, endDate, 'D');
+        if ( end!=-1 ) {
+            
+            if(durationType == YEARMONTHDURATION_TYPE) {
+                throw new SchemaDateTimeException();
+            }
+            
+            //scan day
+            date.day=negate * parseInt(str,start,end);
+            start = end+1;
+            designator = true;
+        }
+        
+        if ( len == endDate && start!=len ) {
+            throw new SchemaDateTimeException();
+        }
+        if ( len !=endDate ) {
+            
+            //scan hours, minutes, seconds
+            //REVISIT: can any item include a decimal fraction or only seconds?
+            //
+            
+            end = indexOf (str, ++start, len, 'H');
+            if ( end!=-1 ) {
+                //scan hours
+                date.hour=negate * parseInt(str,start,end);
+                start=end+1;
+                designator = true;
+            }
+            
+            end = indexOf (str, start, len, 'M');
+            if ( end!=-1 ) {
+                //scan min
+                date.minute=negate * parseInt(str,start,end);
+                start=end+1;
+                designator = true;
+            }
+            
+            end = indexOf (str, start, len, 'S');
+            if ( end!=-1 ) {
+                //scan seconds
+                date.second = negate * parseSecond(str, start, end);
+                start=end+1;
+                designator = true;
+            }
+            // no additional data shouls appear after last item
+            // P1Y1M1DT is illigal value as well
+            if ( start != len || str.charAt(--start)=='T' ) {
+                throw new SchemaDateTimeException();
+            }
+        }
+        
+        if ( !designator ) {
+            throw new SchemaDateTimeException();
+        }
+        
+        return date;
+    }
+
+    /**
+     * Compares 2 given durations. (refer to W3C Schema Datatypes "3.2.6 duration")
+     *
+     * @param date1  Unnormalized duration
+     * @param date2  Unnormalized duration
+     * @param strict (min/max)Exclusive strict == true ( LESS_THAN ) or ( GREATER_THAN )
+     *               (min/max)Inclusive strict == false (LESS_EQUAL) or (GREATER_EQUAL)
+     * @return INDETERMINATE if the order relationship between date1 and date2 is indeterminate.
+     * EQUAL if the order relation between date1 and date2 is EQUAL.
+     * If the strict parameter is true, return LESS_THAN if date1 is less than date2 and
+     * return GREATER_THAN if date1 is greater than date2.
+     * If the strict parameter is false, return LESS_THAN if date1 is less than OR equal to date2 and
+     * return GREATER_THAN if date1 is greater than OR equal to date2
+     */
+    @Override
+    protected  short compareDates(DateTimeData date1, DateTimeData date2, boolean strict) {
+
+        //REVISIT: this is unoptimazed vs of comparing 2 durations
+        //         Algorithm is described in 3.2.6.2 W3C Schema Datatype specs
+        //
+
+        //add constA to both durations
+        short resultA, resultB= INDETERMINATE;
+        //try and see if the objects are equal
+        resultA = compareOrder (date1, date2);
+        if ( resultA == 0 ) {
+            return 0;
+        }
+
+        DateTimeData[] result = new DateTimeData[2];
+        result[0] = new DateTimeData(null, this);
+        result[1] = new DateTimeData(null, this);
+
+        //long comparison algorithm is required
+        DateTimeData tempA = addDuration (date1, DATETIMES[0], result[0]);
+        DateTimeData tempB = addDuration (date2, DATETIMES[0], result[1]);
+        resultA =  compareOrder(tempA, tempB);
+        if ( resultA == INDETERMINATE ) {
+            return INDETERMINATE;
+        }
+
+        tempA = addDuration(date1, DATETIMES[1], result[0]);
+        tempB = addDuration(date2, DATETIMES[1], result[1]);
+        resultB = compareOrder(tempA, tempB);
+        resultA = compareResults(resultA, resultB, strict);
+        if (resultA == INDETERMINATE) {
+            return INDETERMINATE;
+        }
+
+        tempA = addDuration(date1, DATETIMES[2], result[0]);
+        tempB = addDuration(date2, DATETIMES[2], result[1]);
+        resultB = compareOrder(tempA, tempB);
+        resultA = compareResults(resultA, resultB, strict);
+        if (resultA == INDETERMINATE) {
+            return INDETERMINATE;
+        }
+
+        tempA = addDuration(date1, DATETIMES[3], result[0]);
+        tempB = addDuration(date2, DATETIMES[3], result[1]);
+        resultB = compareOrder(tempA, tempB);
+        resultA = compareResults(resultA, resultB, strict);
+
+        return resultA;
+    }
+
+    private short compareResults(short resultA, short resultB, boolean strict){
+
+      if ( resultB == INDETERMINATE ) {
+            return INDETERMINATE;
+        }
+        else if ( resultA!=resultB && strict ) {
+            return INDETERMINATE;
+        }
+        else if ( resultA!=resultB && !strict ) {
+            if ( resultA!=0 && resultB!=0 ) {
+                return INDETERMINATE;
+            }
+            else {
+                return (resultA!=0)?resultA:resultB;
+            }
+        }
+        return resultA;
+    }
+
+    private DateTimeData addDuration(DateTimeData date, DateTimeData addto, DateTimeData duration) {
+
+        //REVISIT: some code could be shared between normalize() and this method,
+        //         however is it worth moving it? The structures are different...
+        //
+
+        resetDateObj(duration);
+        //add months (may be modified additionaly below)
+        int temp = addto.month + date.month;
+        duration.month = modulo (temp, 1, 13);
+        int carry = fQuotient (temp, 1, 13);
+
+        //add years (may be modified additionaly below)
+        duration.year=addto.year + date.year + carry;
+
+        //add seconds
+        double dtemp = addto.second + date.second;
+        carry = (int)Math.floor(dtemp/60);
+        duration.second = dtemp - carry*60;
+
+        //add minutes
+        temp = addto.minute +date.minute + carry;
+        carry = fQuotient (temp, 60);
+        duration.minute= mod(temp, 60, carry);
+
+        //add hours
+        temp = addto.hour + date.hour + carry;
+        carry = fQuotient(temp, 24);
+        duration.hour = mod(temp, 24, carry);
+
+
+        duration.day=addto.day + date.day + carry;
+
+        while ( true ) {
+
+            temp=maxDayInMonthFor(duration.year, duration.month);
+            if ( duration.day < 1 ) { //original duration was negative
+                duration.day = duration.day + maxDayInMonthFor(duration.year, duration.month-1);
+                carry=-1;
+            }
+            else if ( duration.day > temp ) {
+                duration.day = duration.day - temp;
+                carry=1;
+            }
+            else {
+                break;
+            }
+            temp = duration.month+carry;
+            duration.month = modulo(temp, 1, 13);
+            duration.year = duration.year+fQuotient(temp, 1, 13);
+        }
+
+        duration.utc='Z';
+        return duration;
+    }
+
+    @Override
+    protected double parseSecond(String buffer, int start, int end)
+        throws NumberFormatException {
+        int dot = -1;
+        for (int i = start; i < end; i++) {
+            char ch = buffer.charAt(i);
+            if (ch == '.')
+                dot = i;
+            else if (ch > '9' || ch < '0')
+                throw new NumberFormatException("'" + buffer + "' has wrong format");
+        }
+        if (dot+1 == end) {
+            throw new NumberFormatException("'" + buffer + "' has wrong format");
+        }
+        double value = Double.parseDouble(buffer.substring(start, end));
+        if (value == Double.POSITIVE_INFINITY) {
+            throw new NumberFormatException("'" + buffer + "' has wrong format");
+        }
+        return value;
+    }
+
+    @Override
+    protected String dateToString(DateTimeData date) {
+        StringBuffer message = new StringBuffer(30);
+        if ( date.year<0 || date.month<0 || date.day<0
+                || date.hour<0 || date.minute<0 || date.second<0) {
+            message.append('-');
+        }
+        message.append('P');
+        message.append((date.year < 0?-1:1) * date.year);
+        message.append('Y');
+        message.append((date.month < 0?-1:1) * date.month);
+        message.append('M');
+        message.append((date.day < 0?-1:1) * date.day);
+        message.append('D');
+        message.append('T');
+        message.append((date.hour < 0?-1:1) * date.hour);
+        message.append('H');
+        message.append((date.minute < 0?-1:1) * date.minute);
+        message.append('M');
+        append2(message, (date.second < 0?-1:1) * date.second);
+        message.append('S');
+
+        return message.toString();
+    }
+    
+    @Override
+    protected Duration getDuration(DateTimeData date) {
+        int sign = 1;
+        if ( date.year<0 || date.month<0 || date.day<0
+                || date.hour<0 || date.minute<0 || date.second<0) {
+            sign = -1;
+        }
+        return datatypeFactory.newDuration(sign == 1, 
+                date.year != DatatypeConstants.FIELD_UNDEFINED?BigInteger.valueOf(sign*date.year):null, 
+                date.month != DatatypeConstants.FIELD_UNDEFINED?BigInteger.valueOf(sign*date.month):null, 
+                date.day != DatatypeConstants.FIELD_UNDEFINED?BigInteger.valueOf(sign*date.day):null, 
+                date.hour != DatatypeConstants.FIELD_UNDEFINED?BigInteger.valueOf(sign*date.hour):null, 
+                date.minute != DatatypeConstants.FIELD_UNDEFINED?BigInteger.valueOf(sign*date.minute):null, 
+                date.second != DatatypeConstants.FIELD_UNDEFINED?new BigDecimal(String.valueOf(sign*date.second)):null);
+    }
+}

http://git-wip-us.apache.org/repos/asf/jena/blob/c9a7e646/jena-core/src/main/java/org/apache/jena/ext/xerces/impl/dv/xs/EntityDV.java
----------------------------------------------------------------------
diff --git a/jena-core/src/main/java/org/apache/jena/ext/xerces/impl/dv/xs/EntityDV.java b/jena-core/src/main/java/org/apache/jena/ext/xerces/impl/dv/xs/EntityDV.java
new file mode 100644
index 0000000..9d4dec3
--- /dev/null
+++ b/jena-core/src/main/java/org/apache/jena/ext/xerces/impl/dv/xs/EntityDV.java
@@ -0,0 +1,57 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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.jena.ext.xerces.impl.dv.xs;
+
+import org.apache.jena.ext.xerces.impl.dv.InvalidDatatypeValueException;
+import org.apache.jena.ext.xerces.impl.dv.ValidationContext;
+import org.apache.jena.ext.xerces.util.XMLChar;
+
+/**
+ * Represent the schema type "entity"
+ *
+ * @xerces.internal 
+ *
+ * @author Neeraj Bajaj, Sun Microsystems, inc.
+ * @author Sandy Gao, IBM
+ *
+ * @version $Id: EntityDV.java 446745 2006-09-15 21:43:58Z mrglavas $
+ */
+public class EntityDV extends TypeValidator {
+
+    @Override
+    public short getAllowedFacets(){
+        return (XSSimpleTypeDecl.FACET_LENGTH | XSSimpleTypeDecl.FACET_MINLENGTH | XSSimpleTypeDecl.FACET_MAXLENGTH | XSSimpleTypeDecl.FACET_PATTERN | XSSimpleTypeDecl.FACET_ENUMERATION | XSSimpleTypeDecl.FACET_WHITESPACE );
+    }
+
+    @Override
+    public Object getActualValue(String content, ValidationContext context) throws InvalidDatatypeValueException {
+        if (!XMLChar.isValidNCName(content)) {
+            throw new InvalidDatatypeValueException("cvc-datatype-valid.1.2.1", new Object[]{content, "NCName"});
+        }
+
+        return content;
+    }
+
+    @Override
+    public void checkExtraRules(Object value, ValidationContext context) throws InvalidDatatypeValueException {
+        if (!context.isEntityUnparsed((String)value)) {
+            throw new InvalidDatatypeValueException("UndeclaredEntity", new Object[]{value});
+        }
+    }
+
+} // class EntityDV

http://git-wip-us.apache.org/repos/asf/jena/blob/c9a7e646/jena-core/src/main/java/org/apache/jena/ext/xerces/impl/dv/xs/ExtendedSchemaDVFactoryImpl.java
----------------------------------------------------------------------
diff --git a/jena-core/src/main/java/org/apache/jena/ext/xerces/impl/dv/xs/ExtendedSchemaDVFactoryImpl.java b/jena-core/src/main/java/org/apache/jena/ext/xerces/impl/dv/xs/ExtendedSchemaDVFactoryImpl.java
new file mode 100644
index 0000000..63b2e49
--- /dev/null
+++ b/jena-core/src/main/java/org/apache/jena/ext/xerces/impl/dv/xs/ExtendedSchemaDVFactoryImpl.java
@@ -0,0 +1,84 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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.jena.ext.xerces.impl.dv.xs;
+
+import org.apache.jena.ext.xerces.impl.dv.XSSimpleType;
+import org.apache.jena.ext.xerces.util.SymbolHash;
+
+/**
+ * A special factory to create/return built-in schema DVs and create user-defined DVs
+ * that includes anyAtomicType, yearMonthDuration and dayTimeDuration
+ * 
+ * @xerces.internal 
+ *
+ * @author Khaled Noaman, IBM
+ *
+ * @version $Id: ExtendedSchemaDVFactoryImpl.java 710089 2008-11-03 16:01:16Z knoaman $
+ */
+public class ExtendedSchemaDVFactoryImpl extends BaseSchemaDVFactory {
+
+    static SymbolHash fBuiltInTypes = new SymbolHash();
+    static {
+        createBuiltInTypes();
+    }
+    
+    // create all built-in types
+    static void createBuiltInTypes() {
+        final String ANYATOMICTYPE     = "anyAtomicType";
+        final String DURATION          = "duration";
+        final String YEARMONTHDURATION = "yearMonthDuration";
+        final String DAYTIMEDURATION   = "dayTimeDuration";
+
+    	createBuiltInTypes(fBuiltInTypes, XSSimpleTypeDecl.fAnyAtomicType);
+
+        // add anyAtomicType
+        fBuiltInTypes.put(ANYATOMICTYPE, XSSimpleTypeDecl.fAnyAtomicType);
+
+        // add 2 duration types
+        XSSimpleTypeDecl durationDV = (XSSimpleTypeDecl)fBuiltInTypes.get(DURATION);
+        fBuiltInTypes.put(YEARMONTHDURATION, new XSSimpleTypeDecl(durationDV, YEARMONTHDURATION, XSSimpleTypeDecl.DV_YEARMONTHDURATION, XSSimpleType.ORDERED_PARTIAL, false, false, false, true, XSSimpleTypeDecl.YEARMONTHDURATION_DT));
+        fBuiltInTypes.put(DAYTIMEDURATION, new XSSimpleTypeDecl(durationDV, DAYTIMEDURATION, XSSimpleTypeDecl.DV_DAYTIMEDURATION, XSSimpleType.ORDERED_PARTIAL, false, false, false, true, XSSimpleTypeDecl.DAYTIMEDURATION_DT));
+    } //createBuiltInTypes()
+
+    /**
+     * Get a built-in simple type of the given name
+     * REVISIT: its still not decided within the Schema WG how to define the
+     *          ur-types and if all simple types should be derived from a
+     *          complex type, so as of now we ignore the fact that anySimpleType
+     *          is derived from anyType, and pass 'null' as the base of
+     *          anySimpleType. It needs to be changed as per the decision taken.
+     *
+     * @param name  the name of the datatype
+     * @return      the datatype validator of the given name
+     */
+    @Override
+    public XSSimpleType getBuiltInType(String name) {
+        return (XSSimpleType)fBuiltInTypes.get(name);
+    }
+
+    /**
+     * get all built-in simple types, which are stored in a hashtable keyed by
+     * the name
+     *
+     * @return      a hashtable which contains all built-in simple types
+     */
+    @Override
+    public SymbolHash getBuiltInTypes() {
+        return fBuiltInTypes.makeClone();
+    }
+}

http://git-wip-us.apache.org/repos/asf/jena/blob/c9a7e646/jena-core/src/main/java/org/apache/jena/ext/xerces/impl/dv/xs/FloatDV.java
----------------------------------------------------------------------
diff --git a/jena-core/src/main/java/org/apache/jena/ext/xerces/impl/dv/xs/FloatDV.java b/jena-core/src/main/java/org/apache/jena/ext/xerces/impl/dv/xs/FloatDV.java
new file mode 100644
index 0000000..d00decd
--- /dev/null
+++ b/jena-core/src/main/java/org/apache/jena/ext/xerces/impl/dv/xs/FloatDV.java
@@ -0,0 +1,246 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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.jena.ext.xerces.impl.dv.xs;
+
+import org.apache.jena.ext.xerces.impl.dv.InvalidDatatypeValueException;
+import org.apache.jena.ext.xerces.impl.dv.ValidationContext;
+import org.apache.jena.ext.xerces.xs.datatypes.XSFloat;
+
+/**
+ * Represent the schema type "float"
+ *
+ * @xerces.internal 
+ *
+ * @author Neeraj Bajaj, Sun Microsystems, inc.
+ * @author Sandy Gao, IBM
+ *
+ * @version $Id: FloatDV.java 572095 2007-09-02 18:32:43Z mrglavas $
+ */
+public class FloatDV extends TypeValidator {
+
+    @Override
+    public short getAllowedFacets(){
+        return ( XSSimpleTypeDecl.FACET_PATTERN | XSSimpleTypeDecl.FACET_WHITESPACE | XSSimpleTypeDecl.FACET_ENUMERATION |XSSimpleTypeDecl.FACET_MAXINCLUSIVE |XSSimpleTypeDecl.FACET_MININCLUSIVE | XSSimpleTypeDecl.FACET_MAXEXCLUSIVE  | XSSimpleTypeDecl.FACET_MINEXCLUSIVE  );
+    }//getAllowedFacets()
+
+    //convert a String to Float form, we have to take care of cases specified in spec like INF, -INF and NaN
+    @Override
+    public Object getActualValue(String content, ValidationContext context) throws InvalidDatatypeValueException {
+        try{
+            return new XFloat(content);
+        } catch (NumberFormatException ex){
+            throw new InvalidDatatypeValueException("cvc-datatype-valid.1.2.1", new Object[]{content, "float"});
+        }
+    }//getActualValue()
+
+    // Can't call Float#compareTo method, because it's introduced in jdk 1.2
+    @Override
+    public int compare(Object value1, Object value2){
+        return ((XFloat)value1).compareTo((XFloat)value2);
+    }//compare()
+    
+    //distinguishes between identity and equality for float datatype
+    //0.0 is equal but not identical to -0.0
+    @Override
+    public boolean isIdentical (Object value1, Object value2) {  	 	
+        if (value2 instanceof XFloat) {
+            return ((XFloat)value1).isIdentical((XFloat)value2);
+        }
+        return false;
+    }//isIdentical()
+
+    private static final class XFloat implements XSFloat {
+
+        private final float value;
+        public XFloat(String s) throws NumberFormatException {
+            if (DoubleDV.isPossibleFP(s)) {
+                value = Float.parseFloat(s);
+            }
+            else if ( s.equals("INF") ) {
+                value = Float.POSITIVE_INFINITY;
+            }
+            else if ( s.equals("-INF") ) {
+                value = Float.NEGATIVE_INFINITY;
+            }
+            else if ( s.equals("NaN") ) {
+                value = Float.NaN;
+            }
+            else {
+                throw new NumberFormatException(s);
+            }
+        }
+
+        @Override
+        public boolean equals(Object val) {
+            if (val == this)
+                return true;
+
+            if (!(val instanceof XFloat))
+                return false;
+            XFloat oval = (XFloat)val;
+
+            // NOTE: we don't distinguish 0.0 from -0.0
+            if (value == oval.value)
+                return true;
+
+            if (value != value && oval.value != oval.value)
+                return true;
+
+            return false;
+        }
+        
+        @Override
+        public int hashCode() {
+            // This check is necessary because floatToIntBits(+0) != floatToIntBits(-0)
+            return (value == 0f) ? 0 : Float.floatToIntBits(value);
+        }
+        
+        // NOTE: 0.0 is equal but not identical to -0.0
+        public boolean isIdentical (XFloat val) {
+            if (val == this) {
+                return true;
+            }
+            
+            if (value == val.value) {
+                return (value != 0.0f || 
+                    (Float.floatToIntBits(value) == Float.floatToIntBits(val.value)));
+            }
+            
+            if (value != value && val.value != val.value)
+                return true;
+
+            return false;
+        }
+
+        private int compareTo(XFloat val) {
+            float oval = val.value;
+
+            // this < other
+            if (value < oval)
+                return -1;
+            // this > other
+            if (value > oval)
+                return 1;
+            // this == other
+            // NOTE: we don't distinguish 0.0 from -0.0
+            if (value == oval)
+                return 0;
+
+            // one of the 2 values or both is/are NaN(s)
+            
+            if (value != value) {
+                // this = NaN = other
+                if (oval != oval)
+                    return 0;
+                // this is NaN <> other
+                return INDETERMINATE;
+            }
+
+            // other is NaN <> this
+            return INDETERMINATE;
+        }
+
+        private String canonical;
+        @Override
+        public synchronized String toString() {
+            if (canonical == null) {
+                if (value == Float.POSITIVE_INFINITY)
+                    canonical = "INF";
+                else if (value == Float.NEGATIVE_INFINITY)
+                    canonical = "-INF";
+                else if (value != value)
+                    canonical = "NaN";
+                // NOTE: we don't distinguish 0.0 from -0.0
+                else if (value == 0)
+                    canonical = "0.0E1";
+                else {
+                    // REVISIT: use the java algorithm for now, because we
+                    // don't know what to output for 1.1f (which is no
+                    // actually 1.1)
+                    canonical = Float.toString(value);
+                    // if it contains 'E', then it should be a valid schema
+                    // canonical representation
+                    if (canonical.indexOf('E') == -1) {
+                        int len = canonical.length();
+                        // at most 3 longer: E, -, 9
+                        char[] chars = new char[len+3];
+                        canonical.getChars(0, len, chars, 0);
+                        // expected decimal point position
+                        int edp = chars[0] == '-' ? 2 : 1;
+                        // for non-zero integer part
+                        if (value >= 1 || value <= -1) {
+                            // decimal point position
+                            int dp = canonical.indexOf('.');
+                            // move the digits: ddd.d --> d.ddd
+                            for (int i = dp; i > edp; i--) {
+                                chars[i] = chars[i-1];
+                            }
+                            chars[edp] = '.';
+                            // trim trailing zeros: d00.0 --> d.000 --> d.
+                            while (chars[len-1] == '0')
+                                len--;
+                            // add the last zero if necessary: d. --> d.0
+                            if (chars[len-1] == '.')
+                                len++;
+                            // append E: d.dd --> d.ddE
+                            chars[len++] = 'E';
+                            // how far we shifted the decimal point
+                            int shift = dp - edp;
+                            // append the exponent --> d.ddEd
+                            // the exponent is at most 7
+                            chars[len++] = (char)(shift + '0');
+                        }
+                        else {
+                            // non-zero digit point
+                            int nzp = edp + 1;
+                            // skip zeros: 0.003
+                            while (chars[nzp] == '0')
+                                nzp++;
+                            // put the first non-zero digit to the left of '.'
+                            chars[edp-1] = chars[nzp];
+                            chars[edp] = '.';
+                            // move other digits (non-zero) to the right of '.'
+                            for (int i = nzp+1, j = edp+1; i < len; i++, j++)
+                                chars[j] = chars[i];
+                            // adjust the length
+                            len -= nzp - edp;
+                            // append 0 if nessary: 0.03 --> 3. --> 3.0
+                            if (len == edp + 1)
+                                chars[len++] = '0';
+                            // append E-: d.dd --> d.ddE-
+                            chars[len++] = 'E';
+                            chars[len++] = '-';
+                            // how far we shifted the decimal point
+                            int shift = nzp - edp;
+                            // append the exponent --> d.ddEd
+                            // the exponent is at most 3
+                            chars[len++] = (char)(shift + '0');
+                        }
+                        canonical = new String(chars, 0, len);
+                    }
+                }
+            }
+            return canonical;
+        }
+        
+        @Override
+        public float getValue() {
+            return value;
+        }
+    }
+} // class FloatDV

http://git-wip-us.apache.org/repos/asf/jena/blob/c9a7e646/jena-core/src/main/java/org/apache/jena/ext/xerces/impl/dv/xs/FullDVFactory.java
----------------------------------------------------------------------
diff --git a/jena-core/src/main/java/org/apache/jena/ext/xerces/impl/dv/xs/FullDVFactory.java b/jena-core/src/main/java/org/apache/jena/ext/xerces/impl/dv/xs/FullDVFactory.java
new file mode 100644
index 0000000..81d1d6d
--- /dev/null
+++ b/jena-core/src/main/java/org/apache/jena/ext/xerces/impl/dv/xs/FullDVFactory.java
@@ -0,0 +1,169 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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.jena.ext.xerces.impl.dv.xs;
+
+import org.apache.jena.ext.xerces.impl.dv.XSFacets;
+import org.apache.jena.ext.xerces.impl.dv.XSSimpleType;
+import org.apache.jena.ext.xerces.util.SymbolHash;
+import org.apache.jena.ext.xerces.xs.XSConstants;
+
+/**
+ * the factory to create/return built-in schema DVs and create user-defined DVs
+ *
+ * @xerces.internal 
+ *
+ * @author Neeraj Bajaj, Sun Microsystems, inc.
+ * @author Sandy Gao, IBM
+ *
+ * @version $Id: FullDVFactory.java 699892 2008-09-28 21:08:27Z mrglavas $
+ */
+@SuppressWarnings("all")
+public class FullDVFactory extends BaseDVFactory {
+
+    static final String URI_SCHEMAFORSCHEMA = "http://www.w3.org/2001/XMLSchema";
+
+    // there are 45 types. 89 is the closest prime number to 45*2=90.
+    static SymbolHash fFullTypes = new SymbolHash(89);
+    static {
+        createBuiltInTypes(fFullTypes);
+    }
+
+    /**
+     * Get a built-in simple type of the given name
+     * REVISIT: its still not decided within the Schema WG how to define the
+     *          ur-types and if all simple types should be derived from a
+     *          complex type, so as of now we ignore the fact that anySimpleType
+     *          is derived from anyType, and pass 'null' as the base of
+     *          anySimpleType. It needs to be changed as per the decision taken.
+     *
+     * @param name  the name of the datatype
+     * @return      the datatype validator of the given name
+     */
+    @Override
+    public XSSimpleType getBuiltInType(String name) {
+        return (XSSimpleType)fFullTypes.get(name);
+    }
+
+    /**
+     * get all built-in simple types, which are stored in a hashtable keyed by
+     * the name
+     *
+     * @return      a hashtable which contains all built-in simple types
+     */
+    @Override
+    public SymbolHash getBuiltInTypes() {
+        return fFullTypes.makeClone();
+    }
+
+    // create all built-in types
+    static void createBuiltInTypes(SymbolHash types) {
+        // create base types first
+        BaseDVFactory.createBuiltInTypes(types);
+        
+        // full schema simple type names
+        final String DOUBLE            = "double";
+        final String DURATION          = "duration";
+        final String ENTITY            = "ENTITY";
+        final String ENTITIES          = "ENTITIES";
+        final String FLOAT             = "float";
+        final String HEXBINARY         = "hexBinary";
+        final String ID                = "ID";
+        final String IDREF             = "IDREF";
+        final String IDREFS            = "IDREFS";
+        final String NAME              = "Name";
+        final String NCNAME            = "NCName";
+        final String NMTOKEN           = "NMTOKEN";
+        final String NMTOKENS          = "NMTOKENS";
+        final String LANGUAGE          = "language";
+        final String NORMALIZEDSTRING  = "normalizedString";
+        final String NOTATION          = "NOTATION";
+        final String QNAME             = "QName";
+        final String STRING            = "string";
+        final String TOKEN             = "token";
+
+        final XSFacets facets = new XSFacets();
+
+        XSSimpleTypeDecl anySimpleType = XSSimpleTypeDecl.fAnySimpleType;
+        XSSimpleTypeDecl stringDV = (XSSimpleTypeDecl)types.get(STRING);
+
+        types.put(FLOAT, new XSSimpleTypeDecl(anySimpleType, FLOAT, XSSimpleTypeDecl.DV_FLOAT, XSSimpleType.ORDERED_PARTIAL, true, true, true, true, XSConstants.FLOAT_DT));
+        types.put(DOUBLE, new XSSimpleTypeDecl(anySimpleType, DOUBLE, XSSimpleTypeDecl.DV_DOUBLE, XSSimpleType.ORDERED_PARTIAL, true, true, true, true, XSConstants.DOUBLE_DT));
+        types.put(DURATION, new XSSimpleTypeDecl(anySimpleType, DURATION, XSSimpleTypeDecl.DV_DURATION, XSSimpleType.ORDERED_PARTIAL, false, false, false, true, XSConstants.DURATION_DT));
+        types.put(HEXBINARY, new XSSimpleTypeDecl(anySimpleType, HEXBINARY, XSSimpleTypeDecl.DV_HEXBINARY, XSSimpleType.ORDERED_FALSE, false, false, false, true, XSConstants.HEXBINARY_DT));
+        types.put(QNAME, new XSSimpleTypeDecl(anySimpleType, QNAME, XSSimpleTypeDecl.DV_QNAME, XSSimpleType.ORDERED_FALSE, false, false, false, true, XSConstants.QNAME_DT));
+        types.put(NOTATION, new XSSimpleTypeDecl(anySimpleType, NOTATION, XSSimpleTypeDecl.DV_NOTATION, XSSimpleType.ORDERED_FALSE, false, false, false, true, XSConstants.NOTATION_DT));
+
+        facets.whiteSpace =  XSSimpleType.WS_REPLACE;
+        XSSimpleTypeDecl normalizedDV = new XSSimpleTypeDecl(stringDV, NORMALIZEDSTRING , URI_SCHEMAFORSCHEMA, (short)0, false, null, XSConstants.NORMALIZEDSTRING_DT);
+        normalizedDV.applyFacets1(facets, XSSimpleType.FACET_WHITESPACE, (short)0 );
+        types.put(NORMALIZEDSTRING, normalizedDV);
+
+        facets.whiteSpace = XSSimpleType.WS_COLLAPSE;
+        XSSimpleTypeDecl tokenDV = new XSSimpleTypeDecl(normalizedDV, TOKEN , URI_SCHEMAFORSCHEMA, (short)0, false, null, XSConstants.TOKEN_DT);
+        tokenDV.applyFacets1(facets, XSSimpleType.FACET_WHITESPACE, (short)0 );
+        types.put(TOKEN, tokenDV);
+
+        facets.whiteSpace = XSSimpleType.WS_COLLAPSE;
+        facets.pattern  = "([a-zA-Z]{1,8})(-[a-zA-Z0-9]{1,8})*";
+        XSSimpleTypeDecl languageDV = new XSSimpleTypeDecl(tokenDV, LANGUAGE , URI_SCHEMAFORSCHEMA, (short)0, false, null, XSConstants.LANGUAGE_DT);
+        languageDV.applyFacets1(facets, (short)(XSSimpleType.FACET_WHITESPACE | XSSimpleType.FACET_PATTERN) ,(short)0);
+        types.put(LANGUAGE, languageDV);
+
+        facets.whiteSpace =  XSSimpleType.WS_COLLAPSE;
+        XSSimpleTypeDecl nameDV = new XSSimpleTypeDecl(tokenDV, NAME , URI_SCHEMAFORSCHEMA, (short)0, false, null, XSConstants.NAME_DT);
+        nameDV.applyFacets1(facets, XSSimpleType.FACET_WHITESPACE, (short)0, XSSimpleTypeDecl.SPECIAL_PATTERN_NAME);
+        types.put(NAME, nameDV);
+
+        facets.whiteSpace = XSSimpleType.WS_COLLAPSE;
+        XSSimpleTypeDecl ncnameDV = new XSSimpleTypeDecl(nameDV, NCNAME , URI_SCHEMAFORSCHEMA, (short)0, false, null, XSConstants.NCNAME_DT) ;
+        ncnameDV.applyFacets1(facets, XSSimpleType.FACET_WHITESPACE, (short)0, XSSimpleTypeDecl.SPECIAL_PATTERN_NCNAME);
+        types.put(NCNAME, ncnameDV);
+
+        types.put(ID, new XSSimpleTypeDecl(ncnameDV,  ID, XSSimpleTypeDecl.DV_ID, XSSimpleType.ORDERED_FALSE, false, false, false , true, XSConstants.ID_DT));
+        XSSimpleTypeDecl idrefDV = new XSSimpleTypeDecl(ncnameDV,  IDREF , XSSimpleTypeDecl.DV_IDREF, XSSimpleType.ORDERED_FALSE, false, false, false, true, XSConstants.IDREF_DT);
+        types.put(IDREF, idrefDV);
+
+        facets.minLength = 1;
+        XSSimpleTypeDecl tempDV = new XSSimpleTypeDecl(null, URI_SCHEMAFORSCHEMA, (short)0, idrefDV, true, null);
+        XSSimpleTypeDecl idrefsDV = new XSSimpleTypeDecl(tempDV, IDREFS, URI_SCHEMAFORSCHEMA, (short)0, false, null);
+        idrefsDV.applyFacets1(facets, XSSimpleType.FACET_MINLENGTH, (short)0);
+        types.put(IDREFS, idrefsDV);
+
+        XSSimpleTypeDecl entityDV = new XSSimpleTypeDecl(ncnameDV, ENTITY , XSSimpleTypeDecl.DV_ENTITY, XSSimpleType.ORDERED_FALSE, false, false, false, true, XSConstants.ENTITY_DT);
+        types.put(ENTITY, entityDV);
+
+        facets.minLength = 1;
+        tempDV = new XSSimpleTypeDecl(null, URI_SCHEMAFORSCHEMA, (short)0, entityDV, true, null);
+        XSSimpleTypeDecl entitiesDV = new XSSimpleTypeDecl(tempDV, ENTITIES, URI_SCHEMAFORSCHEMA, (short)0, false, null);
+        entitiesDV.applyFacets1(facets, XSSimpleType.FACET_MINLENGTH, (short)0);
+        types.put(ENTITIES, entitiesDV);
+
+
+        facets.whiteSpace  = XSSimpleType.WS_COLLAPSE;
+        XSSimpleTypeDecl nmtokenDV = new XSSimpleTypeDecl(tokenDV, NMTOKEN, URI_SCHEMAFORSCHEMA, (short)0, false, null, XSConstants.NMTOKEN_DT);
+        nmtokenDV.applyFacets1(facets, XSSimpleType.FACET_WHITESPACE, (short)0, XSSimpleTypeDecl.SPECIAL_PATTERN_NMTOKEN);
+        types.put(NMTOKEN, nmtokenDV);
+
+        facets.minLength = 1;
+        tempDV = new XSSimpleTypeDecl(null, URI_SCHEMAFORSCHEMA, (short)0, nmtokenDV, true, null);
+        XSSimpleTypeDecl nmtokensDV = new XSSimpleTypeDecl(tempDV, NMTOKENS, URI_SCHEMAFORSCHEMA, (short)0, false, null);
+        nmtokensDV.applyFacets1(facets, XSSimpleType.FACET_MINLENGTH, (short)0);
+        types.put(NMTOKENS, nmtokensDV);
+    }//createBuiltInTypes(SymbolHash)
+
+}//XFormsDVFactory

http://git-wip-us.apache.org/repos/asf/jena/blob/c9a7e646/jena-core/src/main/java/org/apache/jena/ext/xerces/impl/dv/xs/HexBinaryDV.java
----------------------------------------------------------------------
diff --git a/jena-core/src/main/java/org/apache/jena/ext/xerces/impl/dv/xs/HexBinaryDV.java b/jena-core/src/main/java/org/apache/jena/ext/xerces/impl/dv/xs/HexBinaryDV.java
new file mode 100644
index 0000000..f6cff07
--- /dev/null
+++ b/jena-core/src/main/java/org/apache/jena/ext/xerces/impl/dv/xs/HexBinaryDV.java
@@ -0,0 +1,94 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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.jena.ext.xerces.impl.dv.xs;
+
+import org.apache.jena.ext.xerces.impl.dv.InvalidDatatypeValueException;
+import org.apache.jena.ext.xerces.impl.dv.ValidationContext;
+import org.apache.jena.ext.xerces.impl.dv.util.ByteListImpl;
+import org.apache.jena.ext.xerces.impl.dv.util.HexBin;
+
+/**
+ * Represent the schema type "hexBinary"
+ *
+ * @xerces.internal 
+ *
+ * @author Neeraj Bajaj, Sun Microsystems, inc.
+ * @author Sandy Gao, IBM
+ *
+ * @version $Id: HexBinaryDV.java 446745 2006-09-15 21:43:58Z mrglavas $
+ */
+public class HexBinaryDV extends TypeValidator {
+
+    @Override
+    public short getAllowedFacets(){
+        return (XSSimpleTypeDecl.FACET_LENGTH | XSSimpleTypeDecl.FACET_MINLENGTH | XSSimpleTypeDecl.FACET_MAXLENGTH | XSSimpleTypeDecl.FACET_PATTERN | XSSimpleTypeDecl.FACET_ENUMERATION | XSSimpleTypeDecl.FACET_WHITESPACE );
+    }
+
+    @Override
+    public Object getActualValue(String content, ValidationContext context) throws InvalidDatatypeValueException {
+        byte[] decoded = HexBin.decode(content);
+        if (decoded == null)
+            throw new InvalidDatatypeValueException("cvc-datatype-valid.1.2.1", new Object[]{content, "hexBinary"});
+
+        return new XHex(decoded);
+    }
+
+    // length of a binary type is the number of bytes
+    @Override
+    public int getDataLength(Object value) {
+        return ((XHex)value).getLength();
+    }
+
+    private static final class XHex extends ByteListImpl {
+
+        public XHex(byte[] data) {
+            super(data);
+        }
+        @Override
+        public synchronized String toString() {
+            if (canonical == null) {
+                canonical = HexBin.encode(data);
+            }
+            return canonical;
+        }
+        
+        @Override
+        public boolean equals(Object obj) {
+            if (!(obj instanceof XHex))
+                return false;
+            byte[] odata = ((XHex)obj).data;
+            int len = data.length;
+            if (len != odata.length)
+                return false;
+            for (int i = 0; i < len; i++) {
+                if (data[i] != odata[i])
+                    return false;
+            }
+            return true;
+        }
+        
+        @Override
+        public int hashCode() {
+            int hash = 0;
+            for (int i = 0; i < data.length; ++i) {
+                hash = hash * 37 + ((data[i]) & 0xff);
+            }
+            return hash;
+        }
+    }
+}


[20/24] jena git commit: JENA-1537: Remove dependency on Xerces. Import needed code

Posted by an...@apache.org.
http://git-wip-us.apache.org/repos/asf/jena/blob/c9a7e646/jena-core/src/main/java/org/apache/jena/ext/xerces/impl/dv/xs/AbstractDateTimeDV.java
----------------------------------------------------------------------
diff --git a/jena-core/src/main/java/org/apache/jena/ext/xerces/impl/dv/xs/AbstractDateTimeDV.java b/jena-core/src/main/java/org/apache/jena/ext/xerces/impl/dv/xs/AbstractDateTimeDV.java
new file mode 100644
index 0000000..e91c639
--- /dev/null
+++ b/jena-core/src/main/java/org/apache/jena/ext/xerces/impl/dv/xs/AbstractDateTimeDV.java
@@ -0,0 +1,1107 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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.jena.ext.xerces.impl.dv.xs;
+
+import java.math.BigDecimal;
+
+import javax.xml.datatype.DatatypeFactory;
+import javax.xml.datatype.Duration;
+import javax.xml.datatype.XMLGregorianCalendar;
+
+import org.apache.jena.ext.xerces.DatatypeFactoryInst;
+import org.apache.jena.ext.xerces.impl.Constants;
+import org.apache.jena.ext.xerces.xs.datatypes.XSDateTime;
+
+/**
+ * This is the base class of all date/time datatype validators.
+ * It implements common code for parsing, validating and comparing datatypes.
+ * Classes that extend this class, must implement parse() method.
+ *
+ * REVISIT: There are many instance variables, which would cause problems
+ *          when we support grammar caching. A grammar is possibly used by
+ *          two parser instances at the same time, then the same simple type
+ *          decl object can be used to validate two strings at the same time.
+ *          -SG
+ *          
+ * @xerces.internal 
+ *
+ * @author Elena Litani
+ * @author Len Berman
+ * @author Gopal Sharma, SUN Microsystems Inc.
+ *
+ * @version $Id: AbstractDateTimeDV.java 965250 2010-07-18 16:04:58Z mrglavas $
+ */
+@SuppressWarnings("all")
+public abstract class AbstractDateTimeDV extends TypeValidator {
+	
+	//debugging
+	private static final boolean DEBUG=false;
+	
+	//define shared variables for date/time
+	
+	
+	//define constants to be used in assigning default values for
+	//all date/time excluding duration
+	protected final static int YEAR=2000;
+	protected final static int MONTH=01;
+	protected final static int DAY = 01;
+    
+    protected static final DatatypeFactory datatypeFactory = DatatypeFactoryInst.newDatatypeFactory();
+	
+    public short getAllowedFacets(){
+		return ( XSSimpleTypeDecl.FACET_PATTERN | XSSimpleTypeDecl.FACET_WHITESPACE | XSSimpleTypeDecl.FACET_ENUMERATION |XSSimpleTypeDecl.FACET_MAXINCLUSIVE |XSSimpleTypeDecl.FACET_MININCLUSIVE | XSSimpleTypeDecl.FACET_MAXEXCLUSIVE  | XSSimpleTypeDecl.FACET_MINEXCLUSIVE  );
+	}//getAllowedFacets()
+	
+	
+	// distinguishes between identity and equality for date/time values
+	// ie: two values representing the same "moment in time" but with different 
+	// remembered timezones are now equal but not identical.
+    public boolean isIdentical (Object value1, Object value2) {
+		if (!(value1 instanceof DateTimeData) || !(value2 instanceof DateTimeData)) {
+			return false;
+		}
+		
+		DateTimeData v1 = (DateTimeData)value1;
+		DateTimeData v2 = (DateTimeData)value2;
+		
+		// original timezones must be the same in addition to date/time values
+		// being 'equal'
+		if ((v1.timezoneHr == v2.timezoneHr) && (v1.timezoneMin == v2.timezoneMin)) {
+			return v1.equals(v2);
+		}
+		
+		return false;
+	}//isIdentical()
+	
+	// the parameters are in compiled form (from getActualValue)
+    public int compare (Object value1, Object value2) {
+		return compareDates(((DateTimeData)value1),
+				((DateTimeData)value2), true);
+	}//compare()
+	
+	/**
+	 * Compare algorithm described in dateDime (3.2.7).
+	 * Duration datatype overwrites this method
+	 *
+	 * @param date1  normalized date representation of the first value
+	 * @param date2  normalized date representation of the second value
+	 * @param strict
+	 * @return less, greater, less_equal, greater_equal, equal
+	 */
+	protected short compareDates(DateTimeData date1, DateTimeData date2, boolean strict) {
+		if (date1.utc == date2.utc) {
+			return compareOrder(date1, date2);
+		}
+		short c1, c2;
+		
+		DateTimeData tempDate = new DateTimeData(null, this);
+		
+		if ( date1.utc=='Z' ) {
+			
+			//compare date1<=date1<=(date2 with time zone -14)
+			//
+			cloneDate(date2, tempDate); //clones date1 value to global temporary storage: fTempDate
+			tempDate.timezoneHr=14;
+			tempDate.timezoneMin = 0;
+			tempDate.utc='+';
+			normalize(tempDate);
+			c1 = compareOrder(date1, tempDate);
+			if (c1 == LESS_THAN)
+				return c1;
+			
+			//compare date1>=(date2 with time zone +14)
+			//
+			cloneDate(date2, tempDate); //clones date1 value to global temporary storage: tempDate
+			tempDate.timezoneHr = -14;
+			tempDate.timezoneMin = 0;
+			tempDate.utc='-';
+			normalize(tempDate);
+			c2 = compareOrder(date1, tempDate);
+			if (c2 == GREATER_THAN)
+				return c2;
+			
+			return INDETERMINATE;
+		}
+		else if ( date2.utc=='Z' ) {
+			
+			//compare (date1 with time zone -14)<=date2
+			//
+			cloneDate(date1, tempDate); //clones date1 value to global temporary storage: tempDate
+			tempDate.timezoneHr = -14;
+			tempDate.timezoneMin = 0;
+			tempDate.utc='-';
+			if (DEBUG) {
+				System.out.println("tempDate=" + dateToString(tempDate));
+			}
+			normalize(tempDate);
+			c1 = compareOrder(tempDate, date2);
+			if (DEBUG) {
+				System.out.println("date=" + dateToString(date2));
+				System.out.println("tempDate=" + dateToString(tempDate));
+			}
+			if (c1 == LESS_THAN)
+				return c1;
+			
+			//compare (date1 with time zone +14)<=date2
+			//
+			cloneDate(date1, tempDate); //clones date1 value to global temporary storage: tempDate
+			tempDate.timezoneHr = 14;
+			tempDate.timezoneMin = 0;
+			tempDate.utc='+';
+			normalize(tempDate);
+			c2 = compareOrder(tempDate, date2);
+			if (DEBUG) {
+				System.out.println("tempDate=" + dateToString(tempDate));
+			}
+			if (c2 == GREATER_THAN)
+				return c2;
+			
+			return INDETERMINATE;
+		}
+		return INDETERMINATE;
+		
+	}
+	
+	/**
+	 * Given normalized values, determines order-relation
+	 * between give date/time objects.
+	 *
+	 * @param date1  date/time object
+	 * @param date2  date/time object
+	 * @return 0 if date1 and date2 are equal, a value less than 0 if date1 is less than date2, a value greater than 0 if date1 is greater than date2
+	 */
+	protected short compareOrder(DateTimeData date1, DateTimeData date2) {
+		if(date1.position < 1) {
+			if (date1.year < date2.year)
+				return -1;
+			if (date1.year > date2.year)
+				return 1;
+		}
+		if(date1.position < 2) {
+			if (date1.month < date2.month)
+				return -1;
+			if (date1.month > date2.month)
+				return 1;
+		}
+		if (date1.day < date2.day)
+			return -1;
+		if (date1.day > date2.day)
+			return 1;
+		if (date1.hour < date2.hour)
+			return -1;
+		if (date1.hour > date2.hour)
+			return 1;
+		if (date1.minute < date2.minute)
+			return -1;
+		if (date1.minute > date2.minute)
+			return 1;
+		if (date1.second < date2.second)
+			return -1;
+		if (date1.second > date2.second)
+			return 1;
+		if (date1.utc < date2.utc)
+			return -1;
+		if (date1.utc > date2.utc)
+			return 1;
+		return 0;
+	}
+	
+	/**
+	 * Parses time hh:mm:ss.sss and time zone if any
+	 *
+	 * @param start
+	 * @param end
+	 * @param data
+	 * @exception RuntimeException
+	 */
+	protected  void getTime (String buffer, int start, int end, DateTimeData data) throws RuntimeException{
+		
+		int stop = start+2;
+		
+		//get hours (hh)
+		data.hour=parseInt(buffer, start,stop);
+		
+		//get minutes (mm)
+		
+		if (buffer.charAt(stop++)!=':') {
+			throw new RuntimeException("Error in parsing time zone" );
+		}
+		start = stop;
+		stop = stop+2;
+		data.minute=parseInt(buffer, start,stop);
+		
+		//get seconds (ss)
+		if (buffer.charAt(stop++)!=':') {
+			throw new RuntimeException("Error in parsing time zone" );
+		}
+		
+		//find UTC sign if any
+		int sign = findUTCSign(buffer, start, end);
+		
+		//get seconds (ms)
+		start = stop;
+		stop = sign < 0 ? end : sign;
+		data.second = parseSecond(buffer, start, stop);
+		
+		//parse UTC time zone (hh:mm)
+		if (sign > 0) {
+			getTimeZone(buffer, data, sign, end);
+		}
+	}
+	
+	/**
+	 * Parses date CCYY-MM-DD
+	 *
+	 * @param buffer
+	 * @param start start position
+	 * @param end end position
+	 * @param date
+	 * @exception RuntimeException
+	 */
+	protected int getDate (String buffer, int start, int end, DateTimeData date) throws RuntimeException{
+		
+		start = getYearMonth(buffer, start, end, date);
+		
+		if (buffer.charAt(start++) !='-') {
+			throw new RuntimeException("CCYY-MM must be followed by '-' sign");
+		}
+		int stop = start + 2;
+		date.day=parseInt(buffer, start, stop);
+		return stop;
+	}
+	
+	/**
+	 * Parses date CCYY-MM
+	 *
+	 * @param buffer
+	 * @param start start position
+	 * @param end end position
+	 * @param date
+	 * @exception RuntimeException
+	 */
+	protected int getYearMonth (String buffer, int start, int end, DateTimeData date) throws RuntimeException{
+		
+		if ( buffer.charAt(0)=='-' ) {
+			// REVISIT: date starts with preceding '-' sign
+			//          do we have to do anything with it?
+			//
+			start++;
+		}
+		int i = indexOf(buffer, start, end, '-');
+		if ( i==-1 ) throw new RuntimeException("Year separator is missing or misplaced");
+		int length = i-start;
+		if (length<4) {
+			throw new RuntimeException("Year must have 'CCYY' format");
+		}
+		else if (length > 4 && buffer.charAt(start)=='0'){
+			throw new RuntimeException("Leading zeros are required if the year value would otherwise have fewer than four digits; otherwise they are forbidden");
+		}
+		date.year= parseIntYear(buffer, i);
+		if (buffer.charAt(i)!='-') {
+			throw new RuntimeException("CCYY must be followed by '-' sign");
+		}
+		start = ++i;
+		i = start +2;
+		date.month=parseInt(buffer, start, i);
+		return i; //fStart points right after the MONTH
+	}
+	
+	/**
+	 * Shared code from Date and YearMonth datatypes.
+	 * Finds if time zone sign is present
+	 *
+	 * @param end
+	 * @param date
+	 * @exception RuntimeException
+	 */
+	protected void parseTimeZone (String buffer, int start, int end, DateTimeData date) throws RuntimeException{
+		
+		//fStart points right after the date
+		
+		if ( start < end ) {
+			if (!isNextCharUTCSign(buffer, start, end)) {
+				throw new RuntimeException ("Error in month parsing");
+			}
+			else {
+				getTimeZone(buffer, date, start, end);
+			}
+		}
+	}
+	
+	/**
+	 * Parses time zone: 'Z' or {+,-} followed by  hh:mm
+	 *
+	 * @param data
+	 * @param sign
+	 * @exception RuntimeException
+	 */
+	protected void getTimeZone (String buffer, DateTimeData data, int sign, int end) throws RuntimeException{
+		data.utc=buffer.charAt(sign);
+		
+		if ( buffer.charAt(sign) == 'Z' ) {
+			if (end>(++sign)) {
+				throw new RuntimeException("Error in parsing time zone");
+			}
+			return;
+		}
+		if ( sign<=(end-6) ) {
+			
+			int negate = buffer.charAt(sign) == '-'?-1:1;
+			//parse hr
+			int stop = ++sign+2;
+			data.timezoneHr = negate*parseInt(buffer, sign, stop);
+			if (buffer.charAt(stop++)!=':') {
+				throw new RuntimeException("Error in parsing time zone" );
+			}
+			
+			//parse min
+			data.timezoneMin = negate*parseInt(buffer, stop, stop+2);
+			
+			if ( stop+2!=end ) {
+				throw new RuntimeException("Error in parsing time zone");
+			}
+            if(data.timezoneHr != 0 || data.timezoneMin != 0)
+                data.normalized = false;
+		}
+		else {
+			throw new RuntimeException("Error in parsing time zone");
+		}
+		if ( DEBUG ) {
+			System.out.println("time[hh]="+data.timezoneHr + " time[mm]=" +data.timezoneMin);
+		}
+	}
+	
+	/**
+	 * Computes index of given char within StringBuffer
+	 *
+	 * @param start
+	 * @param end
+	 * @param ch     character to look for in StringBuffer
+	 * @return index of ch within StringBuffer
+	 */
+	protected  int indexOf (String buffer, int start, int end, char ch) {
+		for ( int i=start;i<end;i++ ) {
+			if ( buffer.charAt(i) == ch ) {
+				return i;
+			}
+		}
+		return -1;
+	}
+	
+	/**
+	 * Validates given date/time object accoring to W3C PR Schema
+	 * [D.1 ISO 8601 Conventions]
+	 *
+	 * @param data
+	 */
+	protected void validateDateTime (DateTimeData data) {
+		
+		//REVISIT: should we throw an exception for not valid dates
+		//          or reporting an error message should be sufficient?
+		
+		/**
+		 * XML Schema 1.1 - RQ-123: Allow year 0000 in date related types.
+		 */
+		if (!Constants.SCHEMA_1_1_SUPPORT && data.year==0 ) {
+			throw new RuntimeException("The year \"0000\" is an illegal year value");
+			
+		}
+		
+		if ( data.month<1 || data.month>12 ) {
+			throw new RuntimeException("The month must have values 1 to 12");
+			
+		}
+		
+		//validate days
+		if ( data.day>maxDayInMonthFor(data.year, data.month) || data.day<1 ) {
+			throw new RuntimeException("The day must have values 1 to 31");
+		}
+		
+		//validate hours
+		if ( data.hour>23 || data.hour<0 ) {
+			if (data.hour == 24 && data.minute == 0 && data.second == 0) {
+				data.hour = 0;
+				if (++data.day > maxDayInMonthFor(data.year, data.month)) {
+					data.day = 1;
+					if (++data.month > 12) {
+						data.month = 1;
+						if (Constants.SCHEMA_1_1_SUPPORT) {
+							++data.year;
+						}
+						else if (++data.year == 0) {
+							data.year = 1;
+						}
+					}
+				}
+			}
+			else {
+				throw new RuntimeException("Hour must have values 0-23, unless 24:00:00");
+			}
+		}
+		
+		//validate
+		if ( data.minute>59 || data.minute<0 ) {
+			throw new RuntimeException("Minute must have values 0-59");
+		}
+		
+		//validate
+		if ( data.second>=60 || data.second<0 ) {
+			throw new RuntimeException("Second must have values 0-59");
+			
+		}
+		
+		//validate
+		if ( data.timezoneHr>14 || data.timezoneHr<-14 ) {
+			throw new RuntimeException("Time zone should have range -14:00 to +14:00");
+		}
+		else {
+			if((data.timezoneHr == 14 || data.timezoneHr == -14) && data.timezoneMin != 0)
+				throw new RuntimeException("Time zone should have range -14:00 to +14:00");
+			else if(data.timezoneMin > 59 || data.timezoneMin < -59)
+				throw new RuntimeException("Minute must have values 0-59");
+		}
+		
+	}
+	
+	/**
+	 * Return index of UTC char: 'Z', '+', '-'
+	 *
+	 * @param start
+	 * @param end
+	 * @return index of the UTC character that was found
+	 */
+	protected int findUTCSign (String buffer, int start, int end) {
+		int c;
+		for ( int i=start;i<end;i++ ) {
+			c=buffer.charAt(i);
+			if ( c == 'Z' || c=='+' || c=='-' ) {
+				return i;
+			}
+			
+		}
+		return -1;
+	}
+    
+    /**
+     * Returns <code>true</code> if the character at start is 'Z', '+' or '-'.
+     */
+    protected final boolean isNextCharUTCSign(String buffer, int start, int end) {
+        if (start < end) {
+            char c = buffer.charAt(start);
+            return (c == 'Z' || c == '+' || c == '-');
+        }
+        return false;
+    }
+	
+	/**
+	 * Given start and end position, parses string value
+	 *
+	 * @param buffer string to parse
+	 * @param start  start position
+	 * @param end    end position
+	 * @return  return integer representation of characters
+	 */
+	protected  int parseInt (String buffer, int start, int end)
+	throws NumberFormatException{
+		//REVISIT: more testing on this parsing needs to be done.
+		int radix=10;
+		int result = 0;
+		int digit=0;
+		int limit = -Integer.MAX_VALUE;
+		int multmin = limit / radix;
+		int i = start;
+		do {
+			digit = getDigit(buffer.charAt(i));
+			if ( digit < 0 ) throw new NumberFormatException("'" + buffer + "' has wrong format");
+			if ( result < multmin ) throw new NumberFormatException("'" + buffer + "' has wrong format");
+			result *= radix;
+			if ( result < limit + digit ) throw new NumberFormatException("'" + buffer + "' has wrong format");
+			result -= digit;
+			
+		}while ( ++i < end );
+		return -result;
+	}
+	
+	// parse Year differently to support negative value.
+	protected int parseIntYear (String buffer, int end){
+		int radix=10;
+		int result = 0;
+		boolean negative = false;
+		int i=0;
+		int limit;
+		int multmin;
+		int digit=0;
+		
+		if (buffer.charAt(0) == '-'){
+			negative = true;
+			limit = Integer.MIN_VALUE;
+			i++;
+			
+		}
+		else{
+			limit = -Integer.MAX_VALUE;
+		}
+		multmin = limit / radix;
+		while (i < end)
+		{
+			digit = getDigit(buffer.charAt(i++));
+			if (digit < 0) throw new NumberFormatException("'" + buffer + "' has wrong format");
+			if (result < multmin) throw new NumberFormatException("'" + buffer + "' has wrong format");
+			result *= radix;
+			if (result < limit + digit) throw new NumberFormatException("'" + buffer + "' has wrong format");
+			result -= digit;
+		}
+		
+		if (negative)
+		{
+			if (i > 1) return result;
+			else throw new NumberFormatException("'" + buffer + "' has wrong format");
+		}
+		return -result;
+		
+	}
+	
+	/**
+	 * If timezone present - normalize dateTime  [E Adding durations to dateTimes]
+	 *
+	 * @param date   CCYY-MM-DDThh:mm:ss+03
+	 */
+	protected void normalize(DateTimeData date) {
+		
+		// REVISIT: we have common code in addDuration() for durations
+		//          should consider reorganizing it.
+		//
+		
+		//add minutes (from time zone)
+		int negate = -1;
+		
+		if ( DEBUG ) {
+			System.out.println("==>date.minute"+date.minute);
+			System.out.println("==>date.timezoneMin" +date.timezoneMin);
+		}
+		int temp = date.minute + negate * date.timezoneMin;
+		int carry = fQuotient (temp, 60);
+		date.minute= mod(temp, 60, carry);
+		
+		if ( DEBUG ) {
+			System.out.println("==>carry: " + carry);
+		}
+		//add hours
+		temp = date.hour + negate * date.timezoneHr + carry;
+		carry = fQuotient(temp, 24);
+		date.hour=mod(temp, 24, carry);
+		if ( DEBUG ) {
+			System.out.println("==>date.hour"+date.hour);
+			System.out.println("==>carry: " + carry);
+		}
+		
+		date.day=date.day+carry;
+		
+		while ( true ) {
+			temp=maxDayInMonthFor(date.year, date.month);
+			if (date.day<1) {
+				date.day = date.day + maxDayInMonthFor(date.year, date.month-1);
+				carry=-1;
+			}
+			else if ( date.day>temp ) {
+				date.day=date.day-temp;
+				carry=1;
+			}
+			else {
+				break;
+			}
+			temp=date.month+carry;
+			date.month=modulo(temp, 1, 13);
+			date.year=date.year+fQuotient(temp, 1, 13);
+            if(date.year == 0 && !Constants.SCHEMA_1_1_SUPPORT) {
+                date.year = (date.timezoneHr < 0 || date.timezoneMin < 0)?1:-1;
+            }
+		}
+		date.utc='Z';
+	}
+	
+	
+	/**
+     * @param date
+     */
+    protected void saveUnnormalized(DateTimeData date) {
+        date.unNormYear = date.year;
+        date.unNormMonth = date.month;
+        date.unNormDay = date.day;
+        date.unNormHour = date.hour;
+        date.unNormMinute = date.minute;
+        date.unNormSecond = date.second;
+    }
+
+    /**
+	 * Resets object representation of date/time
+	 *
+	 * @param data   date/time object
+	 */
+	protected void resetDateObj(DateTimeData data) {
+		data.year = 0;
+		data.month = 0;
+		data.day = 0;
+		data.hour = 0;
+		data.minute = 0;
+		data.second = 0;
+		data.utc = 0;
+		data.timezoneHr = 0;
+		data.timezoneMin = 0;
+	}
+	
+	/**
+	 * Given {year,month} computes maximum
+	 * number of days for given month
+	 *
+	 * @param year
+	 * @param month
+	 * @return integer containg the number of days in a given month
+	 */
+	protected int maxDayInMonthFor(int year, int month) {
+		//validate days
+		if ( month==4 || month==6 || month==9 || month==11 ) {
+			return 30;
+		}
+		else if ( month==2 ) {
+			if ( isLeapYear(year) ) {
+				return 29;
+			}
+			else {
+				return 28;
+			}
+		}
+		else {
+			return 31;
+		}
+	}
+	
+	private boolean isLeapYear(int year) {
+		
+		//REVISIT: should we take care about Julian calendar?
+		return((year%4 == 0) && ((year%100 != 0) || (year%400 == 0)));
+	}
+	
+	//
+	// help function described in W3C PR Schema [E Adding durations to dateTimes]
+	//
+	protected int mod (int a, int b, int quotient) {
+		//modulo(a, b) = a - fQuotient(a,b)*b
+		return (a - quotient*b) ;
+	}
+	
+	//
+	// help function described in W3C PR Schema [E Adding durations to dateTimes]
+	//
+	protected int fQuotient (int a, int b) {
+		
+		//fQuotient(a, b) = the greatest integer less than or equal to a/b
+		return (int)Math.floor((float)a/b);
+	}
+	
+	//
+	// help function described in W3C PR Schema [E Adding durations to dateTimes]
+	//
+	protected int modulo (int temp, int low, int high) {
+		//modulo(a - low, high - low) + low
+		int a = temp - low;
+		int b = high - low;
+		return (mod (a, b, fQuotient(a, b)) + low) ;
+	}
+	
+	//
+	// help function described in W3C PR Schema [E Adding durations to dateTimes]
+	//
+	protected int fQuotient (int temp, int low, int high) {
+		//fQuotient(a - low, high - low)
+		
+		return fQuotient(temp - low, high - low);
+	}
+	
+	
+	protected String dateToString(DateTimeData date) {
+		StringBuffer message = new StringBuffer(25);
+		append(message, date.year, 4);
+		message.append('-');
+		append(message, date.month, 2);
+		message.append('-');
+		append(message, date.day, 2);
+		message.append('T');
+		append(message, date.hour, 2);
+		message.append(':');
+		append(message, date.minute, 2);
+		message.append(':');
+		append(message, date.second);
+		append(message, (char)date.utc, 0);
+		return message.toString();
+	}
+	
+	protected final void append(StringBuffer message, int value, int nch) {
+        if (value == Integer.MIN_VALUE) {
+            message.append(value);
+            return;
+        }
+		if (value < 0) {
+			message.append('-');
+			value = -value;
+		}
+		if (nch == 4) {
+			if (value < 10)
+				message.append("000");
+			else if (value < 100)
+				message.append("00");
+			else if (value < 1000)
+				message.append('0');
+			message.append(value);
+		}
+		else if (nch == 2) {
+			if (value < 10)
+				message.append('0');
+			message.append(value);
+		}
+		else {
+			if (value != 0)
+				message.append((char)value);
+		}
+	}
+	
+	protected final void append(StringBuffer message, double value) {
+	    if (value < 0) {
+	        message.append('-');
+	        value = -value;
+	    }
+	    if (value < 10) {
+	        message.append('0');
+	    }
+	    append2(message, value);
+	}
+    
+    protected final void append2(StringBuffer message, double value) {
+        final int intValue = (int) value;
+        if (value == intValue) {
+            message.append(intValue);
+        }
+        else {
+            append3(message, value);
+        }
+    }
+    
+    private void append3(StringBuffer message, double value) {
+        String d = String.valueOf(value);
+        int eIndex = d.indexOf('E');
+        if (eIndex == -1) {
+            message.append(d);
+            return;
+        }
+        int exp;
+        if (value < 1) {
+            // Need to convert from scientific notation of the form 
+            // n.nnn...E-N (N >= 4) to a normal decimal value.
+            try {
+                exp = parseInt(d, eIndex+2, d.length());
+            }
+            // This should never happen. 
+            // It's only possible if String.valueOf(double) is broken.
+            catch (Exception e) {
+                message.append(d);
+                return;
+            }
+            message.append("0.");
+            for (int i = 1; i < exp; ++i) {
+                message.append('0');
+            }
+            // Remove trailing zeros.
+            int end = eIndex - 1;
+            while (end > 0) {
+                char c = d.charAt(end);
+                if (c != '0') {
+                    break;
+                }
+                --end;
+            }
+            // Now append the digits to the end. Skip over the decimal point.
+            for (int i = 0; i <= end; ++i) {
+                char c = d.charAt(i);
+                if (c != '.') {
+                    message.append(c);
+                }
+            }
+        }
+        else {
+            // Need to convert from scientific notation of the form 
+            // n.nnn...EN (N >= 7) to a normal decimal value.
+            try {
+                exp = parseInt(d, eIndex+1, d.length());
+            }
+            // This should never happen. 
+            // It's only possible if String.valueOf(double) is broken.
+            catch (Exception e) {
+                message.append(d);
+                return;
+            }
+            final int integerEnd = exp + 2;
+            for (int i = 0; i < eIndex; ++i) {
+                char c = d.charAt(i);
+                if (c != '.') {
+                    if (i == integerEnd) {
+                        message.append('.');
+                    }
+                    message.append(c);
+                }
+            }
+            // Append trailing zeroes if necessary.
+            for (int i = integerEnd - eIndex; i > 0; --i) {
+                message.append('0');
+            }
+        }
+    }
+	
+	protected double parseSecond(String buffer, int start, int end)
+	throws NumberFormatException {
+		int dot = -1;
+		for (int i = start; i < end; i++) {
+			char ch = buffer.charAt(i);
+			if (ch == '.')
+				dot = i;
+			else if (ch > '9' || ch < '0')
+				throw new NumberFormatException("'" + buffer + "' has wrong format");
+		}
+		if (dot == -1) {
+			if (start+2 != end)
+				throw new NumberFormatException("'" + buffer + "' has wrong format");
+		}
+		else if (start+2 != dot || dot+1 == end) {
+			throw new NumberFormatException("'" + buffer + "' has wrong format");
+		}
+		return Double.parseDouble(buffer.substring(start, end));
+	}
+	
+	//
+	//Private help functions
+	//
+	
+	private void cloneDate (DateTimeData finalValue, DateTimeData tempDate) {
+		tempDate.year = finalValue.year;
+		tempDate.month = finalValue.month;
+		tempDate.day = finalValue.day;
+		tempDate.hour = finalValue.hour;
+		tempDate.minute = finalValue.minute;
+		tempDate.second = finalValue.second;
+		tempDate.utc = finalValue.utc;
+		tempDate.timezoneHr = finalValue.timezoneHr;
+		tempDate.timezoneMin = finalValue.timezoneMin;
+	}
+	
+	/**
+	 * Represents date time data
+	 */
+	static final class DateTimeData implements XSDateTime {
+		int year, month, day, hour, minute, utc;
+		double second;
+		int timezoneHr, timezoneMin;
+        private String originalValue;
+        boolean normalized = true;
+        
+        int unNormYear;
+        int unNormMonth;
+        int unNormDay;
+        int unNormHour;
+        int unNormMinute;
+        double unNormSecond;
+		
+		// used for comparisons - to decide the 'interesting' portions of
+		// a date/time based data type.
+		int position;
+		// a pointer to the type that was used go generate this data
+		// note that this is not the actual simple type, but one of the
+		// statically created XXXDV objects, so this won't cause any GC problem.
+		final AbstractDateTimeDV type;
+		private String canonical;
+		public DateTimeData(String originalValue, AbstractDateTimeDV type) {
+            this.originalValue = originalValue;
+			this.type = type;
+		}
+		public DateTimeData(int year, int month, int day, int hour, int minute,
+				double second, int utc, String originalValue, boolean normalized, AbstractDateTimeDV type) {
+			this.year = year;
+			this.month = month;
+			this.day = day;
+			this.hour = hour;
+			this.minute = minute;
+			this.second = second;
+			this.utc = utc;
+			this.type = type;
+            this.originalValue = originalValue;
+		}
+        public boolean equals(Object obj) {
+			if (!(obj instanceof DateTimeData))
+				return false;
+			return type.compareDates(this, (DateTimeData)obj, true)==0;
+		}
+        public synchronized String toString() {
+			if (canonical == null) {
+				canonical = type.dateToString(this);
+			}
+			return canonical;
+		}
+		/* (non-Javadoc)
+		 * @see org.apache.xerces.xs.datatypes.XSDateTime#getYear()
+		 */
+        public int getYears() {
+            if(type instanceof DurationDV)
+                return 0;
+			return normalized?year:unNormYear;
+		}
+		/* (non-Javadoc)
+		 * @see org.apache.xerces.xs.datatypes.XSDateTime#getMonth()
+		 */
+        public int getMonths() {
+            if(type instanceof DurationDV) {
+                return year*12 + month;
+            }
+			return normalized?month:unNormMonth;
+		}
+		/* (non-Javadoc)
+		 * @see org.apache.xerces.xs.datatypes.XSDateTime#getDay()
+		 */
+        public int getDays() {
+            if(type instanceof DurationDV)
+                return 0;
+			return normalized?day:unNormDay;
+		}
+		/* (non-Javadoc)
+		 * @see org.apache.xerces.xs.datatypes.XSDateTime#getHour()
+		 */
+        public int getHours() {
+            if(type instanceof DurationDV)
+                return 0;
+			return normalized?hour:unNormHour;
+		}
+		/* (non-Javadoc)
+		 * @see org.apache.xerces.xs.datatypes.XSDateTime#getMinutes()
+		 */
+        public int getMinutes() {
+            if(type instanceof DurationDV)
+                return 0;
+			return normalized?minute:unNormMinute;
+		}
+		/* (non-Javadoc)
+		 * @see org.apache.xerces.xs.datatypes.XSDateTime#getSeconds()
+		 */
+        public double getSeconds() {
+            if(type instanceof DurationDV) {
+                return day*24*60*60 + hour*60*60 + minute*60 + second;
+            }
+			return normalized?second:unNormSecond;
+		}
+		/* (non-Javadoc)
+		 * @see org.apache.xerces.xs.datatypes.XSDateTime#hasTimeZone()
+		 */
+        public boolean hasTimeZone() {
+			return utc != 0;
+		}
+		/* (non-Javadoc)
+		 * @see org.apache.xerces.xs.datatypes.XSDateTime#getTimeZoneHours()
+		 */
+        public int getTimeZoneHours() {
+			return timezoneHr;
+		}
+		/* (non-Javadoc)
+		 * @see org.apache.xerces.xs.datatypes.XSDateTime#getTimeZoneMinutes()
+		 */
+        public int getTimeZoneMinutes() {
+			return timezoneMin;
+		}
+        /* (non-Javadoc)
+         * @see org.apache.xerces.xs.datatypes.XSDateTime#getLexicalValue()
+         */
+        public String getLexicalValue() {
+            return originalValue;
+        }
+        /* (non-Javadoc)
+         * @see org.apache.xerces.xs.datatypes.XSDateTime#normalize()
+         */
+        public XSDateTime normalize() {
+            if(!normalized) {
+                DateTimeData dt = (DateTimeData)this.clone();
+                dt.normalized = true;
+                return dt;
+            }
+            return this;
+        }
+        /* (non-Javadoc)
+         * @see org.apache.xerces.xs.datatypes.XSDateTime#isNormalized()
+         */
+        public boolean isNormalized() {
+            return normalized;
+        }
+        
+        public Object clone() {
+            DateTimeData dt = new DateTimeData(this.year, this.month, this.day, this.hour, 
+                        this.minute, this.second, this.utc, this.originalValue, this.normalized, this.type);
+            dt.canonical = this.canonical;
+            dt.position = position;
+            dt.timezoneHr = this.timezoneHr;
+            dt.timezoneMin = this.timezoneMin;
+            dt.unNormYear = this.unNormYear;
+            dt.unNormMonth = this.unNormMonth;
+            dt.unNormDay = this.unNormDay;
+            dt.unNormHour = this.unNormHour;
+            dt.unNormMinute = this.unNormMinute;
+            dt.unNormSecond = this.unNormSecond;
+            return dt;
+        }
+        
+        /* (non-Javadoc)
+         * @see org.apache.xerces.xs.datatypes.XSDateTime#getXMLGregorianCalendar()
+         */
+        public XMLGregorianCalendar getXMLGregorianCalendar() {
+            return type.getXMLGregorianCalendar(this);
+        }
+        /* (non-Javadoc)
+         * @see org.apache.xerces.xs.datatypes.XSDateTime#getDuration()
+         */
+        public Duration getDuration() {
+            return type.getDuration(this);
+        }
+	}
+
+    protected XMLGregorianCalendar getXMLGregorianCalendar(DateTimeData data) {
+        return null;
+    }
+
+    protected Duration getDuration(DateTimeData data) {
+        return null;
+    }
+    
+    protected final BigDecimal getFractionalSecondsAsBigDecimal(DateTimeData data) {
+        final StringBuffer buf = new StringBuffer();
+        append3(buf, data.unNormSecond);
+        String value = buf.toString();
+        final int index = value.indexOf('.');
+        if (index == -1) {
+            return null;
+        }
+        value = value.substring(index);
+        final BigDecimal _val = new BigDecimal(value);
+        if (_val.compareTo(BigDecimal.valueOf(0)) == 0) {
+            return null;
+        }
+        return _val;
+    }
+}

http://git-wip-us.apache.org/repos/asf/jena/blob/c9a7e646/jena-core/src/main/java/org/apache/jena/ext/xerces/impl/dv/xs/AnyAtomicDV.java
----------------------------------------------------------------------
diff --git a/jena-core/src/main/java/org/apache/jena/ext/xerces/impl/dv/xs/AnyAtomicDV.java b/jena-core/src/main/java/org/apache/jena/ext/xerces/impl/dv/xs/AnyAtomicDV.java
new file mode 100644
index 0000000..84694fa
--- /dev/null
+++ b/jena-core/src/main/java/org/apache/jena/ext/xerces/impl/dv/xs/AnyAtomicDV.java
@@ -0,0 +1,43 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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.jena.ext.xerces.impl.dv.xs;
+
+import org.apache.jena.ext.xerces.impl.dv.InvalidDatatypeValueException;
+import org.apache.jena.ext.xerces.impl.dv.ValidationContext;
+
+/**
+ * Represent the schema type "anyAtomicType"
+ * 
+ * @xerces.experimental
+ *
+ * @author Ankit Pasricha, IBM
+ * 
+ * @version $Id: AnyAtomicDV.java 446745 2006-09-15 21:43:58Z mrglavas $
+ */
+@SuppressWarnings("all")
+class AnyAtomicDV extends TypeValidator {
+    
+    public short getAllowedFacets() {
+        return 0;
+    }
+    
+    public Object getActualValue(String content, ValidationContext context) throws InvalidDatatypeValueException {
+        return content;
+    }
+    
+} // class AnyAtomicDV

http://git-wip-us.apache.org/repos/asf/jena/blob/c9a7e646/jena-core/src/main/java/org/apache/jena/ext/xerces/impl/dv/xs/AnySimpleDV.java
----------------------------------------------------------------------
diff --git a/jena-core/src/main/java/org/apache/jena/ext/xerces/impl/dv/xs/AnySimpleDV.java b/jena-core/src/main/java/org/apache/jena/ext/xerces/impl/dv/xs/AnySimpleDV.java
new file mode 100644
index 0000000..5e98ce7
--- /dev/null
+++ b/jena-core/src/main/java/org/apache/jena/ext/xerces/impl/dv/xs/AnySimpleDV.java
@@ -0,0 +1,45 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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.jena.ext.xerces.impl.dv.xs;
+
+import org.apache.jena.ext.xerces.impl.dv.InvalidDatatypeValueException;
+import org.apache.jena.ext.xerces.impl.dv.ValidationContext;
+
+/**
+ * Represent the schema type "anySimpleType"
+ *
+ * @xerces.internal 
+ *
+ * @author Neeraj Bajaj, Sun Microsystems, inc.
+ * @author Sandy Gao, IBM
+ *
+ * @version $Id: AnySimpleDV.java 446745 2006-09-15 21:43:58Z mrglavas $
+ */
+@SuppressWarnings("all")
+public class AnySimpleDV extends TypeValidator {
+
+    public short getAllowedFacets() {
+        // anySimpleType doesn't allow any facet, not even whiteSpace
+        return 0;
+    }
+
+    public Object getActualValue(String content, ValidationContext context) throws InvalidDatatypeValueException {
+        return content;
+    }
+
+} // class AnySimpleDV

http://git-wip-us.apache.org/repos/asf/jena/blob/c9a7e646/jena-core/src/main/java/org/apache/jena/ext/xerces/impl/dv/xs/AnyURIDV.java
----------------------------------------------------------------------
diff --git a/jena-core/src/main/java/org/apache/jena/ext/xerces/impl/dv/xs/AnyURIDV.java b/jena-core/src/main/java/org/apache/jena/ext/xerces/impl/dv/xs/AnyURIDV.java
new file mode 100644
index 0000000..80701ba
--- /dev/null
+++ b/jena-core/src/main/java/org/apache/jena/ext/xerces/impl/dv/xs/AnyURIDV.java
@@ -0,0 +1,170 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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.jena.ext.xerces.impl.dv.xs;
+
+import org.apache.jena.ext.xerces.impl.dv.InvalidDatatypeValueException;
+import org.apache.jena.ext.xerces.impl.dv.ValidationContext;
+import org.apache.jena.ext.xerces.util.URI;
+
+/**
+ * Represent the schema type "anyURI"
+ *
+ * @xerces.internal 
+ *
+ * @author Neeraj Bajaj, Sun Microsystems, inc.
+ * @author Sandy Gao, IBM
+ *
+ * @version $Id: AnyURIDV.java 699892 2008-09-28 21:08:27Z mrglavas $
+ */
+@SuppressWarnings("all")
+public class AnyURIDV extends TypeValidator {
+
+    private static final URI BASE_URI;
+    static {
+        URI uri = null;
+        try {
+            uri = new URI("abc://def.ghi.jkl");
+        } catch (URI.MalformedURIException ex) {
+        }
+        BASE_URI = uri;
+    }
+
+    public short getAllowedFacets(){
+        return (XSSimpleTypeDecl.FACET_LENGTH | XSSimpleTypeDecl.FACET_MINLENGTH | XSSimpleTypeDecl.FACET_MAXLENGTH | XSSimpleTypeDecl.FACET_PATTERN | XSSimpleTypeDecl.FACET_ENUMERATION | XSSimpleTypeDecl.FACET_WHITESPACE );
+    }
+
+    // before we return string we have to make sure it is correct URI as per spec.
+    // for some types (string and derived), they just return the string itself
+    public Object getActualValue(String content, ValidationContext context) throws InvalidDatatypeValueException {
+        // check 3.2.17.c0 must: URI (rfc 2396/2723)
+        try {
+            if( content.length() != 0 ) {
+                // encode special characters using XLink 5.4 algorithm
+                final String encoded = encode(content);
+                // Support for relative URLs
+                // According to Java 1.1: URLs may also be specified with a
+                // String and the URL object that it is related to.
+                new URI(BASE_URI, encoded );
+            }
+        } catch (URI.MalformedURIException ex) {
+            throw new InvalidDatatypeValueException("cvc-datatype-valid.1.2.1", new Object[]{content, "anyURI"});
+        }
+
+        // REVISIT: do we need to return the new URI object?
+        return content;
+    }
+
+    // which ASCII characters need to be escaped
+    private static boolean gNeedEscaping[] = new boolean[128];
+    // the first hex character if a character needs to be escaped
+    private static char gAfterEscaping1[] = new char[128];
+    // the second hex character if a character needs to be escaped
+    private static char gAfterEscaping2[] = new char[128];
+    private static char[] gHexChs = {'0', '1', '2', '3', '4', '5', '6', '7',
+                                     '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};
+    // initialize the above 3 arrays
+    static {
+        for (int i = 0; i <= 0x1f; i++) {
+            gNeedEscaping[i] = true;
+            gAfterEscaping1[i] = gHexChs[i >> 4];
+            gAfterEscaping2[i] = gHexChs[i & 0xf];
+        }
+        gNeedEscaping[0x7f] = true;
+        gAfterEscaping1[0x7f] = '7';
+        gAfterEscaping2[0x7f] = 'F';
+        char[] escChs = {' ', '<', '>', '"', '{', '}',
+                         '|', '\\', '^', '~', '`'};
+        int len = escChs.length;
+        char ch;
+        for (int i = 0; i < len; i++) {
+            ch = escChs[i];
+            gNeedEscaping[ch] = true;
+            gAfterEscaping1[ch] = gHexChs[ch >> 4];
+            gAfterEscaping2[ch] = gHexChs[ch & 0xf];
+        }
+    }
+
+    // To encode special characters in anyURI, by using %HH to represent
+    // special ASCII characters: 0x00~0x1F, 0x7F, ' ', '<', '>', etc.
+    // and non-ASCII characters (whose value >= 128).
+    private static String encode(String anyURI){
+        int len = anyURI.length(), ch;
+        StringBuffer buffer = new StringBuffer(len*3);
+
+        // for each character in the anyURI
+        int i = 0;
+        for (; i < len; i++) {
+            ch = anyURI.charAt(i);
+            // if it's not an ASCII character, break here, and use UTF-8 encoding
+            if (ch >= 128)
+                break;
+            if (gNeedEscaping[ch]) {
+                buffer.append('%');
+                buffer.append(gAfterEscaping1[ch]);
+                buffer.append(gAfterEscaping2[ch]);
+            }
+            else {
+                buffer.append((char)ch);
+            }
+        }
+
+        // we saw some non-ascii character
+        if (i < len) {
+            // get UTF-8 bytes for the remaining sub-string
+            byte[] bytes = null;
+            byte b;
+            try {
+                bytes = anyURI.substring(i).getBytes("UTF-8");
+            } catch (java.io.UnsupportedEncodingException e) {
+                // should never happen
+                return anyURI;
+            }
+            len = bytes.length;
+
+            // for each byte
+            for (i = 0; i < len; i++) {
+                b = bytes[i];
+                // for non-ascii character: make it positive, then escape
+                if (b < 0) {
+                    ch = b + 256;
+                    buffer.append('%');
+                    buffer.append(gHexChs[ch >> 4]);
+                    buffer.append(gHexChs[ch & 0xf]);
+                }
+                else if (gNeedEscaping[b]) {
+                    buffer.append('%');
+                    buffer.append(gAfterEscaping1[b]);
+                    buffer.append(gAfterEscaping2[b]);
+                }
+                else {
+                    buffer.append((char)b);
+                }
+            }
+        }
+
+        // If encoding happened, create a new string;
+        // otherwise, return the orginal one.
+        if (buffer.length() != len) {
+            return buffer.toString();
+        }
+        else {
+            return anyURI;
+        }
+    }
+
+} // class AnyURIDV

http://git-wip-us.apache.org/repos/asf/jena/blob/c9a7e646/jena-core/src/main/java/org/apache/jena/ext/xerces/impl/dv/xs/Base64BinaryDV.java
----------------------------------------------------------------------
diff --git a/jena-core/src/main/java/org/apache/jena/ext/xerces/impl/dv/xs/Base64BinaryDV.java b/jena-core/src/main/java/org/apache/jena/ext/xerces/impl/dv/xs/Base64BinaryDV.java
new file mode 100644
index 0000000..d4417aa
--- /dev/null
+++ b/jena-core/src/main/java/org/apache/jena/ext/xerces/impl/dv/xs/Base64BinaryDV.java
@@ -0,0 +1,92 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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.jena.ext.xerces.impl.dv.xs;
+
+import org.apache.jena.ext.xerces.impl.dv.InvalidDatatypeValueException;
+import org.apache.jena.ext.xerces.impl.dv.ValidationContext;
+import org.apache.jena.ext.xerces.impl.dv.util.Base64;
+import org.apache.jena.ext.xerces.impl.dv.util.ByteListImpl;
+
+/**
+ * Represent the schema type "base64Binary"
+ *
+ * @xerces.internal 
+ *
+ * @author Neeraj Bajaj, Sun Microsystems, inc.
+ * @author Sandy Gao, IBM
+ *
+ * @version $Id: Base64BinaryDV.java 446745 2006-09-15 21:43:58Z mrglavas $
+ */
+@SuppressWarnings("all")
+public class Base64BinaryDV extends TypeValidator {
+
+    public short getAllowedFacets(){
+        return (XSSimpleTypeDecl.FACET_LENGTH | XSSimpleTypeDecl.FACET_MINLENGTH | XSSimpleTypeDecl.FACET_MAXLENGTH | XSSimpleTypeDecl.FACET_PATTERN | XSSimpleTypeDecl.FACET_ENUMERATION | XSSimpleTypeDecl.FACET_WHITESPACE );
+    }
+
+    public Object getActualValue(String content, ValidationContext context) throws InvalidDatatypeValueException {
+        byte[] decoded = Base64.decode(content);
+        if (decoded == null)
+            throw new InvalidDatatypeValueException("cvc-datatype-valid.1.2.1", new Object[]{content, "base64Binary"});
+
+        return new XBase64(decoded);
+    }
+
+    // length of a binary type is the number of bytes
+    public int getDataLength(Object value) {
+        return ((XBase64)value).getLength();
+    }
+
+    /**
+     * represent base64 data
+     */
+    private static final class XBase64 extends ByteListImpl {
+
+        public XBase64(byte[] data) {
+            super(data);
+        }
+        public synchronized String toString() {
+            if (canonical == null) {
+                canonical = Base64.encode(data);
+            }
+            return canonical;
+        }
+        
+        public boolean equals(Object obj) {
+            if (!(obj instanceof XBase64))
+                return false;
+            byte[] odata = ((XBase64)obj).data;
+            int len = data.length;
+            if (len != odata.length)
+                return false;
+            for (int i = 0; i < len; i++) {
+                if (data[i] != odata[i])
+                    return false;
+            }
+            return true;
+        }
+        
+        public int hashCode() {
+            int hash = 0;
+            for (int i = 0; i < data.length; ++i) {
+                hash = hash * 37 + ((data[i]) & 0xff);
+            }
+            return hash;
+        }
+    }
+} // class Base64BinaryDV

http://git-wip-us.apache.org/repos/asf/jena/blob/c9a7e646/jena-core/src/main/java/org/apache/jena/ext/xerces/impl/dv/xs/BaseDVFactory.java
----------------------------------------------------------------------
diff --git a/jena-core/src/main/java/org/apache/jena/ext/xerces/impl/dv/xs/BaseDVFactory.java b/jena-core/src/main/java/org/apache/jena/ext/xerces/impl/dv/xs/BaseDVFactory.java
new file mode 100644
index 0000000..896bcc0
--- /dev/null
+++ b/jena-core/src/main/java/org/apache/jena/ext/xerces/impl/dv/xs/BaseDVFactory.java
@@ -0,0 +1,248 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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.jena.ext.xerces.impl.dv.xs;
+
+import org.apache.jena.ext.xerces.impl.dv.SchemaDVFactory;
+import org.apache.jena.ext.xerces.impl.dv.XSFacets;
+import org.apache.jena.ext.xerces.impl.dv.XSSimpleType;
+import org.apache.jena.ext.xerces.util.SymbolHash;
+import org.apache.jena.ext.xerces.xs.XSConstants;
+import org.apache.jena.ext.xerces.xs.XSObjectList;
+
+/**
+ * the factory to create/return built-in schema DVs and create user-defined DVs
+ *
+ * @xerces.internal 
+ *
+ * @author Neeraj Bajaj, Sun Microsystems, inc.
+ * @author Sandy Gao, IBM
+ *
+ * @version $Id: BaseDVFactory.java 699892 2008-09-28 21:08:27Z mrglavas $
+ */
+@SuppressWarnings("all")
+public class BaseDVFactory extends SchemaDVFactory {
+
+    static final String URI_SCHEMAFORSCHEMA = "http://www.w3.org/2001/XMLSchema";
+
+    // there are 27 types. 53 is the closest prime number to 27*2=54.
+    static SymbolHash fBaseTypes = new SymbolHash(53);
+    static {
+        createBuiltInTypes(fBaseTypes);
+    }
+
+    /**
+     * Get a built-in simple type of the given name
+     * REVISIT: its still not decided within the Schema WG how to define the
+     *          ur-types and if all simple types should be derived from a
+     *          complex type, so as of now we ignore the fact that anySimpleType
+     *          is derived from anyType, and pass 'null' as the base of
+     *          anySimpleType. It needs to be changed as per the decision taken.
+     *
+     * @param name  the name of the datatype
+     * @return      the datatype validator of the given name
+     */
+    public XSSimpleType getBuiltInType(String name) {
+        return (XSSimpleType)fBaseTypes.get(name);
+    }
+
+    /**
+     * get all built-in simple types, which are stored in a hashtable keyed by
+     * the name
+     *
+     * @return      a hashtable which contains all built-in simple types
+     */
+    public SymbolHash getBuiltInTypes() {
+        return fBaseTypes.makeClone();
+    }
+
+    /**
+     * Create a new simple type which is derived by restriction from another
+     * simple type.
+     *
+     * @param name              name of the new type, could be null
+     * @param targetNamespace   target namespace of the new type, could be null
+     * @param finalSet          value of "final"
+     * @param base              base type of the new type
+     * @param annotations       set of annotations
+     * @return                  the newly created simple type
+     */
+    public XSSimpleType createTypeRestriction(String name, String targetNamespace,
+                                              short finalSet, XSSimpleType base, XSObjectList annotations) {
+        return new XSSimpleTypeDecl((XSSimpleTypeDecl)base, name, targetNamespace, finalSet, false, annotations);
+    }
+
+    /**
+     * Create a new simple type which is derived by list from another simple
+     * type.
+     *
+     * @param name              name of the new type, could be null
+     * @param targetNamespace   target namespace of the new type, could be null
+     * @param finalSet          value of "final"
+     * @param itemType          item type of the list type
+     * @param annotations       set of annotations
+     * @return                  the newly created simple type
+     */
+    public XSSimpleType createTypeList(String name, String targetNamespace,
+                                       short finalSet, XSSimpleType itemType,
+                                       XSObjectList annotations) {
+        return new XSSimpleTypeDecl(name, targetNamespace, finalSet, (XSSimpleTypeDecl)itemType, false, annotations);
+    }
+
+    /**
+     * Create a new simple type which is derived by union from a list of other
+     * simple types.
+     *
+     * @param name              name of the new type, could be null
+     * @param targetNamespace   target namespace of the new type, could be null
+     * @param finalSet          value of "final"
+     * @param memberTypes       member types of the union type
+     * @param annotations       set of annotations
+     * @return                  the newly created simple type
+     */
+    public XSSimpleType createTypeUnion(String name, String targetNamespace,
+                                        short finalSet, XSSimpleType[] memberTypes,
+                                        XSObjectList annotations) {
+        int typeNum = memberTypes.length;
+        XSSimpleTypeDecl[] mtypes = new XSSimpleTypeDecl[typeNum];
+        System.arraycopy(memberTypes, 0, mtypes, 0, typeNum);
+
+        return new XSSimpleTypeDecl(name, targetNamespace, finalSet, mtypes, annotations);
+    }
+
+    // create all built-in types
+    static void createBuiltInTypes(SymbolHash types) {
+        // base schema simple type names
+        final String ANYSIMPLETYPE     = "anySimpleType";
+        final String ANYURI            = "anyURI";
+        final String BASE64BINARY      = "base64Binary";
+        final String BOOLEAN           = "boolean";
+        final String BYTE              = "byte";
+        final String DATE              = "date";
+        final String DATETIME          = "dateTime";
+        final String DAY               = "gDay";
+        final String DECIMAL           = "decimal";
+        final String INT               = "int";
+        final String INTEGER           = "integer";
+        final String LONG              = "long";
+        final String NEGATIVEINTEGER   = "negativeInteger";
+        final String MONTH             = "gMonth";
+        final String MONTHDAY          = "gMonthDay";
+        final String NONNEGATIVEINTEGER= "nonNegativeInteger";
+        final String NONPOSITIVEINTEGER= "nonPositiveInteger";
+        final String POSITIVEINTEGER   = "positiveInteger";
+        final String SHORT             = "short";
+        final String STRING            = "string";
+        final String TIME              = "time";
+        final String UNSIGNEDBYTE      = "unsignedByte";
+        final String UNSIGNEDINT       = "unsignedInt";
+        final String UNSIGNEDLONG      = "unsignedLong";
+        final String UNSIGNEDSHORT     = "unsignedShort";
+        final String YEAR              = "gYear";
+        final String YEARMONTH         = "gYearMonth";
+
+        final XSFacets facets = new XSFacets();
+
+        XSSimpleTypeDecl anySimpleType = XSSimpleTypeDecl.fAnySimpleType;
+        types.put(ANYSIMPLETYPE, anySimpleType);
+        XSSimpleTypeDecl stringDV = new XSSimpleTypeDecl(anySimpleType, STRING, XSSimpleTypeDecl.DV_STRING, XSSimpleType.ORDERED_FALSE, false, false, false, true, XSConstants.STRING_DT);
+        types.put(STRING, stringDV);
+        types.put(BOOLEAN, new XSSimpleTypeDecl(anySimpleType, BOOLEAN, XSSimpleTypeDecl.DV_BOOLEAN, XSSimpleType.ORDERED_FALSE, false, true, false, true, XSConstants.BOOLEAN_DT));
+        XSSimpleTypeDecl decimalDV = new XSSimpleTypeDecl(anySimpleType, DECIMAL, XSSimpleTypeDecl.DV_DECIMAL, XSSimpleType.ORDERED_TOTAL, false, false, true, true, XSConstants.DECIMAL_DT);
+        types.put(DECIMAL, decimalDV);
+
+        types.put(ANYURI, new XSSimpleTypeDecl(anySimpleType, ANYURI, XSSimpleTypeDecl.DV_ANYURI, XSSimpleType.ORDERED_FALSE, false, false, false, true, XSConstants.ANYURI_DT));
+        types.put(BASE64BINARY, new XSSimpleTypeDecl(anySimpleType, BASE64BINARY, XSSimpleTypeDecl.DV_BASE64BINARY, XSSimpleType.ORDERED_FALSE, false, false, false, true, XSConstants.BASE64BINARY_DT));
+        types.put(DATETIME, new XSSimpleTypeDecl(anySimpleType, DATETIME, XSSimpleTypeDecl.DV_DATETIME, XSSimpleType.ORDERED_PARTIAL, false, false, false, true, XSConstants.DATETIME_DT));
+        types.put(TIME, new XSSimpleTypeDecl(anySimpleType, TIME, XSSimpleTypeDecl.DV_TIME, XSSimpleType.ORDERED_PARTIAL, false, false, false, true, XSConstants.TIME_DT));
+        types.put(DATE, new XSSimpleTypeDecl(anySimpleType, DATE, XSSimpleTypeDecl.DV_DATE, XSSimpleType.ORDERED_PARTIAL, false, false, false, true, XSConstants.DATE_DT));
+        types.put(YEARMONTH, new XSSimpleTypeDecl(anySimpleType, YEARMONTH, XSSimpleTypeDecl.DV_GYEARMONTH, XSSimpleType.ORDERED_PARTIAL, false, false, false, true, XSConstants.GYEARMONTH_DT));
+        types.put(YEAR, new XSSimpleTypeDecl(anySimpleType, YEAR, XSSimpleTypeDecl.DV_GYEAR, XSSimpleType.ORDERED_PARTIAL, false, false, false, true, XSConstants.GYEAR_DT));
+        types.put(MONTHDAY, new XSSimpleTypeDecl(anySimpleType, MONTHDAY, XSSimpleTypeDecl.DV_GMONTHDAY, XSSimpleType.ORDERED_PARTIAL, false, false, false, true, XSConstants.GMONTHDAY_DT));
+        types.put(DAY, new XSSimpleTypeDecl(anySimpleType, DAY, XSSimpleTypeDecl.DV_GDAY, XSSimpleType.ORDERED_PARTIAL, false, false, false, true, XSConstants.GDAY_DT));
+        types.put(MONTH, new XSSimpleTypeDecl(anySimpleType, MONTH, XSSimpleTypeDecl.DV_GMONTH, XSSimpleType.ORDERED_PARTIAL, false, false, false, true, XSConstants.GMONTH_DT));
+
+        XSSimpleTypeDecl integerDV = new XSSimpleTypeDecl(decimalDV, INTEGER, XSSimpleTypeDecl.DV_INTEGER, XSSimpleType.ORDERED_TOTAL, false, false, true, true, XSConstants.INTEGER_DT);
+        types.put(INTEGER, integerDV);
+
+        facets.maxInclusive = "0";
+        XSSimpleTypeDecl nonPositiveDV = new XSSimpleTypeDecl(integerDV, NONPOSITIVEINTEGER, URI_SCHEMAFORSCHEMA, (short)0, false, null, XSConstants.NONPOSITIVEINTEGER_DT);
+        nonPositiveDV.applyFacets1(facets , XSSimpleType.FACET_MAXINCLUSIVE, (short)0);
+        types.put(NONPOSITIVEINTEGER, nonPositiveDV);
+
+        facets.maxInclusive = "-1";
+        XSSimpleTypeDecl negativeDV = new XSSimpleTypeDecl(nonPositiveDV, NEGATIVEINTEGER, URI_SCHEMAFORSCHEMA, (short)0, false, null, XSConstants.NEGATIVEINTEGER_DT);
+        negativeDV.applyFacets1(facets , XSSimpleType.FACET_MAXINCLUSIVE, (short)0);
+        types.put(NEGATIVEINTEGER, negativeDV);
+
+        facets.maxInclusive = "9223372036854775807";
+        facets.minInclusive = "-9223372036854775808";
+        XSSimpleTypeDecl longDV = new XSSimpleTypeDecl(integerDV, LONG, URI_SCHEMAFORSCHEMA, (short)0, false, null, XSConstants.LONG_DT);
+        longDV.applyFacets1(facets , (short)(XSSimpleType.FACET_MAXINCLUSIVE | XSSimpleType.FACET_MININCLUSIVE), (short)0 );
+        types.put(LONG, longDV);
+
+
+        facets.maxInclusive = "2147483647";
+        facets.minInclusive =  "-2147483648";
+        XSSimpleTypeDecl intDV = new XSSimpleTypeDecl(longDV, INT, URI_SCHEMAFORSCHEMA, (short)0, false, null, XSConstants.INT_DT);
+        intDV.applyFacets1(facets, (short)(XSSimpleType.FACET_MAXINCLUSIVE | XSSimpleType.FACET_MININCLUSIVE), (short)0 );
+        types.put(INT, intDV);
+
+        facets.maxInclusive = "32767";
+        facets.minInclusive = "-32768";
+        XSSimpleTypeDecl shortDV = new XSSimpleTypeDecl(intDV, SHORT , URI_SCHEMAFORSCHEMA, (short)0, false, null, XSConstants.SHORT_DT);
+        shortDV.applyFacets1(facets, (short)(XSSimpleType.FACET_MAXINCLUSIVE | XSSimpleType.FACET_MININCLUSIVE), (short)0 );
+        types.put(SHORT, shortDV);
+
+        facets.maxInclusive = "127";
+        facets.minInclusive = "-128";
+        XSSimpleTypeDecl byteDV = new XSSimpleTypeDecl(shortDV, BYTE , URI_SCHEMAFORSCHEMA, (short)0, false, null, XSConstants.BYTE_DT);
+        byteDV.applyFacets1(facets, (short)(XSSimpleType.FACET_MAXINCLUSIVE | XSSimpleType.FACET_MININCLUSIVE), (short)0 );
+        types.put(BYTE, byteDV);
+
+        facets.minInclusive =  "0" ;
+        XSSimpleTypeDecl nonNegativeDV = new XSSimpleTypeDecl(integerDV, NONNEGATIVEINTEGER , URI_SCHEMAFORSCHEMA, (short)0, false, null, XSConstants.NONNEGATIVEINTEGER_DT);
+        nonNegativeDV.applyFacets1(facets, XSSimpleType.FACET_MININCLUSIVE, (short)0 );
+        types.put(NONNEGATIVEINTEGER, nonNegativeDV);
+
+        facets.maxInclusive = "18446744073709551615" ;
+        XSSimpleTypeDecl unsignedLongDV = new XSSimpleTypeDecl(nonNegativeDV, UNSIGNEDLONG , URI_SCHEMAFORSCHEMA, (short)0, false, null, XSConstants.UNSIGNEDLONG_DT);
+        unsignedLongDV.applyFacets1(facets, XSSimpleType.FACET_MAXINCLUSIVE, (short)0 );
+        types.put(UNSIGNEDLONG, unsignedLongDV);
+
+        facets.maxInclusive = "4294967295" ;
+        XSSimpleTypeDecl unsignedIntDV = new XSSimpleTypeDecl(unsignedLongDV, UNSIGNEDINT , URI_SCHEMAFORSCHEMA, (short)0, false, null, XSConstants.UNSIGNEDINT_DT);
+        unsignedIntDV.applyFacets1(facets, XSSimpleType.FACET_MAXINCLUSIVE, (short)0 );
+        types.put(UNSIGNEDINT, unsignedIntDV);
+
+        facets.maxInclusive = "65535" ;
+        XSSimpleTypeDecl unsignedShortDV = new XSSimpleTypeDecl(unsignedIntDV, UNSIGNEDSHORT , URI_SCHEMAFORSCHEMA, (short)0, false, null, XSConstants.UNSIGNEDSHORT_DT);
+        unsignedShortDV.applyFacets1(facets, XSSimpleType.FACET_MAXINCLUSIVE, (short)0 );
+        types.put(UNSIGNEDSHORT, unsignedShortDV);
+
+        facets.maxInclusive = "255" ;
+        XSSimpleTypeDecl unsignedByteDV = new XSSimpleTypeDecl(unsignedShortDV, UNSIGNEDBYTE , URI_SCHEMAFORSCHEMA, (short)0, false, null, XSConstants.UNSIGNEDBYTE_DT);
+        unsignedByteDV.applyFacets1(facets, XSSimpleType.FACET_MAXINCLUSIVE, (short)0 );
+        types.put(UNSIGNEDBYTE, unsignedByteDV);
+
+        facets.minInclusive = "1" ;
+        XSSimpleTypeDecl positiveIntegerDV = new XSSimpleTypeDecl(nonNegativeDV, POSITIVEINTEGER , URI_SCHEMAFORSCHEMA, (short)0, false, null, XSConstants.POSITIVEINTEGER_DT);
+        positiveIntegerDV.applyFacets1(facets, XSSimpleType.FACET_MININCLUSIVE, (short)0 );
+        types.put(POSITIVEINTEGER, positiveIntegerDV);
+    }//createBuiltInTypes(SymbolHash)
+
+}//BaseDVFactory

http://git-wip-us.apache.org/repos/asf/jena/blob/c9a7e646/jena-core/src/main/java/org/apache/jena/ext/xerces/impl/dv/xs/BaseSchemaDVFactory.java
----------------------------------------------------------------------
diff --git a/jena-core/src/main/java/org/apache/jena/ext/xerces/impl/dv/xs/BaseSchemaDVFactory.java b/jena-core/src/main/java/org/apache/jena/ext/xerces/impl/dv/xs/BaseSchemaDVFactory.java
new file mode 100644
index 0000000..9eca62f
--- /dev/null
+++ b/jena-core/src/main/java/org/apache/jena/ext/xerces/impl/dv/xs/BaseSchemaDVFactory.java
@@ -0,0 +1,326 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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.jena.ext.xerces.impl.dv.xs;
+
+import org.apache.jena.ext.xerces.impl.dv.SchemaDVFactory;
+import org.apache.jena.ext.xerces.impl.dv.XSFacets;
+import org.apache.jena.ext.xerces.impl.dv.XSSimpleType;
+import org.apache.jena.ext.xerces.impl.xs.XSDeclarationPool;
+import org.apache.jena.ext.xerces.util.SymbolHash;
+import org.apache.jena.ext.xerces.xs.XSConstants;
+import org.apache.jena.ext.xerces.xs.XSObjectList;
+
+/**
+ * the base factory to create/return built-in schema DVs and create user-defined DVs
+ * 
+ * @xerces.internal 
+ *
+ * @author Neeraj Bajaj, Sun Microsystems, inc.
+ * @author Sandy Gao, IBM
+ * @author Khaled Noaman, IBM 
+ *
+ * @version $Id: BaseSchemaDVFactory.java 805582 2009-08-18 21:13:20Z sandygao $
+ */
+@SuppressWarnings("all")
+public abstract class BaseSchemaDVFactory extends SchemaDVFactory {
+
+    static final String URI_SCHEMAFORSCHEMA = "http://www.w3.org/2001/XMLSchema";
+
+    protected XSDeclarationPool fDeclPool = null;
+
+    // create common built-in types
+    protected static void createBuiltInTypes(SymbolHash builtInTypes, XSSimpleTypeDecl baseAtomicType) {
+        // all schema simple type names
+        final String ANYSIMPLETYPE     = "anySimpleType";
+        final String ANYURI            = "anyURI";
+        final String BASE64BINARY      = "base64Binary";
+        final String BOOLEAN           = "boolean";
+        final String BYTE              = "byte";
+        final String DATE              = "date";
+        final String DATETIME          = "dateTime";
+        final String DAY               = "gDay";
+        final String DECIMAL           = "decimal";
+        final String DOUBLE            = "double";
+        final String DURATION          = "duration";
+        final String ENTITY            = "ENTITY";
+        final String ENTITIES          = "ENTITIES";
+        final String FLOAT             = "float";
+        final String HEXBINARY         = "hexBinary";
+        final String ID                = "ID";
+        final String IDREF             = "IDREF";
+        final String IDREFS            = "IDREFS";
+        final String INT               = "int";
+        final String INTEGER           = "integer";
+        final String LONG              = "long";
+        final String NAME              = "Name";
+        final String NEGATIVEINTEGER   = "negativeInteger";
+        final String MONTH             = "gMonth";
+        final String MONTHDAY          = "gMonthDay";
+        final String NCNAME            = "NCName";
+        final String NMTOKEN           = "NMTOKEN";
+        final String NMTOKENS          = "NMTOKENS";
+        final String LANGUAGE          = "language";
+        final String NONNEGATIVEINTEGER= "nonNegativeInteger";
+        final String NONPOSITIVEINTEGER= "nonPositiveInteger";
+        final String NORMALIZEDSTRING  = "normalizedString";
+        final String NOTATION          = "NOTATION";
+        final String POSITIVEINTEGER   = "positiveInteger";
+        final String QNAME             = "QName";
+        final String SHORT             = "short";
+        final String STRING            = "string";
+        final String TIME              = "time";
+        final String TOKEN             = "token";
+        final String UNSIGNEDBYTE      = "unsignedByte";
+        final String UNSIGNEDINT       = "unsignedInt";
+        final String UNSIGNEDLONG      = "unsignedLong";
+        final String UNSIGNEDSHORT     = "unsignedShort";
+        final String YEAR              = "gYear";
+        final String YEARMONTH         = "gYearMonth";
+
+        final XSFacets facets = new XSFacets();
+        
+        builtInTypes.put(ANYSIMPLETYPE, XSSimpleTypeDecl.fAnySimpleType);
+
+        XSSimpleTypeDecl stringDV = new XSSimpleTypeDecl(baseAtomicType, STRING, XSSimpleTypeDecl.DV_STRING, XSSimpleType.ORDERED_FALSE, false, false, false , true, XSConstants.STRING_DT);
+        builtInTypes.put(STRING, stringDV);
+        builtInTypes.put(BOOLEAN, new XSSimpleTypeDecl(baseAtomicType, BOOLEAN, XSSimpleTypeDecl.DV_BOOLEAN, XSSimpleType.ORDERED_FALSE, false, true, false, true, XSConstants.BOOLEAN_DT));
+        XSSimpleTypeDecl decimalDV = new XSSimpleTypeDecl(baseAtomicType, DECIMAL, XSSimpleTypeDecl.DV_DECIMAL, XSSimpleType.ORDERED_TOTAL, false, false, true, true, XSConstants.DECIMAL_DT);
+        builtInTypes.put(DECIMAL, decimalDV);
+
+        builtInTypes.put(ANYURI, new XSSimpleTypeDecl(baseAtomicType, ANYURI, XSSimpleTypeDecl.DV_ANYURI, XSSimpleType.ORDERED_FALSE, false, false, false, true, XSConstants.ANYURI_DT));
+        builtInTypes.put(BASE64BINARY, new XSSimpleTypeDecl(baseAtomicType, BASE64BINARY, XSSimpleTypeDecl.DV_BASE64BINARY, XSSimpleType.ORDERED_FALSE, false, false, false, true, XSConstants.BASE64BINARY_DT));
+
+        XSSimpleTypeDecl durationDV = new XSSimpleTypeDecl(baseAtomicType, DURATION, XSSimpleTypeDecl.DV_DURATION, XSSimpleType.ORDERED_PARTIAL, false, false, false, true, XSConstants.DURATION_DT);
+        builtInTypes.put(DURATION, durationDV);
+
+        builtInTypes.put(DATETIME, new XSSimpleTypeDecl(baseAtomicType, DATETIME, XSSimpleTypeDecl.DV_DATETIME, XSSimpleType.ORDERED_PARTIAL, false, false, false, true, XSConstants.DATETIME_DT));
+        builtInTypes.put(TIME, new XSSimpleTypeDecl(baseAtomicType, TIME, XSSimpleTypeDecl.DV_TIME, XSSimpleType.ORDERED_PARTIAL, false, false, false, true, XSConstants.TIME_DT));
+        builtInTypes.put(DATE, new XSSimpleTypeDecl(baseAtomicType, DATE, XSSimpleTypeDecl.DV_DATE, XSSimpleType.ORDERED_PARTIAL, false, false, false, true, XSConstants.DATE_DT));
+        builtInTypes.put(YEARMONTH, new XSSimpleTypeDecl(baseAtomicType, YEARMONTH, XSSimpleTypeDecl.DV_GYEARMONTH, XSSimpleType.ORDERED_PARTIAL, false, false, false, true, XSConstants.GYEARMONTH_DT));
+        builtInTypes.put(YEAR, new XSSimpleTypeDecl(baseAtomicType, YEAR, XSSimpleTypeDecl.DV_GYEAR, XSSimpleType.ORDERED_PARTIAL, false, false, false, true, XSConstants.GYEAR_DT));
+        builtInTypes.put(MONTHDAY, new XSSimpleTypeDecl(baseAtomicType, MONTHDAY, XSSimpleTypeDecl.DV_GMONTHDAY, XSSimpleType.ORDERED_PARTIAL, false, false, false, true, XSConstants.GMONTHDAY_DT));
+        builtInTypes.put(DAY, new XSSimpleTypeDecl(baseAtomicType, DAY, XSSimpleTypeDecl.DV_GDAY, XSSimpleType.ORDERED_PARTIAL, false, false, false, true, XSConstants.GDAY_DT));
+        builtInTypes.put(MONTH, new XSSimpleTypeDecl(baseAtomicType, MONTH, XSSimpleTypeDecl.DV_GMONTH, XSSimpleType.ORDERED_PARTIAL, false, false, false, true, XSConstants.GMONTH_DT));
+
+        XSSimpleTypeDecl integerDV = new XSSimpleTypeDecl(decimalDV, INTEGER, XSSimpleTypeDecl.DV_INTEGER, XSSimpleType.ORDERED_TOTAL, false, false, true, true, XSConstants.INTEGER_DT);
+        builtInTypes.put(INTEGER, integerDV);
+
+        facets.maxInclusive = "0";
+        XSSimpleTypeDecl nonPositiveDV = new XSSimpleTypeDecl(integerDV, NONPOSITIVEINTEGER, URI_SCHEMAFORSCHEMA, (short)0, false, null, XSConstants.NONPOSITIVEINTEGER_DT);
+        nonPositiveDV.applyFacets1(facets , XSSimpleType.FACET_MAXINCLUSIVE, (short)0);
+        builtInTypes.put(NONPOSITIVEINTEGER, nonPositiveDV);
+
+        facets.maxInclusive = "-1";
+        XSSimpleTypeDecl negativeDV = new XSSimpleTypeDecl(nonPositiveDV, NEGATIVEINTEGER, URI_SCHEMAFORSCHEMA, (short)0, false, null, XSConstants.NEGATIVEINTEGER_DT);
+        negativeDV.applyFacets1(facets , XSSimpleType.FACET_MAXINCLUSIVE, (short)0);
+        builtInTypes.put(NEGATIVEINTEGER, negativeDV);
+
+        facets.maxInclusive = "9223372036854775807";
+        facets.minInclusive = "-9223372036854775808";
+        XSSimpleTypeDecl longDV = new XSSimpleTypeDecl(integerDV, LONG, URI_SCHEMAFORSCHEMA, (short)0, false, null, XSConstants.LONG_DT);
+        longDV.applyFacets1(facets , (short)(XSSimpleType.FACET_MAXINCLUSIVE | XSSimpleType.FACET_MININCLUSIVE), (short)0 );
+        builtInTypes.put(LONG, longDV);
+
+        facets.maxInclusive = "2147483647";
+        facets.minInclusive =  "-2147483648";
+        XSSimpleTypeDecl intDV = new XSSimpleTypeDecl(longDV, INT, URI_SCHEMAFORSCHEMA, (short)0, false, null, XSConstants.INT_DT);
+        intDV.applyFacets1(facets, (short)(XSSimpleType.FACET_MAXINCLUSIVE | XSSimpleType.FACET_MININCLUSIVE), (short)0 );
+        builtInTypes.put(INT, intDV);
+
+        facets.maxInclusive = "32767";
+        facets.minInclusive = "-32768";
+        XSSimpleTypeDecl shortDV = new XSSimpleTypeDecl(intDV, SHORT , URI_SCHEMAFORSCHEMA, (short)0, false, null, XSConstants.SHORT_DT);
+        shortDV.applyFacets1(facets, (short)(XSSimpleType.FACET_MAXINCLUSIVE | XSSimpleType.FACET_MININCLUSIVE), (short)0 );
+        builtInTypes.put(SHORT, shortDV);
+
+        facets.maxInclusive = "127";
+        facets.minInclusive = "-128";
+        XSSimpleTypeDecl byteDV = new XSSimpleTypeDecl(shortDV, BYTE , URI_SCHEMAFORSCHEMA, (short)0, false, null, XSConstants.BYTE_DT);
+        byteDV.applyFacets1(facets, (short)(XSSimpleType.FACET_MAXINCLUSIVE | XSSimpleType.FACET_MININCLUSIVE), (short)0 );
+        builtInTypes.put(BYTE, byteDV);
+
+        facets.minInclusive =  "0" ;
+        XSSimpleTypeDecl nonNegativeDV = new XSSimpleTypeDecl(integerDV, NONNEGATIVEINTEGER , URI_SCHEMAFORSCHEMA, (short)0, false, null, XSConstants.NONNEGATIVEINTEGER_DT);
+        nonNegativeDV.applyFacets1(facets, XSSimpleType.FACET_MININCLUSIVE, (short)0 );
+        builtInTypes.put(NONNEGATIVEINTEGER, nonNegativeDV);
+
+        facets.maxInclusive = "18446744073709551615" ;
+        XSSimpleTypeDecl unsignedLongDV = new XSSimpleTypeDecl(nonNegativeDV, UNSIGNEDLONG , URI_SCHEMAFORSCHEMA, (short)0, false, null, XSConstants.UNSIGNEDLONG_DT);
+        unsignedLongDV.applyFacets1(facets, XSSimpleType.FACET_MAXINCLUSIVE, (short)0 );
+        builtInTypes.put(UNSIGNEDLONG, unsignedLongDV);
+
+        facets.maxInclusive = "4294967295" ;
+        XSSimpleTypeDecl unsignedIntDV = new XSSimpleTypeDecl(unsignedLongDV, UNSIGNEDINT , URI_SCHEMAFORSCHEMA, (short)0, false, null, XSConstants.UNSIGNEDINT_DT);
+        unsignedIntDV.applyFacets1(facets, XSSimpleType.FACET_MAXINCLUSIVE, (short)0 );
+        builtInTypes.put(UNSIGNEDINT, unsignedIntDV);
+
+        facets.maxInclusive = "65535" ;
+        XSSimpleTypeDecl unsignedShortDV = new XSSimpleTypeDecl(unsignedIntDV, UNSIGNEDSHORT , URI_SCHEMAFORSCHEMA, (short)0, false, null, XSConstants.UNSIGNEDSHORT_DT);
+        unsignedShortDV.applyFacets1(facets, XSSimpleType.FACET_MAXINCLUSIVE, (short)0 );
+        builtInTypes.put(UNSIGNEDSHORT, unsignedShortDV);
+
+        facets.maxInclusive = "255" ;
+        XSSimpleTypeDecl unsignedByteDV = new XSSimpleTypeDecl(unsignedShortDV, UNSIGNEDBYTE , URI_SCHEMAFORSCHEMA, (short)0, false, null, XSConstants.UNSIGNEDBYTE_DT);
+        unsignedByteDV.applyFacets1(facets, XSSimpleType.FACET_MAXINCLUSIVE, (short)0 );
+        builtInTypes.put(UNSIGNEDBYTE, unsignedByteDV);
+
+        facets.minInclusive = "1" ;
+        XSSimpleTypeDecl positiveIntegerDV = new XSSimpleTypeDecl(nonNegativeDV, POSITIVEINTEGER , URI_SCHEMAFORSCHEMA, (short)0, false, null, XSConstants.POSITIVEINTEGER_DT);
+        positiveIntegerDV.applyFacets1(facets, XSSimpleType.FACET_MININCLUSIVE, (short)0 );
+        builtInTypes.put(POSITIVEINTEGER, positiveIntegerDV);
+
+        builtInTypes.put(FLOAT, new XSSimpleTypeDecl(baseAtomicType, FLOAT, XSSimpleTypeDecl.DV_FLOAT, XSSimpleType.ORDERED_PARTIAL, true, true, true, true, XSConstants.FLOAT_DT));
+        builtInTypes.put(DOUBLE, new XSSimpleTypeDecl(baseAtomicType, DOUBLE, XSSimpleTypeDecl.DV_DOUBLE, XSSimpleType.ORDERED_PARTIAL, true, true, true, true, XSConstants.DOUBLE_DT));
+        builtInTypes.put(HEXBINARY, new XSSimpleTypeDecl(baseAtomicType, HEXBINARY, XSSimpleTypeDecl.DV_HEXBINARY, XSSimpleType.ORDERED_FALSE, false, false, false, true, XSConstants.HEXBINARY_DT));
+        builtInTypes.put(NOTATION, new XSSimpleTypeDecl(baseAtomicType, NOTATION, XSSimpleTypeDecl.DV_NOTATION, XSSimpleType.ORDERED_FALSE, false, false, false, true, XSConstants.NOTATION_DT));
+
+        facets.whiteSpace =  XSSimpleType.WS_REPLACE;
+        XSSimpleTypeDecl normalizedDV = new XSSimpleTypeDecl(stringDV, NORMALIZEDSTRING , URI_SCHEMAFORSCHEMA, (short)0, false, null, XSConstants.NORMALIZEDSTRING_DT);
+        normalizedDV.applyFacets1(facets, XSSimpleType.FACET_WHITESPACE, (short)0 );
+        builtInTypes.put(NORMALIZEDSTRING, normalizedDV);
+
+        facets.whiteSpace = XSSimpleType.WS_COLLAPSE;
+        XSSimpleTypeDecl tokenDV = new XSSimpleTypeDecl(normalizedDV, TOKEN , URI_SCHEMAFORSCHEMA, (short)0, false, null, XSConstants.TOKEN_DT);
+        tokenDV.applyFacets1(facets, XSSimpleType.FACET_WHITESPACE, (short)0 );
+        builtInTypes.put(TOKEN, tokenDV);
+
+        facets.whiteSpace = XSSimpleType.WS_COLLAPSE;
+        facets.pattern  = "([a-zA-Z]{1,8})(-[a-zA-Z0-9]{1,8})*";
+        XSSimpleTypeDecl languageDV = new XSSimpleTypeDecl(tokenDV, LANGUAGE , URI_SCHEMAFORSCHEMA, (short)0, false, null, XSConstants.LANGUAGE_DT);
+        languageDV.applyFacets1(facets, (short)(XSSimpleType.FACET_WHITESPACE | XSSimpleType.FACET_PATTERN) ,(short)0);
+        builtInTypes.put(LANGUAGE, languageDV);
+
+        facets.whiteSpace =  XSSimpleType.WS_COLLAPSE;
+        XSSimpleTypeDecl nameDV = new XSSimpleTypeDecl(tokenDV, NAME , URI_SCHEMAFORSCHEMA, (short)0, false, null, XSConstants.NAME_DT);
+        nameDV.applyFacets1(facets, XSSimpleType.FACET_WHITESPACE, (short)0, XSSimpleTypeDecl.SPECIAL_PATTERN_NAME);
+        builtInTypes.put(NAME, nameDV);
+
+        facets.whiteSpace = XSSimpleType.WS_COLLAPSE;
+        XSSimpleTypeDecl ncnameDV = new XSSimpleTypeDecl(nameDV, NCNAME , URI_SCHEMAFORSCHEMA, (short)0, false, null, XSConstants.NCNAME_DT) ;
+        ncnameDV.applyFacets1(facets, XSSimpleType.FACET_WHITESPACE, (short)0, XSSimpleTypeDecl.SPECIAL_PATTERN_NCNAME);
+        builtInTypes.put(NCNAME, ncnameDV);
+
+        builtInTypes.put(QNAME, new XSSimpleTypeDecl(baseAtomicType, QNAME, XSSimpleTypeDecl.DV_QNAME, XSSimpleType.ORDERED_FALSE, false, false, false, true, XSConstants.QNAME_DT));
+
+        builtInTypes.put(ID, new XSSimpleTypeDecl(ncnameDV,  ID, XSSimpleTypeDecl.DV_ID, XSSimpleType.ORDERED_FALSE, false, false, false , true, XSConstants.ID_DT));
+        XSSimpleTypeDecl idrefDV = new XSSimpleTypeDecl(ncnameDV,  IDREF , XSSimpleTypeDecl.DV_IDREF, XSSimpleType.ORDERED_FALSE, false, false, false, true, XSConstants.IDREF_DT);
+        builtInTypes.put(IDREF, idrefDV);
+
+        facets.minLength = 1;
+        XSSimpleTypeDecl tempDV = new XSSimpleTypeDecl(null, URI_SCHEMAFORSCHEMA, (short)0, idrefDV, true, null);
+        XSSimpleTypeDecl idrefsDV = new XSSimpleTypeDecl(tempDV, IDREFS, URI_SCHEMAFORSCHEMA, (short)0, false, null);
+        idrefsDV.applyFacets1(facets, XSSimpleType.FACET_MINLENGTH, (short)0);
+        builtInTypes.put(IDREFS, idrefsDV);
+
+        XSSimpleTypeDecl entityDV = new XSSimpleTypeDecl(ncnameDV, ENTITY , XSSimpleTypeDecl.DV_ENTITY, XSSimpleType.ORDERED_FALSE, false, false, false, true, XSConstants.ENTITY_DT);
+        builtInTypes.put(ENTITY, entityDV);
+
+        facets.minLength = 1;
+        tempDV = new XSSimpleTypeDecl(null, URI_SCHEMAFORSCHEMA, (short)0, entityDV, true, null);
+        XSSimpleTypeDecl entitiesDV = new XSSimpleTypeDecl(tempDV, ENTITIES, URI_SCHEMAFORSCHEMA, (short)0, false, null);
+        entitiesDV.applyFacets1(facets, XSSimpleType.FACET_MINLENGTH, (short)0);
+        builtInTypes.put(ENTITIES, entitiesDV);
+
+        facets.whiteSpace  = XSSimpleType.WS_COLLAPSE;
+        XSSimpleTypeDecl nmtokenDV = new XSSimpleTypeDecl(tokenDV, NMTOKEN, URI_SCHEMAFORSCHEMA, (short)0, false, null, XSConstants.NMTOKEN_DT);
+        nmtokenDV.applyFacets1(facets, XSSimpleType.FACET_WHITESPACE, (short)0, XSSimpleTypeDecl.SPECIAL_PATTERN_NMTOKEN);
+        builtInTypes.put(NMTOKEN, nmtokenDV);
+
+        facets.minLength = 1;
+        tempDV = new XSSimpleTypeDecl(null, URI_SCHEMAFORSCHEMA, (short)0, nmtokenDV, true, null);
+        XSSimpleTypeDecl nmtokensDV = new XSSimpleTypeDecl(tempDV, NMTOKENS, URI_SCHEMAFORSCHEMA, (short)0, false, null);
+        nmtokensDV.applyFacets1(facets, XSSimpleType.FACET_MINLENGTH, (short)0);
+        builtInTypes.put(NMTOKENS, nmtokensDV);
+    } //createBuiltInTypes()
+
+    /**
+     * Create a new simple type which is derived by restriction from another
+     * simple type.
+     *
+     * @param name              name of the new type, could be null
+     * @param targetNamespace   target namespace of the new type, could be null
+     * @param finalSet          value of "final"
+     * @param base              base type of the new type
+     * @param annotations       set of annotations
+     * @return                  the newly created simple type
+     */
+    public XSSimpleType createTypeRestriction(String name, String targetNamespace,
+                                              short finalSet, XSSimpleType base, XSObjectList annotations) {
+        
+        if (fDeclPool != null) {
+           XSSimpleTypeDecl st= fDeclPool.getSimpleTypeDecl();
+           return st.setRestrictionValues((XSSimpleTypeDecl)base, name, targetNamespace, finalSet, annotations);
+        }
+        return new XSSimpleTypeDecl((XSSimpleTypeDecl)base, name, targetNamespace, finalSet, false, annotations);
+    }
+
+    /**
+     * Create a new simple type which is derived by list from another simple
+     * type.
+     *
+     * @param name              name of the new type, could be null
+     * @param targetNamespace   target namespace of the new type, could be null
+     * @param finalSet          value of "final"
+     * @param itemType          item type of the list type
+     * @param annotations       set of annotations
+     * @return                  the newly created simple type
+     */
+    public XSSimpleType createTypeList(String name, String targetNamespace,
+                                       short finalSet, XSSimpleType itemType,
+                                       XSObjectList annotations) {
+        if (fDeclPool != null) {
+           XSSimpleTypeDecl st= fDeclPool.getSimpleTypeDecl();
+           return st.setListValues(name, targetNamespace, finalSet, (XSSimpleTypeDecl)itemType, annotations);
+        }
+        return new XSSimpleTypeDecl(name, targetNamespace, finalSet, (XSSimpleTypeDecl)itemType, false, annotations);
+    }
+
+    /**
+     * Create a new simple type which is derived by union from a list of other
+     * simple types.
+     *
+     * @param name              name of the new type, could be null
+     * @param targetNamespace   target namespace of the new type, could be null
+     * @param finalSet          value of "final"
+     * @param memberTypes       member types of the union type
+     * @param annotations       set of annotations
+     * @return                  the newly created simple type
+     */
+    public XSSimpleType createTypeUnion(String name, String targetNamespace,
+                                        short finalSet, XSSimpleType[] memberTypes,
+                                        XSObjectList annotations) {
+        int typeNum = memberTypes.length;
+        XSSimpleTypeDecl[] mtypes = new XSSimpleTypeDecl[typeNum];
+        System.arraycopy(memberTypes, 0, mtypes, 0, typeNum);
+
+        if (fDeclPool != null) {
+           XSSimpleTypeDecl st= fDeclPool.getSimpleTypeDecl();
+           return st.setUnionValues(name, targetNamespace, finalSet, mtypes, annotations);
+        }
+        return new XSSimpleTypeDecl(name, targetNamespace, finalSet, mtypes, annotations);
+    }
+
+    public void setDeclPool (XSDeclarationPool declPool){
+        fDeclPool = declPool;
+    }
+
+    /** Implementation internal **/
+    public XSSimpleTypeDecl newXSSimpleTypeDecl() {
+        return new XSSimpleTypeDecl();
+    }
+} //BaseSchemaDVFactory

http://git-wip-us.apache.org/repos/asf/jena/blob/c9a7e646/jena-core/src/main/java/org/apache/jena/ext/xerces/impl/dv/xs/BooleanDV.java
----------------------------------------------------------------------
diff --git a/jena-core/src/main/java/org/apache/jena/ext/xerces/impl/dv/xs/BooleanDV.java b/jena-core/src/main/java/org/apache/jena/ext/xerces/impl/dv/xs/BooleanDV.java
new file mode 100644
index 0000000..2eb2915
--- /dev/null
+++ b/jena-core/src/main/java/org/apache/jena/ext/xerces/impl/dv/xs/BooleanDV.java
@@ -0,0 +1,50 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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.jena.ext.xerces.impl.dv.xs;
+
+import org.apache.jena.ext.xerces.impl.dv.InvalidDatatypeValueException;
+import org.apache.jena.ext.xerces.impl.dv.ValidationContext;
+
+/**
+ * Represent the schema type "boolean"
+ * 
+ * @xerces.internal 
+ *
+ * @author Neeraj Bajaj, Sun Microsystems, inc.
+ * @author Sandy Gao, IBM
+ *
+ * @version $Id: BooleanDV.java 469063 2006-10-30 04:44:22Z mrglavas $
+ */
+@SuppressWarnings("all")
+public class BooleanDV extends TypeValidator {
+
+    public short getAllowedFacets() {
+        return (XSSimpleTypeDecl.FACET_PATTERN | XSSimpleTypeDecl.FACET_WHITESPACE);
+    }
+
+    public Object getActualValue(String content, ValidationContext context) throws InvalidDatatypeValueException {
+        if ("false".equals(content) || "0".equals(content)) {
+            return Boolean.FALSE;
+        }
+        else if ("true".equals(content) || "1".equals(content)) {
+            return Boolean.TRUE;
+        }
+        throw new InvalidDatatypeValueException("cvc-datatype-valid.1.2.1", new Object[]{content, "boolean"});
+    }
+
+} // class BooleanDV


[07/24] jena git commit: JENA-1537: Remove dependency on Xerces. Import needed code

Posted by an...@apache.org.
http://git-wip-us.apache.org/repos/asf/jena/blob/c9a7e646/jena-core/src/main/java/org/apache/jena/ext/xerces/util/URI.java
----------------------------------------------------------------------
diff --git a/jena-core/src/main/java/org/apache/jena/ext/xerces/util/URI.java b/jena-core/src/main/java/org/apache/jena/ext/xerces/util/URI.java
new file mode 100644
index 0000000..3e09bea
--- /dev/null
+++ b/jena-core/src/main/java/org/apache/jena/ext/xerces/util/URI.java
@@ -0,0 +1,2185 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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.jena.ext.xerces.util;
+
+import java.io.IOException;
+import java.io.Serializable;
+import java.util.Locale;
+
+/**********************************************************************
+* A class to represent a Uniform Resource Identifier (URI). This class
+* is designed to handle the parsing of URIs and provide access to
+* the various components (scheme, host, port, userinfo, path, query
+* string and fragment) that may constitute a URI.
+* <p>
+* Parsing of a URI specification is done according to the URI
+* syntax described in 
+* <a href="http://www.ietf.org/rfc/rfc2396.txt?number=2396">RFC 2396</a>,
+* and amended by
+* <a href="http://www.ietf.org/rfc/rfc2732.txt?number=2732">RFC 2732</a>. 
+* <p>
+* Every absolute URI consists of a scheme, followed by a colon (':'), 
+* followed by a scheme-specific part. For URIs that follow the 
+* "generic URI" syntax, the scheme-specific part begins with two 
+* slashes ("//") and may be followed by an authority segment (comprised 
+* of user information, host, and port), path segment, query segment 
+* and fragment. Note that RFC 2396 no longer specifies the use of the 
+* parameters segment and excludes the "user:password" syntax as part of 
+* the authority segment. If "user:password" appears in a URI, the entire 
+* user/password string is stored as userinfo.
+* <p>
+* For URIs that do not follow the "generic URI" syntax (e.g. mailto),
+* the entire scheme-specific part is treated as the "path" portion
+* of the URI.
+* <p>
+* Note that, unlike the java.net.URL class, this class does not provide
+* any built-in network access functionality nor does it provide any
+* scheme-specific functionality (for example, it does not know a
+* default port for a specific scheme). Rather, it only knows the
+* grammar and basic set of operations that can be applied to a URI.
+*
+* @version  $Id: URI.java 712351 2008-11-08 05:45:12Z mrglavas $
+*
+**********************************************************************/
+ public class URI implements Serializable {
+
+  /*******************************************************************
+  * MalformedURIExceptions are thrown in the process of building a URI
+  * or setting fields on a URI when an operation would result in an
+  * invalid URI specification.
+  *
+  ********************************************************************/
+  public static class MalformedURIException extends IOException {
+
+   /******************************************************************
+    * Constructs a <code>MalformedURIException</code> with no specified
+    * detail message.
+    ******************************************************************/
+    public MalformedURIException() {
+      super();
+    }
+
+    /*****************************************************************
+    * Constructs a <code>MalformedURIException</code> with the
+    * specified detail message.
+    *
+    * @param p_msg the detail message.
+    ******************************************************************/
+    public MalformedURIException(String p_msg) {
+      super(p_msg);
+    }
+  }
+
+  private static final byte [] fgLookupTable = new byte[128];
+  
+  /**
+   * Character Classes
+   */
+  
+  /** reserved characters ;/?:@&=+$,[] */
+  //RFC 2732 added '[' and ']' as reserved characters
+  private static final int RESERVED_CHARACTERS = 0x01;
+  
+  /** URI punctuation mark characters: -_.!~*'() - these, combined with
+      alphanumerics, constitute the "unreserved" characters */
+  private static final int MARK_CHARACTERS = 0x02;
+  
+  /** scheme can be composed of alphanumerics and these characters: +-. */
+  private static final int SCHEME_CHARACTERS = 0x04;
+  
+  /** userinfo can be composed of unreserved, escaped and these
+      characters: ;:&=+$, */
+  private static final int USERINFO_CHARACTERS = 0x08;
+  
+  /** ASCII letter characters */
+  private static final int ASCII_ALPHA_CHARACTERS = 0x10;
+  
+  /** ASCII digit characters */
+  private static final int ASCII_DIGIT_CHARACTERS = 0x20;
+  
+  /** ASCII hex characters */
+  private static final int ASCII_HEX_CHARACTERS = 0x40;
+  
+  /** Path characters */
+  private static final int PATH_CHARACTERS = 0x80;
+
+  /** Mask for alpha-numeric characters */
+  private static final int MASK_ALPHA_NUMERIC = ASCII_ALPHA_CHARACTERS | ASCII_DIGIT_CHARACTERS;
+  
+  /** Mask for unreserved characters */
+  private static final int MASK_UNRESERVED_MASK = MASK_ALPHA_NUMERIC | MARK_CHARACTERS;
+  
+  /** Mask for URI allowable characters except for % */
+  private static final int MASK_URI_CHARACTER = MASK_UNRESERVED_MASK | RESERVED_CHARACTERS;
+  
+  /** Mask for scheme characters */
+  private static final int MASK_SCHEME_CHARACTER = MASK_ALPHA_NUMERIC | SCHEME_CHARACTERS;
+  
+  /** Mask for userinfo characters */
+  private static final int MASK_USERINFO_CHARACTER = MASK_UNRESERVED_MASK | USERINFO_CHARACTERS;
+  
+  /** Mask for path characters */
+  private static final int MASK_PATH_CHARACTER = MASK_UNRESERVED_MASK | PATH_CHARACTERS; 
+
+  static {
+      // Add ASCII Digits and ASCII Hex Numbers
+      for (int i = '0'; i <= '9'; ++i) {
+          fgLookupTable[i] |= ASCII_DIGIT_CHARACTERS | ASCII_HEX_CHARACTERS;
+      }
+
+      // Add ASCII Letters and ASCII Hex Numbers
+      for (int i = 'A'; i <= 'F'; ++i) {
+          fgLookupTable[i] |= ASCII_ALPHA_CHARACTERS | ASCII_HEX_CHARACTERS;
+          fgLookupTable[i+0x00000020] |= ASCII_ALPHA_CHARACTERS | ASCII_HEX_CHARACTERS;
+      }
+
+      // Add ASCII Letters
+      for (int i = 'G'; i <= 'Z'; ++i) {
+          fgLookupTable[i] |= ASCII_ALPHA_CHARACTERS;
+          fgLookupTable[i+0x00000020] |= ASCII_ALPHA_CHARACTERS;
+      }
+
+      // Add Reserved Characters
+      fgLookupTable[';'] |= RESERVED_CHARACTERS;
+      fgLookupTable['/'] |= RESERVED_CHARACTERS;
+      fgLookupTable['?'] |= RESERVED_CHARACTERS;
+      fgLookupTable[':'] |= RESERVED_CHARACTERS;
+      fgLookupTable['@'] |= RESERVED_CHARACTERS;
+      fgLookupTable['&'] |= RESERVED_CHARACTERS;
+      fgLookupTable['='] |= RESERVED_CHARACTERS;
+      fgLookupTable['+'] |= RESERVED_CHARACTERS;
+      fgLookupTable['$'] |= RESERVED_CHARACTERS;
+      fgLookupTable[','] |= RESERVED_CHARACTERS;
+      fgLookupTable['['] |= RESERVED_CHARACTERS;
+      fgLookupTable[']'] |= RESERVED_CHARACTERS;
+
+      // Add Mark Characters
+      fgLookupTable['-'] |= MARK_CHARACTERS;
+      fgLookupTable['_'] |= MARK_CHARACTERS;
+      fgLookupTable['.'] |= MARK_CHARACTERS;
+      fgLookupTable['!'] |= MARK_CHARACTERS;
+      fgLookupTable['~'] |= MARK_CHARACTERS;
+      fgLookupTable['*'] |= MARK_CHARACTERS;
+      fgLookupTable['\''] |= MARK_CHARACTERS;
+      fgLookupTable['('] |= MARK_CHARACTERS;
+      fgLookupTable[')'] |= MARK_CHARACTERS;
+
+      // Add Scheme Characters
+      fgLookupTable['+'] |= SCHEME_CHARACTERS;
+      fgLookupTable['-'] |= SCHEME_CHARACTERS;
+      fgLookupTable['.'] |= SCHEME_CHARACTERS;
+
+      // Add Userinfo Characters
+      fgLookupTable[';'] |= USERINFO_CHARACTERS;
+      fgLookupTable[':'] |= USERINFO_CHARACTERS;
+      fgLookupTable['&'] |= USERINFO_CHARACTERS;
+      fgLookupTable['='] |= USERINFO_CHARACTERS;
+      fgLookupTable['+'] |= USERINFO_CHARACTERS;
+      fgLookupTable['$'] |= USERINFO_CHARACTERS;
+      fgLookupTable[','] |= USERINFO_CHARACTERS;
+      
+      // Add Path Characters
+      fgLookupTable[';'] |= PATH_CHARACTERS;
+      fgLookupTable['/'] |= PATH_CHARACTERS;
+      fgLookupTable[':'] |= PATH_CHARACTERS;
+      fgLookupTable['@'] |= PATH_CHARACTERS;
+      fgLookupTable['&'] |= PATH_CHARACTERS;
+      fgLookupTable['='] |= PATH_CHARACTERS;
+      fgLookupTable['+'] |= PATH_CHARACTERS;
+      fgLookupTable['$'] |= PATH_CHARACTERS;
+      fgLookupTable[','] |= PATH_CHARACTERS;
+  }
+
+  /** Stores the scheme (usually the protocol) for this URI. */
+  private String m_scheme = null;
+
+  /** If specified, stores the userinfo for this URI; otherwise null */
+  private String m_userinfo = null;
+
+  /** If specified, stores the host for this URI; otherwise null */
+  private String m_host = null;
+
+  /** If specified, stores the port for this URI; otherwise -1 */
+  private int m_port = -1;
+  
+  /** If specified, stores the registry based authority for this URI; otherwise -1 */
+  private String m_regAuthority = null;
+
+  /** If specified, stores the path for this URI; otherwise null */
+  private String m_path = null;
+
+  /** If specified, stores the query string for this URI; otherwise
+      null.  */
+  private String m_queryString = null;
+
+  /** If specified, stores the fragment for this URI; otherwise null */
+  private String m_fragment = null;
+
+  private static boolean DEBUG = false;
+
+  /**
+  * Construct a new and uninitialized URI.
+  */
+  public URI() {
+  }
+
+ /**
+  * Construct a new URI from another URI. All fields for this URI are
+  * set equal to the fields of the URI passed in.
+  *
+  * @param p_other the URI to copy (cannot be null)
+  */
+  public URI(URI p_other) {
+    initialize(p_other);
+  }
+
+ /**
+  * Construct a new URI from a URI specification string. If the
+  * specification follows the "generic URI" syntax, (two slashes
+  * following the first colon), the specification will be parsed
+  * accordingly - setting the scheme, userinfo, host,port, path, query
+  * string and fragment fields as necessary. If the specification does
+  * not follow the "generic URI" syntax, the specification is parsed
+  * into a scheme and scheme-specific part (stored as the path) only.
+  *
+  * @param p_uriSpec the URI specification string (cannot be null or
+  *                  empty)
+  *
+  * @exception MalformedURIException if p_uriSpec violates any syntax
+  *                                   rules
+  */
+  public URI(String p_uriSpec) throws MalformedURIException {
+    this((URI)null, p_uriSpec);
+  }
+  
+  /**
+   * Construct a new URI from a URI specification string. If the
+   * specification follows the "generic URI" syntax, (two slashes
+   * following the first colon), the specification will be parsed
+   * accordingly - setting the scheme, userinfo, host,port, path, query
+   * string and fragment fields as necessary. If the specification does
+   * not follow the "generic URI" syntax, the specification is parsed
+   * into a scheme and scheme-specific part (stored as the path) only.
+   * Construct a relative URI if boolean is assigned to "true"
+   * and p_uriSpec is not valid absolute URI, instead of throwing an exception. 
+   * 
+   * @param p_uriSpec the URI specification string (cannot be null or
+   *                  empty)
+   * @param allowNonAbsoluteURI true to permit non-absolute URIs, 
+   *                            false otherwise.
+   *
+   * @exception MalformedURIException if p_uriSpec violates any syntax
+   *                                   rules
+   */
+  public URI(String p_uriSpec, boolean allowNonAbsoluteURI) throws MalformedURIException {
+      this((URI)null, p_uriSpec, allowNonAbsoluteURI);
+  }
+  
+ /**
+  * Construct a new URI from a base URI and a URI specification string.
+  * The URI specification string may be a relative URI.
+  *
+  * @param p_base the base URI (cannot be null if p_uriSpec is null or
+  *               empty)
+  * @param p_uriSpec the URI specification string (cannot be null or
+  *                  empty if p_base is null)
+  *
+  * @exception MalformedURIException if p_uriSpec violates any syntax
+  *                                  rules
+  */
+  public URI(URI p_base, String p_uriSpec) throws MalformedURIException {
+    initialize(p_base, p_uriSpec);
+  }
+  
+  /**
+   * Construct a new URI from a base URI and a URI specification string.
+   * The URI specification string may be a relative URI.
+   * Construct a relative URI if boolean is assigned to "true"
+   * and p_uriSpec is not valid absolute URI and p_base is null
+   * instead of throwing an exception. 
+   *
+   * @param p_base the base URI (cannot be null if p_uriSpec is null or
+   *               empty)
+   * @param p_uriSpec the URI specification string (cannot be null or
+   *                  empty if p_base is null)
+   * @param allowNonAbsoluteURI true to permit non-absolute URIs, 
+   *                            false otherwise.
+   *
+   * @exception MalformedURIException if p_uriSpec violates any syntax
+   *                                  rules
+   */
+  public URI(URI p_base, String p_uriSpec, boolean allowNonAbsoluteURI) throws MalformedURIException {
+      initialize(p_base, p_uriSpec, allowNonAbsoluteURI);
+  }
+
+ /**
+  * Construct a new URI that does not follow the generic URI syntax.
+  * Only the scheme and scheme-specific part (stored as the path) are
+  * initialized.
+  *
+  * @param p_scheme the URI scheme (cannot be null or empty)
+  * @param p_schemeSpecificPart the scheme-specific part (cannot be
+  *                             null or empty)
+  *
+  * @exception MalformedURIException if p_scheme violates any
+  *                                  syntax rules
+  */
+  public URI(String p_scheme, String p_schemeSpecificPart)
+             throws MalformedURIException {
+    if (p_scheme == null || p_scheme.trim().length() == 0) {
+      throw new MalformedURIException(
+            "Cannot construct URI with null/empty scheme!");
+    }
+    if (p_schemeSpecificPart == null ||
+        p_schemeSpecificPart.trim().length() == 0) {
+      throw new MalformedURIException(
+          "Cannot construct URI with null/empty scheme-specific part!");
+    }
+    setScheme(p_scheme);
+    setPath(p_schemeSpecificPart);
+  }
+
+ /**
+  * Construct a new URI that follows the generic URI syntax from its
+  * component parts. Each component is validated for syntax and some
+  * basic semantic checks are performed as well.  See the individual
+  * setter methods for specifics.
+  *
+  * @param p_scheme the URI scheme (cannot be null or empty)
+  * @param p_host the hostname, IPv4 address or IPv6 reference for the URI
+  * @param p_path the URI path - if the path contains '?' or '#',
+  *               then the query string and/or fragment will be
+  *               set from the path; however, if the query and
+  *               fragment are specified both in the path and as
+  *               separate parameters, an exception is thrown
+  * @param p_queryString the URI query string (cannot be specified
+  *                      if path is null)
+  * @param p_fragment the URI fragment (cannot be specified if path
+  *                   is null)
+  *
+  * @exception MalformedURIException if any of the parameters violates
+  *                                  syntax rules or semantic rules
+  */
+  public URI(String p_scheme, String p_host, String p_path,
+             String p_queryString, String p_fragment)
+         throws MalformedURIException {
+    this(p_scheme, null, p_host, -1, p_path, p_queryString, p_fragment);
+  }
+
+ /**
+  * Construct a new URI that follows the generic URI syntax from its
+  * component parts. Each component is validated for syntax and some
+  * basic semantic checks are performed as well.  See the individual
+  * setter methods for specifics.
+  *
+  * @param p_scheme the URI scheme (cannot be null or empty)
+  * @param p_userinfo the URI userinfo (cannot be specified if host
+  *                   is null)
+  * @param p_host the hostname, IPv4 address or IPv6 reference for the URI
+  * @param p_port the URI port (may be -1 for "unspecified"; cannot
+  *               be specified if host is null)
+  * @param p_path the URI path - if the path contains '?' or '#',
+  *               then the query string and/or fragment will be
+  *               set from the path; however, if the query and
+  *               fragment are specified both in the path and as
+  *               separate parameters, an exception is thrown
+  * @param p_queryString the URI query string (cannot be specified
+  *                      if path is null)
+  * @param p_fragment the URI fragment (cannot be specified if path
+  *                   is null)
+  *
+  * @exception MalformedURIException if any of the parameters violates
+  *                                  syntax rules or semantic rules
+  */
+  public URI(String p_scheme, String p_userinfo,
+             String p_host, int p_port, String p_path,
+             String p_queryString, String p_fragment)
+         throws MalformedURIException {
+    if (p_scheme == null || p_scheme.trim().length() == 0) {
+      throw new MalformedURIException("Scheme is required!");
+    }
+
+    if (p_host == null) {
+      if (p_userinfo != null) {
+        throw new MalformedURIException(
+             "Userinfo may not be specified if host is not specified!");
+      }
+      if (p_port != -1) {
+        throw new MalformedURIException(
+             "Port may not be specified if host is not specified!");
+      }
+    }
+
+    if (p_path != null) {
+      if (p_path.indexOf('?') != -1 && p_queryString != null) {
+        throw new MalformedURIException(
+          "Query string cannot be specified in path and query string!");
+      }
+
+      if (p_path.indexOf('#') != -1 && p_fragment != null) {
+        throw new MalformedURIException(
+          "Fragment cannot be specified in both the path and fragment!");
+      }
+    }
+
+    setScheme(p_scheme);
+    setHost(p_host);
+    setPort(p_port);
+    setUserinfo(p_userinfo);
+    setPath(p_path);
+    setQueryString(p_queryString);
+    setFragment(p_fragment);
+  }
+
+ /**
+  * Initialize all fields of this URI from another URI.
+  *
+  * @param p_other the URI to copy (cannot be null)
+  */
+  private void initialize(URI p_other) {
+    m_scheme = p_other.getScheme();
+    m_userinfo = p_other.getUserinfo();
+    m_host = p_other.getHost();
+    m_port = p_other.getPort();
+    m_regAuthority = p_other.getRegBasedAuthority();
+    m_path = p_other.getPath();
+    m_queryString = p_other.getQueryString();
+    m_fragment = p_other.getFragment();
+  }
+  
+  /**
+   * Initializes this URI from a base URI and a URI specification string.
+   * See RFC 2396 Section 4 and Appendix B for specifications on parsing
+   * the URI and Section 5 for specifications on resolving relative URIs
+   * and relative paths.
+   *
+   * @param p_base the base URI (may be null if p_uriSpec is an absolute
+   *               URI)
+   * @param p_uriSpec the URI spec string which may be an absolute or
+   *                  relative URI (can only be null/empty if p_base
+   *                  is not null)
+   * @param allowNonAbsoluteURI true to permit non-absolute URIs, 
+   *                         in case of relative URI, false otherwise.
+   *
+   * @exception MalformedURIException if p_base is null and p_uriSpec
+   *                                  is not an absolute URI or if
+   *                                  p_uriSpec violates syntax rules
+   */
+  private void initialize(URI p_base, String p_uriSpec, boolean allowNonAbsoluteURI)
+      throws MalformedURIException {
+      
+      String uriSpec = p_uriSpec;
+      int uriSpecLen = (uriSpec != null) ? uriSpec.length() : 0;
+      
+      if (p_base == null && uriSpecLen == 0) {
+          if (allowNonAbsoluteURI) {
+              m_path = "";
+              return;
+          }
+          throw new MalformedURIException("Cannot initialize URI with empty parameters.");
+      }
+      
+      // just make a copy of the base if spec is empty
+      if (uriSpecLen == 0) {
+          initialize(p_base);
+          return;
+      }
+      
+      int index = 0;
+      
+      // Check for scheme, which must be before '/', '?' or '#'.
+      int colonIdx = uriSpec.indexOf(':');
+      if (colonIdx != -1) {
+          final int searchFrom = colonIdx - 1;
+          // search backwards starting from character before ':'.
+          int slashIdx = uriSpec.lastIndexOf('/', searchFrom);
+          int queryIdx = uriSpec.lastIndexOf('?', searchFrom);
+          int fragmentIdx = uriSpec.lastIndexOf('#', searchFrom);
+          
+          if (colonIdx == 0 || slashIdx != -1 || 
+              queryIdx != -1 || fragmentIdx != -1) {
+              // A standalone base is a valid URI according to spec
+              if (colonIdx == 0 || (p_base == null && fragmentIdx != 0 && !allowNonAbsoluteURI)) {
+                  throw new MalformedURIException("No scheme found in URI.");
+              }
+          }
+          else {
+              initializeScheme(uriSpec);
+              index = m_scheme.length()+1;
+              
+              // Neither 'scheme:' or 'scheme:#fragment' are valid URIs.
+              if (colonIdx == uriSpecLen - 1 || uriSpec.charAt(colonIdx+1) == '#') {
+                  throw new MalformedURIException("Scheme specific part cannot be empty.");   
+              }
+          }
+      }
+      else if (p_base == null && uriSpec.indexOf('#') != 0 && !allowNonAbsoluteURI) {
+          throw new MalformedURIException("No scheme found in URI.");    
+      }
+      
+      // Two slashes means we may have authority, but definitely means we're either
+      // matching net_path or abs_path. These two productions are ambiguous in that
+      // every net_path (except those containing an IPv6Reference) is an abs_path. 
+      // RFC 2396 resolves this ambiguity by applying a greedy left most matching rule. 
+      // Try matching net_path first, and if that fails we don't have authority so 
+      // then attempt to match abs_path.
+      //
+      // net_path = "//" authority [ abs_path ]
+      // abs_path = "/"  path_segments
+      if (((index+1) < uriSpecLen) &&
+          (uriSpec.charAt(index) == '/' && uriSpec.charAt(index+1) == '/')) {
+          index += 2;
+          int startPos = index;
+          
+          // Authority will be everything up to path, query or fragment
+          char testChar = '\0';
+          while (index < uriSpecLen) {
+              testChar = uriSpec.charAt(index);
+              if (testChar == '/' || testChar == '?' || testChar == '#') {
+                  break;
+              }
+              index++;
+          }
+          
+          // Attempt to parse authority. If the section is an empty string
+          // this is a valid server based authority, so set the host to this
+          // value.
+          if (index > startPos) {
+              // If we didn't find authority we need to back up. Attempt to
+              // match against abs_path next.
+              if (!initializeAuthority(uriSpec.substring(startPos, index))) {
+                  index = startPos - 2;
+              }
+          }
+          else {
+              m_host = "";
+          }
+      }
+      
+      initializePath(uriSpec, index);
+      
+      // Resolve relative URI to base URI - see RFC 2396 Section 5.2
+      // In some cases, it might make more sense to throw an exception
+      // (when scheme is specified is the string spec and the base URI
+      // is also specified, for example), but we're just following the
+      // RFC specifications
+      if (p_base != null) {
+          absolutize(p_base);
+      }
+  }
+
+ /**
+  * Initializes this URI from a base URI and a URI specification string.
+  * See RFC 2396 Section 4 and Appendix B for specifications on parsing
+  * the URI and Section 5 for specifications on resolving relative URIs
+  * and relative paths.
+  *
+  * @param p_base the base URI (may be null if p_uriSpec is an absolute
+  *               URI)
+  * @param p_uriSpec the URI spec string which may be an absolute or
+  *                  relative URI (can only be null/empty if p_base
+  *                  is not null)
+  *
+  * @exception MalformedURIException if p_base is null and p_uriSpec
+  *                                  is not an absolute URI or if
+  *                                  p_uriSpec violates syntax rules
+  */
+  private void initialize(URI p_base, String p_uriSpec)
+                         throws MalformedURIException {
+	  
+    String uriSpec = p_uriSpec;
+    int uriSpecLen = (uriSpec != null) ? uriSpec.length() : 0;
+	
+    if (p_base == null && uriSpecLen == 0) {
+      throw new MalformedURIException(
+                  "Cannot initialize URI with empty parameters.");
+    }
+
+    // just make a copy of the base if spec is empty
+    if (uriSpecLen == 0) {
+      initialize(p_base);
+      return;
+    }
+
+    int index = 0;
+
+    // Check for scheme, which must be before '/', '?' or '#'.
+    int colonIdx = uriSpec.indexOf(':');
+    if (colonIdx != -1) {
+        final int searchFrom = colonIdx - 1;
+        // search backwards starting from character before ':'.
+        int slashIdx = uriSpec.lastIndexOf('/', searchFrom);
+        int queryIdx = uriSpec.lastIndexOf('?', searchFrom);
+        int fragmentIdx = uriSpec.lastIndexOf('#', searchFrom);
+       
+        if (colonIdx == 0 || slashIdx != -1 || 
+            queryIdx != -1 || fragmentIdx != -1) {
+            // A standalone base is a valid URI according to spec
+            if (colonIdx == 0 || (p_base == null && fragmentIdx != 0)) {
+                throw new MalformedURIException("No scheme found in URI.");
+            }
+        }
+        else {
+            initializeScheme(uriSpec);
+            index = m_scheme.length()+1;
+            
+            // Neither 'scheme:' or 'scheme:#fragment' are valid URIs.
+            if (colonIdx == uriSpecLen - 1 || uriSpec.charAt(colonIdx+1) == '#') {
+            	throw new MalformedURIException("Scheme specific part cannot be empty.");	
+            }
+        }
+    }
+    else if (p_base == null && uriSpec.indexOf('#') != 0) {
+        throw new MalformedURIException("No scheme found in URI.");    
+    }
+
+    // Two slashes means we may have authority, but definitely means we're either
+    // matching net_path or abs_path. These two productions are ambiguous in that
+    // every net_path (except those containing an IPv6Reference) is an abs_path. 
+    // RFC 2396 resolves this ambiguity by applying a greedy left most matching rule. 
+    // Try matching net_path first, and if that fails we don't have authority so 
+    // then attempt to match abs_path.
+    //
+    // net_path = "//" authority [ abs_path ]
+    // abs_path = "/"  path_segments
+    if (((index+1) < uriSpecLen) &&
+        (uriSpec.charAt(index) == '/' && uriSpec.charAt(index+1) == '/')) {
+      index += 2;
+      int startPos = index;
+
+      // Authority will be everything up to path, query or fragment
+      char testChar = '\0';
+      while (index < uriSpecLen) {
+        testChar = uriSpec.charAt(index);
+        if (testChar == '/' || testChar == '?' || testChar == '#') {
+          break;
+        }
+        index++;
+      }
+
+      // Attempt to parse authority. If the section is an empty string
+      // this is a valid server based authority, so set the host to this
+      // value.
+      if (index > startPos) {
+        // If we didn't find authority we need to back up. Attempt to
+        // match against abs_path next.
+        if (!initializeAuthority(uriSpec.substring(startPos, index))) {
+          index = startPos - 2;
+        }
+      }
+      else {
+        m_host = "";
+      }
+    }
+
+    initializePath(uriSpec, index);
+
+    // Resolve relative URI to base URI - see RFC 2396 Section 5.2
+    // In some cases, it might make more sense to throw an exception
+    // (when scheme is specified is the string spec and the base URI
+    // is also specified, for example), but we're just following the
+    // RFC specifications
+    if (p_base != null) {
+        absolutize(p_base);
+    }
+  }
+
+  /**
+   * Absolutize URI with given base URI.
+   *
+   * @param p_base base URI for absolutization
+   */
+  public void absolutize(URI p_base) {
+
+      // check to see if this is the current doc - RFC 2396 5.2 #2
+      // note that this is slightly different from the RFC spec in that
+      // we don't include the check for query string being null
+      // - this handles cases where the urispec is just a query
+      // string or a fragment (e.g. "?y" or "#s") -
+      // see <http://www.ics.uci.edu/~fielding/url/test1.html> which
+      // identified this as a bug in the RFC
+      if (m_path.length() == 0 && m_scheme == null &&
+          m_host == null && m_regAuthority == null) {
+          m_scheme = p_base.getScheme();
+          m_userinfo = p_base.getUserinfo();
+          m_host = p_base.getHost();
+          m_port = p_base.getPort();
+          m_regAuthority = p_base.getRegBasedAuthority();
+          m_path = p_base.getPath();
+          
+          if (m_queryString == null) {
+              m_queryString = p_base.getQueryString();
+              
+              if (m_fragment == null) {
+                  m_fragment = p_base.getFragment();
+              }
+          }
+          return;
+      }
+      
+      // check for scheme - RFC 2396 5.2 #3
+      // if we found a scheme, it means absolute URI, so we're done
+      if (m_scheme == null) {
+          m_scheme = p_base.getScheme();
+      }
+      else {
+          return;
+      }
+      
+      // check for authority - RFC 2396 5.2 #4
+      // if we found a host, then we've got a network path, so we're done
+      if (m_host == null && m_regAuthority == null) {
+          m_userinfo = p_base.getUserinfo();
+          m_host = p_base.getHost();
+          m_port = p_base.getPort();
+          m_regAuthority = p_base.getRegBasedAuthority();
+      }
+      else {
+          return;
+      }
+      
+      // check for absolute path - RFC 2396 5.2 #5
+      if (m_path.length() > 0 &&
+              m_path.startsWith("/")) {
+          return;
+      }
+      
+      // if we get to this point, we need to resolve relative path
+      // RFC 2396 5.2 #6
+      String path = "";
+      String basePath = p_base.getPath();
+      
+      // 6a - get all but the last segment of the base URI path
+      if (basePath != null && basePath.length() > 0) {
+          int lastSlash = basePath.lastIndexOf('/');
+          if (lastSlash != -1) {
+              path = basePath.substring(0, lastSlash+1);
+          }
+      }
+      else if (m_path.length() > 0) {
+          path = "/";
+      }
+      
+      // 6b - append the relative URI path
+      path = path.concat(m_path);
+      
+      // 6c - remove all "./" where "." is a complete path segment
+      int index = -1;
+      while ((index = path.indexOf("/./")) != -1) {
+          path = path.substring(0, index+1).concat(path.substring(index+3));
+      }
+      
+      // 6d - remove "." if path ends with "." as a complete path segment
+      if (path.endsWith("/.")) {
+          path = path.substring(0, path.length()-1);
+      }
+      
+      // 6e - remove all "<segment>/../" where "<segment>" is a complete
+      // path segment not equal to ".."
+      index = 1;
+      int segIndex = -1;
+      String tempString = null;
+      
+      while ((index = path.indexOf("/../", index)) > 0) {
+          tempString = path.substring(0, path.indexOf("/../"));
+          segIndex = tempString.lastIndexOf('/');
+          if (segIndex != -1) {
+              if (!tempString.substring(segIndex).equals("..")) {
+                  path = path.substring(0, segIndex+1).concat(path.substring(index+4));
+                  index = segIndex;
+              }
+              else {
+                  index += 4;
+              }
+          }
+          else {
+              index += 4;
+          }
+      }
+      
+      // 6f - remove ending "<segment>/.." where "<segment>" is a
+      // complete path segment
+      if (path.endsWith("/..")) {
+          tempString = path.substring(0, path.length()-3);
+          segIndex = tempString.lastIndexOf('/');
+          if (segIndex != -1) {
+              path = path.substring(0, segIndex+1);
+          }
+      }
+      m_path = path;
+  }
+
+ /**
+  * Initialize the scheme for this URI from a URI string spec.
+  *
+  * @param p_uriSpec the URI specification (cannot be null)
+  *
+  * @exception MalformedURIException if URI does not have a conformant
+  *                                  scheme
+  */
+  private void initializeScheme(String p_uriSpec)
+                 throws MalformedURIException {
+    int uriSpecLen = p_uriSpec.length();
+    int index = 0;
+    String scheme = null;
+    char testChar = '\0';
+
+    while (index < uriSpecLen) {
+      testChar = p_uriSpec.charAt(index);
+      if (testChar == ':' || testChar == '/' ||
+          testChar == '?' || testChar == '#') {
+        break;
+      }
+      index++;
+    }
+    scheme = p_uriSpec.substring(0, index);
+
+    if (scheme.length() == 0) {
+      throw new MalformedURIException("No scheme found in URI.");
+    }
+    else {
+      setScheme(scheme);
+    }
+  }
+
+ /**
+  * Initialize the authority (either server or registry based)
+  * for this URI from a URI string spec.
+  *
+  * @param p_uriSpec the URI specification (cannot be null)
+  * 
+  * @return true if the given string matched server or registry
+  * based authority
+  */
+  private boolean initializeAuthority(String p_uriSpec) {
+    
+    int index = 0;
+    int start = 0;
+    int end = p_uriSpec.length();
+
+    char testChar = '\0';
+    String userinfo = null;
+
+    // userinfo is everything up to @
+    if (p_uriSpec.indexOf('@', start) != -1) {
+      while (index < end) {
+        testChar = p_uriSpec.charAt(index);
+        if (testChar == '@') {
+          break;
+        }
+        index++;
+      }
+      userinfo = p_uriSpec.substring(start, index);
+      index++;
+    }
+
+    // host is everything up to last ':', or up to 
+    // and including ']' if followed by ':'.
+    String host = null;
+    start = index;
+    boolean hasPort = false;
+    if (index < end) {
+      if (p_uriSpec.charAt(start) == '[') {
+      	int bracketIndex = p_uriSpec.indexOf(']', start);
+      	index = (bracketIndex != -1) ? bracketIndex : end;
+      	if (index+1 < end && p_uriSpec.charAt(index+1) == ':') {
+      	  ++index;
+      	  hasPort = true;
+      	}
+      	else {
+      	  index = end;
+      	}
+      }
+      else {
+      	int colonIndex = p_uriSpec.lastIndexOf(':', end);
+      	index = (colonIndex > start) ? colonIndex : end;
+      	hasPort = (index != end);
+      }
+    }
+    host = p_uriSpec.substring(start, index);
+    int port = -1;
+    if (host.length() > 0) {
+      // port
+      if (hasPort) {
+        index++;
+        start = index;
+        while (index < end) {
+          index++;
+        }
+        String portStr = p_uriSpec.substring(start, index);
+        if (portStr.length() > 0) {
+          // REVISIT: Remove this code.
+          /** for (int i = 0; i < portStr.length(); i++) {
+            if (!isDigit(portStr.charAt(i))) {
+              throw new MalformedURIException(
+                   portStr +
+                   " is invalid. Port should only contain digits!");
+            }
+          }**/
+          // REVISIT: Remove this code.
+          // Store port value as string instead of integer.
+          try {
+            port = Integer.parseInt(portStr);
+            if (port == -1) --port;
+          }
+          catch (NumberFormatException nfe) {
+            port = -2;
+          }
+        }
+      }
+    }
+    
+    if (isValidServerBasedAuthority(host, port, userinfo)) {
+      m_host = host;
+      m_port = port;
+      m_userinfo = userinfo;
+      return true;
+    }
+    // Note: Registry based authority is being removed from a
+    // new spec for URI which would obsolete RFC 2396. If the
+    // spec is added to XML errata, processing of reg_name
+    // needs to be removed. - mrglavas.
+    else if (isValidRegistryBasedAuthority(p_uriSpec)) {
+      m_regAuthority = p_uriSpec;
+      return true;
+    }
+    return false;
+  }
+  
+  /**
+   * Determines whether the components host, port, and user info
+   * are valid as a server authority.
+   * 
+   * @param host the host component of authority
+   * @param port the port number component of authority
+   * @param userinfo the user info component of authority
+   * 
+   * @return true if the given host, port, and userinfo compose
+   * a valid server authority
+   */
+  private boolean isValidServerBasedAuthority(String host, int port, String userinfo) {
+    
+    // Check if the host is well formed.
+    if (!isWellFormedAddress(host)) {
+      return false;
+    }
+    
+    // Check that port is well formed if it exists.
+    // REVISIT: There's no restriction on port value ranges, but
+    // perform the same check as in setPort to be consistent. Pass
+    // in a string to this method instead of an integer.
+    if (port < -1 || port > 65535) {
+      return false;
+    }
+    
+    // Check that userinfo is well formed if it exists.
+    if (userinfo != null) {
+      // Userinfo can contain alphanumerics, mark characters, escaped
+      // and ';',':','&','=','+','$',','
+      int index = 0;
+      int end = userinfo.length();
+      char testChar = '\0';
+      while (index < end) {
+        testChar = userinfo.charAt(index);
+        if (testChar == '%') {
+          if (index+2 >= end ||
+            !isHex(userinfo.charAt(index+1)) ||
+            !isHex(userinfo.charAt(index+2))) {
+            return false;
+          }
+          index += 2;
+        }
+        else if (!isUserinfoCharacter(testChar)) {
+          return false;
+        }
+        ++index;
+      }
+    }
+    return true;
+  }
+  
+  /**
+   * Determines whether the given string is a registry based authority.
+   * 
+   * @param authority the authority component of a URI
+   * 
+   * @return true if the given string is a registry based authority
+   */
+  private boolean isValidRegistryBasedAuthority(String authority) {
+    int index = 0;
+    int end = authority.length();
+    char testChar;
+  	
+    while (index < end) {
+      testChar = authority.charAt(index);
+      
+      // check for valid escape sequence
+      if (testChar == '%') {
+        if (index+2 >= end ||
+            !isHex(authority.charAt(index+1)) ||
+            !isHex(authority.charAt(index+2))) {
+            return false;
+        }
+        index += 2;
+      }
+      // can check against path characters because the set
+      // is the same except for '/' which we've already excluded.
+      else if (!isPathCharacter(testChar)) {
+        return false;
+      }
+      ++index;
+    }
+    return true;
+  }
+  	
+ /**
+  * Initialize the path for this URI from a URI string spec.
+  *
+  * @param p_uriSpec the URI specification (cannot be null)
+  * @param p_nStartIndex the index to begin scanning from
+  *
+  * @exception MalformedURIException if p_uriSpec violates syntax rules
+  */
+  private void initializePath(String p_uriSpec, int p_nStartIndex)
+                 throws MalformedURIException {
+    if (p_uriSpec == null) {
+      throw new MalformedURIException(
+                "Cannot initialize path from null string!");
+    }
+
+    int index = p_nStartIndex;
+    int start = p_nStartIndex;
+    int end = p_uriSpec.length();
+    char testChar = '\0';
+
+    // path - everything up to query string or fragment
+    if (start < end) {
+    	// RFC 2732 only allows '[' and ']' to appear in the opaque part.
+    	if (getScheme() == null || p_uriSpec.charAt(start) == '/') {
+    	
+            // Scan path.
+            // abs_path = "/"  path_segments
+            // rel_path = rel_segment [ abs_path ]
+            while (index < end) {
+                testChar = p_uriSpec.charAt(index);
+            
+                // check for valid escape sequence
+                if (testChar == '%') {
+                    if (index+2 >= end ||
+                    !isHex(p_uriSpec.charAt(index+1)) ||
+                    !isHex(p_uriSpec.charAt(index+2))) {
+                        throw new MalformedURIException(
+                            "Path contains invalid escape sequence!");
+                    }
+                    index += 2;
+                }
+                // Path segments cannot contain '[' or ']' since pchar
+                // production was not changed by RFC 2732.
+                else if (!isPathCharacter(testChar)) {
+      	            if (testChar == '?' || testChar == '#') {
+      	                break;
+      	            }
+                    throw new MalformedURIException(
+                        "Path contains invalid character: " + testChar);
+                }
+                ++index;
+            }
+        }
+        else {
+            
+            // Scan opaque part.
+            // opaque_part = uric_no_slash *uric
+            while (index < end) {
+                testChar = p_uriSpec.charAt(index);
+            
+                if (testChar == '?' || testChar == '#') {
+                    break;
+      	        }
+                
+                // check for valid escape sequence
+                if (testChar == '%') {
+                    if (index+2 >= end ||
+                    !isHex(p_uriSpec.charAt(index+1)) ||
+                    !isHex(p_uriSpec.charAt(index+2))) {
+                        throw new MalformedURIException(
+                            "Opaque part contains invalid escape sequence!");
+                    }
+                    index += 2;
+                }
+                // If the scheme specific part is opaque, it can contain '['
+                // and ']'. uric_no_slash wasn't modified by RFC 2732, which
+                // I've interpreted as an error in the spec, since the 
+                // production should be equivalent to (uric - '/'), and uric
+                // contains '[' and ']'. - mrglavas
+                else if (!isURICharacter(testChar)) {
+                    throw new MalformedURIException(
+                        "Opaque part contains invalid character: " + testChar);
+                }
+                ++index;
+            }
+        }
+    }
+    m_path = p_uriSpec.substring(start, index);
+
+    // query - starts with ? and up to fragment or end
+    if (testChar == '?') {
+      index++;
+      start = index;
+      while (index < end) {
+        testChar = p_uriSpec.charAt(index);
+        if (testChar == '#') {
+          break;
+        }
+        if (testChar == '%') {
+           if (index+2 >= end ||
+              !isHex(p_uriSpec.charAt(index+1)) ||
+              !isHex(p_uriSpec.charAt(index+2))) {
+            throw new MalformedURIException(
+                    "Query string contains invalid escape sequence!");
+           }
+           index += 2;
+        }
+        else if (!isURICharacter(testChar)) {
+          throw new MalformedURIException(
+                "Query string contains invalid character: " + testChar);
+        }
+        index++;
+      }
+      m_queryString = p_uriSpec.substring(start, index);
+    }
+
+    // fragment - starts with #
+    if (testChar == '#') {
+      index++;
+      start = index;
+      while (index < end) {
+        testChar = p_uriSpec.charAt(index);
+
+        if (testChar == '%') {
+           if (index+2 >= end ||
+              !isHex(p_uriSpec.charAt(index+1)) ||
+              !isHex(p_uriSpec.charAt(index+2))) {
+            throw new MalformedURIException(
+                    "Fragment contains invalid escape sequence!");
+           }
+           index += 2;
+        }
+        else if (!isURICharacter(testChar)) {
+          throw new MalformedURIException(
+                "Fragment contains invalid character: "+testChar);
+        }
+        index++;
+      }
+      m_fragment = p_uriSpec.substring(start, index);
+    }
+  }
+
+ /**
+  * Get the scheme for this URI.
+  *
+  * @return the scheme for this URI
+  */
+  public String getScheme() {
+    return m_scheme;
+  }
+
+ /**
+  * Get the scheme-specific part for this URI (everything following the
+  * scheme and the first colon). See RFC 2396 Section 5.2 for spec.
+  *
+  * @return the scheme-specific part for this URI
+  */
+  public String getSchemeSpecificPart() {
+    StringBuffer schemespec = new StringBuffer();
+
+    if (m_host != null || m_regAuthority != null) {
+      schemespec.append("//");
+    
+      // Server based authority.
+      if (m_host != null) {
+
+        if (m_userinfo != null) {
+          schemespec.append(m_userinfo);
+          schemespec.append('@');
+        }
+        
+        schemespec.append(m_host);
+        
+        if (m_port != -1) {
+          schemespec.append(':');
+          schemespec.append(m_port);
+        }
+      }
+      // Registry based authority.
+      else {
+      	schemespec.append(m_regAuthority);
+      }
+    }
+
+    if (m_path != null) {
+      schemespec.append((m_path));
+    }
+
+    if (m_queryString != null) {
+      schemespec.append('?');
+      schemespec.append(m_queryString);
+    }
+
+    if (m_fragment != null) {
+      schemespec.append('#');
+      schemespec.append(m_fragment);
+    }
+
+    return schemespec.toString();
+  }
+
+ /**
+  * Get the userinfo for this URI.
+  *
+  * @return the userinfo for this URI (null if not specified).
+  */
+  public String getUserinfo() {
+    return m_userinfo;
+  }
+
+  /**
+  * Get the host for this URI.
+  *
+  * @return the host for this URI (null if not specified).
+  */
+  public String getHost() {
+    return m_host;
+  }
+
+ /**
+  * Get the port for this URI.
+  *
+  * @return the port for this URI (-1 if not specified).
+  */
+  public int getPort() {
+    return m_port;
+  }
+  
+  /**
+   * Get the registry based authority for this URI.
+   * 
+   * @return the registry based authority (null if not specified).
+   */
+  public String getRegBasedAuthority() {
+    return m_regAuthority;
+  }
+  
+  /**
+   * Get the authority for this URI.
+   * 
+   * @return the authority
+   */
+  public String getAuthority() {
+      StringBuffer authority = new StringBuffer();
+      if (m_host != null || m_regAuthority != null) {
+          authority.append("//");
+          
+          // Server based authority.
+          if (m_host != null) {
+              
+              if (m_userinfo != null) {
+                  authority.append(m_userinfo);
+                  authority.append('@');
+              }
+              
+              authority.append(m_host);
+              
+              if (m_port != -1) {
+                  authority.append(':');
+                  authority.append(m_port);
+              }
+          }
+          // Registry based authority.
+          else {
+              authority.append(m_regAuthority);
+          }
+      }
+      return authority.toString();
+  }
+
+ /**
+  * Get the path for this URI (optionally with the query string and
+  * fragment).
+  *
+  * @param p_includeQueryString if true (and query string is not null),
+  *                             then a "?" followed by the query string
+  *                             will be appended
+  * @param p_includeFragment if true (and fragment is not null),
+  *                             then a "#" followed by the fragment
+  *                             will be appended
+  *
+  * @return the path for this URI possibly including the query string
+  *         and fragment
+  */
+  public String getPath(boolean p_includeQueryString,
+                        boolean p_includeFragment) {
+    StringBuffer pathString = new StringBuffer(m_path);
+
+    if (p_includeQueryString && m_queryString != null) {
+      pathString.append('?');
+      pathString.append(m_queryString);
+    }
+
+    if (p_includeFragment && m_fragment != null) {
+      pathString.append('#');
+      pathString.append(m_fragment);
+    }
+    return pathString.toString();
+  }
+
+ /**
+  * Get the path for this URI. Note that the value returned is the path
+  * only and does not include the query string or fragment.
+  *
+  * @return the path for this URI.
+  */
+  public String getPath() {
+    return m_path;
+  }
+
+ /**
+  * Get the query string for this URI.
+  *
+  * @return the query string for this URI. Null is returned if there
+  *         was no "?" in the URI spec, empty string if there was a
+  *         "?" but no query string following it.
+  */
+  public String getQueryString() {
+    return m_queryString;
+  }
+
+ /**
+  * Get the fragment for this URI.
+  *
+  * @return the fragment for this URI. Null is returned if there
+  *         was no "#" in the URI spec, empty string if there was a
+  *         "#" but no fragment following it.
+  */
+  public String getFragment() {
+    return m_fragment;
+  }
+
+ /**
+  * Set the scheme for this URI. The scheme is converted to lowercase
+  * before it is set.
+  *
+  * @param p_scheme the scheme for this URI (cannot be null)
+  *
+  * @exception MalformedURIException if p_scheme is not a conformant
+  *                                  scheme name
+  */
+  public void setScheme(String p_scheme) throws MalformedURIException {
+    if (p_scheme == null) {
+      throw new MalformedURIException(
+                "Cannot set scheme from null string!");
+    }
+    if (!isConformantSchemeName(p_scheme)) {
+      throw new MalformedURIException("The scheme is not conformant.");
+    }
+
+    m_scheme = p_scheme.toLowerCase(Locale.ENGLISH);
+  }
+
+ /**
+  * Set the userinfo for this URI. If a non-null value is passed in and
+  * the host value is null, then an exception is thrown.
+  *
+  * @param p_userinfo the userinfo for this URI
+  *
+  * @exception MalformedURIException if p_userinfo contains invalid
+  *                                  characters
+  */
+  public void setUserinfo(String p_userinfo) throws MalformedURIException {
+    if (p_userinfo == null) {
+      m_userinfo = null;
+      return;
+    }
+    else {
+      if (m_host == null) {
+        throw new MalformedURIException(
+                     "Userinfo cannot be set when host is null!");
+      }
+
+      // userinfo can contain alphanumerics, mark characters, escaped
+      // and ';',':','&','=','+','$',','
+      int index = 0;
+      int end = p_userinfo.length();
+      char testChar = '\0';
+      while (index < end) {
+        testChar = p_userinfo.charAt(index);
+        if (testChar == '%') {
+          if (index+2 >= end ||
+              !isHex(p_userinfo.charAt(index+1)) ||
+              !isHex(p_userinfo.charAt(index+2))) {
+            throw new MalformedURIException(
+                  "Userinfo contains invalid escape sequence!");
+          }
+        }
+        else if (!isUserinfoCharacter(testChar)) {
+          throw new MalformedURIException(
+                  "Userinfo contains invalid character:"+testChar);
+        }
+        index++;
+      }
+    }
+    m_userinfo = p_userinfo;
+  }
+
+ /**
+  * <p>Set the host for this URI. If null is passed in, the userinfo
+  * field is also set to null and the port is set to -1.</p>
+  * 
+  * <p>Note: This method overwrites registry based authority if it
+  * previously existed in this URI.</p>
+  *
+  * @param p_host the host for this URI
+  *
+  * @exception MalformedURIException if p_host is not a valid IP
+  *                                  address or DNS hostname.
+  */
+  public void setHost(String p_host) throws MalformedURIException {
+    if (p_host == null || p_host.length() == 0) {
+      if (p_host != null) {
+        m_regAuthority = null;
+      }
+      m_host = p_host;
+      m_userinfo = null;
+      m_port = -1;
+      return;
+    }
+    else if (!isWellFormedAddress(p_host)) {
+      throw new MalformedURIException("Host is not a well formed address!");
+    }
+    m_host = p_host;
+    m_regAuthority = null;
+  }
+
+ /**
+  * Set the port for this URI. -1 is used to indicate that the port is
+  * not specified, otherwise valid port numbers are  between 0 and 65535.
+  * If a valid port number is passed in and the host field is null,
+  * an exception is thrown.
+  *
+  * @param p_port the port number for this URI
+  *
+  * @exception MalformedURIException if p_port is not -1 and not a
+  *                                  valid port number
+  */
+  public void setPort(int p_port) throws MalformedURIException {
+    if (p_port >= 0 && p_port <= 65535) {
+      if (m_host == null) {
+        throw new MalformedURIException(
+                      "Port cannot be set when host is null!");
+      }
+    }
+    else if (p_port != -1) {
+      throw new MalformedURIException("Invalid port number!");
+    }
+    m_port = p_port;
+  }
+  
+  /**
+   * <p>Sets the registry based authority for this URI.</p>
+   * 
+   * <p>Note: This method overwrites server based authority
+   * if it previously existed in this URI.</p>
+   * 
+   * @param authority the registry based authority for this URI
+   * 
+   * @exception MalformedURIException it authority is not a
+   * well formed registry based authority
+   */
+  public void setRegBasedAuthority(String authority) 
+    throws MalformedURIException {
+
+  	if (authority == null) {
+  	  m_regAuthority = null;
+  	  return;
+  	}
+	// reg_name = 1*( unreserved | escaped | "$" | "," | 
+	//            ";" | ":" | "@" | "&" | "=" | "+" )
+  	else if (authority.length() < 1 ||
+  	  !isValidRegistryBasedAuthority(authority) ||
+  	  authority.indexOf('/') != -1) {
+      throw new MalformedURIException("Registry based authority is not well formed.");       	
+  	}
+  	m_regAuthority = authority;
+  	m_host = null;
+  	m_userinfo = null;
+  	m_port = -1;
+  }
+
+ /**
+  * Set the path for this URI. If the supplied path is null, then the
+  * query string and fragment are set to null as well. If the supplied
+  * path includes a query string and/or fragment, these fields will be
+  * parsed and set as well. Note that, for URIs following the "generic
+  * URI" syntax, the path specified should start with a slash.
+  * For URIs that do not follow the generic URI syntax, this method
+  * sets the scheme-specific part.
+  *
+  * @param p_path the path for this URI (may be null)
+  *
+  * @exception MalformedURIException if p_path contains invalid
+  *                                  characters
+  */
+  public void setPath(String p_path) throws MalformedURIException {
+    if (p_path == null) {
+      m_path = null;
+      m_queryString = null;
+      m_fragment = null;
+    }
+    else {
+      initializePath(p_path, 0);
+    }
+  }
+
+ /**
+  * Append to the end of the path of this URI. If the current path does
+  * not end in a slash and the path to be appended does not begin with
+  * a slash, a slash will be appended to the current path before the
+  * new segment is added. Also, if the current path ends in a slash
+  * and the new segment begins with a slash, the extra slash will be
+  * removed before the new segment is appended.
+  *
+  * @param p_addToPath the new segment to be added to the current path
+  *
+  * @exception MalformedURIException if p_addToPath contains syntax
+  *                                  errors
+  */
+  public void appendPath(String p_addToPath)
+                         throws MalformedURIException {
+    if (p_addToPath == null || p_addToPath.trim().length() == 0) {
+      return;
+    }
+
+    if (!isURIString(p_addToPath)) {
+      throw new MalformedURIException(
+              "Path contains invalid character!");
+    }
+
+    if (m_path == null || m_path.trim().length() == 0) {
+      if (p_addToPath.startsWith("/")) {
+        m_path = p_addToPath;
+      }
+      else {
+        m_path = "/" + p_addToPath;
+      }
+    }
+    else if (m_path.endsWith("/")) {
+      if (p_addToPath.startsWith("/")) {
+        m_path = m_path.concat(p_addToPath.substring(1));
+      }
+      else {
+        m_path = m_path.concat(p_addToPath);
+      }
+    }
+    else {
+      if (p_addToPath.startsWith("/")) {
+        m_path = m_path.concat(p_addToPath);
+      }
+      else {
+        m_path = m_path.concat("/" + p_addToPath);
+      }
+    }
+  }
+
+ /**
+  * Set the query string for this URI. A non-null value is valid only
+  * if this is an URI conforming to the generic URI syntax and
+  * the path value is not null.
+  *
+  * @param p_queryString the query string for this URI
+  *
+  * @exception MalformedURIException if p_queryString is not null and this
+  *                                  URI does not conform to the generic
+  *                                  URI syntax or if the path is null
+  */
+  public void setQueryString(String p_queryString) throws MalformedURIException {
+    if (p_queryString == null) {
+      m_queryString = null;
+    }
+    else if (!isGenericURI()) {
+      throw new MalformedURIException(
+              "Query string can only be set for a generic URI!");
+    }
+    else if (getPath() == null) {
+      throw new MalformedURIException(
+              "Query string cannot be set when path is null!");
+    }
+    else if (!isURIString(p_queryString)) {
+      throw new MalformedURIException(
+              "Query string contains invalid character!");
+    }
+    else {
+      m_queryString = p_queryString;
+    }
+  }
+
+ /**
+  * Set the fragment for this URI. A non-null value is valid only
+  * if this is a URI conforming to the generic URI syntax and
+  * the path value is not null.
+  *
+  * @param p_fragment the fragment for this URI
+  *
+  * @exception MalformedURIException if p_fragment is not null and this
+  *                                  URI does not conform to the generic
+  *                                  URI syntax or if the path is null
+  */
+  public void setFragment(String p_fragment) throws MalformedURIException {
+    if (p_fragment == null) {
+      m_fragment = null;
+    }
+    else if (!isGenericURI()) {
+      throw new MalformedURIException(
+         "Fragment can only be set for a generic URI!");
+    }
+    else if (getPath() == null) {
+      throw new MalformedURIException(
+              "Fragment cannot be set when path is null!");
+    }
+    else if (!isURIString(p_fragment)) {
+      throw new MalformedURIException(
+              "Fragment contains invalid character!");
+    }
+    else {
+      m_fragment = p_fragment;
+    }
+  }
+
+ /**
+  * Determines if the passed-in Object is equivalent to this URI.
+  *
+  * @param p_test the Object to test for equality.
+  *
+  * @return true if p_test is a URI with all values equal to this
+  *         URI, false otherwise
+  */
+@Override
+public boolean equals(Object p_test) {
+    if (p_test instanceof URI) {
+      URI testURI = (URI) p_test;
+      if (((m_scheme == null && testURI.m_scheme == null) ||
+           (m_scheme != null && testURI.m_scheme != null &&
+            m_scheme.equals(testURI.m_scheme))) &&
+          ((m_userinfo == null && testURI.m_userinfo == null) ||
+           (m_userinfo != null && testURI.m_userinfo != null &&
+            m_userinfo.equals(testURI.m_userinfo))) &&
+          ((m_host == null && testURI.m_host == null) ||
+           (m_host != null && testURI.m_host != null &&
+            m_host.equals(testURI.m_host))) &&
+            m_port == testURI.m_port &&
+          ((m_path == null && testURI.m_path == null) ||
+           (m_path != null && testURI.m_path != null &&
+            m_path.equals(testURI.m_path))) &&
+          ((m_queryString == null && testURI.m_queryString == null) ||
+           (m_queryString != null && testURI.m_queryString != null &&
+            m_queryString.equals(testURI.m_queryString))) &&
+          ((m_fragment == null && testURI.m_fragment == null) ||
+           (m_fragment != null && testURI.m_fragment != null &&
+            m_fragment.equals(testURI.m_fragment)))) {
+        return true;
+      }
+    }
+    return false;
+  }
+
+ /**
+  * Get the URI as a string specification. See RFC 2396 Section 5.2.
+  *
+  * @return the URI string specification
+  */
+@Override
+public String toString() {
+    StringBuffer uriSpecString = new StringBuffer();
+
+    if (m_scheme != null) {
+      uriSpecString.append(m_scheme);
+      uriSpecString.append(':');
+    }
+    uriSpecString.append(getSchemeSpecificPart());
+    return uriSpecString.toString();
+  }
+
+ /**
+  * Get the indicator as to whether this URI uses the "generic URI"
+  * syntax.
+  *
+  * @return true if this URI uses the "generic URI" syntax, false
+  *         otherwise
+  */
+  public boolean isGenericURI() {
+    // presence of the host (whether valid or empty) means
+    // double-slashes which means generic uri
+    return (m_host != null);
+  }
+  
+  /**
+   * Returns whether this URI represents an absolute URI.
+   *
+   * @return true if this URI represents an absolute URI, false
+   *         otherwise
+   */
+  public boolean isAbsoluteURI() {
+      // presence of the scheme means absolute uri
+      return (m_scheme != null);
+  }
+
+ /**
+  * Determine whether a scheme conforms to the rules for a scheme name.
+  * A scheme is conformant if it starts with an alphanumeric, and
+  * contains only alphanumerics, '+','-' and '.'.
+  *
+  * @return true if the scheme is conformant, false otherwise
+  */
+  public static boolean isConformantSchemeName(String p_scheme) {
+    if (p_scheme == null || p_scheme.trim().length() == 0) {
+      return false;
+    }
+
+    if (!isAlpha(p_scheme.charAt(0))) {
+      return false;
+    }
+
+    char testChar;
+    int schemeLength = p_scheme.length();
+    for (int i = 1; i < schemeLength; ++i) {
+      testChar = p_scheme.charAt(i);
+      if (!isSchemeCharacter(testChar)) {
+        return false;
+      }
+    }
+
+    return true;
+  }
+
+ /**
+  * Determine whether a string is syntactically capable of representing
+  * a valid IPv4 address, IPv6 reference or the domain name of a network host. 
+  * A valid IPv4 address consists of four decimal digit groups separated by a
+  * '.'. Each group must consist of one to three digits. See RFC 2732 Section 3,
+  * and RFC 2373 Section 2.2, for the definition of IPv6 references. A hostname 
+  * consists of domain labels (each of which must begin and end with an alphanumeric 
+  * but may contain '-') separated & by a '.'. See RFC 2396 Section 3.2.2.
+  *
+  * @return true if the string is a syntactically valid IPv4 address, 
+  * IPv6 reference or hostname
+  */
+  public static boolean isWellFormedAddress(String address) {
+    if (address == null) {
+      return false;
+    }
+
+    int addrLength = address.length();
+    if (addrLength == 0) {
+      return false;
+    }
+    
+    // Check if the host is a valid IPv6reference.
+    if (address.startsWith("[")) {
+      return isWellFormedIPv6Reference(address);
+    }
+
+    // Cannot start with a '.', '-', or end with a '-'.
+    if (address.startsWith(".") || 
+        address.startsWith("-") || 
+        address.endsWith("-")) {
+      return false;
+    }
+
+    // rightmost domain label starting with digit indicates IP address
+    // since top level domain label can only start with an alpha
+    // see RFC 2396 Section 3.2.2
+    int index = address.lastIndexOf('.');
+    if (address.endsWith(".")) {
+      index = address.substring(0, index).lastIndexOf('.');
+    }
+
+    if (index+1 < addrLength && isDigit(address.charAt(index+1))) {
+      return isWellFormedIPv4Address(address);
+    }
+    else {
+      // hostname      = *( domainlabel "." ) toplabel [ "." ]
+      // domainlabel   = alphanum | alphanum *( alphanum | "-" ) alphanum
+      // toplabel      = alpha | alpha *( alphanum | "-" ) alphanum
+      
+      // RFC 2396 states that hostnames take the form described in 
+      // RFC 1034 (Section 3) and RFC 1123 (Section 2.1). According
+      // to RFC 1034, hostnames are limited to 255 characters.
+      if (addrLength > 255) {
+      	return false;
+      }
+      
+      // domain labels can contain alphanumerics and '-"
+      // but must start and end with an alphanumeric
+      char testChar;
+      int labelCharCount = 0;
+
+      for (int i = 0; i < addrLength; i++) {
+        testChar = address.charAt(i);
+        if (testChar == '.') {
+          if (!isAlphanum(address.charAt(i-1))) {
+            return false;
+          }
+          if (i+1 < addrLength && !isAlphanum(address.charAt(i+1))) {
+            return false;
+          }
+          labelCharCount = 0;
+        }
+        else if (!isAlphanum(testChar) && testChar != '-') {
+          return false;
+        }
+        // RFC 1034: Labels must be 63 characters or less.
+        else if (++labelCharCount > 63) {
+          return false;
+        }
+      }
+    }
+    return true;
+  }
+  
+  /**
+   * <p>Determines whether a string is an IPv4 address as defined by 
+   * RFC 2373, and under the further constraint that it must be a 32-bit
+   * address. Though not expressed in the grammar, in order to satisfy 
+   * the 32-bit address constraint, each segment of the address cannot 
+   * be greater than 255 (8 bits of information).</p>
+   *
+   * <p><code>IPv4address = 1*3DIGIT "." 1*3DIGIT "." 1*3DIGIT "." 1*3DIGIT</code></p>
+   *
+   * @return true if the string is a syntactically valid IPv4 address
+   */
+  public static boolean isWellFormedIPv4Address(String address) {
+      
+      int addrLength = address.length();
+      char testChar;
+      int numDots = 0;
+      int numDigits = 0;
+
+      // make sure that 1) we see only digits and dot separators, 2) that
+      // any dot separator is preceded and followed by a digit and
+      // 3) that we find 3 dots
+      //
+      // RFC 2732 amended RFC 2396 by replacing the definition 
+      // of IPv4address with the one defined by RFC 2373. - mrglavas
+      //
+      // IPv4address = 1*3DIGIT "." 1*3DIGIT "." 1*3DIGIT "." 1*3DIGIT
+      //
+      // One to three digits must be in each segment.
+      for (int i = 0; i < addrLength; i++) {
+        testChar = address.charAt(i);
+        if (testChar == '.') {
+          if ((i > 0 && !isDigit(address.charAt(i-1))) || 
+              (i+1 < addrLength && !isDigit(address.charAt(i+1)))) {
+            return false;
+          }
+          numDigits = 0;
+          if (++numDots > 3) {
+            return false;
+          }
+        }
+        else if (!isDigit(testChar)) {
+          return false;
+        }
+        // Check that that there are no more than three digits
+        // in this segment.
+        else if (++numDigits > 3) {
+          return false;
+        }
+        // Check that this segment is not greater than 255.
+        else if (numDigits == 3) {
+          char first = address.charAt(i-2);
+          char second = address.charAt(i-1);
+          if (!(first < '2' || 
+               (first == '2' && 
+               (second < '5' || 
+               (second == '5' && testChar <= '5'))))) {
+            return false;
+          }
+        }
+      }
+      return (numDots == 3);
+  }
+  
+  /**
+   * <p>Determines whether a string is an IPv6 reference as defined
+   * by RFC 2732, where IPv6address is defined in RFC 2373. The 
+   * IPv6 address is parsed according to Section 2.2 of RFC 2373,
+   * with the additional constraint that the address be composed of
+   * 128 bits of information.</p>
+   *
+   * <p><code>IPv6reference = "[" IPv6address "]"</code></p>
+   *
+   * <p>Note: The BNF expressed in RFC 2373 Appendix B does not 
+   * accurately describe section 2.2, and was in fact removed from
+   * RFC 3513, the successor of RFC 2373.</p>
+   *
+   * @return true if the string is a syntactically valid IPv6 reference
+   */
+  public static boolean isWellFormedIPv6Reference(String address) {
+
+      int addrLength = address.length();
+      int index = 1;
+      int end = addrLength-1;
+      
+      // Check if string is a potential match for IPv6reference.
+      if (!(addrLength > 2 && address.charAt(0) == '[' 
+          && address.charAt(end) == ']')) {
+          return false;
+      }
+      
+      // Counter for the number of 16-bit sections read in the address.
+      int [] counter = new int[1];
+      
+      // Scan hex sequence before possible '::' or IPv4 address.
+      index = scanHexSequence(address, index, end, counter);
+      if (index == -1) {
+          return false;
+      }
+      // Address must contain 128-bits of information.
+      else if (index == end) {
+          return (counter[0] == 8);
+      }
+      
+      if (index+1 < end && address.charAt(index) == ':') {
+          if (address.charAt(index+1) == ':') {
+              // '::' represents at least one 16-bit group of zeros.
+              if (++counter[0] > 8) {
+                  return false;
+              }
+              index += 2;
+              // Trailing zeros will fill out the rest of the address.
+              if (index == end) {
+                 return true;
+              }
+          }
+          // If the second character wasn't ':', in order to be valid,
+          // the remainder of the string must match IPv4Address, 
+          // and we must have read exactly 6 16-bit groups.
+          else {
+              return (counter[0] == 6) && 
+                  isWellFormedIPv4Address(address.substring(index+1, end));
+          }
+      }
+      else {
+          return false;
+      }
+      
+      // 3. Scan hex sequence after '::'.
+      int prevCount = counter[0];
+      index = scanHexSequence(address, index, end, counter);
+
+      // We've either reached the end of the string, the address ends in
+      // an IPv4 address, or it is invalid. scanHexSequence has already 
+      // made sure that we have the right number of bits. 
+      return (index == end) || 
+          (index != -1 && isWellFormedIPv4Address(
+          address.substring((counter[0] > prevCount) ? index+1 : index, end)));
+  }
+  
+  /**
+   * Helper method for isWellFormedIPv6Reference which scans the 
+   * hex sequences of an IPv6 address. It returns the index of the 
+   * next character to scan in the address, or -1 if the string 
+   * cannot match a valid IPv6 address. 
+   *
+   * @param address the string to be scanned
+   * @param index the beginning index (inclusive)
+   * @param end the ending index (exclusive)
+   * @param counter a counter for the number of 16-bit sections read
+   * in the address
+   *
+   * @return the index of the next character to scan, or -1 if the
+   * string cannot match a valid IPv6 address
+   */
+  private static int scanHexSequence (String address, int index, int end, int [] counter) {
+  	
+      char testChar;
+      int numDigits = 0;
+      int start = index;
+      
+      // Trying to match the following productions:
+      // hexseq = hex4 *( ":" hex4)
+      // hex4   = 1*4HEXDIG
+      for (; index < end; ++index) {
+      	testChar = address.charAt(index);
+      	if (testChar == ':') {
+      	    // IPv6 addresses are 128-bit, so there can be at most eight sections.
+      	    if (numDigits > 0 && ++counter[0] > 8) {
+      	        return -1;
+      	    }
+      	    // This could be '::'.
+      	    if (numDigits == 0 || ((index+1 < end) && address.charAt(index+1) == ':')) {
+      	        return index;
+      	    }
+      	    numDigits = 0;
+        }
+        // This might be invalid or an IPv4address. If it's potentially an IPv4address,
+        // backup to just after the last valid character that matches hexseq.
+        else if (!isHex(testChar)) {
+            if (testChar == '.' && numDigits < 4 && numDigits > 0 && counter[0] <= 6) {
+                int back = index - numDigits - 1;
+                return (back >= start) ? back : (back+1);
+            }
+            return -1;
+        }
+        // There can be at most 4 hex digits per group.
+        else if (++numDigits > 4) {
+            return -1;
+        }
+      }
+      return (numDigits > 0 && ++counter[0] <= 8) ? end : -1;
+  } 
+
+
+ /**
+  * Determine whether a char is a digit.
+  *
+  * @return true if the char is betweeen '0' and '9', false otherwise
+  */
+  private static boolean isDigit(char p_char) {
+    return p_char >= '0' && p_char <= '9';
+  }
+
+ /**
+  * Determine whether a character is a hexadecimal character.
+  *
+  * @return true if the char is betweeen '0' and '9', 'a' and 'f'
+  *         or 'A' and 'F', false otherwise
+  */
+  private static boolean isHex(char p_char) {
+    return (p_char <= 'f' && (fgLookupTable[p_char] & ASCII_HEX_CHARACTERS) != 0);
+  }
+
+ /**
+  * Determine whether a char is an alphabetic character: a-z or A-Z
+  *
+  * @return true if the char is alphabetic, false otherwise
+  */
+  private static boolean isAlpha(char p_char) {
+      return ((p_char >= 'a' && p_char <= 'z') || (p_char >= 'A' && p_char <= 'Z' ));
+  }
+
+ /**
+  * Determine whether a char is an alphanumeric: 0-9, a-z or A-Z
+  *
+  * @return true if the char is alphanumeric, false otherwise
+  */
+  private static boolean isAlphanum(char p_char) {
+     return (p_char <= 'z' && (fgLookupTable[p_char] & MASK_ALPHA_NUMERIC) != 0);
+  }
+
+ /**
+  * Determine whether a character is a reserved character:
+  * ';', '/', '?', ':', '@', '&', '=', '+', '$', ',', '[', or ']'
+  *
+  * @return true if the string contains any reserved characters
+  */
+  private static boolean isReservedCharacter(char p_char) {
+     return (p_char <= ']' && (fgLookupTable[p_char] & RESERVED_CHARACTERS) != 0);
+  }
+
+ /**
+  * Determine whether a char is an unreserved character.
+  *
+  * @return true if the char is unreserved, false otherwise
+  */
+  private static boolean isUnreservedCharacter(char p_char) {
+     return (p_char <= '~' && (fgLookupTable[p_char] & MASK_UNRESERVED_MASK) != 0);
+  }
+
+ /**
+  * Determine whether a char is a URI character (reserved or 
+  * unreserved, not including '%' for escaped octets).
+  *
+  * @return true if the char is a URI character, false otherwise
+  */
+  private static boolean isURICharacter (char p_char) {
+      return (p_char <= '~' && (fgLookupTable[p_char] & MASK_URI_CHARACTER) != 0);
+  }
+
+ /**
+  * Determine whether a char is a scheme character.
+  *
+  * @return true if the char is a scheme character, false otherwise
+  */
+  private static boolean isSchemeCharacter (char p_char) {
+      return (p_char <= 'z' && (fgLookupTable[p_char] & MASK_SCHEME_CHARACTER) != 0);
+  }
+
+ /**
+  * Determine whether a char is a userinfo character.
+  *
+  * @return true if the char is a userinfo character, false otherwise
+  */
+  private static boolean isUserinfoCharacter (char p_char) {
+      return (p_char <= 'z' && (fgLookupTable[p_char] & MASK_USERINFO_CHARACTER) != 0);
+  }
+  
+ /**
+  * Determine whether a char is a path character.
+  * 
+  * @return true if the char is a path character, false otherwise
+  */
+  private static boolean isPathCharacter (char p_char) {
+      return (p_char <= '~' && (fgLookupTable[p_char] & MASK_PATH_CHARACTER) != 0);
+  }
+
+
+ /**
+  * Determine whether a given string contains only URI characters (also
+  * called "uric" in RFC 2396). uric consist of all reserved
+  * characters, unreserved characters and escaped characters.
+  *
+  * @return true if the string is comprised of uric, false otherwise
+  */
+  private static boolean isURIString(String p_uric) {
+    if (p_uric == null) {
+      return false;
+    }
+    int end = p_uric.length();
+    char testChar = '\0';
+    for (int i = 0; i < end; i++) {
+      testChar = p_uric.charAt(i);
+      if (testChar == '%') {
+        if (i+2 >= end ||
+            !isHex(p_uric.charAt(i+1)) ||
+            !isHex(p_uric.charAt(i+2))) {
+          return false;
+        }
+        else {
+          i += 2;
+          continue;
+        }
+      }
+      if (isURICharacter(testChar)) {
+          continue;
+      }
+      else {
+        return false;
+      }
+    }
+    return true;
+  }
+}


[08/24] jena git commit: JENA-1537: Remove dependency on Xerces. Import needed code

Posted by an...@apache.org.
http://git-wip-us.apache.org/repos/asf/jena/blob/c9a7e646/jena-core/src/main/java/org/apache/jena/ext/xerces/util/DatatypeMessageFormatter.java
----------------------------------------------------------------------
diff --git a/jena-core/src/main/java/org/apache/jena/ext/xerces/util/DatatypeMessageFormatter.java b/jena-core/src/main/java/org/apache/jena/ext/xerces/util/DatatypeMessageFormatter.java
new file mode 100644
index 0000000..ec06f25
--- /dev/null
+++ b/jena-core/src/main/java/org/apache/jena/ext/xerces/util/DatatypeMessageFormatter.java
@@ -0,0 +1,96 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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.jena.ext.xerces.util;
+
+import java.util.Locale;
+import java.util.MissingResourceException;
+import java.util.ResourceBundle;
+
+/**
+ * <p>Used to format JAXP 1.3 Datatype API error messages using a specified locale.</p>
+ *
+ * @author  Neeraj Bajaj, Sun Microsystems
+ * @version $Id: DatatypeMessageFormatter.java 813087 2009-09-09 19:35:27Z mrglavas $
+ */
+public class DatatypeMessageFormatter {
+    
+    private static final String BASE_NAME = "org.apache.jena.ext.xerces.impl.msg.DatatypeMessages";
+    
+    /**
+     * Formats a message with the specified arguments using the given
+     * locale information.
+     * 
+     * @param locale    The locale of the message.
+     * @param key       The message key.
+     * @param arguments The message replacement text arguments. The order
+     *                  of the arguments must match that of the placeholders
+     *                  in the actual message.
+     * 
+     * @return          the formatted message.
+     *
+     * @throws MissingResourceException Thrown if the message with the
+     *                                  specified key cannot be found.
+     */
+    public static String formatMessage(Locale locale, 
+        String key, Object[] arguments)
+        throws MissingResourceException {
+
+        if (locale == null) {
+            locale = Locale.getDefault();
+        }
+        final ResourceBundle resourceBundle = 
+            ResourceBundle.getBundle(BASE_NAME, locale);
+
+        // format message
+        String msg;
+        try {
+            msg = resourceBundle.getString(key);
+            if (arguments != null) {
+                try {
+                    msg = java.text.MessageFormat.format(msg, arguments);
+                } 
+                catch (Exception e) {
+                    msg = resourceBundle.getString("FormatFailed");
+                    msg += " " + resourceBundle.getString(key);
+                }
+            } 
+        }
+        
+        // error
+        catch (MissingResourceException e) {
+            msg = resourceBundle.getString("BadMessageKey");
+            throw new MissingResourceException(key, msg, key);
+        }
+
+        // no message
+        if (msg == null) {
+            msg = key;
+            if (arguments.length > 0) {
+                StringBuffer str = new StringBuffer(msg);
+                str.append('?');
+                for (int i = 0; i < arguments.length; i++) {
+                    if (i > 0) {
+                        str.append('&');
+                    }
+                    str.append(String.valueOf(arguments[i]));
+                }
+            }
+        }
+        return msg;
+    }
+}

http://git-wip-us.apache.org/repos/asf/jena/blob/c9a7e646/jena-core/src/main/java/org/apache/jena/ext/xerces/util/IntStack.java
----------------------------------------------------------------------
diff --git a/jena-core/src/main/java/org/apache/jena/ext/xerces/util/IntStack.java b/jena-core/src/main/java/org/apache/jena/ext/xerces/util/IntStack.java
new file mode 100644
index 0000000..8be3463
--- /dev/null
+++ b/jena-core/src/main/java/org/apache/jena/ext/xerces/util/IntStack.java
@@ -0,0 +1,114 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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.jena.ext.xerces.util;
+
+/**
+ * A simple integer based stack.
+ *
+ * moved to org.apache.xerces.util by neilg to support the
+ * XPathMatcher.
+ * @author  Andy Clark, IBM
+ *
+ * @version $Id: IntStack.java 447241 2006-09-18 05:12:57Z mrglavas $
+ */
+public final class IntStack {
+
+    //
+    // Data
+    //
+
+    /** Stack depth. */
+    private int fDepth;
+
+    /** Stack data. */
+    private int[] fData;
+
+    //
+    // Public methods
+    //
+
+    /** Returns the size of the stack. */
+    public int size() {
+        return fDepth;
+    }
+
+    /** Pushes a value onto the stack. */
+    public void push(int value) {
+        ensureCapacity(fDepth + 1);
+        fData[fDepth++] = value;
+    }
+
+    /** Peeks at the top of the stack. */
+    public int peek() {
+        return fData[fDepth - 1];
+    }
+
+    /** Returns the element at the specified depth in the stack. */
+    public int elementAt(int depth) {
+        return fData[depth];
+    }
+
+    /** Pops a value off of the stack. */
+    public int pop() {
+        return fData[--fDepth];
+    }
+
+    /** Clears the stack. */
+    public void clear() {
+        fDepth = 0;
+    }
+
+    // debugging
+
+    /** Prints the stack. */
+    public void print() {
+        System.out.print('(');
+        System.out.print(fDepth);
+        System.out.print(") {");
+        for (int i = 0; i < fDepth; i++) {
+            if (i == 3) {
+                System.out.print(" ...");
+                break;
+            }
+            System.out.print(' ');
+            System.out.print(fData[i]);
+            if (i < fDepth - 1) {
+                System.out.print(',');
+            }
+        }
+        System.out.print(" }");
+        System.out.println();
+    }
+
+    //
+    // Private methods
+    //
+
+    /** Ensures capacity. */
+    private void ensureCapacity(int size) {
+        if (fData == null) {
+            fData = new int[32];
+        }
+        else if (fData.length <= size) {
+            int[] newdata = new int[fData.length * 2];
+            System.arraycopy(fData, 0, newdata, 0, fData.length);
+            fData = newdata;
+        }
+    }
+
+} // class IntStack

http://git-wip-us.apache.org/repos/asf/jena/blob/c9a7e646/jena-core/src/main/java/org/apache/jena/ext/xerces/util/SymbolHash.java
----------------------------------------------------------------------
diff --git a/jena-core/src/main/java/org/apache/jena/ext/xerces/util/SymbolHash.java b/jena-core/src/main/java/org/apache/jena/ext/xerces/util/SymbolHash.java
new file mode 100644
index 0000000..8a05414
--- /dev/null
+++ b/jena-core/src/main/java/org/apache/jena/ext/xerces/util/SymbolHash.java
@@ -0,0 +1,223 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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.jena.ext.xerces.util;
+
+
+/**
+ * This class is an unsynchronized hash table primary used for String
+ * to Object mapping.
+ * <p>
+ * The hash code uses the same algorithm as SymbolTable class.
+ * 
+ * @author Elena Litani
+ * @version $Id: SymbolHash.java 819653 2009-09-28 17:29:56Z knoaman $
+ */
+public class SymbolHash {
+
+    //
+    // Constants
+    //
+
+    /** Default table size. */
+    protected int fTableSize = 101;
+
+    //
+    // Data
+    //
+
+    /** Buckets. */
+    protected Entry[] fBuckets; 
+
+    /** Number of elements. */
+    protected int fNum = 0;
+
+    //
+    // Constructors
+    //
+
+    /** Constructs a key table with the default size. */
+    public SymbolHash() {
+        fBuckets = new Entry[fTableSize];
+    }
+
+    /**
+     * Constructs a key table with a given size.
+     * 
+     * @param size  the size of the key table.
+     */
+    public SymbolHash(int size) {
+        fTableSize = size;
+        fBuckets = new Entry[fTableSize];
+    }
+
+    //
+    // Public methods
+    //
+
+    /**
+     * Adds the key/value mapping to the key table. If the key already exists, 
+     * the previous value associated with this key is overwritten by the new
+     * value.
+     * 
+     * @param key
+     * @param value 
+     */
+    public void put(Object key, Object value) {
+        int bucket = (key.hashCode() & 0x7FFFFFFF) % fTableSize;
+        Entry entry = search(key, bucket);
+
+        // replace old value
+        if (entry != null) {
+            entry.value = value;
+        }
+        // create new entry
+        else {
+            entry = new Entry(key, value, fBuckets[bucket]);
+            fBuckets[bucket] = entry;
+            fNum++;
+        }
+    }
+
+    /**
+     * Get the value associated with the given key.
+     * 
+     * @param key
+     * @return the value associated with the given key.
+     */
+    public Object get(Object key) {
+        int bucket = (key.hashCode() & 0x7FFFFFFF) % fTableSize;
+        Entry entry = search(key, bucket);
+        if (entry != null) {
+            return entry.value;
+        }
+        return null;
+    }
+
+    /**
+     * Get the number of key/value pairs stored in this table.
+     * 
+     * @return the number of key/value pairs stored in this table.
+     */
+    public int getLength() {
+        return fNum;
+    }
+    
+    /**
+     * Add all values to the given array. The array must have enough entry.
+     * 
+     * @param elements  the array to store the elements
+     * @param from      where to start store element in the array
+     * @return          number of elements copied to the array
+     */
+    public int getValues(Object[] elements, int from) {
+        for (int i=0, j=0; i<fTableSize && j<fNum; i++) {
+            for (Entry entry = fBuckets[i]; entry != null; entry = entry.next) {
+                elements[from+j] = entry.value;
+                j++;
+            }
+        }
+        return fNum;
+    }
+
+    /**
+     * Return key/value pairs of all entries in the map
+     */
+    public Object[] getEntries() {
+        Object[] entries = new Object[fNum << 1];
+        for (int i=0, j=0; i<fTableSize && j<fNum << 1; i++) {
+            for (Entry entry = fBuckets[i]; entry != null; entry = entry.next) {
+                entries[j] = entry.key;
+                entries[++j] = entry.value; 
+                j++;
+            }
+        }
+        return entries;
+    }
+
+    /**
+     * Make a clone of this object.
+     */
+    public SymbolHash makeClone() {
+        SymbolHash newTable = new SymbolHash(fTableSize);
+        newTable.fNum = fNum;
+        for (int i = 0; i < fTableSize; i++) {
+            if (fBuckets[i] != null)
+                newTable.fBuckets[i] = fBuckets[i].makeClone();
+        }
+        return newTable;
+    }
+    
+    /**
+     * Remove all key/value assocaition. This tries to save a bit of GC'ing
+     * by at least keeping the fBuckets array around.
+     */
+    public void clear() {
+        for (int i=0; i<fTableSize; i++) {
+            fBuckets[i] = null;
+        }
+        fNum = 0;
+    } // clear():  void
+
+    protected Entry search(Object key, int bucket) {
+        // search for identical key
+        for (Entry entry = fBuckets[bucket]; entry != null; entry = entry.next) {
+            if (key.equals(entry.key))
+                return entry;
+        }
+        return null;
+    }
+    
+    //
+    // Classes
+    //
+
+    /**
+     * This class is a key table entry. Each entry acts as a node
+     * in a linked list.
+     */
+    protected static final class Entry {
+        // key/value
+        public Object key;
+        public Object value;
+        /** The next entry. */
+        public Entry next;
+
+        public Entry() {
+            key = null;
+            value = null;
+            next = null;
+        }
+
+        public Entry(Object key, Object value, Entry next) {
+            this.key = key;
+            this.value = value;
+            this.next = next;
+        }
+        
+        public Entry makeClone() {
+            Entry entry = new Entry();
+            entry.key = key;
+            entry.value = value;
+            if (next != null)
+                entry.next = next.makeClone();
+            return entry;
+        }
+    } // entry
+
+} // class SymbolHash
+

http://git-wip-us.apache.org/repos/asf/jena/blob/c9a7e646/jena-core/src/main/java/org/apache/jena/ext/xerces/util/SymbolTable.java
----------------------------------------------------------------------
diff --git a/jena-core/src/main/java/org/apache/jena/ext/xerces/util/SymbolTable.java b/jena-core/src/main/java/org/apache/jena/ext/xerces/util/SymbolTable.java
new file mode 100644
index 0000000..b09b1bd
--- /dev/null
+++ b/jena-core/src/main/java/org/apache/jena/ext/xerces/util/SymbolTable.java
@@ -0,0 +1,408 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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.jena.ext.xerces.util;
+
+/**
+ * This class is a symbol table implementation that guarantees that
+ * strings used as identifiers are unique references. Multiple calls
+ * to <code>addSymbol</code> will always return the same string
+ * reference.
+ * <p>
+ * The symbol table performs the same task as <code>String.intern()</code>
+ * with the following differences:
+ * <ul>
+ *  <li>
+ *   A new string object does not need to be created in order to
+ *   retrieve a unique reference. Symbols can be added by using
+ *   a series of characters in a character array.
+ *  </li>
+ *  <li>
+ *   Users of the symbol table can provide their own symbol hashing
+ *   implementation. For example, a simple string hashing algorithm
+ *   may fail to produce a balanced set of hashcodes for symbols
+ *   that are <em>mostly</em> unique. Strings with similar leading
+ *   characters are especially prone to this poor hashing behavior.
+ *  </li>
+ * </ul>
+ * 
+ * An instance of <code>SymbolTable</code> has two parameters that affect its
+ * performance: <i>initial capacity</i> and <i>load factor</i>.  The
+ * <i>capacity</i> is the number of <i>buckets</i> in the SymbolTable, and the
+ * <i>initial capacity</i> is simply the capacity at the time the SymbolTable
+ * is created.  Note that the SymbolTable is <i>open</i>: in the case of a "hash
+ * collision", a single bucket stores multiple entries, which must be searched
+ * sequentially.  The <i>load factor</i> is a measure of how full the SymbolTable
+ * is allowed to get before its capacity is automatically increased.
+ * When the number of entries in the SymbolTable exceeds the product of the load
+ * factor and the current capacity, the capacity is increased by calling the
+ * <code>rehash</code> method.<p>
+ *
+ * Generally, the default load factor (.75) offers a good tradeoff between
+ * time and space costs.  Higher values decrease the space overhead but
+ * increase the time cost to look up an entry (which is reflected in most
+ * <tt>SymbolTable</tt> operations, including <tt>addSymbol</tt> and <tt>containsSymbol</tt>).<p>
+ *
+ * The initial capacity controls a tradeoff between wasted space and the
+ * need for <code>rehash</code> operations, which are time-consuming.
+ * No <code>rehash</code> operations will <i>ever</i> occur if the initial
+ * capacity is greater than the maximum number of entries the
+ * <tt>Hashtable</tt> will contain divided by its load factor.  However,
+ * setting the initial capacity too high can waste space.<p>
+ *
+ * If many entries are to be made into a <code>SymbolTable</code>, 
+ * creating it with a sufficiently large capacity may allow the 
+ * entries to be inserted more efficiently than letting it perform 
+ * automatic rehashing as needed to grow the table. <p>
+
+ * @see SymbolHash
+ *
+ * @author Andy Clark
+ * @author John Kim, IBM
+ *
+ * @version $Id: SymbolTable.java 985518 2010-08-14 16:02:52Z mrglavas $
+ */
+public class SymbolTable {
+
+    //
+    // Constants
+    //
+
+    /** Default table size. */
+    protected static final int TABLE_SIZE = 101;
+
+    //
+    // Data
+    //
+
+    /** Buckets. */
+    protected Entry[] fBuckets = null;
+
+    /** actual table size **/
+    protected int fTableSize;
+
+    /** The total number of entries in the hash table. */
+    protected transient int fCount;
+
+    /** The table is rehashed when its size exceeds this threshold.  (The
+     * value of this field is (int)(capacity * loadFactor).) */
+    protected int fThreshold;
+							 
+    /** The load factor for the SymbolTable. */
+    protected float fLoadFactor;
+
+    //
+    // Constructors
+    //
+    
+    /**
+     * Constructs a new, empty SymbolTable with the specified initial 
+     * capacity and the specified load factor.
+     *
+     * @param      initialCapacity   the initial capacity of the SymbolTable.
+     * @param      loadFactor        the load factor of the SymbolTable.
+     * @throws     IllegalArgumentException  if the initial capacity is less
+     *             than zero, or if the load factor is nonpositive.
+     */
+    public SymbolTable(int initialCapacity, float loadFactor) {
+        
+        if (initialCapacity < 0) {
+            throw new IllegalArgumentException("Illegal Capacity: " + initialCapacity);
+        }
+        
+        if (loadFactor <= 0 || Float.isNaN(loadFactor)) {
+            throw new IllegalArgumentException("Illegal Load: " + loadFactor);
+        }
+        
+        if (initialCapacity == 0) {
+            initialCapacity = 1;
+        }
+        
+        fLoadFactor = loadFactor;
+        fTableSize = initialCapacity;
+        fBuckets = new Entry[fTableSize];
+        fThreshold = (int)(fTableSize * loadFactor);
+        fCount = 0;
+    }
+
+    /**
+     * Constructs a new, empty SymbolTable with the specified initial capacity
+     * and default load factor, which is <tt>0.75</tt>.
+     *
+     * @param     initialCapacity   the initial capacity of the hashtable.
+     * @throws    IllegalArgumentException if the initial capacity is less
+     *            than zero.
+     */
+    public SymbolTable(int initialCapacity) {
+        this(initialCapacity, 0.75f);
+    }
+    
+    /**
+     * Constructs a new, empty SymbolTable with a default initial capacity (101)
+     * and load factor, which is <tt>0.75</tt>. 
+     */
+    public SymbolTable() {
+        this(TABLE_SIZE, 0.75f);
+    }
+
+    //
+    // Public methods
+    //
+
+    /**
+     * Adds the specified symbol to the symbol table and returns a
+     * reference to the unique symbol. If the symbol already exists,
+     * the previous symbol reference is returned instead, in order
+     * guarantee that symbol references remain unique.
+     *
+     * @param symbol The new symbol.
+     */
+    public String addSymbol(String symbol) {
+        
+        // search for identical symbol
+        int bucket = hash(symbol) % fTableSize;
+        for (Entry entry = fBuckets[bucket]; entry != null; entry = entry.next) {
+            if (entry.symbol.equals(symbol)) {
+                return entry.symbol;
+            }
+        }
+        
+        if (fCount >= fThreshold) {
+            // Rehash the table if the threshold is exceeded
+            rehash();
+            bucket = hash(symbol) % fTableSize;
+        } 
+        
+        // create new entry
+        Entry entry = new Entry(symbol, fBuckets[bucket]);
+        fBuckets[bucket] = entry;
+        ++fCount;
+        return entry.symbol;
+        
+    } // addSymbol(String):String
+
+    /**
+     * Adds the specified symbol to the symbol table and returns a
+     * reference to the unique symbol. If the symbol already exists,
+     * the previous symbol reference is returned instead, in order
+     * guarantee that symbol references remain unique.
+     *
+     * @param buffer The buffer containing the new symbol.
+     * @param offset The offset into the buffer of the new symbol.
+     * @param length The length of the new symbol in the buffer.
+     */
+    public String addSymbol(char[] buffer, int offset, int length) {
+        
+        // search for identical symbol
+        int bucket = hash(buffer, offset, length) % fTableSize;
+        OUTER: for (Entry entry = fBuckets[bucket]; entry != null; entry = entry.next) {
+            if (length == entry.characters.length) {
+                for (int i = 0; i < length; i++) {
+                    if (buffer[offset + i] != entry.characters[i]) {
+                        continue OUTER;
+                    }
+                }
+                return entry.symbol;
+            }
+        }
+        
+        if (fCount >= fThreshold) {
+            // Rehash the table if the threshold is exceeded
+            rehash();
+            bucket = hash(buffer, offset, length) % fTableSize;
+        } 
+        
+        // add new entry
+        Entry entry = new Entry(buffer, offset, length, fBuckets[bucket]);
+        fBuckets[bucket] = entry;
+        ++fCount;
+        return entry.symbol;
+        
+    } // addSymbol(char[],int,int):String
+
+    /**
+     * Returns a hashcode value for the specified symbol. The value
+     * returned by this method must be identical to the value returned
+     * by the <code>hash(char[],int,int)</code> method when called
+     * with the character array that comprises the symbol string.
+     *
+     * @param symbol The symbol to hash.
+     */
+    public int hash(String symbol) {
+        return symbol.hashCode() & 0x7FFFFFFF;
+    } // hash(String):int
+
+    /**
+     * Returns a hashcode value for the specified symbol information.
+     * The value returned by this method must be identical to the value
+     * returned by the <code>hash(String)</code> method when called
+     * with the string object created from the symbol information.
+     *
+     * @param buffer The character buffer containing the symbol.
+     * @param offset The offset into the character buffer of the start
+     *               of the symbol.
+     * @param length The length of the symbol.
+     */
+    public int hash(char[] buffer, int offset, int length) {
+
+        int code = 0;
+        for (int i = 0; i < length; ++i) {
+            code = code * 31 + buffer[offset + i];
+        }
+        return code & 0x7FFFFFFF;
+
+    } // hash(char[],int,int):int
+
+    /**
+     * Increases the capacity of and internally reorganizes this 
+     * SymbolTable, in order to accommodate and access its entries more 
+     * efficiently.  This method is called automatically when the 
+     * number of keys in the SymbolTable exceeds this hashtable's capacity 
+     * and load factor. 
+     */
+    protected void rehash() {
+
+        int oldCapacity = fBuckets.length;
+        Entry[] oldTable = fBuckets;
+
+        int newCapacity = oldCapacity * 2 + 1;
+        Entry[] newTable = new Entry[newCapacity];
+
+        fThreshold = (int)(newCapacity * fLoadFactor);
+        fBuckets = newTable;
+        fTableSize = fBuckets.length;
+
+        for (int i = oldCapacity ; i-- > 0 ;) {
+            for (Entry old = oldTable[i] ; old != null ; ) {
+                Entry e = old;
+                old = old.next;
+
+                int index = hash(e.characters, 0, e.characters.length) % newCapacity;
+                e.next = newTable[index];
+                newTable[index] = e;
+            }
+        }
+    }
+
+    /**
+     * Returns true if the symbol table already contains the specified
+     * symbol.
+     *
+     * @param symbol The symbol to look for.
+     */
+    public boolean containsSymbol(String symbol) {
+
+        // search for identical symbol
+        int bucket = hash(symbol) % fTableSize;
+        int length = symbol.length();
+        OUTER: for (Entry entry = fBuckets[bucket]; entry != null; entry = entry.next) {
+            if (length == entry.characters.length) {
+                for (int i = 0; i < length; i++) {
+                    if (symbol.charAt(i) != entry.characters[i]) {
+                        continue OUTER;
+                    }
+                }
+                return true;
+            }
+        }
+
+        return false;
+
+    } // containsSymbol(String):boolean
+
+    /**
+     * Returns true if the symbol table already contains the specified
+     * symbol.
+     *
+     * @param buffer The buffer containing the symbol to look for.
+     * @param offset The offset into the buffer.
+     * @param length The length of the symbol in the buffer.
+     */
+    public boolean containsSymbol(char[] buffer, int offset, int length) {
+
+        // search for identical symbol
+        int bucket = hash(buffer, offset, length) % fTableSize;
+        OUTER: for (Entry entry = fBuckets[bucket]; entry != null; entry = entry.next) {
+            if (length == entry.characters.length) {
+                for (int i = 0; i < length; i++) {
+                    if (buffer[offset + i] != entry.characters[i]) {
+                        continue OUTER;
+                    }
+                }
+                return true;
+            }
+        }
+
+        return false;
+
+    } // containsSymbol(char[],int,int):boolean
+
+    //
+    // Classes
+    //
+
+    /**
+     * This class is a symbol table entry. Each entry acts as a node
+     * in a linked list.
+     */
+    protected static final class Entry {
+
+        //
+        // Data
+        //
+
+        /** Symbol. */
+        public final String symbol;
+
+        /**
+         * Symbol characters. This information is duplicated here for
+         * comparison performance.
+         */
+        public final char[] characters;
+
+        /** The next entry. */
+        public Entry next;
+
+        //
+        // Constructors
+        //
+
+        /**
+         * Constructs a new entry from the specified symbol and next entry
+         * reference.
+         */
+        public Entry(String symbol, Entry next) {
+            this.symbol = symbol.intern();
+            characters = new char[symbol.length()];
+            symbol.getChars(0, characters.length, characters, 0);
+            this.next = next;
+        }
+
+        /**
+         * Constructs a new entry from the specified symbol information and
+         * next entry reference.
+         */
+        public Entry(char[] ch, int offset, int length, Entry next) {
+            characters = new char[length];
+            System.arraycopy(ch, offset, characters, 0, length);
+            symbol = new String(characters).intern();
+            this.next = next;
+        }
+
+    } // class Entry
+
+} // class SymbolTable


[06/24] jena git commit: JENA-1537: Remove dependency on Xerces. Import needed code

Posted by an...@apache.org.
http://git-wip-us.apache.org/repos/asf/jena/blob/c9a7e646/jena-core/src/main/java/org/apache/jena/ext/xerces/util/XML11Char.java
----------------------------------------------------------------------
diff --git a/jena-core/src/main/java/org/apache/jena/ext/xerces/util/XML11Char.java b/jena-core/src/main/java/org/apache/jena/ext/xerces/util/XML11Char.java
new file mode 100644
index 0000000..40c3d1f
--- /dev/null
+++ b/jena-core/src/main/java/org/apache/jena/ext/xerces/util/XML11Char.java
@@ -0,0 +1,413 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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.jena.ext.xerces.util;
+
+import java.util.Arrays;
+
+/**
+ * This class defines the basic properties of characters in XML 1.1. The data
+ * in this class can be used to verify that a character is a valid
+ * XML 1.1 character or if the character is a space, name start, or name
+ * character.
+ * <p>
+ * A series of convenience methods are supplied to ease the burden
+ * of the developer.  Using the character as an index into the <code>XML11CHARS</code>
+ * array and applying the appropriate mask flag (e.g.
+ * <code>MASK_VALID</code>), yields the same results as calling the
+ * convenience methods. There is one exception: check the comments
+ * for the <code>isValid</code> method for details.
+ *
+ * @author Glenn Marcy, IBM
+ * @author Andy Clark, IBM
+ * @author Arnaud  Le Hors, IBM
+ * @author Neil Graham, IBM
+ * @author Michael Glavassevich, IBM
+ *
+ * @version $Id: XML11Char.java 674378 2008-07-07 00:52:45Z mrglavas $
+ */
+public class XML11Char {
+
+    //
+    // Constants
+    //
+
+    /** Character flags for XML 1.1. */
+    private static final byte XML11CHARS [] = new byte [1 << 16];
+
+    /** XML 1.1 Valid character mask. */
+    public static final int MASK_XML11_VALID = 0x01;
+
+    /** XML 1.1 Space character mask. */
+    public static final int MASK_XML11_SPACE = 0x02;
+
+    /** XML 1.1 Name start character mask. */
+    public static final int MASK_XML11_NAME_START = 0x04;
+
+    /** XML 1.1 Name character mask. */
+    public static final int MASK_XML11_NAME = 0x08;
+
+    /** XML 1.1 control character mask */
+    public static final int MASK_XML11_CONTROL = 0x10;
+
+    /** XML 1.1 content for external entities (valid - "special" chars - control chars) */
+    public static final int MASK_XML11_CONTENT = 0x20;
+
+    /** XML namespaces 1.1 NCNameStart */
+    public static final int MASK_XML11_NCNAME_START = 0x40;
+
+    /** XML namespaces 1.1 NCName */
+    public static final int MASK_XML11_NCNAME = 0x80;
+    
+    /** XML 1.1 content for internal entities (valid - "special" chars) */
+    public static final int MASK_XML11_CONTENT_INTERNAL = MASK_XML11_CONTROL | MASK_XML11_CONTENT; 
+
+    //
+    // Static initialization
+    //
+
+    static {
+    	
+        // Initializing the Character Flag Array
+        // Code generated by: XML11CharGenerator.
+        
+        Arrays.fill(XML11CHARS, 1, 9, (byte) 17 ); // Fill 8 of value (byte) 17
+        XML11CHARS[9] = 35;
+        XML11CHARS[10] = 3;
+        Arrays.fill(XML11CHARS, 11, 13, (byte) 17 ); // Fill 2 of value (byte) 17
+        XML11CHARS[13] = 3;
+        Arrays.fill(XML11CHARS, 14, 32, (byte) 17 ); // Fill 18 of value (byte) 17
+        XML11CHARS[32] = 35;
+        Arrays.fill(XML11CHARS, 33, 38, (byte) 33 ); // Fill 5 of value (byte) 33
+        XML11CHARS[38] = 1;
+        Arrays.fill(XML11CHARS, 39, 45, (byte) 33 ); // Fill 6 of value (byte) 33
+        Arrays.fill(XML11CHARS, 45, 47, (byte) -87 ); // Fill 2 of value (byte) -87
+        XML11CHARS[47] = 33;
+        Arrays.fill(XML11CHARS, 48, 58, (byte) -87 ); // Fill 10 of value (byte) -87
+        XML11CHARS[58] = 45;
+        XML11CHARS[59] = 33;
+        XML11CHARS[60] = 1;
+        Arrays.fill(XML11CHARS, 61, 65, (byte) 33 ); // Fill 4 of value (byte) 33
+        Arrays.fill(XML11CHARS, 65, 91, (byte) -19 ); // Fill 26 of value (byte) -19
+        Arrays.fill(XML11CHARS, 91, 93, (byte) 33 ); // Fill 2 of value (byte) 33
+        XML11CHARS[93] = 1;
+        XML11CHARS[94] = 33;
+        XML11CHARS[95] = -19;
+        XML11CHARS[96] = 33;
+        Arrays.fill(XML11CHARS, 97, 123, (byte) -19 ); // Fill 26 of value (byte) -19
+        Arrays.fill(XML11CHARS, 123, 127, (byte) 33 ); // Fill 4 of value (byte) 33
+        Arrays.fill(XML11CHARS, 127, 133, (byte) 17 ); // Fill 6 of value (byte) 17
+        XML11CHARS[133] = 35;
+        Arrays.fill(XML11CHARS, 134, 160, (byte) 17 ); // Fill 26 of value (byte) 17
+        Arrays.fill(XML11CHARS, 160, 183, (byte) 33 ); // Fill 23 of value (byte) 33
+        XML11CHARS[183] = -87;
+        Arrays.fill(XML11CHARS, 184, 192, (byte) 33 ); // Fill 8 of value (byte) 33
+        Arrays.fill(XML11CHARS, 192, 215, (byte) -19 ); // Fill 23 of value (byte) -19
+        XML11CHARS[215] = 33;
+        Arrays.fill(XML11CHARS, 216, 247, (byte) -19 ); // Fill 31 of value (byte) -19
+        XML11CHARS[247] = 33;
+        Arrays.fill(XML11CHARS, 248, 768, (byte) -19 ); // Fill 520 of value (byte) -19
+        Arrays.fill(XML11CHARS, 768, 880, (byte) -87 ); // Fill 112 of value (byte) -87
+        Arrays.fill(XML11CHARS, 880, 894, (byte) -19 ); // Fill 14 of value (byte) -19
+        XML11CHARS[894] = 33;
+        Arrays.fill(XML11CHARS, 895, 8192, (byte) -19 ); // Fill 7297 of value (byte) -19
+        Arrays.fill(XML11CHARS, 8192, 8204, (byte) 33 ); // Fill 12 of value (byte) 33
+        Arrays.fill(XML11CHARS, 8204, 8206, (byte) -19 ); // Fill 2 of value (byte) -19
+        Arrays.fill(XML11CHARS, 8206, 8232, (byte) 33 ); // Fill 26 of value (byte) 33
+        XML11CHARS[8232] = 35;
+        Arrays.fill(XML11CHARS, 8233, 8255, (byte) 33 ); // Fill 22 of value (byte) 33
+        Arrays.fill(XML11CHARS, 8255, 8257, (byte) -87 ); // Fill 2 of value (byte) -87
+        Arrays.fill(XML11CHARS, 8257, 8304, (byte) 33 ); // Fill 47 of value (byte) 33
+        Arrays.fill(XML11CHARS, 8304, 8592, (byte) -19 ); // Fill 288 of value (byte) -19
+        Arrays.fill(XML11CHARS, 8592, 11264, (byte) 33 ); // Fill 2672 of value (byte) 33
+        Arrays.fill(XML11CHARS, 11264, 12272, (byte) -19 ); // Fill 1008 of value (byte) -19
+        Arrays.fill(XML11CHARS, 12272, 12289, (byte) 33 ); // Fill 17 of value (byte) 33
+        Arrays.fill(XML11CHARS, 12289, 55296, (byte) -19 ); // Fill 43007 of value (byte) -19
+        Arrays.fill(XML11CHARS, 57344, 63744, (byte) 33 ); // Fill 6400 of value (byte) 33
+        Arrays.fill(XML11CHARS, 63744, 64976, (byte) -19 ); // Fill 1232 of value (byte) -19
+        Arrays.fill(XML11CHARS, 64976, 65008, (byte) 33 ); // Fill 32 of value (byte) 33
+        Arrays.fill(XML11CHARS, 65008, 65534, (byte) -19 ); // Fill 526 of value (byte) -19
+
+    } // <clinit>()
+
+    //
+    // Public static methods
+    //
+
+    /**
+     * Returns true if the specified character is a space character
+     * as amdended in the XML 1.1 specification.
+     *
+     * @param c The character to check.
+     */
+    public static boolean isXML11Space(int c) {
+        return (c < 0x10000 && (XML11CHARS[c] & MASK_XML11_SPACE) != 0);
+    } // isXML11Space(int):boolean
+
+    /**
+     * Returns true if the specified character is valid. This method
+     * also checks the surrogate character range from 0x10000 to 0x10FFFF.
+     * <p>
+     * If the program chooses to apply the mask directly to the
+     * <code>XML11CHARS</code> array, then they are responsible for checking
+     * the surrogate character range.
+     *
+     * @param c The character to check.
+     */
+    public static boolean isXML11Valid(int c) {
+        return (c < 0x10000 && (XML11CHARS[c] & MASK_XML11_VALID) != 0) 
+                || (0x10000 <= c && c <= 0x10FFFF);
+    } // isXML11Valid(int):boolean
+
+    /**
+     * Returns true if the specified character is invalid.
+     *
+     * @param c The character to check.
+     */
+    public static boolean isXML11Invalid(int c) {
+        return !isXML11Valid(c);
+    } // isXML11Invalid(int):boolean
+
+    /**
+     * Returns true if the specified character is valid and permitted outside
+     * of a character reference.  
+     * That is, this method will return false for the same set as
+     * isXML11Valid, except it also reports false for "control characters".
+     *
+     * @param c The character to check.
+     */
+    public static boolean isXML11ValidLiteral(int c) {
+        return ((c < 0x10000 && ((XML11CHARS[c] & MASK_XML11_VALID) != 0 && (XML11CHARS[c] & MASK_XML11_CONTROL) == 0))
+            || (0x10000 <= c && c <= 0x10FFFF)); 
+    } // isXML11ValidLiteral(int):boolean
+
+    /**
+     * Returns true if the specified character can be considered 
+     * content in an external parsed entity.
+     *
+     * @param c The character to check.
+     */
+    public static boolean isXML11Content(int c) {
+        return (c < 0x10000 && (XML11CHARS[c] & MASK_XML11_CONTENT) != 0) ||
+               (0x10000 <= c && c <= 0x10FFFF);
+    } // isXML11Content(int):boolean
+    
+    /**
+     * Returns true if the specified character can be considered 
+     * content in an internal parsed entity.
+     *
+     * @param c The character to check.
+     */
+    public static boolean isXML11InternalEntityContent(int c) {
+        return (c < 0x10000 && (XML11CHARS[c] & MASK_XML11_CONTENT_INTERNAL) != 0) ||
+               (0x10000 <= c && c <= 0x10FFFF);
+    } // isXML11InternalEntityContent(int):boolean
+
+    /**
+     * Returns true if the specified character is a valid name start
+     * character as defined by production [4] in the XML 1.1
+     * specification.
+     *
+     * @param c The character to check.
+     */
+    public static boolean isXML11NameStart(int c) {
+        return (c < 0x10000 && (XML11CHARS[c] & MASK_XML11_NAME_START) != 0)
+            || (0x10000 <= c && c < 0xF0000);
+    } // isXML11NameStart(int):boolean
+
+    /**
+     * Returns true if the specified character is a valid name
+     * character as defined by production [4a] in the XML 1.1
+     * specification.
+     *
+     * @param c The character to check.
+     */
+    public static boolean isXML11Name(int c) {
+        return (c < 0x10000 && (XML11CHARS[c] & MASK_XML11_NAME) != 0) 
+            || (c >= 0x10000 && c < 0xF0000);
+    } // isXML11Name(int):boolean
+
+    /**
+     * Returns true if the specified character is a valid NCName start
+     * character as defined by production [4] in Namespaces in XML
+     * 1.1 recommendation.
+     *
+     * @param c The character to check.
+     */
+    public static boolean isXML11NCNameStart(int c) {
+        return (c < 0x10000 && (XML11CHARS[c] & MASK_XML11_NCNAME_START) != 0)
+            || (0x10000 <= c && c < 0xF0000);
+    } // isXML11NCNameStart(int):boolean
+
+    /**
+     * Returns true if the specified character is a valid NCName
+     * character as defined by production [5] in Namespaces in XML
+     * 1.1 recommendation.
+     *
+     * @param c The character to check.
+     */
+    public static boolean isXML11NCName(int c) {
+        return (c < 0x10000 && (XML11CHARS[c] & MASK_XML11_NCNAME) != 0)
+            || (0x10000 <= c && c < 0xF0000);
+    } // isXML11NCName(int):boolean
+    
+    /**
+     * Returns whether the given character is a valid 
+     * high surrogate for a name character. This includes
+     * all high surrogates for characters [0x10000-0xEFFFF].
+     * In other words everything excluding planes 15 and 16.
+     *
+     * @param c The character to check.
+     */
+    public static boolean isXML11NameHighSurrogate(int c) {
+        return (0xD800 <= c && c <= 0xDB7F);
+    }
+
+    /*
+     * [5] Name ::= NameStartChar NameChar*
+     */
+    /**
+     * Check to see if a string is a valid Name according to [5]
+     * in the XML 1.1 Recommendation
+     *
+     * @param name string to check
+     * @return true if name is a valid Name
+     */
+    public static boolean isXML11ValidName(String name) {
+        final int length = name.length();
+        if (length == 0) {
+            return false;
+        }
+        int i = 1;
+        char ch = name.charAt(0);
+        if (!isXML11NameStart(ch)) {
+            if (length > 1 && isXML11NameHighSurrogate(ch)) {
+                char ch2 = name.charAt(1);
+                if (!XMLChar.isLowSurrogate(ch2) || 
+                    !isXML11NameStart(XMLChar.supplemental(ch, ch2))) {
+                    return false;
+                }
+                i = 2;
+            }
+            else {
+                return false;
+            }
+        }
+        while (i < length) {
+            ch = name.charAt(i);
+            if (!isXML11Name(ch)) {
+                if (++i < length && isXML11NameHighSurrogate(ch)) {
+                    char ch2 = name.charAt(i);
+                    if (!XMLChar.isLowSurrogate(ch2) || 
+                        !isXML11Name(XMLChar.supplemental(ch, ch2))) {
+                        return false;
+                    }
+                }
+                else {
+                    return false;
+                }
+            }
+            ++i;
+        }
+        return true;
+    } // isXML11ValidName(String):boolean
+    
+    /*
+     * from the namespace 1.1 rec
+     * [4] NCName ::= NCNameStartChar NCNameChar*
+     */
+    /**
+     * Check to see if a string is a valid NCName according to [4]
+     * from the XML Namespaces 1.1 Recommendation
+     *
+     * @param ncName string to check
+     * @return true if name is a valid NCName
+     */
+    public static boolean isXML11ValidNCName(String ncName) {
+        final int length = ncName.length();
+        if (length == 0) {
+            return false;
+        }
+        int i = 1;
+        char ch = ncName.charAt(0);
+        if (!isXML11NCNameStart(ch)) {
+            if (length > 1 && isXML11NameHighSurrogate(ch)) {
+                char ch2 = ncName.charAt(1);
+                if (!XMLChar.isLowSurrogate(ch2) || 
+                    !isXML11NCNameStart(XMLChar.supplemental(ch, ch2))) {
+                    return false;
+                }
+                i = 2;
+            }
+            else {
+                return false;
+            }
+        }
+        while (i < length) {
+            ch = ncName.charAt(i);
+            if (!isXML11NCName(ch)) {
+                if (++i < length && isXML11NameHighSurrogate(ch)) {
+                    char ch2 = ncName.charAt(i);
+                    if (!XMLChar.isLowSurrogate(ch2) || 
+                        !isXML11NCName(XMLChar.supplemental(ch, ch2))) {
+                        return false;
+                    }
+                }
+                else {
+                    return false;
+                }
+            }
+            ++i;
+        }
+        return true;
+    } // isXML11ValidNCName(String):boolean
+
+    /*
+     * [7] Nmtoken ::= (NameChar)+
+     */
+    /**
+     * Check to see if a string is a valid Nmtoken according to [7]
+     * in the XML 1.1 Recommendation
+     *
+     * @param nmtoken string to check
+     * @return true if nmtoken is a valid Nmtoken 
+     */
+    public static boolean isXML11ValidNmtoken(String nmtoken) {
+        final int length = nmtoken.length();
+        if (length == 0) {
+            return false;
+        }
+        for (int i = 0; i < length; ++i) {
+            char ch = nmtoken.charAt(i);
+            if (!isXML11Name(ch)) {
+                if (++i < length && isXML11NameHighSurrogate(ch)) {
+                    char ch2 = nmtoken.charAt(i);
+                    if (!XMLChar.isLowSurrogate(ch2) || 
+                        !isXML11Name(XMLChar.supplemental(ch, ch2))) {
+                        return false;
+                    }
+                }
+                else {
+                    return false;
+                }
+            }
+        }
+        return true;
+    } // isXML11ValidName(String):boolean
+
+} // class XML11Char
+

http://git-wip-us.apache.org/repos/asf/jena/blob/c9a7e646/jena-core/src/main/java/org/apache/jena/ext/xerces/util/XMLChar.java
----------------------------------------------------------------------
diff --git a/jena-core/src/main/java/org/apache/jena/ext/xerces/util/XMLChar.java b/jena-core/src/main/java/org/apache/jena/ext/xerces/util/XMLChar.java
new file mode 100644
index 0000000..2e58351
--- /dev/null
+++ b/jena-core/src/main/java/org/apache/jena/ext/xerces/util/XMLChar.java
@@ -0,0 +1,1062 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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.jena.ext.xerces.util;
+
+import java.util.Arrays;
+
+/**
+ * This class defines the basic XML character properties. The data
+ * in this class can be used to verify that a character is a valid
+ * XML character or if the character is a space, name start, or name
+ * character.
+ * <p>
+ * A series of convenience methods are supplied to ease the burden
+ * of the developer. Because inlining the checks can improve per
+ * character performance, the tables of character properties are
+ * public. Using the character as an index into the <code>CHARS</code>
+ * array and applying the appropriate mask flag (e.g.
+ * <code>MASK_VALID</code>), yields the same results as calling the
+ * convenience methods. There is one exception: check the comments
+ * for the <code>isValid</code> method for details.
+ *
+ * @author Glenn Marcy, IBM
+ * @author Andy Clark, IBM
+ * @author Eric Ye, IBM
+ * @author Arnaud  Le Hors, IBM
+ * @author Michael Glavassevich, IBM
+ * @author Rahul Srivastava, Sun Microsystems Inc.
+ *
+ * @version $Id: XMLChar.java 674378 2008-07-07 00:52:45Z mrglavas $
+ */
+public class XMLChar {
+
+    //
+    // Constants
+    //
+
+    /** Character flags. */
+    private static final byte[] CHARS = new byte[1 << 16];
+
+    /** Valid character mask. */
+    public static final int MASK_VALID = 0x01;
+
+    /** Space character mask. */
+    public static final int MASK_SPACE = 0x02;
+
+    /** Name start character mask. */
+    public static final int MASK_NAME_START = 0x04;
+
+    /** Name character mask. */
+    public static final int MASK_NAME = 0x08;
+
+    /** Pubid character mask. */
+    public static final int MASK_PUBID = 0x10;
+    
+    /** 
+     * Content character mask. Special characters are those that can
+     * be considered the start of markup, such as '&lt;' and '&amp;'. 
+     * The various newline characters are considered special as well.
+     * All other valid XML characters can be considered content.
+     * <p>
+     * This is an optimization for the inner loop of character scanning.
+     */
+    public static final int MASK_CONTENT = 0x20;
+
+    /** NCName start character mask. */
+    public static final int MASK_NCNAME_START = 0x40;
+
+    /** NCName character mask. */
+    public static final int MASK_NCNAME = 0x80;
+
+    //
+    // Static initialization
+    //
+
+    static {
+        
+        // Initializing the Character Flag Array
+        // Code generated by: XMLCharGenerator.
+        
+        CHARS[9] = 35;
+        CHARS[10] = 19;
+        CHARS[13] = 19;
+        CHARS[32] = 51;
+        CHARS[33] = 49;
+        CHARS[34] = 33;
+        Arrays.fill(CHARS, 35, 38, (byte) 49 ); // Fill 3 of value (byte) 49
+        CHARS[38] = 1;
+        Arrays.fill(CHARS, 39, 45, (byte) 49 ); // Fill 6 of value (byte) 49
+        Arrays.fill(CHARS, 45, 47, (byte) -71 ); // Fill 2 of value (byte) -71
+        CHARS[47] = 49;
+        Arrays.fill(CHARS, 48, 58, (byte) -71 ); // Fill 10 of value (byte) -71
+        CHARS[58] = 61;
+        CHARS[59] = 49;
+        CHARS[60] = 1;
+        CHARS[61] = 49;
+        CHARS[62] = 33;
+        Arrays.fill(CHARS, 63, 65, (byte) 49 ); // Fill 2 of value (byte) 49
+        Arrays.fill(CHARS, 65, 91, (byte) -3 ); // Fill 26 of value (byte) -3
+        Arrays.fill(CHARS, 91, 93, (byte) 33 ); // Fill 2 of value (byte) 33
+        CHARS[93] = 1;
+        CHARS[94] = 33;
+        CHARS[95] = -3;
+        CHARS[96] = 33;
+        Arrays.fill(CHARS, 97, 123, (byte) -3 ); // Fill 26 of value (byte) -3
+        Arrays.fill(CHARS, 123, 183, (byte) 33 ); // Fill 60 of value (byte) 33
+        CHARS[183] = -87;
+        Arrays.fill(CHARS, 184, 192, (byte) 33 ); // Fill 8 of value (byte) 33
+        Arrays.fill(CHARS, 192, 215, (byte) -19 ); // Fill 23 of value (byte) -19
+        CHARS[215] = 33;
+        Arrays.fill(CHARS, 216, 247, (byte) -19 ); // Fill 31 of value (byte) -19
+        CHARS[247] = 33;
+        Arrays.fill(CHARS, 248, 306, (byte) -19 ); // Fill 58 of value (byte) -19
+        Arrays.fill(CHARS, 306, 308, (byte) 33 ); // Fill 2 of value (byte) 33
+        Arrays.fill(CHARS, 308, 319, (byte) -19 ); // Fill 11 of value (byte) -19
+        Arrays.fill(CHARS, 319, 321, (byte) 33 ); // Fill 2 of value (byte) 33
+        Arrays.fill(CHARS, 321, 329, (byte) -19 ); // Fill 8 of value (byte) -19
+        CHARS[329] = 33;
+        Arrays.fill(CHARS, 330, 383, (byte) -19 ); // Fill 53 of value (byte) -19
+        CHARS[383] = 33;
+        Arrays.fill(CHARS, 384, 452, (byte) -19 ); // Fill 68 of value (byte) -19
+        Arrays.fill(CHARS, 452, 461, (byte) 33 ); // Fill 9 of value (byte) 33
+        Arrays.fill(CHARS, 461, 497, (byte) -19 ); // Fill 36 of value (byte) -19
+        Arrays.fill(CHARS, 497, 500, (byte) 33 ); // Fill 3 of value (byte) 33
+        Arrays.fill(CHARS, 500, 502, (byte) -19 ); // Fill 2 of value (byte) -19
+        Arrays.fill(CHARS, 502, 506, (byte) 33 ); // Fill 4 of value (byte) 33
+        Arrays.fill(CHARS, 506, 536, (byte) -19 ); // Fill 30 of value (byte) -19
+        Arrays.fill(CHARS, 536, 592, (byte) 33 ); // Fill 56 of value (byte) 33
+        Arrays.fill(CHARS, 592, 681, (byte) -19 ); // Fill 89 of value (byte) -19
+        Arrays.fill(CHARS, 681, 699, (byte) 33 ); // Fill 18 of value (byte) 33
+        Arrays.fill(CHARS, 699, 706, (byte) -19 ); // Fill 7 of value (byte) -19
+        Arrays.fill(CHARS, 706, 720, (byte) 33 ); // Fill 14 of value (byte) 33
+        Arrays.fill(CHARS, 720, 722, (byte) -87 ); // Fill 2 of value (byte) -87
+        Arrays.fill(CHARS, 722, 768, (byte) 33 ); // Fill 46 of value (byte) 33
+        Arrays.fill(CHARS, 768, 838, (byte) -87 ); // Fill 70 of value (byte) -87
+        Arrays.fill(CHARS, 838, 864, (byte) 33 ); // Fill 26 of value (byte) 33
+        Arrays.fill(CHARS, 864, 866, (byte) -87 ); // Fill 2 of value (byte) -87
+        Arrays.fill(CHARS, 866, 902, (byte) 33 ); // Fill 36 of value (byte) 33
+        CHARS[902] = -19;
+        CHARS[903] = -87;
+        Arrays.fill(CHARS, 904, 907, (byte) -19 ); // Fill 3 of value (byte) -19
+        CHARS[907] = 33;
+        CHARS[908] = -19;
+        CHARS[909] = 33;
+        Arrays.fill(CHARS, 910, 930, (byte) -19 ); // Fill 20 of value (byte) -19
+        CHARS[930] = 33;
+        Arrays.fill(CHARS, 931, 975, (byte) -19 ); // Fill 44 of value (byte) -19
+        CHARS[975] = 33;
+        Arrays.fill(CHARS, 976, 983, (byte) -19 ); // Fill 7 of value (byte) -19
+        Arrays.fill(CHARS, 983, 986, (byte) 33 ); // Fill 3 of value (byte) 33
+        CHARS[986] = -19;
+        CHARS[987] = 33;
+        CHARS[988] = -19;
+        CHARS[989] = 33;
+        CHARS[990] = -19;
+        CHARS[991] = 33;
+        CHARS[992] = -19;
+        CHARS[993] = 33;
+        Arrays.fill(CHARS, 994, 1012, (byte) -19 ); // Fill 18 of value (byte) -19
+        Arrays.fill(CHARS, 1012, 1025, (byte) 33 ); // Fill 13 of value (byte) 33
+        Arrays.fill(CHARS, 1025, 1037, (byte) -19 ); // Fill 12 of value (byte) -19
+        CHARS[1037] = 33;
+        Arrays.fill(CHARS, 1038, 1104, (byte) -19 ); // Fill 66 of value (byte) -19
+        CHARS[1104] = 33;
+        Arrays.fill(CHARS, 1105, 1117, (byte) -19 ); // Fill 12 of value (byte) -19
+        CHARS[1117] = 33;
+        Arrays.fill(CHARS, 1118, 1154, (byte) -19 ); // Fill 36 of value (byte) -19
+        CHARS[1154] = 33;
+        Arrays.fill(CHARS, 1155, 1159, (byte) -87 ); // Fill 4 of value (byte) -87
+        Arrays.fill(CHARS, 1159, 1168, (byte) 33 ); // Fill 9 of value (byte) 33
+        Arrays.fill(CHARS, 1168, 1221, (byte) -19 ); // Fill 53 of value (byte) -19
+        Arrays.fill(CHARS, 1221, 1223, (byte) 33 ); // Fill 2 of value (byte) 33
+        Arrays.fill(CHARS, 1223, 1225, (byte) -19 ); // Fill 2 of value (byte) -19
+        Arrays.fill(CHARS, 1225, 1227, (byte) 33 ); // Fill 2 of value (byte) 33
+        Arrays.fill(CHARS, 1227, 1229, (byte) -19 ); // Fill 2 of value (byte) -19
+        Arrays.fill(CHARS, 1229, 1232, (byte) 33 ); // Fill 3 of value (byte) 33
+        Arrays.fill(CHARS, 1232, 1260, (byte) -19 ); // Fill 28 of value (byte) -19
+        Arrays.fill(CHARS, 1260, 1262, (byte) 33 ); // Fill 2 of value (byte) 33
+        Arrays.fill(CHARS, 1262, 1270, (byte) -19 ); // Fill 8 of value (byte) -19
+        Arrays.fill(CHARS, 1270, 1272, (byte) 33 ); // Fill 2 of value (byte) 33
+        Arrays.fill(CHARS, 1272, 1274, (byte) -19 ); // Fill 2 of value (byte) -19
+        Arrays.fill(CHARS, 1274, 1329, (byte) 33 ); // Fill 55 of value (byte) 33
+        Arrays.fill(CHARS, 1329, 1367, (byte) -19 ); // Fill 38 of value (byte) -19
+        Arrays.fill(CHARS, 1367, 1369, (byte) 33 ); // Fill 2 of value (byte) 33
+        CHARS[1369] = -19;
+        Arrays.fill(CHARS, 1370, 1377, (byte) 33 ); // Fill 7 of value (byte) 33
+        Arrays.fill(CHARS, 1377, 1415, (byte) -19 ); // Fill 38 of value (byte) -19
+        Arrays.fill(CHARS, 1415, 1425, (byte) 33 ); // Fill 10 of value (byte) 33
+        Arrays.fill(CHARS, 1425, 1442, (byte) -87 ); // Fill 17 of value (byte) -87
+        CHARS[1442] = 33;
+        Arrays.fill(CHARS, 1443, 1466, (byte) -87 ); // Fill 23 of value (byte) -87
+        CHARS[1466] = 33;
+        Arrays.fill(CHARS, 1467, 1470, (byte) -87 ); // Fill 3 of value (byte) -87
+        CHARS[1470] = 33;
+        CHARS[1471] = -87;
+        CHARS[1472] = 33;
+        Arrays.fill(CHARS, 1473, 1475, (byte) -87 ); // Fill 2 of value (byte) -87
+        CHARS[1475] = 33;
+        CHARS[1476] = -87;
+        Arrays.fill(CHARS, 1477, 1488, (byte) 33 ); // Fill 11 of value (byte) 33
+        Arrays.fill(CHARS, 1488, 1515, (byte) -19 ); // Fill 27 of value (byte) -19
+        Arrays.fill(CHARS, 1515, 1520, (byte) 33 ); // Fill 5 of value (byte) 33
+        Arrays.fill(CHARS, 1520, 1523, (byte) -19 ); // Fill 3 of value (byte) -19
+        Arrays.fill(CHARS, 1523, 1569, (byte) 33 ); // Fill 46 of value (byte) 33
+        Arrays.fill(CHARS, 1569, 1595, (byte) -19 ); // Fill 26 of value (byte) -19
+        Arrays.fill(CHARS, 1595, 1600, (byte) 33 ); // Fill 5 of value (byte) 33
+        CHARS[1600] = -87;
+        Arrays.fill(CHARS, 1601, 1611, (byte) -19 ); // Fill 10 of value (byte) -19
+        Arrays.fill(CHARS, 1611, 1619, (byte) -87 ); // Fill 8 of value (byte) -87
+        Arrays.fill(CHARS, 1619, 1632, (byte) 33 ); // Fill 13 of value (byte) 33
+        Arrays.fill(CHARS, 1632, 1642, (byte) -87 ); // Fill 10 of value (byte) -87
+        Arrays.fill(CHARS, 1642, 1648, (byte) 33 ); // Fill 6 of value (byte) 33
+        CHARS[1648] = -87;
+        Arrays.fill(CHARS, 1649, 1720, (byte) -19 ); // Fill 71 of value (byte) -19
+        Arrays.fill(CHARS, 1720, 1722, (byte) 33 ); // Fill 2 of value (byte) 33
+        Arrays.fill(CHARS, 1722, 1727, (byte) -19 ); // Fill 5 of value (byte) -19
+        CHARS[1727] = 33;
+        Arrays.fill(CHARS, 1728, 1743, (byte) -19 ); // Fill 15 of value (byte) -19
+        CHARS[1743] = 33;
+        Arrays.fill(CHARS, 1744, 1748, (byte) -19 ); // Fill 4 of value (byte) -19
+        CHARS[1748] = 33;
+        CHARS[1749] = -19;
+        Arrays.fill(CHARS, 1750, 1765, (byte) -87 ); // Fill 15 of value (byte) -87
+        Arrays.fill(CHARS, 1765, 1767, (byte) -19 ); // Fill 2 of value (byte) -19
+        Arrays.fill(CHARS, 1767, 1769, (byte) -87 ); // Fill 2 of value (byte) -87
+        CHARS[1769] = 33;
+        Arrays.fill(CHARS, 1770, 1774, (byte) -87 ); // Fill 4 of value (byte) -87
+        Arrays.fill(CHARS, 1774, 1776, (byte) 33 ); // Fill 2 of value (byte) 33
+        Arrays.fill(CHARS, 1776, 1786, (byte) -87 ); // Fill 10 of value (byte) -87
+        Arrays.fill(CHARS, 1786, 2305, (byte) 33 ); // Fill 519 of value (byte) 33
+        Arrays.fill(CHARS, 2305, 2308, (byte) -87 ); // Fill 3 of value (byte) -87
+        CHARS[2308] = 33;
+        Arrays.fill(CHARS, 2309, 2362, (byte) -19 ); // Fill 53 of value (byte) -19
+        Arrays.fill(CHARS, 2362, 2364, (byte) 33 ); // Fill 2 of value (byte) 33
+        CHARS[2364] = -87;
+        CHARS[2365] = -19;
+        Arrays.fill(CHARS, 2366, 2382, (byte) -87 ); // Fill 16 of value (byte) -87
+        Arrays.fill(CHARS, 2382, 2385, (byte) 33 ); // Fill 3 of value (byte) 33
+        Arrays.fill(CHARS, 2385, 2389, (byte) -87 ); // Fill 4 of value (byte) -87
+        Arrays.fill(CHARS, 2389, 2392, (byte) 33 ); // Fill 3 of value (byte) 33
+        Arrays.fill(CHARS, 2392, 2402, (byte) -19 ); // Fill 10 of value (byte) -19
+        Arrays.fill(CHARS, 2402, 2404, (byte) -87 ); // Fill 2 of value (byte) -87
+        Arrays.fill(CHARS, 2404, 2406, (byte) 33 ); // Fill 2 of value (byte) 33
+        Arrays.fill(CHARS, 2406, 2416, (byte) -87 ); // Fill 10 of value (byte) -87
+        Arrays.fill(CHARS, 2416, 2433, (byte) 33 ); // Fill 17 of value (byte) 33
+        Arrays.fill(CHARS, 2433, 2436, (byte) -87 ); // Fill 3 of value (byte) -87
+        CHARS[2436] = 33;
+        Arrays.fill(CHARS, 2437, 2445, (byte) -19 ); // Fill 8 of value (byte) -19
+        Arrays.fill(CHARS, 2445, 2447, (byte) 33 ); // Fill 2 of value (byte) 33
+        Arrays.fill(CHARS, 2447, 2449, (byte) -19 ); // Fill 2 of value (byte) -19
+        Arrays.fill(CHARS, 2449, 2451, (byte) 33 ); // Fill 2 of value (byte) 33
+        Arrays.fill(CHARS, 2451, 2473, (byte) -19 ); // Fill 22 of value (byte) -19
+        CHARS[2473] = 33;
+        Arrays.fill(CHARS, 2474, 2481, (byte) -19 ); // Fill 7 of value (byte) -19
+        CHARS[2481] = 33;
+        CHARS[2482] = -19;
+        Arrays.fill(CHARS, 2483, 2486, (byte) 33 ); // Fill 3 of value (byte) 33
+        Arrays.fill(CHARS, 2486, 2490, (byte) -19 ); // Fill 4 of value (byte) -19
+        Arrays.fill(CHARS, 2490, 2492, (byte) 33 ); // Fill 2 of value (byte) 33
+        CHARS[2492] = -87;
+        CHARS[2493] = 33;
+        Arrays.fill(CHARS, 2494, 2501, (byte) -87 ); // Fill 7 of value (byte) -87
+        Arrays.fill(CHARS, 2501, 2503, (byte) 33 ); // Fill 2 of value (byte) 33
+        Arrays.fill(CHARS, 2503, 2505, (byte) -87 ); // Fill 2 of value (byte) -87
+        Arrays.fill(CHARS, 2505, 2507, (byte) 33 ); // Fill 2 of value (byte) 33
+        Arrays.fill(CHARS, 2507, 2510, (byte) -87 ); // Fill 3 of value (byte) -87
+        Arrays.fill(CHARS, 2510, 2519, (byte) 33 ); // Fill 9 of value (byte) 33
+        CHARS[2519] = -87;
+        Arrays.fill(CHARS, 2520, 2524, (byte) 33 ); // Fill 4 of value (byte) 33
+        Arrays.fill(CHARS, 2524, 2526, (byte) -19 ); // Fill 2 of value (byte) -19
+        CHARS[2526] = 33;
+        Arrays.fill(CHARS, 2527, 2530, (byte) -19 ); // Fill 3 of value (byte) -19
+        Arrays.fill(CHARS, 2530, 2532, (byte) -87 ); // Fill 2 of value (byte) -87
+        Arrays.fill(CHARS, 2532, 2534, (byte) 33 ); // Fill 2 of value (byte) 33
+        Arrays.fill(CHARS, 2534, 2544, (byte) -87 ); // Fill 10 of value (byte) -87
+        Arrays.fill(CHARS, 2544, 2546, (byte) -19 ); // Fill 2 of value (byte) -19
+        Arrays.fill(CHARS, 2546, 2562, (byte) 33 ); // Fill 16 of value (byte) 33
+        CHARS[2562] = -87;
+        Arrays.fill(CHARS, 2563, 2565, (byte) 33 ); // Fill 2 of value (byte) 33
+        Arrays.fill(CHARS, 2565, 2571, (byte) -19 ); // Fill 6 of value (byte) -19
+        Arrays.fill(CHARS, 2571, 2575, (byte) 33 ); // Fill 4 of value (byte) 33
+        Arrays.fill(CHARS, 2575, 2577, (byte) -19 ); // Fill 2 of value (byte) -19
+        Arrays.fill(CHARS, 2577, 2579, (byte) 33 ); // Fill 2 of value (byte) 33
+        Arrays.fill(CHARS, 2579, 2601, (byte) -19 ); // Fill 22 of value (byte) -19
+        CHARS[2601] = 33;
+        Arrays.fill(CHARS, 2602, 2609, (byte) -19 ); // Fill 7 of value (byte) -19
+        CHARS[2609] = 33;
+        Arrays.fill(CHARS, 2610, 2612, (byte) -19 ); // Fill 2 of value (byte) -19
+        CHARS[2612] = 33;
+        Arrays.fill(CHARS, 2613, 2615, (byte) -19 ); // Fill 2 of value (byte) -19
+        CHARS[2615] = 33;
+        Arrays.fill(CHARS, 2616, 2618, (byte) -19 ); // Fill 2 of value (byte) -19
+        Arrays.fill(CHARS, 2618, 2620, (byte) 33 ); // Fill 2 of value (byte) 33
+        CHARS[2620] = -87;
+        CHARS[2621] = 33;
+        Arrays.fill(CHARS, 2622, 2627, (byte) -87 ); // Fill 5 of value (byte) -87
+        Arrays.fill(CHARS, 2627, 2631, (byte) 33 ); // Fill 4 of value (byte) 33
+        Arrays.fill(CHARS, 2631, 2633, (byte) -87 ); // Fill 2 of value (byte) -87
+        Arrays.fill(CHARS, 2633, 2635, (byte) 33 ); // Fill 2 of value (byte) 33
+        Arrays.fill(CHARS, 2635, 2638, (byte) -87 ); // Fill 3 of value (byte) -87
+        Arrays.fill(CHARS, 2638, 2649, (byte) 33 ); // Fill 11 of value (byte) 33
+        Arrays.fill(CHARS, 2649, 2653, (byte) -19 ); // Fill 4 of value (byte) -19
+        CHARS[2653] = 33;
+        CHARS[2654] = -19;
+        Arrays.fill(CHARS, 2655, 2662, (byte) 33 ); // Fill 7 of value (byte) 33
+        Arrays.fill(CHARS, 2662, 2674, (byte) -87 ); // Fill 12 of value (byte) -87
+        Arrays.fill(CHARS, 2674, 2677, (byte) -19 ); // Fill 3 of value (byte) -19
+        Arrays.fill(CHARS, 2677, 2689, (byte) 33 ); // Fill 12 of value (byte) 33
+        Arrays.fill(CHARS, 2689, 2692, (byte) -87 ); // Fill 3 of value (byte) -87
+        CHARS[2692] = 33;
+        Arrays.fill(CHARS, 2693, 2700, (byte) -19 ); // Fill 7 of value (byte) -19
+        CHARS[2700] = 33;
+        CHARS[2701] = -19;
+        CHARS[2702] = 33;
+        Arrays.fill(CHARS, 2703, 2706, (byte) -19 ); // Fill 3 of value (byte) -19
+        CHARS[2706] = 33;
+        Arrays.fill(CHARS, 2707, 2729, (byte) -19 ); // Fill 22 of value (byte) -19
+        CHARS[2729] = 33;
+        Arrays.fill(CHARS, 2730, 2737, (byte) -19 ); // Fill 7 of value (byte) -19
+        CHARS[2737] = 33;
+        Arrays.fill(CHARS, 2738, 2740, (byte) -19 ); // Fill 2 of value (byte) -19
+        CHARS[2740] = 33;
+        Arrays.fill(CHARS, 2741, 2746, (byte) -19 ); // Fill 5 of value (byte) -19
+        Arrays.fill(CHARS, 2746, 2748, (byte) 33 ); // Fill 2 of value (byte) 33
+        CHARS[2748] = -87;
+        CHARS[2749] = -19;
+        Arrays.fill(CHARS, 2750, 2758, (byte) -87 ); // Fill 8 of value (byte) -87
+        CHARS[2758] = 33;
+        Arrays.fill(CHARS, 2759, 2762, (byte) -87 ); // Fill 3 of value (byte) -87
+        CHARS[2762] = 33;
+        Arrays.fill(CHARS, 2763, 2766, (byte) -87 ); // Fill 3 of value (byte) -87
+        Arrays.fill(CHARS, 2766, 2784, (byte) 33 ); // Fill 18 of value (byte) 33
+        CHARS[2784] = -19;
+        Arrays.fill(CHARS, 2785, 2790, (byte) 33 ); // Fill 5 of value (byte) 33
+        Arrays.fill(CHARS, 2790, 2800, (byte) -87 ); // Fill 10 of value (byte) -87
+        Arrays.fill(CHARS, 2800, 2817, (byte) 33 ); // Fill 17 of value (byte) 33
+        Arrays.fill(CHARS, 2817, 2820, (byte) -87 ); // Fill 3 of value (byte) -87
+        CHARS[2820] = 33;
+        Arrays.fill(CHARS, 2821, 2829, (byte) -19 ); // Fill 8 of value (byte) -19
+        Arrays.fill(CHARS, 2829, 2831, (byte) 33 ); // Fill 2 of value (byte) 33
+        Arrays.fill(CHARS, 2831, 2833, (byte) -19 ); // Fill 2 of value (byte) -19
+        Arrays.fill(CHARS, 2833, 2835, (byte) 33 ); // Fill 2 of value (byte) 33
+        Arrays.fill(CHARS, 2835, 2857, (byte) -19 ); // Fill 22 of value (byte) -19
+        CHARS[2857] = 33;
+        Arrays.fill(CHARS, 2858, 2865, (byte) -19 ); // Fill 7 of value (byte) -19
+        CHARS[2865] = 33;
+        Arrays.fill(CHARS, 2866, 2868, (byte) -19 ); // Fill 2 of value (byte) -19
+        Arrays.fill(CHARS, 2868, 2870, (byte) 33 ); // Fill 2 of value (byte) 33
+        Arrays.fill(CHARS, 2870, 2874, (byte) -19 ); // Fill 4 of value (byte) -19
+        Arrays.fill(CHARS, 2874, 2876, (byte) 33 ); // Fill 2 of value (byte) 33
+        CHARS[2876] = -87;
+        CHARS[2877] = -19;
+        Arrays.fill(CHARS, 2878, 2884, (byte) -87 ); // Fill 6 of value (byte) -87
+        Arrays.fill(CHARS, 2884, 2887, (byte) 33 ); // Fill 3 of value (byte) 33
+        Arrays.fill(CHARS, 2887, 2889, (byte) -87 ); // Fill 2 of value (byte) -87
+        Arrays.fill(CHARS, 2889, 2891, (byte) 33 ); // Fill 2 of value (byte) 33
+        Arrays.fill(CHARS, 2891, 2894, (byte) -87 ); // Fill 3 of value (byte) -87
+        Arrays.fill(CHARS, 2894, 2902, (byte) 33 ); // Fill 8 of value (byte) 33
+        Arrays.fill(CHARS, 2902, 2904, (byte) -87 ); // Fill 2 of value (byte) -87
+        Arrays.fill(CHARS, 2904, 2908, (byte) 33 ); // Fill 4 of value (byte) 33
+        Arrays.fill(CHARS, 2908, 2910, (byte) -19 ); // Fill 2 of value (byte) -19
+        CHARS[2910] = 33;
+        Arrays.fill(CHARS, 2911, 2914, (byte) -19 ); // Fill 3 of value (byte) -19
+        Arrays.fill(CHARS, 2914, 2918, (byte) 33 ); // Fill 4 of value (byte) 33
+        Arrays.fill(CHARS, 2918, 2928, (byte) -87 ); // Fill 10 of value (byte) -87
+        Arrays.fill(CHARS, 2928, 2946, (byte) 33 ); // Fill 18 of value (byte) 33
+        Arrays.fill(CHARS, 2946, 2948, (byte) -87 ); // Fill 2 of value (byte) -87
+        CHARS[2948] = 33;
+        Arrays.fill(CHARS, 2949, 2955, (byte) -19 ); // Fill 6 of value (byte) -19
+        Arrays.fill(CHARS, 2955, 2958, (byte) 33 ); // Fill 3 of value (byte) 33
+        Arrays.fill(CHARS, 2958, 2961, (byte) -19 ); // Fill 3 of value (byte) -19
+        CHARS[2961] = 33;
+        Arrays.fill(CHARS, 2962, 2966, (byte) -19 ); // Fill 4 of value (byte) -19
+        Arrays.fill(CHARS, 2966, 2969, (byte) 33 ); // Fill 3 of value (byte) 33
+        Arrays.fill(CHARS, 2969, 2971, (byte) -19 ); // Fill 2 of value (byte) -19
+        CHARS[2971] = 33;
+        CHARS[2972] = -19;
+        CHARS[2973] = 33;
+        Arrays.fill(CHARS, 2974, 2976, (byte) -19 ); // Fill 2 of value (byte) -19
+        Arrays.fill(CHARS, 2976, 2979, (byte) 33 ); // Fill 3 of value (byte) 33
+        Arrays.fill(CHARS, 2979, 2981, (byte) -19 ); // Fill 2 of value (byte) -19
+        Arrays.fill(CHARS, 2981, 2984, (byte) 33 ); // Fill 3 of value (byte) 33
+        Arrays.fill(CHARS, 2984, 2987, (byte) -19 ); // Fill 3 of value (byte) -19
+        Arrays.fill(CHARS, 2987, 2990, (byte) 33 ); // Fill 3 of value (byte) 33
+        Arrays.fill(CHARS, 2990, 2998, (byte) -19 ); // Fill 8 of value (byte) -19
+        CHARS[2998] = 33;
+        Arrays.fill(CHARS, 2999, 3002, (byte) -19 ); // Fill 3 of value (byte) -19
+        Arrays.fill(CHARS, 3002, 3006, (byte) 33 ); // Fill 4 of value (byte) 33
+        Arrays.fill(CHARS, 3006, 3011, (byte) -87 ); // Fill 5 of value (byte) -87
+        Arrays.fill(CHARS, 3011, 3014, (byte) 33 ); // Fill 3 of value (byte) 33
+        Arrays.fill(CHARS, 3014, 3017, (byte) -87 ); // Fill 3 of value (byte) -87
+        CHARS[3017] = 33;
+        Arrays.fill(CHARS, 3018, 3022, (byte) -87 ); // Fill 4 of value (byte) -87
+        Arrays.fill(CHARS, 3022, 3031, (byte) 33 ); // Fill 9 of value (byte) 33
+        CHARS[3031] = -87;
+        Arrays.fill(CHARS, 3032, 3047, (byte) 33 ); // Fill 15 of value (byte) 33
+        Arrays.fill(CHARS, 3047, 3056, (byte) -87 ); // Fill 9 of value (byte) -87
+        Arrays.fill(CHARS, 3056, 3073, (byte) 33 ); // Fill 17 of value (byte) 33
+        Arrays.fill(CHARS, 3073, 3076, (byte) -87 ); // Fill 3 of value (byte) -87
+        CHARS[3076] = 33;
+        Arrays.fill(CHARS, 3077, 3085, (byte) -19 ); // Fill 8 of value (byte) -19
+        CHARS[3085] = 33;
+        Arrays.fill(CHARS, 3086, 3089, (byte) -19 ); // Fill 3 of value (byte) -19
+        CHARS[3089] = 33;
+        Arrays.fill(CHARS, 3090, 3113, (byte) -19 ); // Fill 23 of value (byte) -19
+        CHARS[3113] = 33;
+        Arrays.fill(CHARS, 3114, 3124, (byte) -19 ); // Fill 10 of value (byte) -19
+        CHARS[3124] = 33;
+        Arrays.fill(CHARS, 3125, 3130, (byte) -19 ); // Fill 5 of value (byte) -19
+        Arrays.fill(CHARS, 3130, 3134, (byte) 33 ); // Fill 4 of value (byte) 33
+        Arrays.fill(CHARS, 3134, 3141, (byte) -87 ); // Fill 7 of value (byte) -87
+        CHARS[3141] = 33;
+        Arrays.fill(CHARS, 3142, 3145, (byte) -87 ); // Fill 3 of value (byte) -87
+        CHARS[3145] = 33;
+        Arrays.fill(CHARS, 3146, 3150, (byte) -87 ); // Fill 4 of value (byte) -87
+        Arrays.fill(CHARS, 3150, 3157, (byte) 33 ); // Fill 7 of value (byte) 33
+        Arrays.fill(CHARS, 3157, 3159, (byte) -87 ); // Fill 2 of value (byte) -87
+        Arrays.fill(CHARS, 3159, 3168, (byte) 33 ); // Fill 9 of value (byte) 33
+        Arrays.fill(CHARS, 3168, 3170, (byte) -19 ); // Fill 2 of value (byte) -19
+        Arrays.fill(CHARS, 3170, 3174, (byte) 33 ); // Fill 4 of value (byte) 33
+        Arrays.fill(CHARS, 3174, 3184, (byte) -87 ); // Fill 10 of value (byte) -87
+        Arrays.fill(CHARS, 3184, 3202, (byte) 33 ); // Fill 18 of value (byte) 33
+        Arrays.fill(CHARS, 3202, 3204, (byte) -87 ); // Fill 2 of value (byte) -87
+        CHARS[3204] = 33;
+        Arrays.fill(CHARS, 3205, 3213, (byte) -19 ); // Fill 8 of value (byte) -19
+        CHARS[3213] = 33;
+        Arrays.fill(CHARS, 3214, 3217, (byte) -19 ); // Fill 3 of value (byte) -19
+        CHARS[3217] = 33;
+        Arrays.fill(CHARS, 3218, 3241, (byte) -19 ); // Fill 23 of value (byte) -19
+        CHARS[3241] = 33;
+        Arrays.fill(CHARS, 3242, 3252, (byte) -19 ); // Fill 10 of value (byte) -19
+        CHARS[3252] = 33;
+        Arrays.fill(CHARS, 3253, 3258, (byte) -19 ); // Fill 5 of value (byte) -19
+        Arrays.fill(CHARS, 3258, 3262, (byte) 33 ); // Fill 4 of value (byte) 33
+        Arrays.fill(CHARS, 3262, 3269, (byte) -87 ); // Fill 7 of value (byte) -87
+        CHARS[3269] = 33;
+        Arrays.fill(CHARS, 3270, 3273, (byte) -87 ); // Fill 3 of value (byte) -87
+        CHARS[3273] = 33;
+        Arrays.fill(CHARS, 3274, 3278, (byte) -87 ); // Fill 4 of value (byte) -87
+        Arrays.fill(CHARS, 3278, 3285, (byte) 33 ); // Fill 7 of value (byte) 33
+        Arrays.fill(CHARS, 3285, 3287, (byte) -87 ); // Fill 2 of value (byte) -87
+        Arrays.fill(CHARS, 3287, 3294, (byte) 33 ); // Fill 7 of value (byte) 33
+        CHARS[3294] = -19;
+        CHARS[3295] = 33;
+        Arrays.fill(CHARS, 3296, 3298, (byte) -19 ); // Fill 2 of value (byte) -19
+        Arrays.fill(CHARS, 3298, 3302, (byte) 33 ); // Fill 4 of value (byte) 33
+        Arrays.fill(CHARS, 3302, 3312, (byte) -87 ); // Fill 10 of value (byte) -87
+        Arrays.fill(CHARS, 3312, 3330, (byte) 33 ); // Fill 18 of value (byte) 33
+        Arrays.fill(CHARS, 3330, 3332, (byte) -87 ); // Fill 2 of value (byte) -87
+        CHARS[3332] = 33;
+        Arrays.fill(CHARS, 3333, 3341, (byte) -19 ); // Fill 8 of value (byte) -19
+        CHARS[3341] = 33;
+        Arrays.fill(CHARS, 3342, 3345, (byte) -19 ); // Fill 3 of value (byte) -19
+        CHARS[3345] = 33;
+        Arrays.fill(CHARS, 3346, 3369, (byte) -19 ); // Fill 23 of value (byte) -19
+        CHARS[3369] = 33;
+        Arrays.fill(CHARS, 3370, 3386, (byte) -19 ); // Fill 16 of value (byte) -19
+        Arrays.fill(CHARS, 3386, 3390, (byte) 33 ); // Fill 4 of value (byte) 33
+        Arrays.fill(CHARS, 3390, 3396, (byte) -87 ); // Fill 6 of value (byte) -87
+        Arrays.fill(CHARS, 3396, 3398, (byte) 33 ); // Fill 2 of value (byte) 33
+        Arrays.fill(CHARS, 3398, 3401, (byte) -87 ); // Fill 3 of value (byte) -87
+        CHARS[3401] = 33;
+        Arrays.fill(CHARS, 3402, 3406, (byte) -87 ); // Fill 4 of value (byte) -87
+        Arrays.fill(CHARS, 3406, 3415, (byte) 33 ); // Fill 9 of value (byte) 33
+        CHARS[3415] = -87;
+        Arrays.fill(CHARS, 3416, 3424, (byte) 33 ); // Fill 8 of value (byte) 33
+        Arrays.fill(CHARS, 3424, 3426, (byte) -19 ); // Fill 2 of value (byte) -19
+        Arrays.fill(CHARS, 3426, 3430, (byte) 33 ); // Fill 4 of value (byte) 33
+        Arrays.fill(CHARS, 3430, 3440, (byte) -87 ); // Fill 10 of value (byte) -87
+        Arrays.fill(CHARS, 3440, 3585, (byte) 33 ); // Fill 145 of value (byte) 33
+        Arrays.fill(CHARS, 3585, 3631, (byte) -19 ); // Fill 46 of value (byte) -19
+        CHARS[3631] = 33;
+        CHARS[3632] = -19;
+        CHARS[3633] = -87;
+        Arrays.fill(CHARS, 3634, 3636, (byte) -19 ); // Fill 2 of value (byte) -19
+        Arrays.fill(CHARS, 3636, 3643, (byte) -87 ); // Fill 7 of value (byte) -87
+        Arrays.fill(CHARS, 3643, 3648, (byte) 33 ); // Fill 5 of value (byte) 33
+        Arrays.fill(CHARS, 3648, 3654, (byte) -19 ); // Fill 6 of value (byte) -19
+        Arrays.fill(CHARS, 3654, 3663, (byte) -87 ); // Fill 9 of value (byte) -87
+        CHARS[3663] = 33;
+        Arrays.fill(CHARS, 3664, 3674, (byte) -87 ); // Fill 10 of value (byte) -87
+        Arrays.fill(CHARS, 3674, 3713, (byte) 33 ); // Fill 39 of value (byte) 33
+        Arrays.fill(CHARS, 3713, 3715, (byte) -19 ); // Fill 2 of value (byte) -19
+        CHARS[3715] = 33;
+        CHARS[3716] = -19;
+        Arrays.fill(CHARS, 3717, 3719, (byte) 33 ); // Fill 2 of value (byte) 33
+        Arrays.fill(CHARS, 3719, 3721, (byte) -19 ); // Fill 2 of value (byte) -19
+        CHARS[3721] = 33;
+        CHARS[3722] = -19;
+        Arrays.fill(CHARS, 3723, 3725, (byte) 33 ); // Fill 2 of value (byte) 33
+        CHARS[3725] = -19;
+        Arrays.fill(CHARS, 3726, 3732, (byte) 33 ); // Fill 6 of value (byte) 33
+        Arrays.fill(CHARS, 3732, 3736, (byte) -19 ); // Fill 4 of value (byte) -19
+        CHARS[3736] = 33;
+        Arrays.fill(CHARS, 3737, 3744, (byte) -19 ); // Fill 7 of value (byte) -19
+        CHARS[3744] = 33;
+        Arrays.fill(CHARS, 3745, 3748, (byte) -19 ); // Fill 3 of value (byte) -19
+        CHARS[3748] = 33;
+        CHARS[3749] = -19;
+        CHARS[3750] = 33;
+        CHARS[3751] = -19;
+        Arrays.fill(CHARS, 3752, 3754, (byte) 33 ); // Fill 2 of value (byte) 33
+        Arrays.fill(CHARS, 3754, 3756, (byte) -19 ); // Fill 2 of value (byte) -19
+        CHARS[3756] = 33;
+        Arrays.fill(CHARS, 3757, 3759, (byte) -19 ); // Fill 2 of value (byte) -19
+        CHARS[3759] = 33;
+        CHARS[3760] = -19;
+        CHARS[3761] = -87;
+        Arrays.fill(CHARS, 3762, 3764, (byte) -19 ); // Fill 2 of value (byte) -19
+        Arrays.fill(CHARS, 3764, 3770, (byte) -87 ); // Fill 6 of value (byte) -87
+        CHARS[3770] = 33;
+        Arrays.fill(CHARS, 3771, 3773, (byte) -87 ); // Fill 2 of value (byte) -87
+        CHARS[3773] = -19;
+        Arrays.fill(CHARS, 3774, 3776, (byte) 33 ); // Fill 2 of value (byte) 33
+        Arrays.fill(CHARS, 3776, 3781, (byte) -19 ); // Fill 5 of value (byte) -19
+        CHARS[3781] = 33;
+        CHARS[3782] = -87;
+        CHARS[3783] = 33;
+        Arrays.fill(CHARS, 3784, 3790, (byte) -87 ); // Fill 6 of value (byte) -87
+        Arrays.fill(CHARS, 3790, 3792, (byte) 33 ); // Fill 2 of value (byte) 33
+        Arrays.fill(CHARS, 3792, 3802, (byte) -87 ); // Fill 10 of value (byte) -87
+        Arrays.fill(CHARS, 3802, 3864, (byte) 33 ); // Fill 62 of value (byte) 33
+        Arrays.fill(CHARS, 3864, 3866, (byte) -87 ); // Fill 2 of value (byte) -87
+        Arrays.fill(CHARS, 3866, 3872, (byte) 33 ); // Fill 6 of value (byte) 33
+        Arrays.fill(CHARS, 3872, 3882, (byte) -87 ); // Fill 10 of value (byte) -87
+        Arrays.fill(CHARS, 3882, 3893, (byte) 33 ); // Fill 11 of value (byte) 33
+        CHARS[3893] = -87;
+        CHARS[3894] = 33;
+        CHARS[3895] = -87;
+        CHARS[3896] = 33;
+        CHARS[3897] = -87;
+        Arrays.fill(CHARS, 3898, 3902, (byte) 33 ); // Fill 4 of value (byte) 33
+        Arrays.fill(CHARS, 3902, 3904, (byte) -87 ); // Fill 2 of value (byte) -87
+        Arrays.fill(CHARS, 3904, 3912, (byte) -19 ); // Fill 8 of value (byte) -19
+        CHARS[3912] = 33;
+        Arrays.fill(CHARS, 3913, 3946, (byte) -19 ); // Fill 33 of value (byte) -19
+        Arrays.fill(CHARS, 3946, 3953, (byte) 33 ); // Fill 7 of value (byte) 33
+        Arrays.fill(CHARS, 3953, 3973, (byte) -87 ); // Fill 20 of value (byte) -87
+        CHARS[3973] = 33;
+        Arrays.fill(CHARS, 3974, 3980, (byte) -87 ); // Fill 6 of value (byte) -87
+        Arrays.fill(CHARS, 3980, 3984, (byte) 33 ); // Fill 4 of value (byte) 33
+        Arrays.fill(CHARS, 3984, 3990, (byte) -87 ); // Fill 6 of value (byte) -87
+        CHARS[3990] = 33;
+        CHARS[3991] = -87;
+        CHARS[3992] = 33;
+        Arrays.fill(CHARS, 3993, 4014, (byte) -87 ); // Fill 21 of value (byte) -87
+        Arrays.fill(CHARS, 4014, 4017, (byte) 33 ); // Fill 3 of value (byte) 33
+        Arrays.fill(CHARS, 4017, 4024, (byte) -87 ); // Fill 7 of value (byte) -87
+        CHARS[4024] = 33;
+        CHARS[4025] = -87;
+        Arrays.fill(CHARS, 4026, 4256, (byte) 33 ); // Fill 230 of value (byte) 33
+        Arrays.fill(CHARS, 4256, 4294, (byte) -19 ); // Fill 38 of value (byte) -19
+        Arrays.fill(CHARS, 4294, 4304, (byte) 33 ); // Fill 10 of value (byte) 33
+        Arrays.fill(CHARS, 4304, 4343, (byte) -19 ); // Fill 39 of value (byte) -19
+        Arrays.fill(CHARS, 4343, 4352, (byte) 33 ); // Fill 9 of value (byte) 33
+        CHARS[4352] = -19;
+        CHARS[4353] = 33;
+        Arrays.fill(CHARS, 4354, 4356, (byte) -19 ); // Fill 2 of value (byte) -19
+        CHARS[4356] = 33;
+        Arrays.fill(CHARS, 4357, 4360, (byte) -19 ); // Fill 3 of value (byte) -19
+        CHARS[4360] = 33;
+        CHARS[4361] = -19;
+        CHARS[4362] = 33;
+        Arrays.fill(CHARS, 4363, 4365, (byte) -19 ); // Fill 2 of value (byte) -19
+        CHARS[4365] = 33;
+        Arrays.fill(CHARS, 4366, 4371, (byte) -19 ); // Fill 5 of value (byte) -19
+        Arrays.fill(CHARS, 4371, 4412, (byte) 33 ); // Fill 41 of value (byte) 33
+        CHARS[4412] = -19;
+        CHARS[4413] = 33;
+        CHARS[4414] = -19;
+        CHARS[4415] = 33;
+        CHARS[4416] = -19;
+        Arrays.fill(CHARS, 4417, 4428, (byte) 33 ); // Fill 11 of value (byte) 33
+        CHARS[4428] = -19;
+        CHARS[4429] = 33;
+        CHARS[4430] = -19;
+        CHARS[4431] = 33;
+        CHARS[4432] = -19;
+        Arrays.fill(CHARS, 4433, 4436, (byte) 33 ); // Fill 3 of value (byte) 33
+        Arrays.fill(CHARS, 4436, 4438, (byte) -19 ); // Fill 2 of value (byte) -19
+        Arrays.fill(CHARS, 4438, 4441, (byte) 33 ); // Fill 3 of value (byte) 33
+        CHARS[4441] = -19;
+        Arrays.fill(CHARS, 4442, 4447, (byte) 33 ); // Fill 5 of value (byte) 33
+        Arrays.fill(CHARS, 4447, 4450, (byte) -19 ); // Fill 3 of value (byte) -19
+        CHARS[4450] = 33;
+        CHARS[4451] = -19;
+        CHARS[4452] = 33;
+        CHARS[4453] = -19;
+        CHARS[4454] = 33;
+        CHARS[4455] = -19;
+        CHARS[4456] = 33;
+        CHARS[4457] = -19;
+        Arrays.fill(CHARS, 4458, 4461, (byte) 33 ); // Fill 3 of value (byte) 33
+        Arrays.fill(CHARS, 4461, 4463, (byte) -19 ); // Fill 2 of value (byte) -19
+        Arrays.fill(CHARS, 4463, 4466, (byte) 33 ); // Fill 3 of value (byte) 33
+        Arrays.fill(CHARS, 4466, 4468, (byte) -19 ); // Fill 2 of value (byte) -19
+        CHARS[4468] = 33;
+        CHARS[4469] = -19;
+        Arrays.fill(CHARS, 4470, 4510, (byte) 33 ); // Fill 40 of value (byte) 33
+        CHARS[4510] = -19;
+        Arrays.fill(CHARS, 4511, 4520, (byte) 33 ); // Fill 9 of value (byte) 33
+        CHARS[4520] = -19;
+        Arrays.fill(CHARS, 4521, 4523, (byte) 33 ); // Fill 2 of value (byte) 33
+        CHARS[4523] = -19;
+        Arrays.fill(CHARS, 4524, 4526, (byte) 33 ); // Fill 2 of value (byte) 33
+        Arrays.fill(CHARS, 4526, 4528, (byte) -19 ); // Fill 2 of value (byte) -19
+        Arrays.fill(CHARS, 4528, 4535, (byte) 33 ); // Fill 7 of value (byte) 33
+        Arrays.fill(CHARS, 4535, 4537, (byte) -19 ); // Fill 2 of value (byte) -19
+        CHARS[4537] = 33;
+        CHARS[4538] = -19;
+        CHARS[4539] = 33;
+        Arrays.fill(CHARS, 4540, 4547, (byte) -19 ); // Fill 7 of value (byte) -19
+        Arrays.fill(CHARS, 4547, 4587, (byte) 33 ); // Fill 40 of value (byte) 33
+        CHARS[4587] = -19;
+        Arrays.fill(CHARS, 4588, 4592, (byte) 33 ); // Fill 4 of value (byte) 33
+        CHARS[4592] = -19;
+        Arrays.fill(CHARS, 4593, 4601, (byte) 33 ); // Fill 8 of value (byte) 33
+        CHARS[4601] = -19;
+        Arrays.fill(CHARS, 4602, 7680, (byte) 33 ); // Fill 3078 of value (byte) 33
+        Arrays.fill(CHARS, 7680, 7836, (byte) -19 ); // Fill 156 of value (byte) -19
+        Arrays.fill(CHARS, 7836, 7840, (byte) 33 ); // Fill 4 of value (byte) 33
+        Arrays.fill(CHARS, 7840, 7930, (byte) -19 ); // Fill 90 of value (byte) -19
+        Arrays.fill(CHARS, 7930, 7936, (byte) 33 ); // Fill 6 of value (byte) 33
+        Arrays.fill(CHARS, 7936, 7958, (byte) -19 ); // Fill 22 of value (byte) -19
+        Arrays.fill(CHARS, 7958, 7960, (byte) 33 ); // Fill 2 of value (byte) 33
+        Arrays.fill(CHARS, 7960, 7966, (byte) -19 ); // Fill 6 of value (byte) -19
+        Arrays.fill(CHARS, 7966, 7968, (byte) 33 ); // Fill 2 of value (byte) 33
+        Arrays.fill(CHARS, 7968, 8006, (byte) -19 ); // Fill 38 of value (byte) -19
+        Arrays.fill(CHARS, 8006, 8008, (byte) 33 ); // Fill 2 of value (byte) 33
+        Arrays.fill(CHARS, 8008, 8014, (byte) -19 ); // Fill 6 of value (byte) -19
+        Arrays.fill(CHARS, 8014, 8016, (byte) 33 ); // Fill 2 of value (byte) 33
+        Arrays.fill(CHARS, 8016, 8024, (byte) -19 ); // Fill 8 of value (byte) -19
+        CHARS[8024] = 33;
+        CHARS[8025] = -19;
+        CHARS[8026] = 33;
+        CHARS[8027] = -19;
+        CHARS[8028] = 33;
+        CHARS[8029] = -19;
+        CHARS[8030] = 33;
+        Arrays.fill(CHARS, 8031, 8062, (byte) -19 ); // Fill 31 of value (byte) -19
+        Arrays.fill(CHARS, 8062, 8064, (byte) 33 ); // Fill 2 of value (byte) 33
+        Arrays.fill(CHARS, 8064, 8117, (byte) -19 ); // Fill 53 of value (byte) -19
+        CHARS[8117] = 33;
+        Arrays.fill(CHARS, 8118, 8125, (byte) -19 ); // Fill 7 of value (byte) -19
+        CHARS[8125] = 33;
+        CHARS[8126] = -19;
+        Arrays.fill(CHARS, 8127, 8130, (byte) 33 ); // Fill 3 of value (byte) 33
+        Arrays.fill(CHARS, 8130, 8133, (byte) -19 ); // Fill 3 of value (byte) -19
+        CHARS[8133] = 33;
+        Arrays.fill(CHARS, 8134, 8141, (byte) -19 ); // Fill 7 of value (byte) -19
+        Arrays.fill(CHARS, 8141, 8144, (byte) 33 ); // Fill 3 of value (byte) 33
+        Arrays.fill(CHARS, 8144, 8148, (byte) -19 ); // Fill 4 of value (byte) -19
+        Arrays.fill(CHARS, 8148, 8150, (byte) 33 ); // Fill 2 of value (byte) 33
+        Arrays.fill(CHARS, 8150, 8156, (byte) -19 ); // Fill 6 of value (byte) -19
+        Arrays.fill(CHARS, 8156, 8160, (byte) 33 ); // Fill 4 of value (byte) 33
+        Arrays.fill(CHARS, 8160, 8173, (byte) -19 ); // Fill 13 of value (byte) -19
+        Arrays.fill(CHARS, 8173, 8178, (byte) 33 ); // Fill 5 of value (byte) 33
+        Arrays.fill(CHARS, 8178, 8181, (byte) -19 ); // Fill 3 of value (byte) -19
+        CHARS[8181] = 33;
+        Arrays.fill(CHARS, 8182, 8189, (byte) -19 ); // Fill 7 of value (byte) -19
+        Arrays.fill(CHARS, 8189, 8400, (byte) 33 ); // Fill 211 of value (byte) 33
+        Arrays.fill(CHARS, 8400, 8413, (byte) -87 ); // Fill 13 of value (byte) -87
+        Arrays.fill(CHARS, 8413, 8417, (byte) 33 ); // Fill 4 of value (byte) 33
+        CHARS[8417] = -87;
+        Arrays.fill(CHARS, 8418, 8486, (byte) 33 ); // Fill 68 of value (byte) 33
+        CHARS[8486] = -19;
+        Arrays.fill(CHARS, 8487, 8490, (byte) 33 ); // Fill 3 of value (byte) 33
+        Arrays.fill(CHARS, 8490, 8492, (byte) -19 ); // Fill 2 of value (byte) -19
+        Arrays.fill(CHARS, 8492, 8494, (byte) 33 ); // Fill 2 of value (byte) 33
+        CHARS[8494] = -19;
+        Arrays.fill(CHARS, 8495, 8576, (byte) 33 ); // Fill 81 of value (byte) 33
+        Arrays.fill(CHARS, 8576, 8579, (byte) -19 ); // Fill 3 of value (byte) -19
+        Arrays.fill(CHARS, 8579, 12293, (byte) 33 ); // Fill 3714 of value (byte) 33
+        CHARS[12293] = -87;
+        CHARS[12294] = 33;
+        CHARS[12295] = -19;
+        Arrays.fill(CHARS, 12296, 12321, (byte) 33 ); // Fill 25 of value (byte) 33
+        Arrays.fill(CHARS, 12321, 12330, (byte) -19 ); // Fill 9 of value (byte) -19
+        Arrays.fill(CHARS, 12330, 12336, (byte) -87 ); // Fill 6 of value (byte) -87
+        CHARS[12336] = 33;
+        Arrays.fill(CHARS, 12337, 12342, (byte) -87 ); // Fill 5 of value (byte) -87
+        Arrays.fill(CHARS, 12342, 12353, (byte) 33 ); // Fill 11 of value (byte) 33
+        Arrays.fill(CHARS, 12353, 12437, (byte) -19 ); // Fill 84 of value (byte) -19
+        Arrays.fill(CHARS, 12437, 12441, (byte) 33 ); // Fill 4 of value (byte) 33
+        Arrays.fill(CHARS, 12441, 12443, (byte) -87 ); // Fill 2 of value (byte) -87
+        Arrays.fill(CHARS, 12443, 12445, (byte) 33 ); // Fill 2 of value (byte) 33
+        Arrays.fill(CHARS, 12445, 12447, (byte) -87 ); // Fill 2 of value (byte) -87
+        Arrays.fill(CHARS, 12447, 12449, (byte) 33 ); // Fill 2 of value (byte) 33
+        Arrays.fill(CHARS, 12449, 12539, (byte) -19 ); // Fill 90 of value (byte) -19
+        CHARS[12539] = 33;
+        Arrays.fill(CHARS, 12540, 12543, (byte) -87 ); // Fill 3 of value (byte) -87
+        Arrays.fill(CHARS, 12543, 12549, (byte) 33 ); // Fill 6 of value (byte) 33
+        Arrays.fill(CHARS, 12549, 12589, (byte) -19 ); // Fill 40 of value (byte) -19
+        Arrays.fill(CHARS, 12589, 19968, (byte) 33 ); // Fill 7379 of value (byte) 33
+        Arrays.fill(CHARS, 19968, 40870, (byte) -19 ); // Fill 20902 of value (byte) -19
+        Arrays.fill(CHARS, 40870, 44032, (byte) 33 ); // Fill 3162 of value (byte) 33
+        Arrays.fill(CHARS, 44032, 55204, (byte) -19 ); // Fill 11172 of value (byte) -19
+        Arrays.fill(CHARS, 55204, 55296, (byte) 33 ); // Fill 92 of value (byte) 33
+        Arrays.fill(CHARS, 57344, 65534, (byte) 33 ); // Fill 8190 of value (byte) 33
+
+    } // <clinit>()
+
+    //
+    // Public static methods
+    //
+
+    /**
+     * Returns true if the specified character is a supplemental character.
+     *
+     * @param c The character to check.
+     */
+    public static boolean isSupplemental(int c) {
+        return (c >= 0x10000 && c <= 0x10FFFF);
+    }
+
+    /**
+     * Returns true the supplemental character corresponding to the given
+     * surrogates.
+     *
+     * @param h The high surrogate.
+     * @param l The low surrogate.
+     */
+    public static int supplemental(char h, char l) {
+        return (h - 0xD800) * 0x400 + (l - 0xDC00) + 0x10000;
+    }
+
+    /**
+     * Returns the high surrogate of a supplemental character
+     *
+     * @param c The supplemental character to "split".
+     */
+    public static char highSurrogate(int c) {
+        return (char) (((c - 0x00010000) >> 10) + 0xD800);
+    }
+
+    /**
+     * Returns the low surrogate of a supplemental character
+     *
+     * @param c The supplemental character to "split".
+     */
+    public static char lowSurrogate(int c) {
+        return (char) (((c - 0x00010000) & 0x3FF) + 0xDC00);
+    }
+
+    /**
+     * Returns whether the given character is a high surrogate
+     *
+     * @param c The character to check.
+     */
+    public static boolean isHighSurrogate(int c) {
+        return (0xD800 <= c && c <= 0xDBFF);
+    }
+
+    /**
+     * Returns whether the given character is a low surrogate
+     *
+     * @param c The character to check.
+     */
+    public static boolean isLowSurrogate(int c) {
+        return (0xDC00 <= c && c <= 0xDFFF);
+    }
+
+
+    /**
+     * Returns true if the specified character is valid. This method
+     * also checks the surrogate character range from 0x10000 to 0x10FFFF.
+     * <p>
+     * If the program chooses to apply the mask directly to the
+     * <code>CHARS</code> array, then they are responsible for checking
+     * the surrogate character range.
+     *
+     * @param c The character to check.
+     */
+    public static boolean isValid(int c) {
+        return (c < 0x10000 && (CHARS[c] & MASK_VALID) != 0) ||
+               (0x10000 <= c && c <= 0x10FFFF);
+    } // isValid(int):boolean
+
+    /**
+     * Returns true if the specified character is invalid.
+     *
+     * @param c The character to check.
+     */
+    public static boolean isInvalid(int c) {
+        return !isValid(c);
+    } // isInvalid(int):boolean
+
+    /**
+     * Returns true if the specified character can be considered content.
+     *
+     * @param c The character to check.
+     */
+    public static boolean isContent(int c) {
+        return (c < 0x10000 && (CHARS[c] & MASK_CONTENT) != 0) ||
+               (0x10000 <= c && c <= 0x10FFFF);
+    } // isContent(int):boolean
+
+    /**
+     * Returns true if the specified character can be considered markup.
+     * Markup characters include '&lt;', '&amp;', and '%'.
+     *
+     * @param c The character to check.
+     */
+    public static boolean isMarkup(int c) {
+        return c == '<' || c == '&' || c == '%';
+    } // isMarkup(int):boolean
+
+    /**
+     * Returns true if the specified character is a space character
+     * as defined by production [3] in the XML 1.0 specification.
+     *
+     * @param c The character to check.
+     */
+    public static boolean isSpace(int c) {
+        return c <= 0x20 && (CHARS[c] & MASK_SPACE) != 0;
+    } // isSpace(int):boolean
+
+    /**
+     * Returns true if the specified character is a valid name start
+     * character as defined by production [5] in the XML 1.0
+     * specification.
+     *
+     * @param c The character to check.
+     */
+    public static boolean isNameStart(int c) {
+        return c < 0x10000 && (CHARS[c] & MASK_NAME_START) != 0;
+    } // isNameStart(int):boolean
+
+    /**
+     * Returns true if the specified character is a valid name
+     * character as defined by production [4] in the XML 1.0
+     * specification.
+     *
+     * @param c The character to check.
+     */
+    public static boolean isName(int c) {
+        return c < 0x10000 && (CHARS[c] & MASK_NAME) != 0;
+    } // isName(int):boolean
+
+    /**
+     * Returns true if the specified character is a valid NCName start
+     * character as defined by production [4] in Namespaces in XML
+     * recommendation.
+     *
+     * @param c The character to check.
+     */
+    public static boolean isNCNameStart(int c) {
+        return c < 0x10000 && (CHARS[c] & MASK_NCNAME_START) != 0;
+    } // isNCNameStart(int):boolean
+
+    /**
+     * Returns true if the specified character is a valid NCName
+     * character as defined by production [5] in Namespaces in XML
+     * recommendation.
+     *
+     * @param c The character to check.
+     */
+    public static boolean isNCName(int c) {
+        return c < 0x10000 && (CHARS[c] & MASK_NCNAME) != 0;
+    } // isNCName(int):boolean
+
+    /**
+     * Returns true if the specified character is a valid Pubid
+     * character as defined by production [13] in the XML 1.0
+     * specification.
+     *
+     * @param c The character to check.
+     */
+    public static boolean isPubid(int c) {
+        return c < 0x10000 && (CHARS[c] & MASK_PUBID) != 0;
+    } // isPubid(int):boolean
+
+    /*
+     * [5] Name ::= (Letter | '_' | ':') (NameChar)*
+     */
+    /**
+     * Check to see if a string is a valid Name according to [5]
+     * in the XML 1.0 Recommendation
+     *
+     * @param name string to check
+     * @return true if name is a valid Name
+     */
+    public static boolean isValidName(String name) {
+        final int length = name.length();
+        if (length == 0) {
+            return false;
+        }
+        char ch = name.charAt(0);
+        if (!isNameStart(ch)) {
+            return false;
+        }
+        for (int i = 1; i < length; ++i) {
+            ch = name.charAt(i);
+            if (!isName(ch)) {
+                return false;
+            }
+        }
+        return true;
+    } // isValidName(String):boolean
+    
+    /*
+     * from the namespace rec
+     * [4] NCName ::= (Letter | '_') (NCNameChar)*
+     */
+    /**
+     * Check to see if a string is a valid NCName according to [4]
+     * from the XML Namespaces 1.0 Recommendation
+     *
+     * @param ncName string to check
+     * @return true if name is a valid NCName
+     */
+    public static boolean isValidNCName(String ncName) {
+        final int length = ncName.length();
+        if (length == 0) {
+            return false;
+        }
+        char ch = ncName.charAt(0);
+        if (!isNCNameStart(ch)) {
+            return false;
+        }
+        for (int i = 1; i < length; ++i) {
+            ch = ncName.charAt(i);
+            if (!isNCName(ch)) {
+                return false;
+            }
+        }
+        return true;
+    } // isValidNCName(String):boolean
+
+    /*
+     * [7] Nmtoken ::= (NameChar)+
+     */
+    /**
+     * Check to see if a string is a valid Nmtoken according to [7]
+     * in the XML 1.0 Recommendation
+     *
+     * @param nmtoken string to check
+     * @return true if nmtoken is a valid Nmtoken 
+     */
+    public static boolean isValidNmtoken(String nmtoken) {
+        final int length = nmtoken.length();
+        if (length == 0) {
+            return false;
+        }
+        for (int i = 0; i < length; ++i) {
+            char ch = nmtoken.charAt(i);
+            if (!isName(ch)) {
+                return false;
+            }
+        }
+        return true;
+    } // isValidName(String):boolean
+
+
+
+
+
+    // encodings
+
+    /**
+     * Returns true if the encoding name is a valid IANA encoding.
+     * This method does not verify that there is a decoder available
+     * for this encoding, only that the characters are valid for an
+     * IANA encoding name.
+     *
+     * @param ianaEncoding The IANA encoding name.
+     */
+    public static boolean isValidIANAEncoding(String ianaEncoding) {
+        if (ianaEncoding != null) {
+            int length = ianaEncoding.length();
+            if (length > 0) {
+                char c = ianaEncoding.charAt(0);
+                if ((c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z')) {
+                    for (int i = 1; i < length; i++) {
+                        c = ianaEncoding.charAt(i);
+                        if ((c < 'A' || c > 'Z') && (c < 'a' || c > 'z') &&
+                            (c < '0' || c > '9') && c != '.' && c != '_' &&
+                            c != '-') {
+                            return false;
+                        }
+                    }
+                    return true;
+                }
+            }
+        }
+        return false;
+    } // isValidIANAEncoding(String):boolean
+
+    /**
+     * Returns true if the encoding name is a valid Java encoding.
+     * This method does not verify that there is a decoder available
+     * for this encoding, only that the characters are valid for an
+     * Java encoding name.
+     *
+     * @param javaEncoding The Java encoding name.
+     */
+    public static boolean isValidJavaEncoding(String javaEncoding) {
+        if (javaEncoding != null) {
+            int length = javaEncoding.length();
+            if (length > 0) {
+                for (int i = 1; i < length; i++) {
+                    char c = javaEncoding.charAt(i);
+                    if ((c < 'A' || c > 'Z') && (c < 'a' || c > 'z') &&
+                        (c < '0' || c > '9') && c != '.' && c != '_' &&
+                        c != '-') {
+                        return false;
+                    }
+                }
+                return true;
+            }
+        }
+        return false;
+    } // isValidIANAEncoding(String):boolean
+    
+    // other methods
+    
+    /**
+     * Trims space characters as defined by production [3] in 
+     * the XML 1.0 specification from both ends of the given string.
+     * 
+     * @param value the string to be trimmed
+     * @return the given string with the space characters trimmed
+     * from both ends
+     */
+    public static String trim(String value) {
+        int start;
+        int end;
+        final int lengthMinusOne = value.length() - 1;
+        for (start = 0; start <= lengthMinusOne; ++start) {
+            if (!isSpace(value.charAt(start))) {
+                break;
+            }
+        }
+        for (end = lengthMinusOne; end >= start; --end) {
+            if (!isSpace(value.charAt(end))) {
+                break;
+            }
+        }
+        if (start == 0 && end == lengthMinusOne) {
+            return value;
+        }
+        if (start > lengthMinusOne) {
+            return "";
+        }
+        return value.substring(start, end + 1);
+    } // trim(String):String
+
+} // class XMLChar

http://git-wip-us.apache.org/repos/asf/jena/blob/c9a7e646/jena-core/src/main/java/org/apache/jena/ext/xerces/xni/NamespaceContext.java
----------------------------------------------------------------------
diff --git a/jena-core/src/main/java/org/apache/jena/ext/xerces/xni/NamespaceContext.java b/jena-core/src/main/java/org/apache/jena/ext/xerces/xni/NamespaceContext.java
new file mode 100644
index 0000000..cb2235c
--- /dev/null
+++ b/jena-core/src/main/java/org/apache/jena/ext/xerces/xni/NamespaceContext.java
@@ -0,0 +1,177 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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.jena.ext.xerces.xni;
+
+import java.util.Enumeration;
+
+/**
+ * Represents an interface to query namespace information.
+ * <p>
+ * The prefix and namespace must be identical references for equal strings, thus
+ * each string should be internalized (@see String.intern()) 
+ * or added to the <code>SymbolTable</code>
+ *
+ * @see <a href="../../../../../xerces2/org/apache/xerces/util/SymbolTable.html">
+ * org.apache.xerces.util.SymbolTable</a>
+ *
+ * @author Andy Clark, IBM
+ *
+ * @version $Id: NamespaceContext.java 447247 2006-09-18 05:23:52Z mrglavas $
+ */
+public interface NamespaceContext {
+
+    //
+    // Constants
+    //
+
+    /**
+     * The XML Namespace ("http://www.w3.org/XML/1998/namespace"). This is
+     * the Namespace URI that is automatically mapped to the "xml" prefix.
+     */
+    public final static String XML_URI = "http://www.w3.org/XML/1998/namespace".intern();
+
+    /**
+     * XML Information Set REC
+     * all namespace attributes (including those named xmlns, 
+     * whose [prefix] property has no value) have a namespace URI of http://www.w3.org/2000/xmlns/
+     */
+    public final static String XMLNS_URI = "http://www.w3.org/2000/xmlns/".intern();
+
+    //
+    // NamespaceContext methods
+    //
+        
+    /**
+     * Start a new Namespace context.
+     * <p>
+     * A new context should be pushed at the beginning
+     * of each XML element: the new context will automatically inherit
+     * the declarations of its parent context, but it will also keep
+     * track of which declarations were made within this context.
+     * <p>
+     *
+     * @see #popContext
+     */
+    public void pushContext();
+
+   /**
+     * Revert to the previous Namespace context.
+     * <p>
+     * The context should be popped at the end of each
+     * XML element.  After popping the context, all Namespace prefix
+     * mappings that were previously in force are restored.
+     * <p>
+     * Users must not attempt to declare additional Namespace
+     * prefixes after popping a context, unless you push another
+     * context first.
+     *
+     * @see #pushContext
+     */
+    public void popContext();
+
+    /**
+     * Declare a Namespace prefix.
+     * <p>
+     * This method declares a prefix in the current Namespace
+     * context; the prefix will remain in force until this context
+     * is popped, unless it is shadowed in a descendant context.
+     * <p>
+     * Note that to declare a default Namespace, use the empty string.  
+     * The prefixes "xml" and "xmlns" can't be rebound.
+     * <p>
+     * Note that you must <em>not</em> declare a prefix after
+     * you've pushed and popped another Namespace.
+     *
+     * @param prefix The prefix to declare, or null for the empty
+     *        string. 
+     * @param uri The Namespace URI to associate with the prefix.
+     *
+     * @return true if the prefix was legal, false otherwise
+     *
+     * @see #getURI
+     * @see #getDeclaredPrefixAt
+     */
+    public boolean declarePrefix(String prefix, String uri);
+    
+
+    /**
+     * Look up a prefix and get the currently-mapped Namespace URI.
+     * <p>
+     * This method looks up the prefix in the current context. If no mapping 
+     * is found, this methods will continue lookup in the parent context(s).
+     * Use the empty string ("") for the default Namespace.
+     *
+     * @param prefix The prefix to look up. 
+     *
+     * @return The associated Namespace URI, or null if the prefix
+     *         is undeclared in this context.
+     */
+    public String getURI(String prefix);
+    
+    /**
+     * Look up a namespace URI and get one of the mapped prefix.
+     * <p>
+     * This method looks up the namespace URI in the current context.
+     * If more than one prefix is currently mapped to the same URI, 
+     * this method will make an arbitrary selection
+     * If no mapping is found, this methods will continue lookup in the 
+     * parent context(s).
+     *
+     * @param uri The namespace URI to look up.
+     *
+     * @return One of the associated prefixes, or null if the uri
+     *         does not map to any prefix.
+     *
+     * @see #getPrefix
+     */
+    public String getPrefix(String uri);
+    
+    /**
+     * Return a count of locally declared prefixes, including
+     * the default prefix if bound.
+     */
+    public int getDeclaredPrefixCount();
+
+    /** 
+     * Returns the prefix at the specified index in the current context.
+     */
+    public String getDeclaredPrefixAt(int index);
+
+	/**
+	 * Return an enumeration of all prefixes whose declarations are active 
+     * in the current context. This includes declarations from parent contexts 
+     * that have not been overridden.
+	 * @return Enumeration
+	 */
+    @SuppressWarnings("all")
+    public Enumeration getAllPrefixes();
+    
+    /**
+     * Reset this Namespace support object for reuse.
+     *
+     * <p>It is necessary to invoke this method before reusing the
+     * Namespace support object for a new session.</p>
+     * 
+     * <p>Note that implementations of this method need to ensure that
+     * the declaration of the prefixes "xmlns" and "xml" are available.</p>
+     */
+    public void reset();
+    
+
+
+} // interface NamespaceContext

http://git-wip-us.apache.org/repos/asf/jena/blob/c9a7e646/jena-core/src/main/java/org/apache/jena/ext/xerces/xs/AttributePSVI.java
----------------------------------------------------------------------
diff --git a/jena-core/src/main/java/org/apache/jena/ext/xerces/xs/AttributePSVI.java b/jena-core/src/main/java/org/apache/jena/ext/xerces/xs/AttributePSVI.java
new file mode 100644
index 0000000..a07360d
--- /dev/null
+++ b/jena-core/src/main/java/org/apache/jena/ext/xerces/xs/AttributePSVI.java
@@ -0,0 +1,30 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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.jena.ext.xerces.xs;
+
+/**
+ *  Represents a PSVI item for one attribute information item. 
+ */
+public interface AttributePSVI extends ItemPSVI {
+    /**
+     * [attribute declaration]: An item isomorphic to the declaration 
+     * component itself. 
+     */
+    public XSAttributeDeclaration getAttributeDeclaration();
+
+}

http://git-wip-us.apache.org/repos/asf/jena/blob/c9a7e646/jena-core/src/main/java/org/apache/jena/ext/xerces/xs/ElementPSVI.java
----------------------------------------------------------------------
diff --git a/jena-core/src/main/java/org/apache/jena/ext/xerces/xs/ElementPSVI.java b/jena-core/src/main/java/org/apache/jena/ext/xerces/xs/ElementPSVI.java
new file mode 100644
index 0000000..d85e4cb
--- /dev/null
+++ b/jena-core/src/main/java/org/apache/jena/ext/xerces/xs/ElementPSVI.java
@@ -0,0 +1,47 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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.jena.ext.xerces.xs;
+
+/**
+ *  Represents a PSVI item for one element information item. 
+ */
+public interface ElementPSVI extends ItemPSVI {
+    /**
+     * [element declaration]: an item isomorphic to the element declaration 
+     * used to validate this element. 
+     */
+    public XSElementDeclaration getElementDeclaration();
+
+    /**
+     *  [notation]: the notation declaration. 
+     */
+    public XSNotationDeclaration getNotation();
+
+    /**
+     * [nil]: true if clause 3.2 of Element Locally Valid (Element) (3.3.4) is 
+     * satisfied, otherwise false. 
+     */
+    public boolean getNil();
+
+    /**
+     * schema information: the schema information property if it is the 
+     * validation root, <code>null</code> otherwise. 
+     */
+    public XSModel getSchemaInformation();
+
+}


[18/24] jena git commit: JENA-1537: Remove dependency on Xerces. Import needed code

Posted by an...@apache.org.
http://git-wip-us.apache.org/repos/asf/jena/blob/c9a7e646/jena-core/src/main/java/org/apache/jena/ext/xerces/impl/dv/xs/IDDV.java
----------------------------------------------------------------------
diff --git a/jena-core/src/main/java/org/apache/jena/ext/xerces/impl/dv/xs/IDDV.java b/jena-core/src/main/java/org/apache/jena/ext/xerces/impl/dv/xs/IDDV.java
new file mode 100644
index 0000000..d76d8c3
--- /dev/null
+++ b/jena-core/src/main/java/org/apache/jena/ext/xerces/impl/dv/xs/IDDV.java
@@ -0,0 +1,56 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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.jena.ext.xerces.impl.dv.xs;
+
+import org.apache.jena.ext.xerces.impl.dv.InvalidDatatypeValueException;
+import org.apache.jena.ext.xerces.impl.dv.ValidationContext;
+import org.apache.jena.ext.xerces.util.XMLChar;
+
+/**
+ * Represent the schema type "ID"
+ *
+ * @xerces.internal 
+ *
+ * @author Neeraj Bajaj, Sun Microsystems, inc.
+ * @author Sandy Gao, IBM
+ *
+ * @version $Id: IDDV.java 699892 2008-09-28 21:08:27Z mrglavas $
+ */
+public class IDDV extends TypeValidator{
+
+    @Override
+    public short getAllowedFacets(){
+        return (XSSimpleTypeDecl.FACET_LENGTH | XSSimpleTypeDecl.FACET_MINLENGTH | XSSimpleTypeDecl.FACET_MAXLENGTH | XSSimpleTypeDecl.FACET_PATTERN | XSSimpleTypeDecl.FACET_ENUMERATION | XSSimpleTypeDecl.FACET_WHITESPACE );
+    }
+
+    @Override
+    public Object getActualValue(String content, ValidationContext context) throws InvalidDatatypeValueException {
+        if (!XMLChar.isValidNCName(content)) {
+            throw new InvalidDatatypeValueException("cvc-datatype-valid.1.2.1", new Object[]{content, "NCName"});
+        }
+        return content;
+    }
+
+    @Override
+    public void checkExtraRules(Object value, ValidationContext context) throws InvalidDatatypeValueException {
+        String content = (String)value;
+        if (context.isIdDeclared(content))
+            throw new InvalidDatatypeValueException("cvc-id.2", new Object[]{content});
+        context.addId(content);
+    }
+} // class IDDV

http://git-wip-us.apache.org/repos/asf/jena/blob/c9a7e646/jena-core/src/main/java/org/apache/jena/ext/xerces/impl/dv/xs/IDREFDV.java
----------------------------------------------------------------------
diff --git a/jena-core/src/main/java/org/apache/jena/ext/xerces/impl/dv/xs/IDREFDV.java b/jena-core/src/main/java/org/apache/jena/ext/xerces/impl/dv/xs/IDREFDV.java
new file mode 100644
index 0000000..369a347
--- /dev/null
+++ b/jena-core/src/main/java/org/apache/jena/ext/xerces/impl/dv/xs/IDREFDV.java
@@ -0,0 +1,55 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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.jena.ext.xerces.impl.dv.xs;
+
+import org.apache.jena.ext.xerces.impl.dv.InvalidDatatypeValueException;
+import org.apache.jena.ext.xerces.impl.dv.ValidationContext;
+import org.apache.jena.ext.xerces.util.XMLChar;
+
+/**
+ * Represent the schema type "IDREF"
+ *
+ * @xerces.internal 
+ *
+ * @author Neeraj Bajaj, Sun Microsystems, inc.
+ * @author Sandy Gao, IBM
+ *
+ * @version $Id: IDREFDV.java 446745 2006-09-15 21:43:58Z mrglavas $
+ */
+public class IDREFDV extends TypeValidator{
+
+    @Override
+    public short getAllowedFacets(){
+        return (XSSimpleTypeDecl.FACET_LENGTH | XSSimpleTypeDecl.FACET_MINLENGTH | XSSimpleTypeDecl.FACET_MAXLENGTH | XSSimpleTypeDecl.FACET_PATTERN | XSSimpleTypeDecl.FACET_ENUMERATION | XSSimpleTypeDecl.FACET_WHITESPACE );
+    }
+
+    @Override
+    public Object getActualValue(String content, ValidationContext context) throws InvalidDatatypeValueException {
+        if (!XMLChar.isValidNCName(content)) {
+            throw new InvalidDatatypeValueException("cvc-datatype-valid.1.2.1", new Object[]{content, "NCName"});
+        }
+        return content;
+    }
+
+    @Override
+    public void checkExtraRules(Object value, ValidationContext context) throws InvalidDatatypeValueException {
+        context.addIdRef((String)value);
+    }
+
+}//IDREF class
+

http://git-wip-us.apache.org/repos/asf/jena/blob/c9a7e646/jena-core/src/main/java/org/apache/jena/ext/xerces/impl/dv/xs/IntegerDV.java
----------------------------------------------------------------------
diff --git a/jena-core/src/main/java/org/apache/jena/ext/xerces/impl/dv/xs/IntegerDV.java b/jena-core/src/main/java/org/apache/jena/ext/xerces/impl/dv/xs/IntegerDV.java
new file mode 100644
index 0000000..69a6405
--- /dev/null
+++ b/jena-core/src/main/java/org/apache/jena/ext/xerces/impl/dv/xs/IntegerDV.java
@@ -0,0 +1,43 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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.jena.ext.xerces.impl.dv.xs;
+
+import org.apache.jena.ext.xerces.impl.dv.InvalidDatatypeValueException;
+import org.apache.jena.ext.xerces.impl.dv.ValidationContext;
+
+/**
+ * Represent the schema type "integer"
+ *
+ * @xerces.internal 
+ *
+ * @author Sandy Gao, IBM
+ *
+ * @version $Id: IntegerDV.java 446745 2006-09-15 21:43:58Z mrglavas $
+ */
+public class IntegerDV extends DecimalDV {
+
+    @Override
+    public Object getActualValue(String content, ValidationContext context) throws InvalidDatatypeValueException {
+        try {
+            return new XDecimal(content, true);
+        } catch (NumberFormatException nfe) {
+            throw new InvalidDatatypeValueException("cvc-datatype-valid.1.2.1", new Object[]{content, "integer"});
+        }
+    }
+    
+} // class EntityDV

http://git-wip-us.apache.org/repos/asf/jena/blob/c9a7e646/jena-core/src/main/java/org/apache/jena/ext/xerces/impl/dv/xs/ListDV.java
----------------------------------------------------------------------
diff --git a/jena-core/src/main/java/org/apache/jena/ext/xerces/impl/dv/xs/ListDV.java b/jena-core/src/main/java/org/apache/jena/ext/xerces/impl/dv/xs/ListDV.java
new file mode 100644
index 0000000..b07202a
--- /dev/null
+++ b/jena-core/src/main/java/org/apache/jena/ext/xerces/impl/dv/xs/ListDV.java
@@ -0,0 +1,146 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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.jena.ext.xerces.impl.dv.xs;
+
+import java.util.AbstractList;
+
+import org.apache.jena.ext.xerces.impl.dv.InvalidDatatypeValueException;
+import org.apache.jena.ext.xerces.impl.dv.ValidationContext;
+import org.apache.jena.ext.xerces.xs.datatypes.ObjectList;
+
+/**
+ * Represent the schema list types
+ *
+ * @xerces.internal 
+ *
+ * @author Neeraj Bajaj, Sun Microsystems, inc.
+ * @author Sandy Gao, IBM
+ *
+ * @version $Id: ListDV.java 725840 2008-12-11 22:19:06Z mrglavas $
+ */
+public class ListDV extends TypeValidator{
+
+    @Override
+    public short getAllowedFacets(){
+          return (XSSimpleTypeDecl.FACET_LENGTH | XSSimpleTypeDecl.FACET_MINLENGTH | XSSimpleTypeDecl.FACET_MAXLENGTH | XSSimpleTypeDecl.FACET_PATTERN | XSSimpleTypeDecl.FACET_ENUMERATION | XSSimpleTypeDecl.FACET_WHITESPACE );
+    }
+
+    // this method should never be called: XSSimpleTypeDecl is responsible for
+    // calling the item type for the convertion
+    @Override
+    public Object getActualValue(String content, ValidationContext context) throws InvalidDatatypeValueException{
+        return content;
+    }
+
+    // length of a list type is the number of items in the list
+    @Override
+    public int getDataLength(Object value) {
+        return ((ListData)value).getLength();
+    }
+
+    final static class ListData extends AbstractList<Object> implements ObjectList {
+        final Object[] data;
+        private String canonical;
+        public ListData(Object[] data) {
+            this.data = data;
+        }
+        @Override
+        public synchronized String toString() {
+            if (canonical == null) {
+                int len = data.length;
+                StringBuffer buf = new StringBuffer();
+                if (len > 0) {
+                    buf.append(data[0].toString());
+                }
+                for (int i = 1; i < len; i++) {
+                    buf.append(' ');
+                    buf.append(data[i].toString());
+                }
+                canonical = buf.toString();
+            }
+            return canonical;
+        }
+        @Override
+        public int getLength() {
+            return data.length;
+        }
+        @Override
+        public boolean equals(Object obj) {
+            if (!(obj instanceof ListData))
+                return false;
+            Object[] odata = ((ListData)obj).data;
+    
+            int count = data.length;
+            if (count != odata.length)
+                return false;
+    
+            for (int i = 0 ; i < count ; i++) {
+                if (!data[i].equals(odata[i]))
+                    return false;
+            }//end of loop
+    
+            //everything went fine.
+            return true;
+        }
+        
+        @Override
+        public int hashCode() {
+            int hash = 0;
+            for (int i = 0; i < data.length; ++i) {
+                hash ^= data[i].hashCode();
+            }
+            return hash;
+        }
+        
+        @Override
+        public boolean contains(Object item) {
+            for (int i = 0;i < data.length; i++) {
+                if (item == data[i]) {
+                    return true;
+                }
+            }
+            return false;
+        }
+        
+        @Override
+        public Object item(int index) {
+            if (index < 0 || index >= data.length) {
+                return null;
+            }
+            return data[index];
+        }
+        
+        /*
+         * List methods
+         */
+        
+        @Override
+        public Object get(int index) {
+            if (index >= 0 && index < data.length) {
+                return data[index];
+            }
+            throw new IndexOutOfBoundsException("Index: " + index);
+        }
+        
+        @Override
+        public int size() {
+            return getLength();
+        }
+    }
+} // class ListDV
+

http://git-wip-us.apache.org/repos/asf/jena/blob/c9a7e646/jena-core/src/main/java/org/apache/jena/ext/xerces/impl/dv/xs/MonthDV.java
----------------------------------------------------------------------
diff --git a/jena-core/src/main/java/org/apache/jena/ext/xerces/impl/dv/xs/MonthDV.java b/jena-core/src/main/java/org/apache/jena/ext/xerces/impl/dv/xs/MonthDV.java
new file mode 100644
index 0000000..1e83f51
--- /dev/null
+++ b/jena-core/src/main/java/org/apache/jena/ext/xerces/impl/dv/xs/MonthDV.java
@@ -0,0 +1,168 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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.jena.ext.xerces.impl.dv.xs;
+
+import javax.xml.datatype.DatatypeConstants;
+import javax.xml.datatype.XMLGregorianCalendar;
+
+import org.apache.jena.ext.xerces.impl.dv.InvalidDatatypeValueException;
+import org.apache.jena.ext.xerces.impl.dv.ValidationContext;
+
+/**
+ * Validator for &lt;gMonth&gt; datatype (W3C Schema Datatypes)
+ *
+ * @xerces.internal 
+ *
+ * @author Elena Litani
+ * @author Gopal Sharma, SUN Microsystem Inc.
+ *
+ * @version $Id: MonthDV.java 937741 2010-04-25 04:25:46Z mrglavas $
+ */
+
+public class MonthDV extends AbstractDateTimeDV {
+
+    /**
+     * Convert a string to a compiled form
+     *
+     * @param  content The lexical representation of gMonth
+     * @return a valid and normalized gMonth object
+     */
+    @Override
+    public Object getActualValue(String content, ValidationContext context) throws InvalidDatatypeValueException{
+        try{
+            return parse(content);
+        } catch(Exception ex){
+            throw new InvalidDatatypeValueException("cvc-datatype-valid.1.2.1", new Object[]{content, "gMonth"});
+        }
+    }
+
+    /**
+     * Parses, validates and computes normalized version of gMonth object
+     *
+     * @param str    The lexical representation of gMonth object --MM
+     *               with possible time zone Z or (-),(+)hh:mm
+     * @return normalized date representation
+     * @exception SchemaDateTimeException Invalid lexical representation
+     */
+    protected DateTimeData parse(String str) throws SchemaDateTimeException{
+        DateTimeData date = new DateTimeData(str, this);
+        int len = str.length();
+
+        //set constants
+        date.year=YEAR;
+        date.day=DAY;
+        if (str.charAt(0)!='-' || str.charAt(1)!='-') {
+            throw new SchemaDateTimeException("Invalid format for gMonth: "+str);
+        }
+        int stop = 4;
+        date.month=parseInt(str,2,stop);
+
+        // REVISIT: allow both --MM and --MM-- now.
+        // need to remove the following 4 lines to disallow --MM--
+        // when the errata is offically in the rec.
+        if (str.length() >= stop+2 &&
+            str.charAt(stop) == '-' && str.charAt(stop+1) == '-') {
+            stop += 2;
+        }
+        if (stop < len) {
+            if (!isNextCharUTCSign(str, stop, len)) {
+                throw new SchemaDateTimeException ("Error in month parsing: "+str);
+            }
+            else {
+                getTimeZone(str, date, stop, len);
+            }
+        }
+        //validate and normalize
+        validateDateTime(date);
+
+        //save unnormalized values
+        saveUnnormalized(date);
+        
+        if ( date.utc!=0 && date.utc!='Z' ) {
+            normalize(date);
+        }
+        date.position = 1;
+        return date;
+    }
+
+    /**
+     * Overwrite compare algorithm to optimize month comparison
+     *
+     * REVISIT: this one is lack of the third parameter: boolean strict, so it
+     *          doesn't override the method in the base. But maybe this method
+     *          is not correctly implemented, and I did encounter errors when
+     *          trying to add the extra parameter. I'm leaving it as is. -SG
+     *
+     * @param date1
+     * @param date2
+     * @return less, greater, equal, indeterminate
+     */
+    /*protected  short compareDates(DateTimeData date1, DateTimeData date2) {
+
+        if ( date1.utc==date2.utc ) {
+            return (short)((date1.month>=date2.month)?(date1.month>date2.month)?1:0:-1);
+        }
+
+        if ( date1.utc=='Z' || date2.utc=='Z' ) {
+
+            if ( date1.month==date2.month ) {
+                //--05--Z and --05--
+                return INDETERMINATE;
+            }
+            if ( (date1.month+1 == date2.month || date1.month-1 == date2.month) ) {
+                //--05--Z and (--04-- or --05--)
+                //REVISIT: should this case be less than or equal?
+                //         maxExclusive should fail but what about maxInclusive
+                //
+                return INDETERMINATE;
+            }
+        }
+
+        if ( date1.month<date2.month ) {
+            return -1;
+        }
+        else {
+            return 1;
+        }
+
+    }*/
+
+    /**
+     * Converts month object representation to String
+     *
+     * @param date   month object
+     * @return lexical representation of month: --MM with an optional time zone sign
+     */
+    @Override
+    protected String dateToString(DateTimeData date) {
+        StringBuffer message = new StringBuffer(5);
+        message.append('-');
+        message.append('-');
+        append(message, date.month, 2);
+        append(message, (char)date.utc, 0);
+        return message.toString();
+    }
+    
+    @Override
+    protected XMLGregorianCalendar getXMLGregorianCalendar(DateTimeData date) {
+        return datatypeFactory.newXMLGregorianCalendar(DatatypeConstants.FIELD_UNDEFINED, date.unNormMonth, 
+                DatatypeConstants.FIELD_UNDEFINED, DatatypeConstants.FIELD_UNDEFINED, DatatypeConstants.FIELD_UNDEFINED, 
+                DatatypeConstants.FIELD_UNDEFINED, DatatypeConstants.FIELD_UNDEFINED, 
+                date.hasTimeZone() ? date.timezoneHr * 60 + date.timezoneMin : DatatypeConstants.FIELD_UNDEFINED);
+    }
+}

http://git-wip-us.apache.org/repos/asf/jena/blob/c9a7e646/jena-core/src/main/java/org/apache/jena/ext/xerces/impl/dv/xs/MonthDayDV.java
----------------------------------------------------------------------
diff --git a/jena-core/src/main/java/org/apache/jena/ext/xerces/impl/dv/xs/MonthDayDV.java b/jena-core/src/main/java/org/apache/jena/ext/xerces/impl/dv/xs/MonthDayDV.java
new file mode 100644
index 0000000..db5af38
--- /dev/null
+++ b/jena-core/src/main/java/org/apache/jena/ext/xerces/impl/dv/xs/MonthDayDV.java
@@ -0,0 +1,132 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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.jena.ext.xerces.impl.dv.xs;
+
+import javax.xml.datatype.DatatypeConstants;
+import javax.xml.datatype.XMLGregorianCalendar;
+
+import org.apache.jena.ext.xerces.impl.dv.InvalidDatatypeValueException;
+import org.apache.jena.ext.xerces.impl.dv.ValidationContext;
+
+/**
+ * Validator for &lt;gMonthDay&gt; datatype (W3C Schema Datatypes)
+ *
+ * @xerces.internal 
+ *
+ * @author Elena Litani
+ * @author Gopal Sharma, SUN Microsystem Inc.
+ *
+ * @version $Id: MonthDayDV.java 937741 2010-04-25 04:25:46Z mrglavas $
+ */
+
+public class MonthDayDV extends AbstractDateTimeDV {
+
+    //size without time zone: --MM-DD
+    private final static int MONTHDAY_SIZE = 7;
+
+    /**
+     * Convert a string to a compiled form
+     *
+     * @param  content The lexical representation of gMonthDay
+     * @return a valid and normalized gMonthDay object
+     */
+    @Override
+    public Object getActualValue(String content, ValidationContext context) throws InvalidDatatypeValueException {
+        try{
+            return parse(content);
+        } catch(Exception ex){
+            throw new InvalidDatatypeValueException("cvc-datatype-valid.1.2.1", new Object[]{content, "gMonthDay"});
+        }
+    }
+
+    /**
+     * Parses, validates and computes normalized version of gMonthDay object
+     *
+     * @param str    The lexical representation of gMonthDay object --MM-DD
+     *               with possible time zone Z or (-),(+)hh:mm
+     * @return normalized date representation
+     * @exception SchemaDateTimeException Invalid lexical representation
+     */
+    protected DateTimeData parse(String str) throws SchemaDateTimeException{
+        DateTimeData date = new DateTimeData(str, this);
+        int len = str.length();
+
+        //initialize
+        date.year=YEAR;
+
+        if (str.charAt(0)!='-' || str.charAt(1)!='-') {
+            throw new SchemaDateTimeException("Invalid format for gMonthDay: "+str);
+        }
+        date.month=parseInt(str, 2, 4);
+        int start=4;
+
+        if (str.charAt(start++)!='-') {
+            throw new SchemaDateTimeException("Invalid format for gMonthDay: " + str);
+        }
+
+        date.day=parseInt(str, start, start+2);
+
+        if ( MONTHDAY_SIZE<len ) {
+            if (!isNextCharUTCSign(str, MONTHDAY_SIZE, len)) {
+                throw new SchemaDateTimeException ("Error in month parsing:" +str);
+            }
+            else {
+                getTimeZone(str, date, MONTHDAY_SIZE, len);
+            }
+        }
+        //validate and normalize
+
+        validateDateTime(date);
+        
+        //save unnormalized values
+        saveUnnormalized(date);
+        
+        if ( date.utc!=0 && date.utc!='Z' ) {
+            normalize(date);
+        }
+        date.position = 1;
+        return date;
+    }
+
+    /**
+     * Converts gMonthDay object representation to String
+     *
+     * @param date   gmonthDay object
+     * @return lexical representation of month: --MM-DD with an optional time zone sign
+     */
+    @Override
+    protected String dateToString(DateTimeData date) {
+        StringBuffer message = new StringBuffer(8);
+        message.append('-');
+        message.append('-');
+        append(message, date.month, 2);
+        message.append('-');
+        append(message, date.day, 2);
+        append(message, (char)date.utc, 0);
+        return message.toString();
+    }
+    
+    @Override
+    protected XMLGregorianCalendar getXMLGregorianCalendar(DateTimeData date) {
+        return datatypeFactory.newXMLGregorianCalendar(DatatypeConstants.FIELD_UNDEFINED, date.unNormMonth, date.unNormDay, 
+                DatatypeConstants.FIELD_UNDEFINED, DatatypeConstants.FIELD_UNDEFINED, 
+                DatatypeConstants.FIELD_UNDEFINED, DatatypeConstants.FIELD_UNDEFINED, 
+                date.hasTimeZone() ? date.timezoneHr * 60 + date.timezoneMin : DatatypeConstants.FIELD_UNDEFINED);
+    }
+}
+

http://git-wip-us.apache.org/repos/asf/jena/blob/c9a7e646/jena-core/src/main/java/org/apache/jena/ext/xerces/impl/dv/xs/PrecisionDecimalDV.java
----------------------------------------------------------------------
diff --git a/jena-core/src/main/java/org/apache/jena/ext/xerces/impl/dv/xs/PrecisionDecimalDV.java b/jena-core/src/main/java/org/apache/jena/ext/xerces/impl/dv/xs/PrecisionDecimalDV.java
new file mode 100644
index 0000000..e2bd4c3
--- /dev/null
+++ b/jena-core/src/main/java/org/apache/jena/ext/xerces/impl/dv/xs/PrecisionDecimalDV.java
@@ -0,0 +1,369 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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.jena.ext.xerces.impl.dv.xs;
+
+import org.apache.jena.ext.xerces.impl.dv.InvalidDatatypeValueException;
+import org.apache.jena.ext.xerces.impl.dv.ValidationContext;
+
+/**
+ * Validator for <precisionDecimal> datatype (W3C Schema 1.1)
+ * 
+ * @xerces.experimental
+ * 
+ * @author Ankit Pasricha, IBM
+ * 
+ * @version $Id: PrecisionDecimalDV.java 446745 2006-09-15 21:43:58Z mrglavas $
+ */
+@SuppressWarnings("all")
+class PrecisionDecimalDV extends TypeValidator {
+    
+    static class XPrecisionDecimal {
+        
+        // sign: 0 for absent; 1 for positive values; -1 for negative values (except in case of INF, -INF)
+        int sign = 1;
+        // total digits. >= 1
+        int totalDigits = 0;
+        // integer digits when sign != 0
+        int intDigits = 0;
+        // fraction digits when sign != 0
+        int fracDigits = 0;
+        //precision
+        //int precision = 0;
+        // the string representing the integer part
+        String ivalue = "";
+        // the string representing the fraction part
+        String fvalue = "";
+        
+        int pvalue = 0;
+        
+        
+        XPrecisionDecimal(String content) throws NumberFormatException {
+            if(content.equals("NaN")) {
+                ivalue = content;
+                sign = 0;
+            }
+            if(content.equals("+INF") || content.equals("INF") || content.equals("-INF")) {
+                ivalue = content.charAt(0) == '+' ? content.substring(1) : content;
+                return;
+            }
+            initD(content);
+        }
+        
+        void initD(String content) throws NumberFormatException {
+            int len = content.length();
+            if (len == 0)
+                throw new NumberFormatException();
+            
+            // these 4 variables are used to indicate where the integre/fraction
+            // parts start/end.
+            int intStart = 0, intEnd = 0, fracStart = 0, fracEnd = 0;
+            
+            // Deal with leading sign symbol if present
+            if (content.charAt(0) == '+') {
+                // skip '+', so intStart should be 1
+                intStart = 1;
+            }
+            else if (content.charAt(0) == '-') {
+                intStart = 1;
+                sign = -1;
+            }
+            
+            // skip leading zeroes in integer part
+            int actualIntStart = intStart;
+            while (actualIntStart < len && content.charAt(actualIntStart) == '0') {
+                actualIntStart++;
+            }
+            
+            // Find the ending position of the integer part
+            for (intEnd = actualIntStart; intEnd < len && TypeValidator.isDigit(content.charAt(intEnd)); intEnd++);
+            
+            // Not reached the end yet
+            if (intEnd < len) {
+                // the remaining part is not ".DDD" or "EDDD" or "eDDD", error
+                if (content.charAt(intEnd) != '.' && content.charAt(intEnd) != 'E' && content.charAt(intEnd) != 'e')
+                    throw new NumberFormatException();
+                
+                if(content.charAt(intEnd) == '.') {
+                    // fraction part starts after '.', and ends at the end of the input
+                    fracStart = intEnd + 1;
+                    
+                    // find location of E or e (if present)
+                    // Find the ending position of the fracion part
+                    for (fracEnd = fracStart;
+                    fracEnd < len && TypeValidator.isDigit(content.charAt(fracEnd));
+                    fracEnd++);
+                }
+                else {
+                    pvalue = Integer.parseInt(content.substring(intEnd + 1, len));
+                }
+            }
+            
+            // no integer part, no fraction part, error.
+            if (intStart == intEnd && fracStart == fracEnd)
+                throw new NumberFormatException();
+            
+            // ignore trailing zeroes in fraction part
+            /*while (fracEnd > fracStart && content.charAt(fracEnd-1) == '0') {
+             fracEnd--;
+             }*/
+            
+            // check whether there is non-digit characters in the fraction part
+            for (int fracPos = fracStart; fracPos < fracEnd; fracPos++) {
+                if (!TypeValidator.isDigit(content.charAt(fracPos)))
+                    throw new NumberFormatException();
+            }
+            
+            intDigits = intEnd - actualIntStart;
+            fracDigits = fracEnd - fracStart;
+            
+            if (intDigits > 0) {
+                ivalue = content.substring(actualIntStart, intEnd);
+            }
+            
+            if (fracDigits > 0) {
+                fvalue = content.substring(fracStart, fracEnd);
+                if(fracEnd < len) {
+                    pvalue = Integer.parseInt(content.substring(fracEnd + 1, len));
+                }
+            }
+            totalDigits = intDigits + fracDigits;
+        }
+        
+        
+        @Override
+        public boolean equals(Object val) {
+            if (val == this)
+                return true;
+            
+            if (!(val instanceof XPrecisionDecimal))
+                return false;
+            XPrecisionDecimal oval = (XPrecisionDecimal)val;
+            
+            return this.compareTo(oval) == EQUAL;
+        }
+        
+        /**
+         * @return
+         */
+        private int compareFractionalPart(XPrecisionDecimal oval) {
+            if(fvalue.equals(oval.fvalue))
+                return EQUAL;
+            
+            StringBuffer temp1 = new StringBuffer(fvalue);
+            StringBuffer temp2 = new StringBuffer(oval.fvalue);
+            
+            truncateTrailingZeros(temp1, temp2);
+            return temp1.toString().compareTo(temp2.toString());
+        }
+        
+        private void truncateTrailingZeros(StringBuffer fValue, StringBuffer otherFValue) {
+            for(int i = fValue.length() - 1;i >= 0; i--)
+                if(fValue.charAt(i) == '0')
+                    fValue.deleteCharAt(i);
+                else
+                    break;
+            
+            for(int i = otherFValue.length() - 1;i >= 0; i--)
+                if(otherFValue.charAt(i) == '0')
+                    otherFValue.deleteCharAt(i);
+                else
+                    break;
+        }
+        
+        public int compareTo(XPrecisionDecimal val) {
+            
+            // seen NaN
+            if(sign == 0)
+                return INDETERMINATE;
+            
+            //INF is greater than everything and equal to itself
+            if(ivalue.equals("INF") || val.ivalue.equals("INF")) {
+                if(ivalue.equals(val.ivalue))
+                    return EQUAL;
+                else if(ivalue.equals("INF"))
+                    return GREATER_THAN;
+                return LESS_THAN;
+            }
+            
+            //-INF is smaller than everything and equal itself
+            if(ivalue.equals("-INF") || val.ivalue.equals("-INF")) {
+                if(ivalue.equals(val.ivalue))
+                    return EQUAL;
+                else if(ivalue.equals("-INF"))
+                    return LESS_THAN;
+                return GREATER_THAN;
+            }
+            
+            if (sign != val.sign)
+                return sign > val.sign ? GREATER_THAN : LESS_THAN;
+            
+            return sign * compare(val);
+        }
+        
+        // To enable comparison - the exponent part of the decimal will be limited
+        // to the max value of int.
+        private int compare(XPrecisionDecimal val) {     	
+            
+            if(pvalue != 0 || val.pvalue != 0) {
+                if(pvalue == val.pvalue)
+                    return intComp(val);
+                else {
+                    
+                    if(intDigits + pvalue != val.intDigits + val.pvalue)
+                        return intDigits + pvalue > val.intDigits + val.pvalue ? GREATER_THAN : LESS_THAN;
+                    
+                    //otherwise the 2 combined values are the same
+                    if(pvalue > val.pvalue) {
+                        int expDiff = pvalue - val.pvalue;
+                        StringBuffer buffer = new StringBuffer(ivalue);
+                        StringBuffer fbuffer = new StringBuffer(fvalue);
+                        for(int i = 0;i < expDiff; i++) {
+                            if(i < fracDigits) {
+                                buffer.append(fvalue.charAt(i));
+                                fbuffer.deleteCharAt(i);
+                            }
+                            else
+                                buffer.append('0');
+                        }       				
+                        return compareDecimal(buffer.toString(), val.ivalue, fbuffer.toString(), val.fvalue);
+                    }
+                    else {
+                        int expDiff = val.pvalue - pvalue;
+                        StringBuffer buffer = new StringBuffer(val.ivalue);
+                        StringBuffer fbuffer = new StringBuffer(val.fvalue);
+                        for(int i = 0;i < expDiff; i++) {
+                            if(i < val.fracDigits) {
+                                buffer.append(val.fvalue.charAt(i));
+                                fbuffer.deleteCharAt(i);
+                            }
+                            else
+                                buffer.append('0');
+                        }       				
+                        return compareDecimal(ivalue, buffer.toString(), fvalue, fbuffer.toString());
+                    }
+                }
+            }
+            else {
+                return intComp(val);
+            }
+        }
+        
+        /**
+         * @param val
+         * @return
+         */
+        private int intComp(XPrecisionDecimal val) {
+            if (intDigits != val.intDigits)
+                return intDigits > val.intDigits ? GREATER_THAN : LESS_THAN;
+            
+            return compareDecimal(ivalue, val.ivalue, fvalue, val.fvalue);
+        }
+        
+        /**
+         * @param val
+         * @return
+         */
+        private int compareDecimal(String iValue, String fValue, String otherIValue, String otherFValue) {
+            int ret = iValue.compareTo(otherIValue);
+            if (ret != 0)
+                return ret > 0 ? GREATER_THAN : LESS_THAN;
+            
+            if(fValue.equals(otherFValue))
+                return EQUAL;
+            
+            StringBuffer temp1=new StringBuffer(fValue);
+            StringBuffer temp2=new StringBuffer(otherFValue);
+            
+            truncateTrailingZeros(temp1, temp2);
+            ret = temp1.toString().compareTo(temp2.toString());
+            return ret == 0 ? EQUAL : (ret > 0 ? GREATER_THAN : LESS_THAN);
+        }
+        
+        private String canonical;
+        
+        @Override
+        public synchronized String toString() {
+            if (canonical == null) {
+                makeCanonical();
+            }
+            return canonical;
+        }
+        
+        private void makeCanonical() {
+            // REVISIT: to be determined by working group
+            canonical = "TBD by Working Group";
+        }
+        
+        /**
+         * @param decimal
+         * @return
+         */
+        public boolean isIdentical(XPrecisionDecimal decimal) {
+            if(ivalue.equals(decimal.ivalue) && (ivalue.equals("INF") || ivalue.equals("-INF") || ivalue.equals("NaN")))
+                return true;
+            
+            if(sign == decimal.sign && intDigits == decimal.intDigits && fracDigits == decimal.fracDigits && pvalue == decimal.pvalue 
+                    && ivalue.equals(decimal.ivalue) && fvalue.equals(decimal.fvalue))
+                return true;
+            return false;
+        }
+        
+    }
+    /* (non-Javadoc)
+     * @see org.apache.xerces.impl.dv.xs.TypeValidator#getAllowedFacets()
+     */
+    @Override
+    public short getAllowedFacets() {
+        return ( XSSimpleTypeDecl.FACET_PATTERN | XSSimpleTypeDecl.FACET_WHITESPACE | XSSimpleTypeDecl.FACET_ENUMERATION |XSSimpleTypeDecl.FACET_MAXINCLUSIVE |XSSimpleTypeDecl.FACET_MININCLUSIVE | XSSimpleTypeDecl.FACET_MAXEXCLUSIVE  | XSSimpleTypeDecl.FACET_MINEXCLUSIVE | XSSimpleTypeDecl.FACET_TOTALDIGITS | XSSimpleTypeDecl.FACET_FRACTIONDIGITS);
+    }
+    
+    /* (non-Javadoc)
+     * @see org.apache.xerces.impl.dv.xs.TypeValidator#getActualValue(java.lang.String, org.apache.xerces.impl.dv.ValidationContext)
+     */
+    @Override
+    public Object getActualValue(String content, ValidationContext context)
+    throws InvalidDatatypeValueException {
+        try {
+            return new XPrecisionDecimal(content);
+        } catch (NumberFormatException nfe) {
+            throw new InvalidDatatypeValueException("cvc-datatype-valid.1.2.1", new Object[]{content, "precisionDecimal"});
+        }
+    }
+    
+    @Override
+    public int compare(Object value1, Object value2) {
+        return ((XPrecisionDecimal)value1).compareTo((XPrecisionDecimal)value2);
+    }
+    
+    @Override
+    public int getFractionDigits(Object value) {
+        return ((XPrecisionDecimal)value).fracDigits;
+    }
+    
+    @Override
+    public int getTotalDigits(Object value) {
+        return ((XPrecisionDecimal)value).totalDigits;
+    }
+    
+    @Override
+    public boolean isIdentical(Object value1, Object value2) {
+        if(!(value2 instanceof XPrecisionDecimal) || !(value1 instanceof XPrecisionDecimal))
+            return false;
+        return ((XPrecisionDecimal)value1).isIdentical((XPrecisionDecimal)value2);	
+    }
+}

http://git-wip-us.apache.org/repos/asf/jena/blob/c9a7e646/jena-core/src/main/java/org/apache/jena/ext/xerces/impl/dv/xs/QNameDV.java
----------------------------------------------------------------------
diff --git a/jena-core/src/main/java/org/apache/jena/ext/xerces/impl/dv/xs/QNameDV.java b/jena-core/src/main/java/org/apache/jena/ext/xerces/impl/dv/xs/QNameDV.java
new file mode 100644
index 0000000..f0ac0ed
--- /dev/null
+++ b/jena-core/src/main/java/org/apache/jena/ext/xerces/impl/dv/xs/QNameDV.java
@@ -0,0 +1,112 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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.jena.ext.xerces.impl.dv.xs;
+
+// UNUSED
+public class QNameDV {}
+//
+//import org.apache.xerces.impl.dv.InvalidDatatypeValueException;
+//import org.apache.xerces.impl.dv.ValidationContext;
+//import org.apache.xerces.util.XMLChar;
+//import org.apache.xerces.xni.QName;
+//import org.apache.xerces.xs.datatypes.XSQName;
+//
+///**
+// * Represent the schema type "QName" and "NOTATION"
+// *
+// * @xerces.internal 
+// *
+// * @author Neeraj Bajaj, Sun Microsystems, inc.
+// * @author Sandy Gao, IBM
+// *
+// * @version $Id: QNameDV.java 701915 2008-10-06 02:39:42Z mrglavas $
+// */
+//public class QNameDV extends TypeValidator {
+//
+//    private static final String EMPTY_STRING = "".intern();
+//
+//    public short getAllowedFacets() {
+//        return (XSSimpleTypeDecl.FACET_LENGTH | XSSimpleTypeDecl.FACET_MINLENGTH | XSSimpleTypeDecl.FACET_MAXLENGTH | XSSimpleTypeDecl.FACET_PATTERN | XSSimpleTypeDecl.FACET_ENUMERATION | XSSimpleTypeDecl.FACET_WHITESPACE);
+//    }
+//
+//    public Object getActualValue(String content, ValidationContext context)
+//        throws InvalidDatatypeValueException {
+//
+//        // "prefix:localpart" or "localpart"
+//        // get prefix and local part out of content
+//        String prefix, localpart;
+//        int colonptr = content.indexOf(":");
+//        if (colonptr > 0) {
+//            prefix = context.getSymbol(content.substring(0,colonptr));
+//            localpart = content.substring(colonptr+1);
+//        } else {
+//            prefix = EMPTY_STRING;
+//            localpart = content;
+//        }
+//
+//        // both prefix (if any) a nd localpart must be valid NCName
+//        if (prefix.length() > 0 && !XMLChar.isValidNCName(prefix))
+//            throw new InvalidDatatypeValueException("cvc-datatype-valid.1.2.1", new Object[]{content, "QName"});
+//
+//        if(!XMLChar.isValidNCName(localpart))
+//            throw new InvalidDatatypeValueException("cvc-datatype-valid.1.2.1", new Object[]{content, "QName"});
+//
+//        // resove prefix to a uri, report an error if failed
+//        String uri = context.getURI(prefix);
+//        if (prefix.length() > 0 && uri == null)
+//            throw new InvalidDatatypeValueException("UndeclaredPrefix", new Object[]{content, prefix});
+//
+//        return new XQName(prefix, context.getSymbol(localpart), context.getSymbol(content), uri);
+//
+//    }
+//
+//    // REVISIT: qname and notation shouldn't support length facets.
+//    //          now we just return the length of the rawname
+//    public int getDataLength(Object value) {
+//        return ((XQName)value).rawname.length();
+//    }
+//
+//    /**
+//     * represent QName data
+//     */
+//    private static final class XQName extends QName implements XSQName {
+//        /** Constructs a QName with the specified values. */
+//        public XQName(String prefix, String localpart, String rawname, String uri) {
+//            setValues(prefix, localpart, rawname, uri);
+//        } // <init>(String,String,String,String)
+//
+//        /** Returns true if the two objects are equal. */
+//        public boolean equals(Object object) {
+//            if (object instanceof QName) {
+//                QName qname = (QName)object;
+//                return uri == qname.uri && localpart == qname.localpart;
+//            }
+//            return false;
+//        } // equals(Object):boolean
+//
+//        public String toString() {
+//            return rawname;
+//        }
+//        public javax.xml.namespace.QName getJAXPQName() {
+//            return new javax.xml.namespace.QName(uri, localpart, prefix);
+//        }
+//        public QName getXNIQName() {
+//            return this;
+//        }
+//    }
+//} // class QNameDVDV

http://git-wip-us.apache.org/repos/asf/jena/blob/c9a7e646/jena-core/src/main/java/org/apache/jena/ext/xerces/impl/dv/xs/SchemaDVFactoryImpl.java
----------------------------------------------------------------------
diff --git a/jena-core/src/main/java/org/apache/jena/ext/xerces/impl/dv/xs/SchemaDVFactoryImpl.java b/jena-core/src/main/java/org/apache/jena/ext/xerces/impl/dv/xs/SchemaDVFactoryImpl.java
new file mode 100644
index 0000000..54520e4
--- /dev/null
+++ b/jena-core/src/main/java/org/apache/jena/ext/xerces/impl/dv/xs/SchemaDVFactoryImpl.java
@@ -0,0 +1,76 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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.jena.ext.xerces.impl.dv.xs;
+
+import org.apache.jena.ext.xerces.impl.dv.XSSimpleType;
+import org.apache.jena.ext.xerces.util.SymbolHash;
+
+/**
+ * the factory to create/return built-in schema 1.0 DVs and create user-defined DVs
+ * 
+ * @xerces.internal 
+ *
+ * @author Neeraj Bajaj, Sun Microsystems, inc.
+ * @author Sandy Gao, IBM
+ * @author Khaled Noaman, IBM
+ *
+ * @version $Id: SchemaDVFactoryImpl.java 710089 2008-11-03 16:01:16Z knoaman $
+ */
+public class SchemaDVFactoryImpl extends BaseSchemaDVFactory {
+
+    static final SymbolHash fBuiltInTypes = new SymbolHash();
+    
+    static {
+        createBuiltInTypes();
+    }
+
+    // create all built-in types
+    static void createBuiltInTypes() {
+    	createBuiltInTypes(fBuiltInTypes, XSSimpleTypeDecl.fAnySimpleType);
+    	
+        // TODO: move specific 1.0 DV implementation from base
+    } //createBuiltInTypes()
+
+    /**
+     * Get a built-in simple type of the given name
+     * REVISIT: its still not decided within the Schema WG how to define the
+     *          ur-types and if all simple types should be derived from a
+     *          complex type, so as of now we ignore the fact that anySimpleType
+     *          is derived from anyType, and pass 'null' as the base of
+     *          anySimpleType. It needs to be changed as per the decision taken.
+     *
+     * @param name  the name of the datatype
+     * @return      the datatype validator of the given name
+     */
+    @Override
+    public XSSimpleType getBuiltInType(String name) {
+        return (XSSimpleType)fBuiltInTypes.get(name);
+    }
+
+    /**
+     * get all built-in simple types, which are stored in a hashtable keyed by
+     * the name
+     *
+     * @return      a hashtable which contains all built-in simple types
+     */
+    @Override
+    public SymbolHash getBuiltInTypes() {
+        return fBuiltInTypes.makeClone();
+    }
+
+}//SchemaDVFactoryImpl

http://git-wip-us.apache.org/repos/asf/jena/blob/c9a7e646/jena-core/src/main/java/org/apache/jena/ext/xerces/impl/dv/xs/SchemaDateTimeException.java
----------------------------------------------------------------------
diff --git a/jena-core/src/main/java/org/apache/jena/ext/xerces/impl/dv/xs/SchemaDateTimeException.java b/jena-core/src/main/java/org/apache/jena/ext/xerces/impl/dv/xs/SchemaDateTimeException.java
new file mode 100644
index 0000000..265b33a
--- /dev/null
+++ b/jena-core/src/main/java/org/apache/jena/ext/xerces/impl/dv/xs/SchemaDateTimeException.java
@@ -0,0 +1,37 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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.jena.ext.xerces.impl.dv.xs;
+
+/**
+ * @xerces.internal 
+ *  
+ * @version $Id: SchemaDateTimeException.java 446745 2006-09-15 21:43:58Z mrglavas $
+ */
+public class SchemaDateTimeException extends RuntimeException {
+    
+    /** Serialization version. */
+    static final long serialVersionUID = -8520832235337769040L;
+    
+    public SchemaDateTimeException () {
+        super();
+    }
+
+    public SchemaDateTimeException (String s) {
+        super (s);
+    }
+}

http://git-wip-us.apache.org/repos/asf/jena/blob/c9a7e646/jena-core/src/main/java/org/apache/jena/ext/xerces/impl/dv/xs/StringDV.java
----------------------------------------------------------------------
diff --git a/jena-core/src/main/java/org/apache/jena/ext/xerces/impl/dv/xs/StringDV.java b/jena-core/src/main/java/org/apache/jena/ext/xerces/impl/dv/xs/StringDV.java
new file mode 100644
index 0000000..aa75e41
--- /dev/null
+++ b/jena-core/src/main/java/org/apache/jena/ext/xerces/impl/dv/xs/StringDV.java
@@ -0,0 +1,46 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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.jena.ext.xerces.impl.dv.xs;
+
+import org.apache.jena.ext.xerces.impl.dv.InvalidDatatypeValueException;
+import org.apache.jena.ext.xerces.impl.dv.ValidationContext;
+
+/**
+ * Represent the schema type "string"
+ * 
+ * @xerces.internal 
+ *
+ * @author Neeraj Bajaj, Sun Microsystems, inc.
+ * @author Sandy Gao, IBM
+ *
+ * @version $Id: StringDV.java 446745 2006-09-15 21:43:58Z mrglavas $
+ */
+public class StringDV extends TypeValidator {
+
+    @Override
+    public short getAllowedFacets(){
+        return (XSSimpleTypeDecl.FACET_LENGTH | XSSimpleTypeDecl.FACET_MINLENGTH | XSSimpleTypeDecl.FACET_MAXLENGTH | XSSimpleTypeDecl.FACET_PATTERN | XSSimpleTypeDecl.FACET_ENUMERATION | XSSimpleTypeDecl.FACET_WHITESPACE );
+    }
+
+    @Override
+    public Object getActualValue(String content, ValidationContext context)
+        throws InvalidDatatypeValueException {
+        return content;
+    }
+
+} // class StringDV

http://git-wip-us.apache.org/repos/asf/jena/blob/c9a7e646/jena-core/src/main/java/org/apache/jena/ext/xerces/impl/dv/xs/TimeDV.java
----------------------------------------------------------------------
diff --git a/jena-core/src/main/java/org/apache/jena/ext/xerces/impl/dv/xs/TimeDV.java b/jena-core/src/main/java/org/apache/jena/ext/xerces/impl/dv/xs/TimeDV.java
new file mode 100644
index 0000000..e5342b4
--- /dev/null
+++ b/jena-core/src/main/java/org/apache/jena/ext/xerces/impl/dv/xs/TimeDV.java
@@ -0,0 +1,114 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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.jena.ext.xerces.impl.dv.xs;
+
+import javax.xml.datatype.DatatypeConstants;
+import javax.xml.datatype.XMLGregorianCalendar;
+
+import org.apache.jena.ext.xerces.impl.dv.InvalidDatatypeValueException;
+import org.apache.jena.ext.xerces.impl.dv.ValidationContext;
+
+/**
+ * Validator for &lt;time&gt; datatype (W3C Schema Datatypes)
+ * 
+ * @xerces.internal 
+ *
+ * @author Elena Litani
+ * @author Gopal Sharma, SUN Microsystem Inc.
+ *
+ * @version $Id: TimeDV.java 937741 2010-04-25 04:25:46Z mrglavas $
+ */
+public class TimeDV extends AbstractDateTimeDV {
+
+    /**
+     * Convert a string to a compiled form
+     *
+     * @param  content The lexical representation of time
+     * @return a valid and normalized time object
+     */
+    @Override
+    public Object getActualValue(String content, ValidationContext context) throws InvalidDatatypeValueException{
+        try{
+            return parse(content);
+        } catch(Exception ex){
+            throw new InvalidDatatypeValueException("cvc-datatype-valid.1.2.1", new Object[]{content, "time"});
+        }
+    }
+
+    /**
+     * Parses, validates and computes normalized version of time object
+     *
+     * @param str    The lexical representation of time object hh:mm:ss.sss
+     *               with possible time zone Z or (-),(+)hh:mm
+     *               Pattern: "(\\d\\d):(\\d\\d):(\\d\\d)(\\.(\\d)*)?(Z|(([-+])(\\d\\d)(:(\\d\\d))?))?")
+     * @return normalized time representation
+     * @exception SchemaDateTimeException Invalid lexical representation
+     */
+    protected DateTimeData parse(String str) throws SchemaDateTimeException{
+        DateTimeData date = new DateTimeData(str, this);
+        int len = str.length();
+
+        // time
+        // initialize to default values
+        date.year=YEAR;
+        date.month=MONTH;
+        date.day=15;
+        getTime(str, 0, len, date);
+
+        //validate and normalize
+
+        validateDateTime(date);
+
+        //save unnormalized values
+        saveUnnormalized(date);
+        
+        if ( date.utc!=0 && date.utc != 'Z') {
+            normalize(date);
+            date.day = 15;
+        }
+        date.position = 2;
+        return date;
+    }
+
+    /**
+     * Converts time object representation to String
+     *
+     * @param date   time object
+     * @return lexical representation of time: hh:mm:ss.sss with an optional time zone sign
+     */
+    @Override
+    protected String dateToString(DateTimeData date) {
+        StringBuffer message = new StringBuffer(16);
+        append(message, date.hour, 2);
+        message.append(':');
+        append(message, date.minute, 2);
+        message.append(':');
+        append(message, date.second);
+
+        append(message, (char)date.utc, 0);
+        return message.toString();
+    }
+    
+    @Override
+    protected XMLGregorianCalendar getXMLGregorianCalendar(DateTimeData date) {
+        return datatypeFactory.newXMLGregorianCalendar(null, DatatypeConstants.FIELD_UNDEFINED, 
+                DatatypeConstants.FIELD_UNDEFINED, date.unNormHour, date.unNormMinute, 
+                (int)date.unNormSecond, date.unNormSecond != 0 ? getFractionalSecondsAsBigDecimal(date) : null,
+                date.hasTimeZone() ? (date.timezoneHr * 60 + date.timezoneMin) : DatatypeConstants.FIELD_UNDEFINED);
+    }
+}

http://git-wip-us.apache.org/repos/asf/jena/blob/c9a7e646/jena-core/src/main/java/org/apache/jena/ext/xerces/impl/dv/xs/TypeValidator.java
----------------------------------------------------------------------
diff --git a/jena-core/src/main/java/org/apache/jena/ext/xerces/impl/dv/xs/TypeValidator.java b/jena-core/src/main/java/org/apache/jena/ext/xerces/impl/dv/xs/TypeValidator.java
new file mode 100644
index 0000000..8149c95
--- /dev/null
+++ b/jena-core/src/main/java/org/apache/jena/ext/xerces/impl/dv/xs/TypeValidator.java
@@ -0,0 +1,108 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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.jena.ext.xerces.impl.dv.xs;
+
+import org.apache.jena.ext.xerces.impl.dv.InvalidDatatypeValueException;
+import org.apache.jena.ext.xerces.impl.dv.ValidationContext;
+
+/**
+ * All primitive types plus ID/IDREF/ENTITY/INTEGER are derived from this abstract
+ * class. It provides extra information XSSimpleTypeDecl requires from each
+ * type: allowed facets, converting String to actual value, check equality,
+ * comparison, etc.
+ * 
+ * @xerces.internal 
+ *
+ * @author Neeraj Bajaj, Sun Microsystems, inc.
+ * @author Sandy Gao, IBM
+ *
+ * @version $Id: TypeValidator.java 446745 2006-09-15 21:43:58Z mrglavas $
+ */
+public abstract class TypeValidator {
+
+    // which facets are allowed for this type
+    public abstract short getAllowedFacets();
+
+    // convert a string to an actual value. for example,
+    // for number types (decimal, double, float, and types derived from them),
+    // get the BigDecimal, Double, Flout object.
+    // for some types (string and derived), they just return the string itself
+    public abstract Object getActualValue(String content, ValidationContext context)
+        throws InvalidDatatypeValueException;
+
+    // for ID/IDREF/ENTITY types, do some extra checking after the value is
+    // checked to be valid with respect to both lexical representation and
+    // facets
+    public void checkExtraRules(Object value, ValidationContext context) throws InvalidDatatypeValueException {
+    }
+
+    // the following methods might not be supported by every DV.
+    // but XSSimpleTypeDecl should know which type supports which methods,
+    // and it's an *internal* error if a method is called on a DV that
+    // doesn't support it.
+
+    //order constants
+    public static final short LESS_THAN     = -1;
+    public static final short EQUAL         = 0;
+    public static final short GREATER_THAN  = 1;
+    public static final short INDETERMINATE = 2;
+    
+    // where there is distinction between identity and equality, this method
+    // will be overwritten
+    // checks whether the two values are identical; for ex, this distinguishes 
+    // -0.0 from 0.0 
+    public boolean isIdentical (Object value1, Object value2) {
+        return value1.equals(value2);
+    }
+
+    // check the order relation between the two values
+    // the parameters are in compiled form (from getActualValue)
+    public int compare(Object value1, Object value2) {
+        return -1;
+    }
+
+    // get the length of the value
+    // the parameters are in compiled form (from getActualValue)
+    public int getDataLength(Object value) {
+        return (value instanceof String) ? ((String)value).length() : -1;
+    }
+
+    // get the number of digits of the value
+    // the parameters are in compiled form (from getActualValue)
+    public int getTotalDigits(Object value) {
+        return -1;
+    }
+
+    // get the number of fraction digits of the value
+    // the parameters are in compiled form (from getActualValue)
+    public int getFractionDigits(Object value) {
+        return -1;
+    }
+
+    // check whether the character is in the range 0x30 ~ 0x39
+    public static final boolean isDigit(char ch) {
+        return ch >= '0' && ch <= '9';
+    }
+    
+    // if the character is in the range 0x30 ~ 0x39, return its int value (0~9),
+    // otherwise, return -1
+    public static final int getDigit(char ch) {
+        return isDigit(ch) ? ch - '0' : -1;
+    }
+    
+} // interface TypeValidator

http://git-wip-us.apache.org/repos/asf/jena/blob/c9a7e646/jena-core/src/main/java/org/apache/jena/ext/xerces/impl/dv/xs/UnionDV.java
----------------------------------------------------------------------
diff --git a/jena-core/src/main/java/org/apache/jena/ext/xerces/impl/dv/xs/UnionDV.java b/jena-core/src/main/java/org/apache/jena/ext/xerces/impl/dv/xs/UnionDV.java
new file mode 100644
index 0000000..0421f3e
--- /dev/null
+++ b/jena-core/src/main/java/org/apache/jena/ext/xerces/impl/dv/xs/UnionDV.java
@@ -0,0 +1,47 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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.jena.ext.xerces.impl.dv.xs;
+
+import org.apache.jena.ext.xerces.impl.dv.InvalidDatatypeValueException;
+import org.apache.jena.ext.xerces.impl.dv.ValidationContext;
+
+/**
+ * Represent the schema union types
+ * 
+ * @xerces.internal 
+ *
+ * @author Neeraj Bajaj, Sun Microsystems, inc.
+ * @author Sandy Gao, IBM
+ *
+ * @version $Id: UnionDV.java 446745 2006-09-15 21:43:58Z mrglavas $
+ */
+public class UnionDV extends TypeValidator{
+
+    @Override
+    public short getAllowedFacets(){
+          return (XSSimpleTypeDecl.FACET_PATTERN | XSSimpleTypeDecl.FACET_ENUMERATION );
+    }
+
+    // this method should never be called: XSSimpleTypeDecl is responsible for
+    // calling the member types for the convertion
+    @Override
+    public Object getActualValue(String content, ValidationContext context) throws InvalidDatatypeValueException{
+        return content;
+    }
+
+} // class UnionDV


[09/24] jena git commit: JENA-1537: Remove dependency on Xerces. Import needed code

Posted by an...@apache.org.
http://git-wip-us.apache.org/repos/asf/jena/blob/c9a7e646/jena-core/src/main/java/org/apache/jena/ext/xerces/jaxp/datatype/XMLGregorianCalendarImpl.java
----------------------------------------------------------------------
diff --git a/jena-core/src/main/java/org/apache/jena/ext/xerces/jaxp/datatype/XMLGregorianCalendarImpl.java b/jena-core/src/main/java/org/apache/jena/ext/xerces/jaxp/datatype/XMLGregorianCalendarImpl.java
new file mode 100644
index 0000000..e9183c7
--- /dev/null
+++ b/jena-core/src/main/java/org/apache/jena/ext/xerces/jaxp/datatype/XMLGregorianCalendarImpl.java
@@ -0,0 +1,3232 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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.jena.ext.xerces.jaxp.datatype;
+
+import java.io.IOException;
+import java.io.Serializable;
+import java.math.BigDecimal;
+import java.math.BigInteger;
+import java.util.Calendar;
+import java.util.Date;
+import java.util.GregorianCalendar;
+import java.util.Locale;
+import java.util.TimeZone;
+
+import javax.xml.datatype.DatatypeConstants;
+import javax.xml.datatype.Duration;
+import javax.xml.datatype.XMLGregorianCalendar;
+import javax.xml.namespace.QName;
+
+import org.apache.jena.ext.xerces.util.DatatypeMessageFormatter;
+
+/** 
+ * <p>Representation for W3C XML Schema 1.0 date/time datatypes.
+ * Specifically, these date/time datatypes are 
+ * {@link DatatypeConstants#DATETIME dateTime},
+ * {@link DatatypeConstants#TIME time},
+ * {@link DatatypeConstants#DATE date},
+ * {@link DatatypeConstants#GYEARMONTH gYearMonth},
+ * {@link DatatypeConstants#GMONTHDAY gMonthDay},
+ * {@link DatatypeConstants#GYEAR gYear}, 
+ * {@link DatatypeConstants#GMONTH gMonth} and
+ * {@link DatatypeConstants#GDAY gDay}
+ * defined in the XML Namespace
+ * <code>"http://www.w3.org/2001/XMLSchema"</code>.
+ * These datatypes are normatively defined in 
+ * <a href="http://www.w3.org/TR/xmlschema-2/#dateTime">W3C XML Schema 1.0 Part 2, Section 3.2.7-14</a>.</p>
+ *
+ * <p>The table below defines the mapping between XML Schema 1.0
+ * date/time datatype fields and this class' fields. It also summarizes
+ * the value constraints for the date and time fields defined in
+ * <a href="http://www.w3.org/TR/xmlschema-2/#isoformats">W3C XML Schema 1.0 Part 2, Appendix D,
+ * <i>ISO 8601 Date and Time Formats</i></a>.</p>
+ * 
+ * <a name="datetimefieldsmapping"/>
+ * <table border="2" rules="all" cellpadding="2">
+ *   <thead>
+ *     <tr>
+ *       <th align="center" colspan="3">
+ *         Date/time datatype field mapping between XML Schema 1.0 and Java representation
+ *       </th>
+ *     </tr>
+ *   </thead>
+ *   <tbody>
+ *     <tr>
+ *       <th>XML Schema 1.0<br/>
+ *           datatype<br/> 
+ *            field</th>
+ *       <th>Related<br/>XMLGregorianCalendar<br/>Accessor(s)</th>
+ *       <th>Value Range</th>
+ *     </tr>
+ *     <a name="datetimefield-year"/>
+ *     <tr>
+ *       <td> year </td>
+ *       <td> {@link #getYear()} + {@link #getEon()} or<br/>
+ *            {@link #getEonAndYear}
+ *       </td>
+ *       <td> <code>getYear()</code> is a value between -(10^9-1) to (10^9)-1 
+ *            or {@link DatatypeConstants#FIELD_UNDEFINED}.<br/>
+ *            {@link #getEon()} is high order year value in billion of years.<br/>
+ *            <code>getEon()</code> has values greater than or equal to (10^9) or less than or equal to -(10^9).
+ *            A value of null indicates field is undefined.</br>
+ *            Given that <a href="http://www.w3.org/2001/05/xmlschema-errata#e2-63">XML Schema 1.0 errata</a> states that the year zero
+ *            will be a valid lexical value in a future version of XML Schema, 
+ *            this class allows the year field to be set to zero. Otherwise,
+ *            the year field value is handled exactly as described
+ *            in the errata and [ISO-8601-1988]. Note that W3C XML Schema 1.0
+ *            validation does not allow for the year field to have a value of zero.
+ *            </td>
+ *     </tr>
+ *     <a name="datetimefield-month"/>
+ *     <tr>
+ *       <td> month </td>
+ *       <td> {@link #getMonth()} </td>
+ *       <td> 1 to 12 or {@link DatatypeConstants#FIELD_UNDEFINED} </td>
+ *     </tr>
+ *     <a name="datetimefield-day"/>
+ *     <tr>
+ *       <td> day </td>
+ *       <td> {@link #getDay()} </td>
+ *       <td> Independent of month, max range is 1 to 31 or {@link DatatypeConstants#FIELD_UNDEFINED}.<br/>
+ *            The normative value constraint stated relative to month 
+ *            field's value is in <a href="http://www.w3.org/TR/xmlschema-2/#isoformats">W3C XML Schema 1.0 Part 2, Appendix D</a>.
+ *       </td> 
+ *     </tr>
+ *     <a name="datetimefield-hour"/>
+ *     <tr>
+ *       <td> hour </td>
+ *       <td> {@link #getHour()} </td>
+ *       <td>
+ *         0 to 24 or {@link DatatypeConstants#FIELD_UNDEFINED}
+ *         <a href="http://www.w3.org/2001/05/xmlschema-errata#e2-45">For a value of 24, the minute and second field must be zero.</a>
+ *       </td>
+ *     </tr>
+ *     <a name="datetimefield-minute"/>
+ *     <tr>
+ *       <td> minute </td>
+ *       <td> {@link #getMinute()} </td>
+ *       <td> 0 to 59 or {@link DatatypeConstants#FIELD_UNDEFINED} </td>
+ *     </tr>
+ *     <a name="datetimefield-second"/>
+ *     <tr>
+ *       <td>second</td>
+ *       <td>
+ *         {@link #getSecond()} + {@link #getMillisecond()}/1000 or<br/>
+ *         {@link #getSecond()} + {@link #getFractionalSecond()}
+ *       </td>
+ *       <td>
+ *         {@link #getSecond()} from 0 to 60 or {@link DatatypeConstants#FIELD_UNDEFINED}.<br/>
+ *         <i>(Note: 60 only allowable for leap second.)</i><br/>
+ *         {@link #getFractionalSecond()} allows for infinite precision over the range from 0.0 to 1.0 when 
+ *         the {@link #getSecond()} is defined.<br/>
+ *         <code>FractionalSecond</code> is optional and has a value of <code>null</code> when it is undefined.<br />
+ *            {@link #getMillisecond()} is the convenience 
+ *            millisecond precision of value of {@link #getFractionalSecond()}.
+ *       </td>
+ *     </tr>
+ *     <tr id="datetimefield-timezone">
+ *       <td> timezone </td>
+ *       <td> {@link #getTimezone()} </td>
+ *       <td> Number of minutes or {@link DatatypeConstants#FIELD_UNDEFINED}.
+ *         Value range from -14 hours (-14 * 60 minutes) to 14 hours (14 * 60 minutes).
+ *       </td>
+ *     </tr>
+ *   </tbody>
+ *  </table>
+ *
+ * <p>All maximum value space constraints listed for the fields in the table 
+ * above are checked by factory methods, setter methods and parse methods of
+ * this class. <code>IllegalArgumentException</code> is thrown when 
+ * parameter's value is outside the maximum value constraint for the field.
+ * Validation checks, for example, whether days in month should be 
+ * limited to 29, 30 or 31 days, that are dependent on the values of other 
+ * fields are not checked by these methods. 
+ * </p>
+ * 
+ * <p>The following operations are defined for this class:
+ * <ul>
+ *   <li>factory methods to create instances</li>
+ *   <li>accessors/mutators for independent date/time fields</li>
+ *   <li>conversion between this class and W3C XML Schema 1.0 lexical representation</li>
+ *   <li>conversion between this class and <code>java.util.GregorianCalendar</code></li>
+ *   <li>partial order relation comparator method, {@link #compare(XMLGregorianCalendar)}</li>
+ *   <li>{@link #equals(Object)} defined relative to {@link #compare(XMLGregorianCalendar)}.</li>
+ *   <li> addition operation with {@link javax.xml.datatype.Duration}. 
+ * instance as defined in <a href="http://www.w3.org/TR/xmlschema-2/#adding-durations-to-dateTimes">
+ * W3C XML Schema 1.0 Part 2, Appendix E, <i>Adding durations to dateTimes</i></a>.</li>
+ * </ul>
+ * </p>
+ * 
+ * @author <a href="mailto:Kohsuke.Kawaguchi@Sun.com">Kohsuke Kawaguchi</a>
+ * @author <a href="mailto:Joseph.Fialli@Sun.com">Joseph Fialli</a>
+ * @version $Id: XMLGregorianCalendarImpl.java 759809 2009-03-30 00:44:05Z mrglavas $
+ * @see javax.xml.datatype.Duration
+ */
+@SuppressWarnings("all")
+class XMLGregorianCalendarImpl
+	extends XMLGregorianCalendar
+	implements Serializable, Cloneable {
+    
+    /**
+     * <p>Stream Unique Identifier.</p>
+     */
+    private static final long serialVersionUID = 3905403108073447394L;
+
+    /** Backup values **/
+    private BigInteger orig_eon;
+    private int orig_year = DatatypeConstants.FIELD_UNDEFINED;
+    private int orig_month = DatatypeConstants.FIELD_UNDEFINED;
+    private int orig_day = DatatypeConstants.FIELD_UNDEFINED;
+    private int orig_hour = DatatypeConstants.FIELD_UNDEFINED;
+    private int orig_minute = DatatypeConstants.FIELD_UNDEFINED;
+    private int orig_second = DatatypeConstants.FIELD_UNDEFINED;
+    private BigDecimal orig_fracSeconds;
+    private int orig_timezone = DatatypeConstants.FIELD_UNDEFINED;
+    
+    /**
+     * <p>Eon of this <code>XMLGregorianCalendar</code>.</p>
+     */
+    private BigInteger eon = null;
+    
+    /**
+     * <p>Year of this <code>XMLGregorianCalendar</code>.</p>
+     */
+    private int year = DatatypeConstants.FIELD_UNDEFINED;
+
+    /**
+     * <p>Month of this <code>XMLGregorianCalendar</code>.</p>
+     */
+    private int month = DatatypeConstants.FIELD_UNDEFINED;
+    
+    /**
+     * <p>Day of this <code>XMLGregorianCalendar</code>.</p>
+     */
+    private int day = DatatypeConstants.FIELD_UNDEFINED;
+    
+    /**
+     * <p>Timezone of this <code>XMLGregorianCalendar</code> in minutes.</p>
+     */
+    private int timezone = DatatypeConstants.FIELD_UNDEFINED;
+    
+    /**
+     * <p>Hour of this <code>XMLGregorianCalendar</code>.</p>
+     */
+    private int hour = DatatypeConstants.FIELD_UNDEFINED;
+    
+    /**
+     * <p>Minute of this <code>XMLGregorianCalendar</code>.</p>
+     */
+    private int minute = DatatypeConstants.FIELD_UNDEFINED;
+    
+    /**
+     * <p>Second of this <code>XMLGregorianCalendar</code>.</p>
+     */
+    private int second = DatatypeConstants.FIELD_UNDEFINED ;
+    
+    /**
+     * <p>Fractional second of this <code>XMLGregorianCalendar</code>.</p>
+     */
+    private BigDecimal fractionalSecond = null;
+
+    /**
+     * <p>BigInteger constant; representing a billion.</p>
+     */
+    private static final BigInteger BILLION_B = BigInteger.valueOf(1000000000);
+    
+    /**
+     * <p>int constant; representing a billion.</p>
+     */
+    private static final int BILLION_I = 1000000000;
+
+    /**
+     *   <p>Obtain a pure Gregorian Calendar by calling
+     *   GregorianCalendar.setChange(PURE_GREGORIAN_CHANGE). </p>
+     */
+    private static final Date PURE_GREGORIAN_CHANGE = new Date(Long.MIN_VALUE);
+
+    /**
+     * Year index for MIN_ and MAX_FIELD_VALUES.
+     */
+    private static final int YEAR   = 0;
+
+    /**
+     * Month index for MIN_ and MAX_FIELD_VALUES.
+     */
+    private static final int MONTH  = 1;
+
+    /**
+     * Day index for MIN_ and MAX_FIELD_VALUES.
+     */
+    private static final int DAY    = 2;
+
+    /**
+     * Hour index for MIN_ and MAX_FIELD_VALUES.
+     */
+    private static final int HOUR   = 3;
+
+    /**
+     * Minute index for MIN_ and MAX_FIELD_VALUES.
+     */
+    private static final int MINUTE = 4;
+
+    /**
+     * Second index for MIN_ and MAX_FIELD_VALUES.
+     */
+    private static final int SECOND = 5;
+
+    /**
+     * Second index for MIN_ and MAX_FIELD_VALUES.
+     */
+    private static final int MILLISECOND = 6;
+
+    /**
+     * Timezone index for MIN_ and MAX_FIELD_VALUES
+     */
+    private static final int TIMEZONE = 7;
+
+    /**
+     * Minimum field values indexed by YEAR..TIMEZONE.
+     */
+    private static final int MIN_FIELD_VALUE[] = { 
+        Integer.MIN_VALUE,  //Year field can be smaller than this,
+        // only constraint on integer value of year. 
+        DatatypeConstants.JANUARY, 
+        1,       //day of month
+        0,       //hour
+        0,       //minute
+        0,       //second
+        0,       //millisecond
+        -14 * 60 //timezone
+    };
+
+    /**
+     * Maximum field values indexed by YEAR..TIMEZONE.
+     */
+    private static final int MAX_FIELD_VALUE[] = { 
+        Integer.MAX_VALUE,  // Year field can be bigger than this, 
+        // only constraint on integer value of year.
+        DatatypeConstants.DECEMBER,              
+        31,       //day of month                         
+        24,       //hour
+        59,       //minute
+        60,       //second (leap second allows for 60)
+        999,      //millisecond
+        14 * 60   //timezone
+    }; 
+
+    /**
+     * field names indexed by YEAR..TIMEZONE.
+     */
+    private static final String FIELD_NAME[] = { 
+        "Year",
+        "Month",
+        "Day",
+        "Hour",
+        "Minute",
+        "Second",
+        "Millisecond",
+        "Timezone"
+    };
+
+    /**
+     * <p>Use as a template for default field values when 
+     * converting to a {@link GregorianCalendar}, set to a leap 
+     * year date of January 1, 0400 at midnight.</p>
+     * 
+     * <p>Fields that are optional for an <code>xsd:dateTime</code> instances are defaulted to not being set to any value.
+     * <code>XMLGregorianCalendar</code> fields millisecond, fractional second and timezone return the value indicating
+     * that the field is not set, {@link DatatypeConstants#FIELD_UNDEFINED} for millisecond and timezone
+     * and <code>null</code> for fractional second.</p>
+     * 
+     * @see #toGregorianCalendar(TimeZone, Locale, XMLGregorianCalendar)
+     */
+    public static final XMLGregorianCalendar LEAP_YEAR_DEFAULT =
+        createDateTime(
+                400,  //year
+                DatatypeConstants.JANUARY,  //month
+                1,  // day
+                0,  // hour
+                0,  // minute
+                0,  // second
+                DatatypeConstants.FIELD_UNDEFINED,  // milliseconds
+                DatatypeConstants.FIELD_UNDEFINED // timezone
+        );
+
+    // Constructors
+
+    /**
+     * Constructs a new XMLGregorianCalendar object.
+     * 
+     * String parsing documented by {@link #parse(String)}.
+     * 
+     * Returns a non-null valid XMLGregorianCalendar object that holds the 
+     * value indicated by the lexicalRepresentation parameter.
+     *
+     * @param lexicalRepresentation
+     *      Lexical representation of one the eight
+     *      XML Schema date/time datatypes.
+     * @throws IllegalArgumentException
+     *      If the given string does not conform as documented in 
+     *      {@link #parse(String)}.
+     * @throws NullPointerException
+     *      If the given string is null.
+     */
+    protected XMLGregorianCalendarImpl(String lexicalRepresentation)
+        throws IllegalArgumentException {
+
+        // compute format string for this lexical representation.
+        String format = null;
+        String lexRep = lexicalRepresentation;
+        final int NOT_FOUND = -1;
+        int lexRepLength = lexRep.length();
+
+        // current parser needs a format string,
+        // use following heuristics to figure out what xml schema date/time
+        // datatype this lexical string could represent.
+        if (lexRep.indexOf('T') != NOT_FOUND) {
+            // found Date Time separater, must be xsd:DateTime
+            format = "%Y-%M-%DT%h:%m:%s" + "%z";
+        } 
+        else if (lexRepLength >= 3 && lexRep.charAt(2) == ':') {
+            // found ":", must be xsd:Time
+            format = "%h:%m:%s" +"%z";
+        } 
+        else if (lexRep.startsWith("--")) {
+            // check for GDay || GMonth || GMonthDay
+            if (lexRepLength >= 3 && lexRep.charAt(2) == '-') {
+                // GDAY
+                // Fix 4971612: invalid SCCS macro substitution in data string
+                format = "---%D" + "%z";
+            } 
+            else if (lexRepLength == 4 || (lexRepLength >= 6 && (lexRep.charAt(4) == '+' || (lexRep.charAt(4) == '-' && (lexRep.charAt(5) == '-' || lexRepLength == 10))))) {
+                // GMonth
+                // Fix 4971612: invalid SCCS macro substitution in data string
+                format = "--%M--%z";
+                Parser p = new Parser(format, lexRep);
+                try {
+                    p.parse();
+                    // check for validity
+                    if (!isValid()) {
+                        throw new IllegalArgumentException(
+                                DatatypeMessageFormatter.formatMessage(null,"InvalidXGCRepresentation", new Object[]{lexicalRepresentation})
+                                //"\"" + lexicalRepresentation + "\" is not a valid representation of an XML Gregorian Calendar value."
+                        );
+                    }
+                    save();
+                    return;
+                }
+                catch(IllegalArgumentException e) {
+                    format = "--%M%z";
+                }
+            } 
+            else {
+                // GMonthDay or invalid lexicalRepresentation
+                format = "--%M-%D" + "%z";
+            }
+        } 
+        else {
+            // check for Date || GYear | GYearMonth
+            int countSeparator = 0;
+
+            // start at index 1 to skip potential negative sign for year.
+
+
+            int timezoneOffset = lexRep.indexOf(':');
+            if (timezoneOffset != NOT_FOUND) {
+
+                // found timezone, strip it off for distinguishing
+                // between Date, GYear and GYearMonth so possible
+                // negative sign in timezone is not mistaken as
+                // a separator.
+                lexRepLength -= 6;
+            }
+
+            for (int i=1; i < lexRepLength; i++) {
+                if (lexRep.charAt(i) == '-') {
+                    countSeparator++;
+                }
+            }
+            if (countSeparator == 0) {
+                // GYear
+                format = "%Y" + "%z";
+            } 
+            else if (countSeparator == 1) {
+                // GYearMonth
+                format = "%Y-%M" + "%z";
+            } 
+            else {
+                // Date or invalid lexicalRepresentation
+                // Fix 4971612: invalid SCCS macro substitution in data string
+                format = "%Y-%M-%D" + "%z";
+            }
+        }
+        Parser p = new Parser(format, lexRep);
+        p.parse();
+
+        // check for validity
+        if (!isValid()) {
+            throw new IllegalArgumentException(
+                    DatatypeMessageFormatter.formatMessage(null,"InvalidXGCRepresentation", new Object[]{lexicalRepresentation})
+                    //"\"" + lexicalRepresentation + "\" is not a valid representation of an XML Gregorian Calendar value."
+            );
+        }
+        save();
+    }
+    
+    /**
+     * 
+     */
+    private void save() {
+        orig_eon = eon;
+        orig_year = year;
+        orig_month = month;
+        orig_day = day;
+        orig_hour = hour;
+        orig_minute = minute;
+        orig_second = second;
+        orig_fracSeconds = fractionalSecond;
+        orig_timezone = timezone;
+    }
+
+    /**
+     * <p>Create an instance with all date/time datatype fields set to 
+     * {@link DatatypeConstants#FIELD_UNDEFINED} or null respectively.</p>
+     */
+    public XMLGregorianCalendarImpl() {
+    	
+        // field initializers already do the correct initialization.
+    }
+
+    /**
+     * <p>Private constructor allowing for complete value spaces allowed by 
+     * W3C XML Schema 1.0 recommendation for xsd:dateTime and related 
+     * builtin datatypes. Note that <code>year</code> parameter supports
+     * arbitrarily large numbers and fractionalSecond has infinite 
+     * precision.</p>
+     * 
+     * @param year of <code>XMLGregorianCalendar</code> to be created.
+     * @param month of <code>XMLGregorianCalendar</code> to be created.
+     * @param day of <code>XMLGregorianCalendar</code> to be created.
+     * @param hour of <code>XMLGregorianCalendar</code> to be created.
+     * @param minute of <code>XMLGregorianCalendar</code> to be created.
+     * @param second of <code>XMLGregorianCalendar</code> to be created.
+     * @param fractionalSecond of <code>XMLGregorianCalendar</code> to be created.
+     * @param timezone of <code>XMLGregorianCalendar</code> to be created.
+     * 
+     */
+    protected XMLGregorianCalendarImpl(
+        BigInteger year,
+        int month,
+        int day,
+        int hour,
+        int minute,
+        int second,
+        BigDecimal fractionalSecond,
+        int timezone) {
+        	
+		setYear(year);
+        setMonth(month);
+        setDay(day);
+        setTime(hour, minute, second, fractionalSecond);
+		setTimezone(timezone);
+		
+		// check for validity
+		if (!isValid()) {
+			
+            throw new IllegalArgumentException(
+                DatatypeMessageFormatter.formatMessage(null, 
+                    "InvalidXGCValue-fractional", 
+                    new Object[] { year, new Integer(month), new Integer(day), 
+                    new Integer(hour), new Integer(minute), new Integer(second),
+                    fractionalSecond, new Integer(timezone)})
+			);
+                    
+			/**
+                String yearString = "null";
+                if (year != null) {
+                    yearString = year.toString();
+                }
+                String fractionalSecondString = "null";
+                if (fractionalSecond != null) {
+                    fractionalSecondString = fractionalSecond.toString();
+                }
+             
+                throw new IllegalArgumentException(
+                    "year = " + yearString
+                    + ", month = " + month
+                    + ", day = " + day
+                    + ", hour = " + hour
+                    + ", minute = " + minute
+                    + ", second = " + second
+                    + ", fractionalSecond = " + fractionalSecondString
+                    + ", timezone = " + timezone
+                    + ", is not a valid representation of an XML Gregorian Calendar value."
+                );
+                */
+            
+		}
+        
+        save();
+		
+    }
+
+    /**
+     * <p>Private constructor of value spaces that a
+     * <code>java.util.GregorianCalendar</code> instance would need to convert to an
+     * <code>XMLGregorianCalendar</code> instance.</p>
+     *    
+     * <p><code>XMLGregorianCalendar eon</code> and 
+     * <code>fractionalSecond</code> are set to <code>null</code></p>
+     *
+     * @param year of <code>XMLGregorianCalendar</code> to be created.
+     * @param month of <code>XMLGregorianCalendar</code> to be created.
+     * @param day of <code>XMLGregorianCalendar</code> to be created.
+     * @param hour of <code>XMLGregorianCalendar</code> to be created.
+     * @param minute of <code>XMLGregorianCalendar</code> to be created.
+     * @param second of <code>XMLGregorianCalendar</code> to be created.
+     * @param millisecond of <code>XMLGregorianCalendar</code> to be created.
+     * @param timezone of <code>XMLGregorianCalendar</code> to be created.
+     */
+    private XMLGregorianCalendarImpl(
+        int year,
+        int month,
+        int day,
+        int hour,
+        int minute,
+        int second,
+        int millisecond,
+        int timezone) {
+
+        setYear(year);
+        setMonth(month);
+        setDay(day);
+        setTime(hour, minute, second);
+        setTimezone(timezone);
+        BigDecimal realMilliseconds = null;
+        if (millisecond != DatatypeConstants.FIELD_UNDEFINED) {
+            realMilliseconds = BigDecimal.valueOf(millisecond, 3);
+        }
+        setFractionalSecond(realMilliseconds);
+
+        if (!isValid()) {		
+
+            throw new IllegalArgumentException(
+                    DatatypeMessageFormatter.formatMessage(null, 
+                            "InvalidXGCValue-milli", 
+                            new Object[] { new Integer(year), new Integer(month), new Integer(day), 
+                            new Integer(hour), new Integer(minute), new Integer(second), 
+                            new Integer(millisecond), new Integer(timezone)})                
+            );
+            /*
+                throw new IllegalArgumentException(
+                    "year = " + year
+                    + ", month = " + month
+                    + ", day = " + day
+                    + ", hour = " + hour
+                    + ", minute = " + minute
+                    + ", second = " + second
+                    + ", millisecond = " + millisecond
+                    + ", timezone = " + timezone
+                    + ", is not a valid representation of an XML Gregorian Calendar value."
+                    );
+             */
+
+        }
+        save();
+    }
+    
+	/**
+	 * <p>Convert a <code>java.util.GregorianCalendar</code> to XML Schema 1.0 
+	 * representation.</p>
+	 *
+	 * <table border="2" rules="all" cellpadding="2">
+	 *   <thead>
+	 *     <tr>
+	 *       <th align="center" colspan="2">
+	 *          Field by Field Conversion from
+	 *          <code>java.util.GregorianCalendar</code> to this class 
+	 *       </th>
+	 *     </tr>
+	 *   </thead>
+	 *   <tbody>
+	 *     <tr>
+	 *        <th><code>javax.xml.datatype.XMLGregorianCalendar</code> field</th>
+	 *        <th><code>java.util.GregorianCalendar</code> field</th>
+	 *     </tr>
+	 *     <tr>
+	 *       <th>{@link #setYear(int)}</th>
+	 *       <th><code>ERA == GregorianCalendar.BC ? -YEAR : YEAR</code></th>
+	 *     </tr>
+	 *     <tr>
+	 *       <th>{@link #setMonth(int)}</th>
+	 *       <th><code>MONTH + 1</code></th>
+	 *     </tr>
+	 *     <tr>
+	 *       <th>{@link #setDay(int)}</th>
+	 *       <th><code>DAY_OF_MONTH</code></th>
+	 *     </tr>
+	 *     <tr>
+	 *       <th>{@link #setTime(int,int,int, BigDecimal)}</th>
+	 *       <th><code>HOUR_OF_DAY, MINUTE, SECOND, MILLISECOND</code></th>
+	 *     </tr>
+	 *     <tr>
+	 *       <th>{@link #setTimezone(int)}<i>*</i></th>
+	 *       <th><code>(ZONE_OFFSET + DST_OFFSET) / (60*1000)</code><br/>
+	 *       <i>(in minutes)</i>
+	 *       </th>
+	 *     </tr>
+	 *   </tbody>
+	 * </table>
+	 * <p><i>*</i>conversion loss of information. It is not possible to represent 
+	 * a <code>java.util.GregorianCalendar</code> daylight savings timezone id in the 
+	 * XML Schema 1.0 date/time datatype representation.</p>
+	 * 
+	 * <p>To compute the return value's <code>TimeZone</code> field,
+	 * <ul>
+	 * <li>when <code>this.getTimezone() != DatatypeConstants.FIELD_UNDEFINED</code>,
+	 * create a <code>java.util.TimeZone</code> with a custom timezone id 
+	 * using the <code>this.getTimezone()</code>.</li>
+	 * <li>else use the <code>GregorianCalendar</code> default timezone value 
+	 * for the host is defined as specified by 
+	 * <code>java.util.TimeZone.getDefault()</code>.</li></p>     
+	 *
+	 * @param cal <code>java.util.GregorianCalendar</code> used to create <code>XMLGregorianCalendar</code>
+	 */
+    public XMLGregorianCalendarImpl(GregorianCalendar cal) {
+
+        int year = cal.get(Calendar.YEAR);
+        if (cal.get(Calendar.ERA) == GregorianCalendar.BC) {
+            year = -year;
+        }
+        this.setYear(year);
+
+        // Calendar.MONTH is zero based, XSD Date datatype's month field starts
+        // with JANUARY as 1.
+        this.setMonth(cal.get(Calendar.MONTH) + 1);
+        this.setDay(cal.get(Calendar.DAY_OF_MONTH));
+        this.setTime(
+                cal.get(Calendar.HOUR_OF_DAY),
+                cal.get(Calendar.MINUTE), 
+                cal.get(Calendar.SECOND),
+                cal.get(Calendar.MILLISECOND));
+
+        // Calendar ZONE_OFFSET and DST_OFFSET fields are in milliseconds.
+        int offsetInMinutes = (cal.get(Calendar.ZONE_OFFSET) + cal.get(Calendar.DST_OFFSET)) / (60 * 1000);
+        this.setTimezone(offsetInMinutes);
+        save();
+    }
+
+    // Factories
+
+    /**
+     * <p>Create a Java representation of XML Schema builtin datatype <code>dateTime</code>.
+     * All possible fields are specified for this factory method.</p>
+     * 
+     * @param year represents both high-order eons and low-order year.
+     * @param month of <code>dateTime</code>
+     * @param day of <code>dateTime</code>
+     * @param hours of <code>dateTime</code>
+     * @param minutes of <code>dateTime</code>
+     * @param seconds of <code>dateTime</code>
+     * @param fractionalSecond value of null indicates optional field is absent.
+     * @param timezone offset in minutes. {@link DatatypeConstants#FIELD_UNDEFINED} indicates optional field is not set.
+     * 
+     * @return <code>XMLGregorianCalendar</code> created from parameter values.
+     * 
+     * @see DatatypeConstants#FIELD_UNDEFINED
+     *
+     * @throws IllegalArgumentException if any parameter is outside value 
+     * constraints for the field as specified in 
+     * <a href="#datetimefieldmapping">date/time field mapping table</a>.
+     */
+	public static XMLGregorianCalendar createDateTime(
+	        BigInteger year,
+	        int month,
+	        int day,
+	        int hours,
+	        int minutes,
+	        int seconds,
+	        BigDecimal fractionalSecond,
+	        int timezone) {
+
+	    return new XMLGregorianCalendarImpl(
+	            year,
+	            month, 
+	            day, 
+	            hours,
+	            minutes,
+	            seconds, 
+	            fractionalSecond,
+	            timezone);
+	}
+
+    /**
+     * <p>Create a Java instance of XML Schema builtin datatype dateTime.</p>
+     * 
+     * @param year represents both high-order eons and low-order year.
+     * @param month of <code>dateTime</code>
+     * @param day of <code>dateTime</code>
+     * @param hour of <code>dateTime</code>
+     * @param minute of <code>dateTime</code>
+     * @param second of <code>dateTime</code>
+     *
+     * @return <code>XMLGregorianCalendar</code> created from parameter values.
+     * 
+     * @throws IllegalArgumentException if any parameter is outside value constraints for the field as specified in 
+     *   <a href="#datetimefieldmapping">date/time field mapping table</a>.
+     * 
+     * @see DatatypeConstants#FIELD_UNDEFINED
+     */
+    public static XMLGregorianCalendar createDateTime(
+            int year,
+            int month,
+            int day,
+            int hour,
+            int minute,
+            int second) {
+
+        return new XMLGregorianCalendarImpl(
+                year,
+                month,
+                day,
+                hour,
+                minute,
+                second,
+                DatatypeConstants.FIELD_UNDEFINED,  //millisecond
+                DatatypeConstants.FIELD_UNDEFINED //timezone
+        );
+    }
+
+    /**
+     * <p>Create a Java representation of XML Schema builtin datatype <code>dateTime</code>.
+     * All possible fields are specified for this factory method.</p>
+     * 
+     * @param year represents low-order year.
+     * @param month of <code>dateTime</code>
+     * @param day of <code>dateTime</code>
+     * @param hours of <code>dateTime</code>
+     * @param minutes of <code>dateTime</code>
+     * @param seconds of <code>dateTime</code>
+     * @param milliseconds of <code>dateTime</code>. {@link DatatypeConstants#FIELD_UNDEFINED} indicates optional field is not set.
+     * @param timezone offset in minutes. {@link DatatypeConstants#FIELD_UNDEFINED} indicates optional field is not set.
+     *
+     * @return <code>XMLGregorianCalendar</code> created from parameter values.
+     * 
+     * @throws IllegalArgumentException if any parameter is outside value constraints for the field as specified in 
+     *   <a href="#datetimefieldmapping">date/time field mapping table</a>.
+     * 
+     * @see DatatypeConstants#FIELD_UNDEFINED
+     */
+    public static XMLGregorianCalendar createDateTime(
+            int year,
+            int month,
+            int day,
+            int hours,
+            int minutes,
+            int seconds,
+            int milliseconds,
+            int timezone) {
+
+        return new XMLGregorianCalendarImpl(
+                year,
+                month,
+                day,
+                hours,
+                minutes,
+                seconds,
+                milliseconds,
+                timezone);
+    }
+
+    /**
+     * <p>Create a Java representation of XML Schema builtin datatype <code>date</code> or <code>g*</code>.</p>
+     * 
+     * <p>For example, an instance of <code>gYear</code> can be created invoking this factory 
+     * with <code>month</code> and <code>day</code> parameters set to 
+     * {@link DatatypeConstants#FIELD_UNDEFINED}.</p>
+     * 
+     * @param year of <code>XMLGregorianCalendar</code> to be created.
+     * @param month of <code>XMLGregorianCalendar</code> to be created.
+     * @param day of <code>XMLGregorianCalendar</code> to be created.
+     * @param timezone offset in minutes. {@link DatatypeConstants#FIELD_UNDEFINED} indicates optional field is not set.
+     * 
+     * @return <code>XMLGregorianCalendar</code> created from parameter values.
+     * 
+     * @see DatatypeConstants#FIELD_UNDEFINED
+     *
+     * @throws IllegalArgumentException if any parameter is outside value 
+     * constraints for the field as specified in 
+     * <a href="#datetimefieldmapping">date/time field mapping table</a>.
+     */
+    public static XMLGregorianCalendar createDate(
+            int year,
+            int month,
+            int day,
+            int timezone) {
+
+        return new XMLGregorianCalendarImpl(
+                year,
+                month,
+                day,
+                DatatypeConstants.FIELD_UNDEFINED, // hour
+                DatatypeConstants.FIELD_UNDEFINED, // minute
+                DatatypeConstants.FIELD_UNDEFINED, // second
+                DatatypeConstants.FIELD_UNDEFINED, // millisecond
+                timezone);
+    }
+
+    /**
+     * Create a Java instance of XML Schema builtin datatype <code>time</code>.
+     * @param hours number of hours
+     * @param minutes number of minutes
+     * @param seconds number of seconds
+     * @param timezone offset in minutes. {@link DatatypeConstants#FIELD_UNDEFINED} indicates optional field is not set.
+     * 
+     * @return <code>XMLGregorianCalendar</code> created from parameter values.
+     * 
+     * @see DatatypeConstants#FIELD_UNDEFINED
+     *
+     * @throws IllegalArgumentException if any parameter is outside value 
+     * constraints for the field as specified in 
+     * <a href="#datetimefieldmapping">date/time field mapping table</a>.
+     */
+    public static XMLGregorianCalendar createTime(
+            int hours,
+            int minutes,
+            int seconds,
+            int timezone) {
+
+        return new XMLGregorianCalendarImpl(
+                DatatypeConstants.FIELD_UNDEFINED, // Year
+                DatatypeConstants.FIELD_UNDEFINED, // Month
+                DatatypeConstants.FIELD_UNDEFINED, // Day
+                hours,
+                minutes,
+                seconds, 
+                DatatypeConstants.FIELD_UNDEFINED, //Millisecond
+                timezone);
+    }
+
+    /**
+     * <p>Create a Java instance of XML Schema builtin datatype time.</p>
+     * 
+     * @param hours number of hours
+     * @param minutes number of minutes
+     * @param seconds number of seconds
+     * @param fractionalSecond value of <code>null</code> indicates that this optional field is not set.
+     * @param timezone offset in minutes. {@link DatatypeConstants#FIELD_UNDEFINED} indicates optional field is not set.
+     * 
+     * @return <code>XMLGregorianCalendar</code> created from parameter values.
+     * 
+     * @see DatatypeConstants#FIELD_UNDEFINED
+     *
+     * @throws IllegalArgumentException if any parameter is outside value 
+     * constraints for the field as specified in 
+     * <a href="#datetimefieldmapping">date/time field mapping table</a>.
+     */
+    public static XMLGregorianCalendar createTime(
+            int hours,
+            int minutes,
+            int seconds,
+            BigDecimal fractionalSecond,
+            int timezone) {
+
+        return new XMLGregorianCalendarImpl(
+                null,            // Year
+                DatatypeConstants.FIELD_UNDEFINED, // month
+                DatatypeConstants.FIELD_UNDEFINED, // day
+                hours,
+                minutes,
+                seconds,
+                fractionalSecond,
+                timezone);
+    }
+
+    /**
+     * <p>Create a Java instance of XML Schema builtin datatype time.</p>
+     * 
+     * @param hours number of hours
+     * @param minutes number of minutes
+     * @param seconds number of seconds
+     * @param milliseconds number of milliseconds
+     * @param timezone offset in minutes. {@link DatatypeConstants#FIELD_UNDEFINED} indicates optional field is not set.
+     * 
+     * @return <code>XMLGregorianCalendar</code> created from parameter values.
+     * 
+     * @see DatatypeConstants#FIELD_UNDEFINED
+     *
+     * @throws IllegalArgumentException if any parameter is outside value 
+     * constraints for the field as specified in 
+     * <a href="#datetimefieldmapping">date/time field mapping table</a>.
+     */
+    public static XMLGregorianCalendar createTime(
+            int hours,
+            int minutes,
+            int seconds,
+            int milliseconds,
+            int timezone) {
+
+        return new XMLGregorianCalendarImpl(
+                DatatypeConstants.FIELD_UNDEFINED, // year
+                DatatypeConstants.FIELD_UNDEFINED, // month
+                DatatypeConstants.FIELD_UNDEFINED, // day
+                hours,
+                minutes,
+                seconds,
+                milliseconds,
+                timezone);
+    }
+
+    // Accessors
+
+    /** 
+     * <p>Return high order component for XML Schema 1.0 dateTime datatype field for 
+     * <code>year</code>.
+     * <code>null</code> if this optional part of the year field is not defined.</p>
+     * 
+     * <p>Value constraints for this value are summarized in 
+     * <a href="#datetimefield-year">year field of date/time field mapping table</a>.</p>
+     * @return eon of this <code>XMLGregorianCalendar</code>. The value 
+     * returned is an integer multiple of 10^9.
+     * 
+     * @see #getYear()
+     * @see #getEonAndYear()
+     */
+    @Override
+    public BigInteger getEon() {
+	   return eon;
+    }
+
+    /** 
+     * <p>Return low order component for XML Schema 1.0 dateTime datatype field for 
+     * <code>year</code> or {@link DatatypeConstants#FIELD_UNDEFINED}.</p>
+     * 
+     * <p>Value constraints for this value are summarized in 
+     * <a href="#datetimefield-year">year field of date/time field mapping table</a>.</p>
+     * 
+     * @return year  of this <code>XMLGregorianCalendar</code>.
+     * 
+     * @see #getEon()
+     * @see #getEonAndYear()
+     */
+    @Override
+    public int getYear() {
+	   return year;
+    }
+
+    /** 
+     * <p>Return XML Schema 1.0 dateTime datatype field for 
+     * <code>year</code>.</p>
+     * 
+     * <p>Value constraints for this value are summarized in 
+     * <a href="#datetimefield-year">year field of date/time field mapping table</a>.</p>
+     * 
+     * @return sum of <code>eon</code> and <code>BigInteger.valueOf(year)</code>
+     * when both fields are defined. When only <code>year</code> is defined, 
+     * return it. When both <code>eon</code> and <code>year</code> are not 
+     * defined, return <code>null</code>.
+     * 
+     * @see #getEon()
+     * @see #getYear()
+     */
+    @Override
+    public BigInteger getEonAndYear() {
+
+        // both are defined
+        if (year != DatatypeConstants.FIELD_UNDEFINED
+            && eon != null) {
+
+            return eon.add(BigInteger.valueOf(year));
+        }
+
+        // only year is defined
+        if (year != DatatypeConstants.FIELD_UNDEFINED
+            && eon == null) {
+
+            return BigInteger.valueOf(year);
+        }
+
+        // neither are defined
+        // or only eon is defined which is not valid without a year 
+        return null;
+    }
+
+    /** 
+     * <p>Return number of month or {@link DatatypeConstants#FIELD_UNDEFINED}.</p>
+     * 
+     * <p>Value constraints for this value are summarized in 
+     * <a href="#datetimefield-month">month field of date/time field mapping table</a>.</p>
+     * 
+     * @return year  of this <code>XMLGregorianCalendar</code>.
+     * 
+     */
+    @Override
+    public int getMonth() {
+        return month;
+    }
+
+    /** 
+     * Return day in month or {@link DatatypeConstants#FIELD_UNDEFINED}.</p>
+     *
+     * <p>Value constraints for this value are summarized in 
+     * <a href="#datetimefield-day">day field of date/time field mapping table</a>.</p>
+     * 
+     * @see #setDay(int)
+     */
+    @Override
+    public int getDay() {
+        return day;
+    }
+
+    /** 
+     * Return timezone offset in minutes or 
+     * {@link DatatypeConstants#FIELD_UNDEFINED} if this optional field is not defined.
+     *
+     * <p>Value constraints for this value are summarized in 
+     * <a href="#datetimefield-timezone">timezone field of date/time field mapping table</a>.</p>
+     * 
+     * @see #setTimezone(int)
+     */
+    @Override
+    public int getTimezone() {
+        return timezone;
+    }
+
+    /** 
+     * Return hours or {@link DatatypeConstants#FIELD_UNDEFINED}.
+     * Returns {@link DatatypeConstants#FIELD_UNDEFINED} if this field is not defined.
+     *
+     * <p>Value constraints for this value are summarized in 
+     * <a href="#datetimefield-hour">hour field of date/time field mapping table</a>.</p>
+     * @see #setTime(int, int, int)
+     */
+    @Override
+    public int getHour() {
+        return hour;
+    }
+
+    /**
+     * Return minutes or {@link DatatypeConstants#FIELD_UNDEFINED}.<\p>
+     * Returns {@link DatatypeConstants#FIELD_UNDEFINED} if this field is not defined.
+     *
+     * <p>Value constraints for this value are summarized in 
+     * <a href="#datetimefield-minute">minute field of date/time field mapping table</a>.</p>
+     * @see #setTime(int, int, int)
+     */
+    @Override
+    public int getMinute() {
+        return minute;
+    }
+
+    /** 
+     * <p>Return seconds or {@link DatatypeConstants#FIELD_UNDEFINED}.<\p>
+     * 
+     * <p>Returns {@link DatatypeConstants#FIELD_UNDEFINED} if this field is not defined.
+     * When this field is not defined, the optional xs:dateTime 
+     * fractional seconds field, represented by 
+     * {@link #getFractionalSecond()} and {@link #getMillisecond()},
+     * must not be defined.</p>
+     * 
+     * <p>Value constraints for this value are summarized in 
+     * <a href="#datetimefield-second">second field of date/time field mapping table</a>.</p>
+     * 
+     * @return Second  of this <code>XMLGregorianCalendar</code>.
+     * 
+     * @see #getFractionalSecond()
+     * @see #getMillisecond()
+     * @see #setTime(int, int, int)
+     */
+    @Override
+    public int getSecond() {
+	   return second;
+    }
+
+    /**
+     * @return result of adding second and fractional second field
+     */
+    private BigDecimal getSeconds() {
+
+        if (second == DatatypeConstants.FIELD_UNDEFINED) {
+            return DECIMAL_ZERO;
+        } 
+        BigDecimal result = BigDecimal.valueOf(second);
+        if (fractionalSecond != null){
+            return result.add(fractionalSecond);
+        } 
+        else {
+            return result;
+        }
+    }
+
+    /** 
+     * <p>Return millisecond precision of {@link #getFractionalSecond()}.<\p>
+     * 
+     * <p>This method represents a convenience accessor to infinite
+     * precision fractional second value returned by 
+     * {@link #getFractionalSecond()}. The returned value is the rounded 
+     * down to milliseconds value of 
+     * {@link #getFractionalSecond()}. When {@link #getFractionalSecond()} 
+     * returns <code>null</code>, this method must return 
+     * {@link DatatypeConstants#FIELD_UNDEFINED}.</p>
+     *
+     * <p>Value constraints for this value are summarized in 
+     * <a href="#datetimefield-second">second field of date/time field mapping table</a>.</p>
+     * 
+     * @return Millisecond  of this <code>XMLGregorianCalendar</code>.
+     * 
+     * @see #getFractionalSecond()
+     * @see #setTime(int, int, int)
+     */
+    @Override
+    public int getMillisecond() {
+        if (fractionalSecond == null) {
+            return DatatypeConstants.FIELD_UNDEFINED;
+        } 
+        else {
+            // TODO: Non-optimal solution for now.
+            // Efficient implementation would only store as BigDecimal
+            // when needed and millisecond otherwise.
+            return fractionalSecond.movePointRight(3).intValue();
+        }
+    }
+
+    /** 
+     * <p>Return fractional seconds.</p>
+     * 
+     * <p><code>null</code> is returned when this optional field is not defined.</p>
+     * 
+     * <p>Value constraints are detailed in
+     * <a href="#datetimefield-second">second field of date/time field mapping table</a>.</p>
+     * 
+     * <p>This optional field can only have a defined value when the
+     * xs:dateTime second field, represented by ({@link #getSecond()}, 
+     * does not return {@link DatatypeConstants#FIELD_UNDEFINED}).</p>
+     *
+     * @return fractional seconds  of this <code>XMLGregorianCalendar</code>.
+     * 
+     * @see #getSecond()
+     * @see #setTime(int, int, int, BigDecimal)
+     */
+    @Override
+    public BigDecimal getFractionalSecond() {
+	   return fractionalSecond;
+    }
+
+    // setters
+
+    /**
+     * <p>Set low and high order component of XSD <code>dateTime</code> year field.</p>
+     * 
+     * <p>Unset this field by invoking the setter with a parameter value of <code>null</code>.</p>
+     *
+     * @param year value constraints summarized in <a href="#datetimefield-year">year field of date/time field mapping table</a>.     
+     *
+     * @throws IllegalArgumentException if <code>year</code> parameter is 
+     * outside value constraints for the field as specified in 
+     * <a href="#datetimefieldmapping">date/time field mapping table</a>.
+     */
+    @Override
+    public void setYear(BigInteger year) {
+        if (year == null) {
+            this.eon = null;
+            this.year = DatatypeConstants.FIELD_UNDEFINED;
+        } 
+        else {
+            BigInteger temp = year.remainder(BILLION_B);
+            this.year = temp.intValue();
+            setEon(year.subtract(temp));
+        }
+    }
+
+    /**
+     * <p>Set year of XSD <code>dateTime</code> year field.</p>
+     *
+     * <p>Unset this field by invoking the setter with a parameter value of 
+     * {@link DatatypeConstants#FIELD_UNDEFINED}.</p>
+     *
+     * <p>Note: if the absolute value of the <code>year</code> parameter 
+     * is less than 10^9, the eon component of the XSD year field is set to 
+     * <code>null</code> by this method.</p>
+     *
+     * @param year value constraints are summarized in <a href="#datetimefield-year">year field of date/time field mapping table</a>.
+     *   If year is {@link DatatypeConstants#FIELD_UNDEFINED}, then eon is set to <code>null</code>.
+     */
+    @Override
+    public void setYear(int year) { 
+        if (year == DatatypeConstants.FIELD_UNDEFINED) {
+            this.year = DatatypeConstants.FIELD_UNDEFINED;
+            this.eon = null;
+        } 
+        else if (Math.abs(year) < BILLION_I) {
+            this.year = year;
+            this.eon = null;
+        } 
+        else {
+            BigInteger theYear = BigInteger.valueOf(year);
+            BigInteger remainder = theYear.remainder(BILLION_B);
+            this.year = remainder.intValue();
+            setEon(theYear.subtract(remainder));
+        }
+    }
+
+    /**
+     * <p>Set high order part of XSD <code>dateTime</code> year field.</p>
+     *
+     * <p>Unset this field by invoking the setter with a parameter value of 
+     * <code>null</code>.</p>
+     *
+     * @param eon value constraints summarized in <a href="#datetimefield-year">year field of date/time field mapping table</a>.
+     */
+    private void setEon(BigInteger eon) {
+        if (eon != null && eon.compareTo(BigInteger.ZERO) == 0) {
+            // Treat ZERO as field being undefined.
+            this.eon = null;
+        } 
+        else {
+            this.eon = eon;
+        }
+    }
+
+    /**
+     * <p>Set month.</p>
+     *
+     * <p>Unset this field by invoking the setter with a parameter value of {@link DatatypeConstants#FIELD_UNDEFINED}.</p>
+     *
+     * @param month value constraints summarized in <a href="#datetimefield-month">month field of date/time field mapping table</a>.
+     *
+     * @throws IllegalArgumentException if <code>month</code> parameter is 
+     * outside value constraints for the field as specified in 
+     * <a href="#datetimefieldmapping">date/time field mapping table</a>.
+     */
+    @Override
+    public void setMonth(int month) { 
+        checkFieldValueConstraint(MONTH, month);
+        this.month = month;
+    }
+
+    /**
+     * <p>Set days in month.</p>
+     *
+     * <p>Unset this field by invoking the setter with a parameter value of {@link DatatypeConstants#FIELD_UNDEFINED}.</p>
+     *
+     * @param day value constraints summarized in <a href="#datetimefield-day">day field of date/time field mapping table</a>.
+     *
+     * @throws IllegalArgumentException if <code>day</code> parameter is 
+     * outside value constraints for the field as specified in 
+     * <a href="#datetimefieldmapping">date/time field mapping table</a>.
+     */
+    @Override
+    public void setDay(int day) {  
+        checkFieldValueConstraint(DAY, day);
+        this.day = day;
+    }
+
+    /**
+     * <p>Set the number of minutes in the timezone offset.</p>
+     *
+     * <p>Unset this field by invoking the setter with a parameter value of {@link DatatypeConstants#FIELD_UNDEFINED}.</p>
+     *
+     * @param offset value constraints summarized in <a href="#datetimefield-timezone">
+     *   timezone field of date/time field mapping table</a>.
+     *
+     * @throws IllegalArgumentException if <code>offset</code> parameter is 
+     * outside value constraints for the field as specified in 
+     * <a href="#datetimefieldmapping">date/time field mapping table</a>.
+     */
+    @Override
+    public void setTimezone(int offset) {
+        checkFieldValueConstraint(TIMEZONE, offset);
+        this.timezone = offset;
+    }
+
+    /**
+     * <p>Set time as one unit.</p>
+     *
+     * @param hour value constraints are summarized in 
+     * <a href="#datetimefield-hour">hour field of date/time field mapping table</a>.
+     * @param minute value constraints are summarized in 
+     * <a href="#datetimefield-minute">minute field of date/time field mapping table</a>.
+     * @param second value constraints are summarized in 
+     * <a href="#datetimefield-second">second field of date/time field mapping table</a>.
+     *
+     * @see #setTime(int, int, int, BigDecimal)
+     *
+     * @throws IllegalArgumentException if any parameter is 
+     * outside value constraints for the field as specified in 
+     * <a href="#datetimefieldmapping">date/time field mapping table</a>.
+     */
+    @Override
+    public void setTime(int hour, int minute, int second) {
+        setTime(hour, minute, second, null);
+    }
+
+    private void checkFieldValueConstraint(int field, int value)
+        throws IllegalArgumentException {
+        if ((value < MIN_FIELD_VALUE[field] && value != DatatypeConstants.FIELD_UNDEFINED) ||
+                value > MAX_FIELD_VALUE[field]) {
+            /**
+            throw new IllegalArgumentException("invalid value " + value +
+					       " for " + FIELD_NAME[field] +
+					       " field");
+             */
+            throw new IllegalArgumentException(
+                    DatatypeMessageFormatter.formatMessage(null, "InvalidFieldValue", new Object[]{ new Integer(value), FIELD_NAME[field]})
+            );
+        }
+    }
+
+    @Override
+    public void setHour(int hour) {
+        checkFieldValueConstraint(HOUR, hour);
+        this.hour = hour;
+    }
+
+    @Override
+    public void setMinute(int minute) {
+        checkFieldValueConstraint(MINUTE, minute);
+        this.minute = minute;
+    }
+
+    @Override
+    public void setSecond(int second) {
+        checkFieldValueConstraint(SECOND, second);
+        this.second  = second;
+    }
+
+    /**
+     * <p>Set time as one unit, including the optional infinite precison 
+     * fractional seconds.</p>
+     *
+     * @param hour value constraints are summarized in 
+     * <a href="#datetimefield-hour">hour field of date/time field mapping table</a>.
+     * @param minute value constraints are summarized in 
+     * <a href="#datetimefield-minute">minute field of date/time field mapping table</a>.
+     * @param second value constraints are summarized in 
+     * <a href="#datetimefield-second">second field of date/time field mapping table</a>.
+     * @param fractional value of <code>null</code> indicates this optional 
+     *                   field is not set.
+     *
+     * @throws IllegalArgumentException if any parameter is 
+     * outside value constraints for the field as specified in 
+     * <a href="#datetimefieldmapping">date/time field mapping table</a>.
+     */
+    @Override
+    public void setTime(
+            int hour,
+            int minute,
+            int second,
+            BigDecimal fractional) {
+        setHour(hour);
+        setMinute(minute);
+        setSecond(second);
+        setFractionalSecond(fractional);
+    }
+
+    /**
+     * <p>Set time as one unit, including optional milliseconds.</p>
+     *
+     * @param hour value constraints are summarized in 
+     * <a href="#datetimefield-hour">hour field of date/time field mapping table</a>.
+     * @param minute value constraints are summarized in 
+     * <a href="#datetimefield-minute">minute field of date/time field mapping table</a>.
+     * @param second value constraints are summarized in 
+     * <a href="#datetimefield-second">second field of date/time field mapping table</a>.
+     * @param millisecond value of {@link DatatypeConstants#FIELD_UNDEFINED} indicates this 
+     *                    optional field is not set. 
+     *
+     * @throws IllegalArgumentException if any parameter is 
+     * outside value constraints for the field as specified in 
+     * <a href="#datetimefieldmapping">date/time field mapping table</a>.
+     */
+    @Override
+    public void setTime(int hour, int minute, int second, int millisecond) {
+        setHour(hour);
+        setMinute(minute);
+        setSecond(second);
+        setMillisecond(millisecond);
+    }
+
+    // comparisons
+    /**
+     * <p>Compare two instances of W3C XML Schema 1.0 date/time datatypes 
+     * according to partial order relation defined in 
+     * <a href="http://www.w3.org/TR/xmlschema-2/#dateTime-order">W3C XML Schema 1.0 Part 2, Section 3.2.7.3,
+     * <i>Order relation on dateTime</i></a>.</p>
+     *
+     * <p><code>xsd:dateTime</code> datatype field mapping to accessors of
+     * this class are defined in
+     * <a href="#datetimefieldmapping">date/time field mapping table</a>.</p>
+     * 
+     * @param rhs instance of <code>XMLGregorianCalendar</code> to compare
+     * 
+     * @return the relationship between <code>lhs</code> and <code>rhs</code> as 
+     *   {@link DatatypeConstants#LESSER},
+     *   {@link DatatypeConstants#EQUAL},
+     *   {@link DatatypeConstants#GREATER} or
+     *   {@link DatatypeConstants#INDETERMINATE}.
+     *
+     * @throws NullPointerException if <code>lhs</code> or <code>rhs</code> 
+     * parameters are null. 
+     */
+    @Override
+    public int compare(XMLGregorianCalendar rhs) {
+
+        //MLGregorianCalendar lhs = this;
+
+        int result = DatatypeConstants.INDETERMINATE;
+        XMLGregorianCalendar P = this;
+        XMLGregorianCalendar Q = rhs;
+
+        if (P.getTimezone() == Q.getTimezone()) {
+            // Optimization: 
+            // both instances are in same timezone or
+            // both are FIELD_UNDEFINED. 
+            // Avoid costly normalization of timezone to 'Z' time.
+            return internalCompare(P, Q);
+
+        } 
+        else if (P.getTimezone() != DatatypeConstants.FIELD_UNDEFINED &&
+                Q.getTimezone() != DatatypeConstants.FIELD_UNDEFINED) {
+
+            // Both instances have different timezones.
+            // Normalize to UTC time and compare.
+            P = P.normalize();
+            Q = Q.normalize();
+            return internalCompare(P, Q);
+        } 
+        else if (P.getTimezone() != DatatypeConstants.FIELD_UNDEFINED) {
+
+            if (P.getTimezone() != 0) {
+                P = P.normalize();
+            }
+
+            // C. step 1
+            XMLGregorianCalendar MinQ = normalizeToTimezone(Q, DatatypeConstants.MIN_TIMEZONE_OFFSET);
+            result = internalCompare(P, MinQ);
+            if (result == DatatypeConstants.LESSER) {
+                return result;
+            } 
+
+            // C. step 2
+            XMLGregorianCalendar MaxQ = normalizeToTimezone(Q, DatatypeConstants.MAX_TIMEZONE_OFFSET);
+            result = internalCompare(P, MaxQ);
+            if (result == DatatypeConstants.GREATER) {
+                return result;
+            } 
+            else {
+                // C. step 3
+                return DatatypeConstants.INDETERMINATE;
+            }
+        } 
+        else { // Q.getTimezone() != DatatypeConstants.FIELD_UNDEFINED
+            // P has no timezone and Q does.
+            if (Q.getTimezone() != 0 ) { 
+                Q = normalizeToTimezone(Q, Q.getTimezone());
+            }
+
+            // D. step 1
+            XMLGregorianCalendar MaxP = normalizeToTimezone(P, DatatypeConstants.MAX_TIMEZONE_OFFSET);
+            result = internalCompare(MaxP, Q);
+            if (result == DatatypeConstants.LESSER) {
+                return result;
+            } 
+
+            // D. step 2
+            XMLGregorianCalendar MinP = normalizeToTimezone(P, DatatypeConstants.MIN_TIMEZONE_OFFSET);
+            result = internalCompare(MinP, Q);
+            if (result == DatatypeConstants.GREATER) {
+                return result;
+            } 
+            else {
+                // D. step 3
+                return DatatypeConstants.INDETERMINATE;
+            }
+        }
+    }
+
+    /**
+     * <p>Normalize this instance to UTC.</p>
+     *
+     * <p>2000-03-04T23:00:00+03:00 normalizes to 2000-03-04T20:00:00Z</p>
+     * <p>Implements W3C XML Schema Part 2, Section 3.2.7.3 (A).</p>
+     */
+    @Override
+    public XMLGregorianCalendar normalize() {
+
+        XMLGregorianCalendar normalized = normalizeToTimezone(this, timezone);
+        
+        // if timezone was undefined, leave it undefined
+        if (getTimezone() == DatatypeConstants.FIELD_UNDEFINED) {
+            normalized.setTimezone(DatatypeConstants.FIELD_UNDEFINED);
+        }
+        
+        // if milliseconds was undefined, leave it undefined
+        if (getMillisecond() == DatatypeConstants.FIELD_UNDEFINED) {
+            normalized.setMillisecond(DatatypeConstants.FIELD_UNDEFINED);
+        }
+        
+        return normalized;
+    }
+    
+	/**
+	 * <p>Normalize this instance to UTC.</p>
+	 *
+	 * <p>2000-03-04T23:00:00+03:00 normalizes to 2000-03-04T20:00:00Z</p>
+	 * <p>Implements W3C XML Schema Part 2, Section 3.2.7.3 (A).</p>
+	 */
+    private XMLGregorianCalendar normalizeToTimezone(XMLGregorianCalendar cal, int timezone) {
+
+        int minutes = timezone;    	
+        XMLGregorianCalendar result = (XMLGregorianCalendar) cal.clone();
+
+        // normalizing to UTC time negates the timezone offset before 
+        // addition.
+        minutes = -minutes;
+        Duration d = new DurationImpl(minutes >= 0, // isPositive
+                0, //years
+                0, //months
+                0, //days
+                0, //hours
+                minutes < 0 ? -minutes : minutes, // absolute
+                        0  //seconds
+        );
+        result.add(d);
+
+        // set to zulu UTC time.
+        result.setTimezone(0);
+        return result;
+    }
+
+    /** 
+     * 
+     *  <p>Implements Step B from http://www.w3.org/TR/xmlschema-2/#dateTime-order </p>
+     * @param P calendar instance with normalized timezone offset or 
+     *          having same timezone as Q
+     * @param Q calendar instance with normalized timezone offset or 
+     *          having same timezone as P
+     * 
+     * @return result of comparing P and Q, value of
+     *   {@link DatatypeConstants#EQUAL},
+     *   {@link DatatypeConstants#LESSER},
+     *   {@link DatatypeConstants#GREATER} or 
+     *   {@link DatatypeConstants#INDETERMINATE}.
+     */
+	private static int internalCompare(XMLGregorianCalendar P,
+	        XMLGregorianCalendar Q) {
+
+	    int result;
+
+	    // compare Year.
+	    if (P.getEon() == Q.getEon()) {
+	        // Eon field is only equal when null.
+	        // optimized case for comparing year not requiring eon field.
+	        result = compareField(P.getYear(), Q.getYear());
+	        if (result != DatatypeConstants.EQUAL) {
+	            return result;
+	        }
+	    } 
+        else {
+	        result = compareField(P.getEonAndYear(), Q.getEonAndYear());
+	        if (result != DatatypeConstants.EQUAL) {
+	            return result;
+	        }
+	    }
+
+	    result = compareField(P.getMonth(), Q.getMonth());
+	    if (result != DatatypeConstants.EQUAL) {
+	        return result;
+	    }
+
+	    result = compareField(P.getDay(), Q.getDay());
+	    if (result != DatatypeConstants.EQUAL) {
+	        return result;
+	    }
+
+	    result = compareField(P.getHour(), Q.getHour());
+	    if (result != DatatypeConstants.EQUAL) {
+	        return result;
+	    }
+
+	    result = compareField(P.getMinute(), Q.getMinute());
+	    if (result != DatatypeConstants.EQUAL) {
+	        return result;
+	    }
+	    result = compareField(P.getSecond(), Q.getSecond());
+	    if (result != DatatypeConstants.EQUAL) {
+	        return result;
+	    }
+
+	    result = compareField(P.getFractionalSecond(), Q.getFractionalSecond());
+	    return result;
+	}
+
+    /**
+     * <p>Implement Step B from 
+     * http://www.w3.org/TR/xmlschema-2/#dateTime-order.</p>
+     */
+    private static int compareField(int Pfield, int Qfield) {
+        if (Pfield == Qfield) {
+            //fields are either equal in value or both undefined.
+            // Step B. 1.1 AND optimized result of performing 1.1-1.4.
+            return DatatypeConstants.EQUAL;
+        } 
+        else {
+            if (Pfield == DatatypeConstants.FIELD_UNDEFINED || Qfield == DatatypeConstants.FIELD_UNDEFINED) {
+                // Step B. 1.2
+                return DatatypeConstants.INDETERMINATE;
+            } 
+            else {
+                // Step B. 1.3-4.
+                return (Pfield < Qfield ? DatatypeConstants.LESSER : DatatypeConstants.GREATER);
+            }
+        }
+    }
+
+    private static int compareField(BigInteger Pfield, BigInteger Qfield) {
+        if (Pfield == null) {
+            return (Qfield == null ? DatatypeConstants.EQUAL : DatatypeConstants.INDETERMINATE);
+        }
+        if (Qfield == null) {
+            return DatatypeConstants.INDETERMINATE;
+        }
+        return Pfield.compareTo(Qfield);
+    }
+
+    private static int compareField(BigDecimal Pfield, BigDecimal Qfield) {
+        // optimization. especially when both arguments are null.
+        if (Pfield == Qfield) {
+            return DatatypeConstants.EQUAL;
+        }
+
+        if (Pfield == null) {
+            Pfield = DECIMAL_ZERO;
+        }
+
+        if (Qfield == null) {
+            Qfield = DECIMAL_ZERO;
+        }
+
+        return Pfield.compareTo(Qfield);
+    }
+
+    /**
+     * <p>Indicates whether parameter <code>obj</code> is "equal to" this one.</p>
+     * 
+     * @param obj to compare.
+     *
+     * @return <code>true</code> when <code>compare(this,(XMLGregorianCalendar)obj) == EQUAL.</code>.
+     */
+    @Override
+    public boolean equals(Object obj) {
+        if (obj == this) {
+            return true;
+        }
+        if (obj instanceof XMLGregorianCalendar) {
+            return compare((XMLGregorianCalendar) obj) == DatatypeConstants.EQUAL;
+        }
+        return false;
+    }
+
+    /**
+     * <p>Returns a hash code consistent with the definition of the equals method.</p>
+     * 
+     * @return hash code of this object.
+     */
+    @Override
+    public int hashCode() {
+
+        // Following two dates compare to EQUALS since in different timezones.
+        // 2000-01-15T12:00:00-05:00 == 2000-01-15T13:00:00-04:00 	
+        //
+        // Must ensure both instances generate same hashcode by normalizing 
+        // this to UTC timezone.
+        int timezone = getTimezone();
+        if (timezone == DatatypeConstants.FIELD_UNDEFINED) {
+            timezone = 0;
+        }
+        XMLGregorianCalendar gc = this;
+        if (timezone != 0) {
+            gc = normalizeToTimezone(this, getTimezone());
+        }
+        return gc.getYear() + gc.getMonth() + gc.getDay() + 
+        gc.getHour() + gc.getMinute() + gc.getSecond();
+    }
+    
+    
+    /**
+     * <p>Constructs a new XMLGregorianCalendar object by
+     * parsing its lexical string representation as defined in 
+     * <a href="http://www.w3.org/TR/xmlschema-2/#dateTime-order">XML Schema 1.0 Part 2, Section 3.2.[7-14].1,
+     * <i>Lexical Representation</i>.</a></p>
+     * 
+     * <p>The string representation may not have any leading and trailing whitespaces.</p>
+     * 
+     * <p>The parsing is done field by field so that   
+     * the following holds for any lexically correct string x:</p>
+     * <pre>
+     * new XMLGregorianCalendar(x).toXMLFormat().equals(x)
+     * </pre>
+     * Except for the noted lexical/canonical representation mismatches
+     * listed in <a href="http://www.w3.org/2001/05/xmlschema-errata#e2-45">
+     * XML Schema 1.0 errata, Section 3.2.7.2</a>.
+     * 
+     * <p>Returns a non-null valid XMLGregorianCalendar object that holds the value
+     * indicated by the lexicalRepresentation parameter.</p>
+     *
+     * @param lexicalRepresentation Lexical representation of one the 8 XML Schema calendar datatypes.
+     * 
+     * @return <code>XMLGregorianCalendar</code> created from parsing <code>lexicalRepresentation</code> parameter.
+     * 
+     * @throws IllegalArgumentException
+     *      If the given string does not conform to the aforementioned
+     *      specification.
+     * @throws NullPointerException
+     *      If the given string is null.
+     */
+    public static XMLGregorianCalendar parse(String lexicalRepresentation) {
+    	
+		return new XMLGregorianCalendarImpl(lexicalRepresentation);
+    }
+
+    /**
+     * <p>Return the lexical representation of <code>this</code> instance. 
+     * The format is specified in 
+     * <a href="http://www.w3.org/TR/xmlschema-2/#dateTime-order">XML Schema 1.0 Part 2, Section 3.2.[7-14].1,
+     * <i>Lexical Representation</i>".</a></p>
+     * 
+     * <p>Specific target lexical representation format is determined by 
+     * {@link #getXMLSchemaType()}.</p>
+     * 
+     * @return XML, as <code>String</code>, representation of this <code>XMLGregorianCalendar</code> 
+     * 
+     * @throws java.lang.IllegalStateException if the combination of set fields
+     *    does not match one of the eight defined XML Schema builtin date/time datatypes. 
+     */
+    @Override
+    public String toXMLFormat() {
+
+        QName typekind = getXMLSchemaType();
+
+        String formatString = null;
+        if (typekind == DatatypeConstants.DATETIME) {
+            formatString = "%Y-%M-%DT%h:%m:%s"+ "%z";
+        } 
+        else if (typekind == DatatypeConstants.DATE) {
+            // Fix 4971612: invalid SCCS macro substitution in data string
+            formatString = "%Y-%M-%D" +"%z";
+        } 
+        else if (typekind == DatatypeConstants.TIME) {
+            formatString = "%h:%m:%s"+ "%z";
+        } 
+        else if (typekind == DatatypeConstants.GMONTH) {
+            formatString = "--%M--%z";
+        } 
+        else if (typekind == DatatypeConstants.GDAY) {
+            // Fix 4971612: invalid SCCS macro substitution in data string
+            formatString = "---%D" + "%z";
+        } 
+        else if (typekind == DatatypeConstants.GYEAR) {
+            formatString = "%Y" + "%z";
+        } 
+        else if (typekind == DatatypeConstants.GYEARMONTH) {
+            // Fix 4971612: invalid SCCS macro substitution in data string
+            formatString = "%Y-%M" + "%z";
+        } 
+        else if (typekind == DatatypeConstants.GMONTHDAY) {
+            // Fix 4971612: invalid SCCS macro substitution in data string
+            formatString = "--%M-%D" +"%z";
+        }
+        return format(formatString);
+    }
+    
+    /**
+     * <p>Return the name of the XML Schema date/time type that this instance 
+     * maps to. Type is computed based on fields that are set.</p>
+     *
+     * <table border="2" rules="all" cellpadding="2">
+     *   <thead>
+     *     <tr>
+     *       <th align="center" colspan="7">
+     *         Required fields for XML Schema 1.0 Date/Time Datatypes.<br/>
+     *         <i>(timezone is optional for all date/time datatypes)</i>
+     *       </th>
+     *     </tr>
+     *   </thead>
+     *   <tbody>
+     *     <tr>
+     *       <td>Datatype</td>
+     *       <td>year</td>
+     *       <td>month</td>
+     *       <td>day</td>
+     *       <td>hour</td>
+     *       <td>minute</td>
+     *       <td>second</td>
+     *     </tr>
+     *     <tr>
+     *       <td>{@link DatatypeConstants#DATETIME}</td>
+     *       <td>X</td>
+     *       <td>X</td>
+     *       <td>X</td>
+     *       <td>X</td>
+     *       <td>X</td>
+     *       <td>X</td>
+     *     </tr>
+     *     <tr>
+     *       <td>{@link DatatypeConstants#DATE}</td>
+     *       <td>X</td>
+     *       <td>X</td>
+     *       <td>X</td>
+     *       <td></td>
+     *       <td></td>
+     *       <td></td>
+     *     </tr>
+     *     <tr>
+     *       <td>{@link DatatypeConstants#TIME}</td>
+     *       <td></td>
+     *       <td></td>
+     *       <td></td>
+     *       <td>X</td>
+     *       <td>X</td>
+     *       <td>X</td>
+     *     </tr>
+     *     <tr>
+     *       <td>{@link DatatypeConstants#GYEARMONTH}</td>
+     *       <td>X</td>
+     *       <td>X</td>
+     *       <td></td>
+     *       <td></td>
+     *       <td></td>
+     *       <td></td>
+     *     </tr>
+     *     <tr>
+     *       <td>{@link DatatypeConstants#GMONTHDAY}</td>
+     *       <td></td>
+     *       <td>X</td>
+     *       <td>X</td>
+     *       <td></td>
+     *       <td></td>
+     *       <td></td>
+     *     </tr>
+     *     <tr>
+     *       <td>{@link DatatypeConstants#GYEAR}</td>
+     *       <td>X</td>
+     *       <td></td>
+     *       <td></td>
+     *       <td></td>
+     *       <td></td>
+     *       <td></td>
+     *     </tr>
+     *     <tr>
+     *       <td>{@link DatatypeConstants#GMONTH}</td>
+     *       <td></td>
+     *       <td>X</td>
+     *       <td></td>
+     *       <td></td>
+     *       <td></td>
+     *       <td></td>
+     *     </tr>
+     *     <tr>
+     *       <td>{@link DatatypeConstants#GDAY}</td>
+     *       <td></td>
+     *       <td></td>
+     *       <td>X</td>
+     *       <td></td>
+     *       <td></td>
+     *       <td></td>
+     *     </tr>
+     *   </tbody>
+     * </table>
+     * 
+     * @throws java.lang.IllegalStateException if the combination of set fields
+     *    does not match one of the eight defined XML Schema builtin 
+     *    date/time datatypes.
+     * @return One of the following class constants:
+     *   {@link DatatypeConstants#DATETIME},
+     *   {@link DatatypeConstants#TIME},
+     *   {@link DatatypeConstants#DATE},
+     *   {@link DatatypeConstants#GYEARMONTH},
+     *   {@link DatatypeConstants#GMONTHDAY},
+     *   {@link DatatypeConstants#GYEAR},
+     *   {@link DatatypeConstants#GMONTH} or
+     *   {@link DatatypeConstants#GDAY}.
+     */
+    @Override
+    public QName getXMLSchemaType() {
+    	
+    	// DATETIME
+    	if (year != DatatypeConstants.FIELD_UNDEFINED
+    		&& month != DatatypeConstants.FIELD_UNDEFINED
+			&& day != DatatypeConstants.FIELD_UNDEFINED
+			&& hour != DatatypeConstants.FIELD_UNDEFINED
+			&& minute != DatatypeConstants.FIELD_UNDEFINED
+			&& second != DatatypeConstants.FIELD_UNDEFINED) {
+    		return DatatypeConstants.DATETIME;
+    	}
+
+    	// DATE
+    	if (year != DatatypeConstants.FIELD_UNDEFINED
+    		&& month != DatatypeConstants.FIELD_UNDEFINED
+			&& day != DatatypeConstants.FIELD_UNDEFINED
+			&& hour == DatatypeConstants.FIELD_UNDEFINED
+			&& minute == DatatypeConstants.FIELD_UNDEFINED
+			&& second == DatatypeConstants.FIELD_UNDEFINED) {
+    		return DatatypeConstants.DATE;
+    	}
+
+    	// TIME
+    	if (year == DatatypeConstants.FIELD_UNDEFINED
+    		&& month == DatatypeConstants.FIELD_UNDEFINED
+			&& day == DatatypeConstants.FIELD_UNDEFINED
+			&& hour != DatatypeConstants.FIELD_UNDEFINED
+			&& minute != DatatypeConstants.FIELD_UNDEFINED
+			&& second != DatatypeConstants.FIELD_UNDEFINED) {
+    		return DatatypeConstants.TIME;
+    	}
+
+
+    	// GYEARMONTH
+    	if (year != DatatypeConstants.FIELD_UNDEFINED
+    		&& month != DatatypeConstants.FIELD_UNDEFINED
+			&& day == DatatypeConstants.FIELD_UNDEFINED
+			&& hour == DatatypeConstants.FIELD_UNDEFINED
+			&& minute == DatatypeConstants.FIELD_UNDEFINED
+			&& second == DatatypeConstants.FIELD_UNDEFINED) {
+    		return DatatypeConstants.GYEARMONTH;
+    	}
+
+    	// GMONTHDAY
+    	if (year == DatatypeConstants.FIELD_UNDEFINED
+    		&& month != DatatypeConstants.FIELD_UNDEFINED
+			&& day != DatatypeConstants.FIELD_UNDEFINED
+			&& hour == DatatypeConstants.FIELD_UNDEFINED
+			&& minute == DatatypeConstants.FIELD_UNDEFINED
+			&& second == DatatypeConstants.FIELD_UNDEFINED) {
+    		return DatatypeConstants.GMONTHDAY;
+    	}
+
+    	// GYEAR
+    	if (year != DatatypeConstants.FIELD_UNDEFINED
+    		&& month == DatatypeConstants.FIELD_UNDEFINED
+			&& day == DatatypeConstants.FIELD_UNDEFINED
+			&& hour == DatatypeConstants.FIELD_UNDEFINED
+			&& minute == DatatypeConstants.FIELD_UNDEFINED
+			&& second == DatatypeConstants.FIELD_UNDEFINED) {
+    		return DatatypeConstants.GYEAR;
+    	}
+
+    	// GMONTH
+    	if (year == DatatypeConstants.FIELD_UNDEFINED
+    		&& month != DatatypeConstants.FIELD_UNDEFINED
+			&& day == DatatypeConstants.FIELD_UNDEFINED
+			&& hour == DatatypeConstants.FIELD_UNDEFINED
+			&& minute == DatatypeConstants.FIELD_UNDEFINED
+			&& second == DatatypeConstants.FIELD_UNDEFINED) {
+    		return DatatypeConstants.GMONTH;
+    	}
+
+    	// GDAY
+    	if (year == DatatypeConstants.FIELD_UNDEFINED
+    		&& month == DatatypeConstants.FIELD_UNDEFINED
+			&& day != DatatypeConstants.FIELD_UNDEFINED
+			&& hour == DatatypeConstants.FIELD_UNDEFINED
+			&& minute == DatatypeConstants.FIELD_UNDEFINED
+			&& second == DatatypeConstants.FIELD_UNDEFINED) {
+    		return DatatypeConstants.GDAY;
+    	}
+
+    	// unknown
+		throw new IllegalStateException(
+			this.getClass().getName()
+			+ "#getXMLSchemaType() :"
+            + DatatypeMessageFormatter.formatMessage(null, "InvalidXGCFields", null)
+		);
+    }
+
+    
+    /**
+     * Validate instance by <code>getXMLSchemaType()</code> constraints.
+     * @return true if data values are valid.
+     */
+    @Override
+    public boolean isValid() {
+        // since setters do not allow for invalid values, 
+        // (except for exceptional case of year field of zero),
+        // no need to check for anything except for constraints
+        // between fields. 
+
+        // check if days in month is valid. Can be dependent on leap year.
+        if (month != DatatypeConstants.FIELD_UNDEFINED && day != DatatypeConstants.FIELD_UNDEFINED) {
+            if (year != DatatypeConstants.FIELD_UNDEFINED) {
+                if (eon == null) {
+                    if (day > maximumDayInMonthFor(year, month)) {
+                        return false;
+                    }
+                }
+                else if (day > maximumDayInMonthFor(getEonAndYear(), month)) {
+                    return false;
+                }
+            }
+            // Use 2000 as a default since it's a leap year.
+            else if (day > maximumDayInMonthFor(2000, month)) {
+                return false;
+            }
+        }
+
+        // http://www.w3.org/2001/05/xmlschema-errata#e2-45
+        if (hour == 24 && (minute != 0 || second != 0 || 
+                (fractionalSecond != null && fractionalSecond.compareTo(DECIMAL_ZERO) != 0))) {
+            return false;
+        }
+
+        // XML Schema 1.0 specification defines year value of zero as
+        // invalid. Allow this class to set year field to zero
+        // since XML Schema 1.0 errata states that lexical zero will 
+        // be allowed in next version and treated as 1 B.C.E.
+        if (eon == null && year == 0) {
+            return false;
+        }
+        return true;
+    }
+
+    /**
+     * <p>Add <code>duration</code> to this instance.<\p>
+     * 
+     * <p>The computation is specified in
+     * <a href="http://www.w3.org/TR/xmlschema-2/#adding-durations-to-dateTimes">XML Schema 1.0 Part 2, Appendix E,
+     * <i>Adding durations to dateTimes</i>></a>.
+     * <a href="#datetimefieldsmapping">date/time field mapping table</a>
+     * defines the mapping from XML Schema 1.0 <code>dateTime</code> fields 
+     * to this class' representation of those fields.</p>
+     * 
+     * @param duration Duration to add to this <code>XMLGregorianCalendar</code>.
+     * 
+     * @throws NullPointerException  when <code>duration</code> parameter is <code>null</code>.
+     */
+    @Override
+    public void add(Duration duration) {
+
+        /*
+         * Extracted from 
+         * http://www.w3.org/TR/xmlschema-2/#adding-durations-to-dateTimes 
+         * to ensure implemented properly. See spec for definitions of methods
+         * used in algorithm.
+         * 
+         * Given a dateTime S and a duration D, specifies how to compute a 
+         * dateTime E where E is the end of the time period with start S and 
+         * duration D i.e. E = S + D.
+         * 
+         * The following is the precise specification. 
+         * These steps must be followed in the same order. 
+         * If a field in D is not specified, it is treated as if it were zero.
+         * If a field in S is not specified, it is treated in the calculation 
+         * as if it were the minimum allowed value in that field, however, 
+         * after the calculation is concluded, the corresponding field in 
+         * E is removed (set to unspecified).
+         * 
+         * Months (may be modified additionally below)
+         *  temp := S[month] + D[month]
+         *  E[month] := modulo(temp, 1, 13)
+         *  carry := fQuotient(temp, 1, 13)
+         */
+
+        boolean fieldUndefined[] = {
+                false,
+                false,
+                false, 
+                false,
+                false,
+                false
+        };
+
+        int signum = duration.getSign();
+
+        int startMonth = getMonth();
+        if (startMonth == DatatypeConstants.FIELD_UNDEFINED) {
+            startMonth = MIN_FIELD_VALUE[MONTH];
+            fieldUndefined[MONTH] = true;
+        }
+
+        BigInteger dMonths = sanitize(duration.getField(DatatypeConstants.MONTHS), signum);
+        BigInteger temp = BigInteger.valueOf(startMonth).add(dMonths);
+        setMonth(temp.subtract(BigInteger.ONE).mod(TWELVE).intValue() + 1);
+        BigInteger carry =
+            new BigDecimal(temp.subtract(BigInteger.ONE)).divide(new BigDecimal(TWELVE), BigDecimal.ROUND_FLOOR).toBigInteger();
+
+        /* Years (may be modified additionally below)
+         *  E[year] := S[year] + D[year] + carry
+         */
+        BigInteger startYear = getEonAndYear();
+        if (startYear == null) {
+            fieldUndefined[YEAR] = true;
+            startYear = BigInteger.ZERO;
+        }
+        BigInteger dYears = sanitize(duration.getField(DatatypeConstants.YEARS), signum);
+        BigInteger endYear = startYear.add(dYears).add(carry);
+        setYear(endYear);
+
+        /* Zone
+         *  E[zone] := S[zone]
+         * 
+         * no-op since adding to this, not to a new end point.
+         */
+
+        /* Seconds
+         *  temp := S[second] + D[second]
+         *  E[second] := modulo(temp, 60)
+         *  carry := fQuotient(temp, 60)
+         */
+        BigDecimal startSeconds;
+        if (getSecond() == DatatypeConstants.FIELD_UNDEFINED) {
+            fieldUndefined[SECOND] = true;
+            startSeconds = DECIMAL_ZERO;
+        } 
+        else {
+            // seconds + fractionalSeconds
+            startSeconds = getSeconds();
+        }
+
+        // Duration seconds is SECONDS + FRACTIONALSECONDS.
+        BigDecimal dSeconds = DurationImpl.sanitize((BigDecimal) duration.getField(DatatypeConstants.SECONDS), signum);
+        BigDecimal tempBD = startSeconds.add(dSeconds);
+        BigDecimal fQuotient = 
+            new BigDecimal(new BigDecimal(tempBD.toBigInteger()).divide(DECIMAL_SIXTY, BigDecimal.ROUND_FLOOR).toBigInteger());
+        BigDecimal endSeconds = tempBD.subtract(fQuotient.multiply(DECIMAL_SIXTY));
+
+        carry = fQuotient.toBigInteger();
+        setSecond(endSeconds.intValue());
+        BigDecimal tempFracSeconds = endSeconds.subtract(new BigDecimal(BigInteger.valueOf(getSecond())));
+        if (tempFracSeconds.compareTo(DECIMAL_ZERO) < 0) {
+            setFractionalSecond(DECIMAL_ONE.add(tempFracSeconds));
+            if (getSecond() == 0) {
+                setSecond(59);
+                carry = carry.subtract(BigInteger.ONE);
+            } 
+            else {
+                setSecond(getSecond() - 1);
+            }
+        } 
+        else {
+            setFractionalSecond(tempFracSeconds);
+        }
+
+        /* Minutes
+         *  temp := S[minute] + D[minute] + carry
+         *  E[minute] := modulo(temp, 60)
+         *  carry := fQuotient(temp, 60)
+         */
+        int startMinutes = getMinute();
+        if (startMinutes == DatatypeConstants.FIELD_UNDEFINED) {
+            fieldUndefined[MINUTE] = true;
+            startMinutes = MIN_FIELD_VALUE[MINUTE];
+        }
+        BigInteger dMinutes = sanitize(duration.getField(DatatypeConstants.MINUTES), signum);
+
+        temp = BigInteger.valueOf(startMinutes).add(dMinutes).add(carry);
+        setMinute(temp.mod(SIXTY).intValue());
+        carry = new BigDecimal(temp).divide(DECIMAL_SIXTY, BigDecimal.ROUND_FLOOR).toBigInteger();
+
+        /* Hours
+         *  temp := S[hour] + D[hour] + carry
+         *  E[hour] := modulo(temp, 24)
+         *  carry := fQuotient(temp, 24)
+         */
+        int startHours = getHour();
+        if (startHours == DatatypeConstants.FIELD_UNDEFINED) {
+            fieldUndefined[HOUR] = true;
+            startHours = MIN_FIELD_VALUE[HOUR];
+        }
+        BigInteger dHours = sanitize(duration.getField(DatatypeConstants.HOURS), signum);
+
+        temp = BigInteger.valueOf(startHours).add(dHours).add(carry);
+        setHour(temp.mod(TWENTY_FOUR).intValue());
+        carry = new BigDecimal(temp).divide(new BigDecimal(TWENTY_FOUR), BigDecimal.ROUND_FLOOR).toBigInteger();
+
+        /* Days
+         *  if S[day] > maximumDayInMonthFor(E[year], E[month])
+         *       + tempDays := maximumDayInMonthFor(E[year], E[month])
+         *  else if S[day] < 1
+         *       + tempDays := 1
+         *  else
+         *       + tempDays := S[day]
+         *  E[day] := tempDays + D[day] + carry
+         *  START LOOP
+         *       + IF E[day] < 1
+         *             # E[day] := E[day] + 
+         *                 maximumDayInMonthFor(E[year], E[month] - 1)
+         *             # carry := -1
+         *       + ELSE IF E[day] > maximumDayInMonthFor(E[year], E[month])
+         *             # E[day] := 
+         *                    E[day] - maximumDayInMonthFor(E[year], E[month])
+         *             # carry := 1
+         *       + ELSE EXIT LOOP
+         *       + temp := E[month] + carry
+         *       + E[month] := modulo(temp, 1, 13)
+         *       + E[year] := E[year] + fQuotient(temp, 1, 13)
+         *       + GOTO START LOOP
+         */
+        BigInteger tempDays;
+        int startDay = getDay();
+        if (startDay == DatatypeConstants.FIELD_UNDEFINED) {
+            fieldUndefined[DAY] = true;
+            startDay = MIN_FIELD_VALUE[DAY];
+        }
+        BigInteger dDays = sanitize(duration.getField(DatatypeConstants.DAYS), signum);
+        int maxDayInMonth = maximumDayInMonthFor(getEonAndYear(), getMonth());
+        if (startDay > maxDayInMonth) {
+            tempDays =  BigInteger.valueOf(maxDayInMonth);
+        } 
+        else if (startDay < 1) {
+            tempDays = BigInteger.ONE;
+        } 
+        else {
+            tempDays = BigInteger.valueOf(startDay);
+        }
+        BigInteger endDays = tempDays.add(dDays).add(carry);
+        int monthCarry;
+        int intTemp;
+        while (true) {
+            if (endDays.compareTo(BigInteger.ONE) < 0) {
+                // calculate days in previous month, watch for month roll over
+                BigInteger mdimf = null;
+                if (month >= 2) {
+                    mdimf = BigInteger.valueOf(maximumDayInMonthFor(getEonAndYear(), getMonth() - 1));
+                } 
+                else {
+                    // roll over to December of previous year
+                    mdimf = BigInteger.valueOf(maximumDayInMonthFor(getEonAndYear().subtract(BigInteger.valueOf(1)), 12));
+                }
+                endDays = endDays.add(mdimf);
+                monthCarry = -1;
+            } 
+            else if (endDays.compareTo(BigInteger.valueOf(maximumDayInMonthFor(getEonAndYear(), getMonth()))) > 0) {
+                endDays = endDays.add(BigInteger.valueOf(-maximumDayInMonthFor(getEonAndYear(), getMonth())));
+                monthCarry = 1;
+            } 
+            else {
+                break;
+            } 
+
+            intTemp = getMonth() + monthCarry;
+            int endMonth = (intTemp - 1) % (13 - 1);
+            int quotient;
+            if (endMonth < 0) {
+                endMonth = (13 - 1) + endMonth + 1;
+                quotient = BigDecimal.valueOf(intTemp - 1).divide(new BigDecimal(TWELVE), BigDecimal.ROUND_UP).intValue();
+            } 
+            else {
+                quotient = (intTemp - 1) / (13 - 1);
+                endMonth += 1;
+            }
+            setMonth(endMonth);
+            if (quotient != 0)  {
+                setYear(getEonAndYear().add(BigInteger.valueOf(quotient)));
+            } 
+        }
+        setDay(endDays.intValue());
+
+        // set fields that where undefined before this addition, back to undefined.
+        for (int i = YEAR; i <= SECOND; i++) {
+            if (fieldUndefined[i]) {
+                switch (i) {
+                    case YEAR:
+                        setYear(DatatypeConstants.FIELD_UNDEFINED);
+                        break;
+                    case MONTH:
+                        setMonth(DatatypeConstants.FIELD_UNDEFINED);
+                        break;
+                    case DAY:
+                        setDay(DatatypeConstants.FIELD_UNDEFINED);
+                 

<TRUNCATED>

[11/24] jena git commit: JENA-1537: Remove dependency on Xerces. Import needed code

Posted by an...@apache.org.
http://git-wip-us.apache.org/repos/asf/jena/blob/c9a7e646/jena-core/src/main/java/org/apache/jena/ext/xerces/impl/xs/XSDeclarationPool.java
----------------------------------------------------------------------
diff --git a/jena-core/src/main/java/org/apache/jena/ext/xerces/impl/xs/XSDeclarationPool.java b/jena-core/src/main/java/org/apache/jena/ext/xerces/impl/xs/XSDeclarationPool.java
new file mode 100644
index 0000000..d033a19
--- /dev/null
+++ b/jena-core/src/main/java/org/apache/jena/ext/xerces/impl/xs/XSDeclarationPool.java
@@ -0,0 +1,315 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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.jena.ext.xerces.impl.xs;
+
+import org.apache.jena.ext.xerces.impl.dv.xs.SchemaDVFactoryImpl;
+import org.apache.jena.ext.xerces.impl.dv.xs.XSSimpleTypeDecl;
+
+/**
+ * This class is pool that enables caching of XML Schema declaration objects.
+ * Before a compiled grammar object is garbage collected,
+ * the implementation will add all XML Schema component
+ * declarations to the pool.
+ * Note: The cashing mechanism is not implemented yet.
+ *
+ * @xerces.internal 
+ * 
+ * @author Elena Litani, IBM
+ * @version $Id: XSDeclarationPool.java 805582 2009-08-18 21:13:20Z sandygao $
+ */
+public final class XSDeclarationPool {
+    /** Chunk shift (8). */
+    private static final int CHUNK_SHIFT = 8; // 2^8 = 256
+
+    /** Chunk size (1 << CHUNK_SHIFT). */
+    private static final int CHUNK_SIZE = 1 << CHUNK_SHIFT;
+
+    /** Chunk mask (CHUNK_SIZE - 1). */
+    private static final int CHUNK_MASK = CHUNK_SIZE - 1;
+
+    /** Initial chunk count (). */
+    private static final int INITIAL_CHUNK_COUNT = (1 << (10 - CHUNK_SHIFT)); // 2^10 = 1k
+//
+//    /** Element declaration pool*/
+//    private XSElementDecl fElementDecl[][] = new XSElementDecl[INITIAL_CHUNK_COUNT][];
+//    private int fElementDeclIndex = 0;
+//
+//    /** Particle declaration pool */
+//    private XSParticleDecl fParticleDecl[][] = new XSParticleDecl[INITIAL_CHUNK_COUNT][];
+//    private int fParticleDeclIndex = 0;
+//
+//    /** Particle declaration pool */
+//    private XSModelGroupImpl fModelGroup[][] = new XSModelGroupImpl[INITIAL_CHUNK_COUNT][];
+//    private int fModelGroupIndex = 0;
+//
+//    /** Attribute declaration pool */
+//    private XSAttributeDecl fAttrDecl[][] = new XSAttributeDecl[INITIAL_CHUNK_COUNT][];
+//    private int fAttrDeclIndex = 0;
+//
+//    /** ComplexType declaration pool */
+//    private XSComplexTypeDecl fCTDecl[][] = new XSComplexTypeDecl[INITIAL_CHUNK_COUNT][];
+//    private int fCTDeclIndex = 0;
+//
+    /** SimpleType declaration pool */
+    private XSSimpleTypeDecl fSTDecl[][] = new XSSimpleTypeDecl[INITIAL_CHUNK_COUNT][];
+    private int fSTDeclIndex = 0;
+//
+//    /** AttributeUse declaration pool */
+//    private XSAttributeUseImpl fAttributeUse[][] = new XSAttributeUseImpl[INITIAL_CHUNK_COUNT][];
+//    private int fAttributeUseIndex = 0;
+//    
+    private SchemaDVFactoryImpl dvFactory;
+    public void setDVFactory(SchemaDVFactoryImpl dvFactory) {
+        this.dvFactory = dvFactory;
+    }
+//
+//    public final  XSElementDecl getElementDecl(){
+//        int     chunk       = fElementDeclIndex >> CHUNK_SHIFT;
+//        int     index       = fElementDeclIndex &  CHUNK_MASK;
+//        ensureElementDeclCapacity(chunk);
+//        if (fElementDecl[chunk][index] == null) {
+//            fElementDecl[chunk][index] = new XSElementDecl();
+//        } else {
+//            fElementDecl[chunk][index].reset();
+//        }
+//        fElementDeclIndex++;
+//        return fElementDecl[chunk][index];
+//    }
+//
+//    public final XSAttributeDecl getAttributeDecl(){
+//        int     chunk       = fAttrDeclIndex >> CHUNK_SHIFT;
+//        int     index       = fAttrDeclIndex &  CHUNK_MASK;
+//        ensureAttrDeclCapacity(chunk);
+//        if (fAttrDecl[chunk][index] == null) {
+//            fAttrDecl[chunk][index] = new XSAttributeDecl();
+//        } else {
+//            fAttrDecl[chunk][index].reset();
+//        }
+//        fAttrDeclIndex++;
+//        return fAttrDecl[chunk][index];
+//
+//    }
+//
+//    public final XSAttributeUseImpl getAttributeUse(){
+//        int     chunk       = fAttributeUseIndex >> CHUNK_SHIFT;
+//        int     index       = fAttributeUseIndex &  CHUNK_MASK;
+//        ensureAttributeUseCapacity(chunk);
+//        if (fAttributeUse[chunk][index] == null) {
+//            fAttributeUse[chunk][index] = new XSAttributeUseImpl();
+//        } else {
+//            fAttributeUse[chunk][index].reset();
+//        }
+//        fAttributeUseIndex++;
+//        return fAttributeUse[chunk][index];
+//
+//    }
+//    
+//    public final XSComplexTypeDecl getComplexTypeDecl(){
+//        int     chunk       = fCTDeclIndex >> CHUNK_SHIFT;
+//        int     index       = fCTDeclIndex &  CHUNK_MASK;
+//        ensureCTDeclCapacity(chunk);
+//        if (fCTDecl[chunk][index] == null) {
+//
+//            fCTDecl[chunk][index] = new XSComplexTypeDecl();
+//        } else {
+//            fCTDecl[chunk][index].reset();
+//        }
+//        fCTDeclIndex++;
+//        return fCTDecl[chunk][index];
+//    }
+//
+    public final XSSimpleTypeDecl getSimpleTypeDecl(){
+        int     chunk       = fSTDeclIndex >> CHUNK_SHIFT;
+        int     index       = fSTDeclIndex &  CHUNK_MASK;
+        ensureSTDeclCapacity(chunk);
+        if (fSTDecl[chunk][index] == null) {
+            fSTDecl[chunk][index] = dvFactory.newXSSimpleTypeDecl();
+        } else {
+            fSTDecl[chunk][index].reset();
+        }
+        fSTDeclIndex++;
+        return fSTDecl[chunk][index];
+
+    } 
+//
+//    public final XSParticleDecl getParticleDecl(){
+//        int     chunk       = fParticleDeclIndex >> CHUNK_SHIFT;
+//        int     index       = fParticleDeclIndex &  CHUNK_MASK;
+//        ensureParticleDeclCapacity(chunk);
+//        if (fParticleDecl[chunk][index] == null) {
+//            fParticleDecl[chunk][index] = new XSParticleDecl();
+//        } else {
+//            fParticleDecl[chunk][index].reset();
+//        }
+//        fParticleDeclIndex++;
+//        return fParticleDecl[chunk][index];
+//    }
+//
+//    public final XSModelGroupImpl getModelGroup(){
+//        int     chunk       = fModelGroupIndex >> CHUNK_SHIFT;
+//        int     index       = fModelGroupIndex &  CHUNK_MASK;
+//        ensureModelGroupCapacity(chunk);
+//        if (fModelGroup[chunk][index] == null) {
+//            fModelGroup[chunk][index] = new XSModelGroupImpl();
+//        } else {
+//            fModelGroup[chunk][index].reset();
+//        }
+//        fModelGroupIndex++;
+//        return fModelGroup[chunk][index];
+//    }
+//
+//    // REVISIT: do we need decl pool for group declarations, attribute group,
+//    //          notations?
+//    //          it seems like each schema would use a small number of those
+//    //          components, so it probably is not worth keeping those components
+//    //          in the pool.
+//
+//    private boolean ensureElementDeclCapacity(int chunk) {
+//        if (chunk >= fElementDecl.length) {
+//            fElementDecl = resize(fElementDecl, fElementDecl.length * 2);
+//        } else if (fElementDecl[chunk] != null) {
+//            return false;
+//        }
+//
+//        fElementDecl[chunk] = new XSElementDecl[CHUNK_SIZE];
+//        return true;
+//    }
+//
+//    private static XSElementDecl[][] resize(XSElementDecl array[][], int newsize) {
+//        XSElementDecl newarray[][] = new XSElementDecl[newsize][];
+//        System.arraycopy(array, 0, newarray, 0, array.length);
+//        return newarray;
+//    }
+//
+//    private boolean ensureParticleDeclCapacity(int chunk) {
+//        if (chunk >= fParticleDecl.length) {
+//            fParticleDecl = resize(fParticleDecl, fParticleDecl.length * 2);
+//        } else if (fParticleDecl[chunk] != null) {
+//            return false;
+//        }
+//
+//        fParticleDecl[chunk] = new XSParticleDecl[CHUNK_SIZE];
+//        return true;
+//    }
+//
+//    private boolean ensureModelGroupCapacity(int chunk) {
+//        if (chunk >= fModelGroup.length) {
+//            fModelGroup = resize(fModelGroup, fModelGroup.length * 2);
+//        } else if (fModelGroup[chunk] != null) {
+//            return false;
+//        }
+//
+//        fModelGroup[chunk] = new XSModelGroupImpl[CHUNK_SIZE];
+//        return true;
+//    }
+//
+//    private static XSParticleDecl[][] resize(XSParticleDecl array[][], int newsize) {
+//        XSParticleDecl newarray[][] = new XSParticleDecl[newsize][];
+//        System.arraycopy(array, 0, newarray, 0, array.length);
+//        return newarray;
+//    }
+//
+//    private static XSModelGroupImpl[][] resize(XSModelGroupImpl array[][], int newsize) {
+//        XSModelGroupImpl newarray[][] = new XSModelGroupImpl[newsize][];
+//        System.arraycopy(array, 0, newarray, 0, array.length);
+//        return newarray;
+//    }
+//
+//    private boolean ensureAttrDeclCapacity(int chunk) {
+//        if (chunk >= fAttrDecl.length) {
+//            fAttrDecl = resize(fAttrDecl, fAttrDecl.length * 2);
+//        } else if (fAttrDecl[chunk] != null) {            
+//            return false;
+//        }
+//
+//        fAttrDecl[chunk] = new XSAttributeDecl[CHUNK_SIZE];
+//        return true;
+//    }
+//
+//    private static XSAttributeDecl[][] resize(XSAttributeDecl array[][], int newsize) {
+//        XSAttributeDecl newarray[][] = new XSAttributeDecl[newsize][];
+//        System.arraycopy(array, 0, newarray, 0, array.length);
+//        return newarray;
+//    }
+//
+//    private boolean ensureAttributeUseCapacity(int chunk) {
+//        if (chunk >= fAttributeUse.length) {
+//            fAttributeUse = resize(fAttributeUse, fAttributeUse.length * 2);
+//        } else if (fAttributeUse[chunk] != null) {
+//            return false;
+//        }
+//
+//        fAttributeUse[chunk] = new XSAttributeUseImpl[CHUNK_SIZE];
+//        return true;
+//    }
+//
+//    private static XSAttributeUseImpl[][] resize(XSAttributeUseImpl array[][], int newsize) {
+//        XSAttributeUseImpl newarray[][] = new XSAttributeUseImpl[newsize][];
+//        System.arraycopy(array, 0, newarray, 0, array.length);
+//        return newarray;
+//    }
+//
+    private boolean ensureSTDeclCapacity(int chunk) {
+        if (chunk >= fSTDecl.length) {
+            fSTDecl = resize(fSTDecl, fSTDecl.length * 2);
+        } else if (fSTDecl[chunk] != null) {
+            return false;
+        }
+
+        fSTDecl[chunk] = new XSSimpleTypeDecl[CHUNK_SIZE];
+        return true;
+    }
+
+    private static XSSimpleTypeDecl[][] resize(XSSimpleTypeDecl array[][], int newsize) {
+        XSSimpleTypeDecl newarray[][] = new XSSimpleTypeDecl[newsize][];
+        System.arraycopy(array, 0, newarray, 0, array.length);
+        return newarray;
+    }
+//
+//    private boolean ensureCTDeclCapacity(int chunk) {
+//
+//        if (chunk >= fCTDecl.length) {
+//            fCTDecl = resize(fCTDecl, fCTDecl.length * 2);
+//        } else if (fCTDecl[chunk] != null){
+//            return false;
+//        }
+//
+//        fCTDecl[chunk] = new XSComplexTypeDecl[CHUNK_SIZE];
+//        return true;
+//    }
+//
+//    private static XSComplexTypeDecl[][] resize(XSComplexTypeDecl array[][], int newsize) {
+//        XSComplexTypeDecl newarray[][] = new XSComplexTypeDecl[newsize][];
+//        System.arraycopy(array, 0, newarray, 0, array.length);
+//        return newarray;
+//    }
+//
+//
+//
+    public void reset(){
+//        fElementDeclIndex = 0;
+//        fParticleDeclIndex = 0;
+//        fModelGroupIndex = 0;
+        fSTDeclIndex = 0;
+//        fCTDeclIndex = 0;
+//        fAttrDeclIndex = 0;
+//        fAttributeUseIndex = 0;
+    }
+//
+//
+}

http://git-wip-us.apache.org/repos/asf/jena/blob/c9a7e646/jena-core/src/main/java/org/apache/jena/ext/xerces/impl/xs/util/ObjectListImpl.java
----------------------------------------------------------------------
diff --git a/jena-core/src/main/java/org/apache/jena/ext/xerces/impl/xs/util/ObjectListImpl.java b/jena-core/src/main/java/org/apache/jena/ext/xerces/impl/xs/util/ObjectListImpl.java
new file mode 100644
index 0000000..062f397
--- /dev/null
+++ b/jena-core/src/main/java/org/apache/jena/ext/xerces/impl/xs/util/ObjectListImpl.java
@@ -0,0 +1,123 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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.jena.ext.xerces.impl.xs.util;
+
+import java.lang.reflect.Array;
+import java.util.AbstractList;
+
+import org.apache.jena.ext.xerces.xs.datatypes.ObjectList;
+
+/**
+ * Contains a list of Objects.
+ * 
+ * @xerces.internal
+ * 
+ * @version $Id: ObjectListImpl.java 789785 2009-06-30 15:10:26Z knoaman $
+ */
+@SuppressWarnings("all")
+public final class ObjectListImpl extends AbstractList<Object> implements ObjectList {
+
+    /**
+     * An immutable empty list.
+     */
+    public static final ObjectListImpl EMPTY_LIST = new ObjectListImpl(new Object[0], 0);
+    
+    // The array to hold all data
+    private final Object[] fArray;
+    
+    // Number of elements in this list
+    private final int fLength;
+
+    public ObjectListImpl(Object[] array, int length) {
+        fArray = array;
+        fLength = length;
+    }
+
+    @Override
+    public int getLength() {
+        return fLength;
+    }
+    
+    @Override
+    public boolean contains(Object item) {
+        if (item == null) {
+            for (int i = 0; i < fLength; i++) {
+                if (fArray[i] == null)
+                    return true;
+            }
+        }
+        else {
+            for (int i = 0; i < fLength; i++) {
+                if (item.equals(fArray[i]))
+                    return true;
+            }
+        }
+        return false;
+    }
+    
+    @Override
+    public Object item(int index) {
+        if (index < 0 || index >= fLength) {
+            return null;
+        }
+        return fArray[index];
+    }
+    
+    /*
+     * List methods
+     */
+    @Override
+    public Object get(int index) {
+        if (index >= 0 && index < fLength) {
+            return fArray[index];
+        }
+        throw new IndexOutOfBoundsException("Index: " + index);
+    }
+
+    @Override
+    public int size() {
+        return getLength();
+    }
+    
+    @Override
+    public Object[] toArray() {
+        Object[] a = new Object[fLength];
+        toArray0(a);
+        return a;
+    }
+    
+    @Override
+    public Object[] toArray(Object[] a) {
+        if (a.length < fLength) {
+            Class arrayClass = a.getClass();
+            Class componentType = arrayClass.getComponentType();
+            a = (Object[]) Array.newInstance(componentType, fLength);
+        }
+        toArray0(a);
+        if (a.length > fLength) {
+            a[fLength] = null;
+        }
+        return a;
+    }
+
+    private void toArray0(Object[] a) {
+        if (fLength > 0) {
+            System.arraycopy(fArray, 0, a, 0, fLength);
+        }
+    }
+}

http://git-wip-us.apache.org/repos/asf/jena/blob/c9a7e646/jena-core/src/main/java/org/apache/jena/ext/xerces/impl/xs/util/ShortListImpl.java
----------------------------------------------------------------------
diff --git a/jena-core/src/main/java/org/apache/jena/ext/xerces/impl/xs/util/ShortListImpl.java b/jena-core/src/main/java/org/apache/jena/ext/xerces/impl/xs/util/ShortListImpl.java
new file mode 100644
index 0000000..8479915
--- /dev/null
+++ b/jena-core/src/main/java/org/apache/jena/ext/xerces/impl/xs/util/ShortListImpl.java
@@ -0,0 +1,128 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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.jena.ext.xerces.impl.xs.util;
+
+import java.util.AbstractList;
+
+import org.apache.jena.ext.xerces.xs.ShortList;
+import org.apache.jena.ext.xerces.xs.XSException;
+
+/**
+ * Contains a list of shorts.
+ *
+ * @xerces.internal 
+ *
+ * @author Sandy Gao, IBM
+ *
+ * @version $Id: ShortListImpl.java 725840 2008-12-11 22:19:06Z mrglavas $
+ */
+@SuppressWarnings("all")
+public final class ShortListImpl extends AbstractList implements ShortList {
+
+    /**
+     * An immutable empty list.
+     */
+    public static final ShortListImpl EMPTY_LIST = new ShortListImpl(new short[0], 0);
+    
+    // The array to hold all data
+    private final short[] fArray;
+    // Number of elements in this list
+    private final int fLength;
+
+    /**
+     * Construct an XSObjectList implementation
+     * 
+     * @param array     the data array
+     * @param length    the number of elements
+     */
+    public ShortListImpl(short[] array, int length) {
+        fArray = array;
+        fLength = length;
+    }
+
+    /**
+     * The number of <code>Objects</code> in the list. The range of valid
+     * child node indices is 0 to <code>length-1</code> inclusive.
+     */
+    @Override
+    public int getLength() {
+        return fLength;
+    }
+
+    /**
+     *  Checks if the <code>unsigned short</code> <code>item</code> is a 
+     * member of this list. 
+     * @param item  <code>unsigned short</code> whose presence in this list 
+     *   is to be tested. 
+     * @return  True if this list contains the <code>unsigned short</code> 
+     *   <code>item</code>. 
+     */
+    @Override
+    public boolean contains(short item) {
+        for (int i = 0; i < fLength; i++) {
+            if (fArray[i] == item) {
+                return true;
+            }
+        }
+        return false;
+    }
+    
+    @Override
+    public short item(int index) throws XSException {
+        if (index < 0 || index >= fLength) {
+            throw new XSException(XSException.INDEX_SIZE_ERR, null);
+        }
+        return fArray[index];
+    }
+    
+    @Override
+    public boolean equals(Object obj) {
+        if (obj == null || !(obj instanceof ShortList)) {
+            return false;
+        }
+        ShortList rhs = (ShortList)obj;
+        
+        if (fLength != rhs.getLength()) {
+            return false;
+        }
+        for (int i = 0;i < fLength; ++i) {
+            if (fArray[i] != rhs.item(i)) {
+                return false;
+            }
+        }
+        return true;
+    }
+    
+    /*
+     * List methods
+     */
+
+    @Override
+    public Object get(int index) {
+        if (index >= 0 && index < fLength) {
+            return new Short(fArray[index]);
+        }
+        throw new IndexOutOfBoundsException("Index: " + index);
+    }
+
+    @Override
+    public int size() {
+        return getLength();
+    }
+
+} // class ShortListImpl

http://git-wip-us.apache.org/repos/asf/jena/blob/c9a7e646/jena-core/src/main/java/org/apache/jena/ext/xerces/impl/xs/util/StringListImpl.java
----------------------------------------------------------------------
diff --git a/jena-core/src/main/java/org/apache/jena/ext/xerces/impl/xs/util/StringListImpl.java b/jena-core/src/main/java/org/apache/jena/ext/xerces/impl/xs/util/StringListImpl.java
new file mode 100644
index 0000000..81a7916
--- /dev/null
+++ b/jena-core/src/main/java/org/apache/jena/ext/xerces/impl/xs/util/StringListImpl.java
@@ -0,0 +1,171 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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.jena.ext.xerces.impl.xs.util;
+
+import java.lang.reflect.Array;
+import java.util.AbstractList;
+import java.util.Vector;
+
+import org.apache.jena.ext.xerces.xs.StringList;
+
+/**
+ * Contains a list of Strings.
+ *
+ * @xerces.internal 
+ *
+ * @author Sandy Gao, IBM
+ *
+ * @version $Id: StringListImpl.java 776326 2009-05-19 14:27:24Z mrglavas $
+ */
+@SuppressWarnings("all")
+public final class StringListImpl extends AbstractList implements StringList {
+
+    /**
+     * An immutable empty list.
+     */
+    public static final StringListImpl EMPTY_LIST = new StringListImpl(new String[0], 0);
+    
+    // The array to hold all data
+    private final String[] fArray;
+    // Number of elements in this list
+    private final int fLength;
+
+    // REVISIT: this is temp solution. In general we need to use this class
+    //          instead of the Vector.
+    private final Vector fVector;
+
+    public StringListImpl(Vector v) {
+        fVector = v;        
+        fLength = (v == null) ? 0 : v.size();
+        fArray = null;
+    }
+
+    /**
+     * Construct an XSObjectList implementation
+     * 
+     * @param array     the data array
+     * @param length    the number of elements
+     */
+    public StringListImpl(String[] array, int length) {
+        fArray = array;
+        fLength = length;
+        fVector = null;
+    }
+
+    /**
+     * The number of <code>Objects</code> in the list. The range of valid
+     * child node indices is 0 to <code>length-1</code> inclusive.
+     */
+    @Override
+    public int getLength() {
+        return fLength;
+    }
+
+    /**
+     *  Checks if the <code>GenericString</code> <code>item</code> is a member 
+     * of this list. 
+     * @param item  <code>GenericString</code> whose presence in this list is 
+     *   to be tested. 
+     * @return  True if this list contains the <code>GenericString</code> 
+     *   <code>item</code>. 
+     */
+    @Override
+    public boolean contains(String item) {
+        if (fVector != null) {
+            return fVector.contains(item);
+        }
+        if (item == null) {
+            for (int i = 0; i < fLength; i++) {
+                if (fArray[i] == null)
+                    return true;
+            }
+        }
+        else {
+            for (int i = 0; i < fLength; i++) {
+                if (item.equals(fArray[i]))
+                    return true;
+            }
+        }
+        return false;
+    }
+
+    @Override
+    public String item(int index) {
+        if (index < 0 || index >= fLength) {
+            return null;
+        }
+        if (fVector != null) {
+            return (String)fVector.elementAt(index);
+        }
+        return fArray[index];
+    }
+    
+    /*
+     * List methods
+     */
+
+    @Override
+    public Object get(int index) {
+        if (index >= 0 && index < fLength) {
+            if (fVector != null) {
+                return fVector.elementAt(index);
+            }
+            return fArray[index];
+        }
+        throw new IndexOutOfBoundsException("Index: " + index);
+    }
+
+    @Override
+    public int size() {
+        return getLength();
+    }
+    
+    @Override
+    public Object[] toArray() {
+        if (fVector != null) {
+            return fVector.toArray();
+        }
+        Object[] a = new Object[fLength];
+        toArray0(a);
+        return a;
+    }
+    
+    @Override
+    public Object[] toArray(Object[] a) {
+        if (fVector != null) {
+            return fVector.toArray(a);
+        }
+        if (a.length < fLength) {
+            Class arrayClass = a.getClass();
+            Class componentType = arrayClass.getComponentType();
+            a = (Object[]) Array.newInstance(componentType, fLength);
+        }
+        toArray0(a);
+        if (a.length > fLength) {
+            a[fLength] = null;
+        }
+        return a;
+    }
+    
+    private void toArray0(Object[] a) {
+        if (fLength > 0) {
+            System.arraycopy(fArray, 0, a, 0, fLength);
+        }
+    }
+
+} // class StringListImpl

http://git-wip-us.apache.org/repos/asf/jena/blob/c9a7e646/jena-core/src/main/java/org/apache/jena/ext/xerces/impl/xs/util/XSObjectListImpl.java
----------------------------------------------------------------------
diff --git a/jena-core/src/main/java/org/apache/jena/ext/xerces/impl/xs/util/XSObjectListImpl.java b/jena-core/src/main/java/org/apache/jena/ext/xerces/impl/xs/util/XSObjectListImpl.java
new file mode 100644
index 0000000..22bc47b
--- /dev/null
+++ b/jena-core/src/main/java/org/apache/jena/ext/xerces/impl/xs/util/XSObjectListImpl.java
@@ -0,0 +1,293 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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.jena.ext.xerces.impl.xs.util;
+
+import java.lang.reflect.Array;
+import java.util.AbstractList;
+import java.util.Iterator;
+import java.util.ListIterator;
+import java.util.NoSuchElementException;
+
+import org.apache.jena.ext.xerces.xs.XSObject;
+import org.apache.jena.ext.xerces.xs.XSObjectList;
+
+/**
+ * Contains a list of XSObjects.
+ *
+ * @xerces.internal 
+ *
+ * @author Sandy Gao, IBM
+ *
+ * @version $Id: XSObjectListImpl.java 776079 2009-05-18 20:22:27Z mrglavas $
+ */
+@SuppressWarnings("all")
+public class XSObjectListImpl extends AbstractList implements XSObjectList {
+    
+    /**
+     * An immutable empty list.
+     */
+    public static final XSObjectListImpl EMPTY_LIST = new XSObjectListImpl(new XSObject[0], 0);
+    private static final ListIterator EMPTY_ITERATOR = new ListIterator() {
+        @Override
+        public boolean hasNext() {
+            return false;
+        }
+        @Override
+        public Object next() {
+            throw new NoSuchElementException();
+        }
+        @Override
+        public boolean hasPrevious() {
+            return false;
+        }
+        @Override
+        public Object previous() {
+            throw new NoSuchElementException();
+        }
+        @Override
+        public int nextIndex() {
+            return 0;
+        }
+        @Override
+        public int previousIndex() {
+            return -1;
+        }
+        @Override
+        public void remove() {
+            throw new UnsupportedOperationException();
+        }
+        @Override
+        public void set(Object object) {
+            throw new UnsupportedOperationException();
+        }
+        @Override
+        public void add(Object object) {
+            throw new UnsupportedOperationException();
+        }
+    };
+    
+    private static final int DEFAULT_SIZE = 4;
+
+    // The array to hold all data
+    private XSObject[] fArray = null;
+    // Number of elements in this list
+    private int fLength = 0;
+    
+    public XSObjectListImpl() {
+        fArray = new XSObject[DEFAULT_SIZE];
+        fLength = 0;
+    }
+
+    /**
+     * Construct an XSObjectList implementation
+     * 
+     * @param array     the data array
+     * @param length    the number of elements
+     */
+    public XSObjectListImpl(XSObject[] array, int length) {
+        fArray = array;
+        fLength = length;
+    }
+
+    /**
+     * The number of <code>XSObjects</code> in the list. The range of valid
+     * child node indices is 0 to <code>length-1</code> inclusive.
+     */
+    @Override
+    public int getLength() {
+        return fLength;
+    }
+
+    /**
+     * Returns the <code>index</code>th item in the collection. The index
+     * starts at 0. If <code>index</code> is greater than or equal to the
+     * number of nodes in the list, this returns <code>null</code>.
+     * @param index index into the collection.
+     * @return The XSObject at the <code>index</code>th position in the
+     *   <code>XSObjectList</code>, or <code>null</code> if that is not a
+     *   valid index.
+     */
+    @Override
+    public XSObject item(int index) {
+        if (index < 0 || index >= fLength) {
+            return null;
+        }
+        return fArray[index];
+    }
+
+    // clear this object
+    public void clearXSObjectList() {
+        for (int i=0; i<fLength; i++) {
+            fArray[i] = null;
+        }
+        fArray = null;
+        fLength = 0;
+    }
+    
+    public void addXSObject(XSObject object) {
+       if (fLength == fArray.length) {  
+           XSObject[] temp = new XSObject[fLength + 4];
+           System.arraycopy(fArray, 0, temp, 0, fLength);
+           fArray = temp;
+       }
+       fArray[fLength++] = object;
+    }
+    
+    public void addXSObject(int index, XSObject object) {
+        fArray[index] = object;
+    }
+    
+    /*
+     * List methods
+     */
+    
+    @Override
+    public boolean contains(Object value) {
+        return (value == null) ? containsNull() : containsObject(value);
+    }
+
+    @Override
+    public Object get(int index) {
+        if (index >= 0 && index < fLength) {
+            return fArray[index];
+        }
+        throw new IndexOutOfBoundsException("Index: " + index);
+    }
+
+    @Override
+    public int size() {
+        return getLength();
+    }
+    
+    @Override
+    public Iterator iterator() {
+        return listIterator0(0);
+    }
+    
+    @Override
+    public ListIterator listIterator() {
+        return listIterator0(0);
+    }
+    
+    @Override
+    public ListIterator listIterator(int index) {
+        if (index >= 0 && index < fLength) {
+            return listIterator0(index);
+        }
+        throw new IndexOutOfBoundsException("Index: " + index);
+    }
+    
+    private ListIterator listIterator0(int index) {
+        return fLength == 0 ? EMPTY_ITERATOR : new XSObjectListIterator(index);
+    }
+    
+    private boolean containsObject(Object value) {
+        for (int i = fLength - 1; i >= 0; --i) {
+            if (value.equals(fArray[i])) {
+                return true;
+            }
+        }
+        return false;
+    }
+    
+    private boolean containsNull() {
+        for (int i = fLength - 1; i >= 0; --i) {
+            if (fArray[i] == null) {
+                return true;
+            }
+        }
+        return false;
+    }
+    
+    @Override
+    public Object[] toArray() {
+        Object[] a = new Object[fLength];
+        toArray0(a);
+        return a;
+    }
+    
+    @Override
+    public Object[] toArray(Object[] a) {
+        if (a.length < fLength) {
+            Class arrayClass = a.getClass();
+            Class componentType = arrayClass.getComponentType();
+            a = (Object[]) Array.newInstance(componentType, fLength);
+        }
+        toArray0(a);
+        if (a.length > fLength) {
+            a[fLength] = null;
+        }
+        return a;
+    }
+    
+    private void toArray0(Object[] a) {
+        if (fLength > 0) {
+            System.arraycopy(fArray, 0, a, 0, fLength);
+        }
+    }
+    
+    private final class XSObjectListIterator implements ListIterator {
+        private int index;
+        public XSObjectListIterator(int index) {
+            this.index = index;
+        }
+        @Override
+        public boolean hasNext() {
+            return (index < fLength);
+        }
+        @Override
+        public Object next() {
+            if (index < fLength) {
+                return fArray[index++];
+            }
+            throw new NoSuchElementException();
+        }
+        @Override
+        public boolean hasPrevious() {
+            return (index > 0);
+        }
+        @Override
+        public Object previous() {
+            if (index > 0) {
+                return fArray[--index];
+            }
+            throw new NoSuchElementException();
+        }
+        @Override
+        public int nextIndex() {
+            return index;
+        }
+        @Override
+        public int previousIndex() {
+            return index - 1;
+        }
+        @Override
+        public void remove() {
+            throw new UnsupportedOperationException();
+        }
+        @Override
+        public void set(Object o) {
+            throw new UnsupportedOperationException();
+        }
+        @Override
+        public void add(Object o) {
+            throw new UnsupportedOperationException();
+        }
+    }
+
+} // class XSObjectListImpl

http://git-wip-us.apache.org/repos/asf/jena/blob/c9a7e646/jena-core/src/main/java/org/apache/jena/ext/xerces/jaxp/datatype/DatatypeFactoryImpl.java
----------------------------------------------------------------------
diff --git a/jena-core/src/main/java/org/apache/jena/ext/xerces/jaxp/datatype/DatatypeFactoryImpl.java b/jena-core/src/main/java/org/apache/jena/ext/xerces/jaxp/datatype/DatatypeFactoryImpl.java
new file mode 100644
index 0000000..4d26668
--- /dev/null
+++ b/jena-core/src/main/java/org/apache/jena/ext/xerces/jaxp/datatype/DatatypeFactoryImpl.java
@@ -0,0 +1,394 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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.jena.ext.xerces.jaxp.datatype;
+
+import java.math.BigDecimal;
+import java.math.BigInteger;
+import java.util.GregorianCalendar;
+
+import javax.xml.datatype.DatatypeConfigurationException;
+import javax.xml.datatype.DatatypeConstants;
+import javax.xml.datatype.DatatypeFactory;
+import javax.xml.datatype.Duration;
+import javax.xml.datatype.XMLGregorianCalendar;
+
+// This is nolonger in the services/javax.xml.datatype.DatatypeFactory file.
+/**
+ * <p>Factory that creates new <code>javax.xml.datatype</code> <code>Object</code>s that map XML to/from Java <code>Object</code>s.</p>
+ * 
+ * <p id="DatatypeFactory.newInstance">{@link #newInstance()} is used to create a new <code>DatatypeFactory</code>.
+ * The following implementation resolution mechanisms are used in the following order:</p>
+ * <ol>
+ *    <li>
+ *      If the system property specified by {@link #DATATYPEFACTORY_PROPERTY}, "<code>javax.xml.datatype.DatatypeFactory</code>",
+ *      exists, a class with the name of the property's value is instantiated.
+ *      Any Exception thrown during the instantiation process is wrapped as a {@link DatatypeConfigurationException}.
+ *    </li>
+ *    <li>
+ *      If the file ${JAVA_HOME}/lib/jaxp.properties exists, it is loaded in a {@link java.util.Properties} <code>Object</code>.
+ *      The <code>Properties</code> <code>Object </code> is then queried for the property as documented in the prior step
+ *      and processed as documented in the prior step.
+ *    </li>
+ *    <li>
+ *      The services resolution mechanism is used, e.g. <code>META-INF/services/java.xml.datatype.DatatypeFactory</code>.
+ *      Any Exception thrown during the instantiation process is wrapped as a {@link DatatypeConfigurationException}.
+ *    </li>
+ *    <li>
+ *      The final mechanism is to attempt to instantiate the <code>Class</code> specified by
+ *      {@link #DATATYPEFACTORY_IMPLEMENTATION_CLASS}, "<code>javax.xml.datatype.DatatypeFactoryImpl</code>".
+ *      Any Exception thrown during the instantiation process is wrapped as a {@link DatatypeConfigurationException}.
+ *    </li>
+ * </ol> 
+ * 
+ * @author <a href="mailto:Joseph.Fialli@Sun.COM">Joseph Fialli</a>
+ * @author <a href="mailto:Jeff.Suttor@Sun.com">Jeff Suttor</a>
+ * @version $Id: DatatypeFactoryImpl.java 554381 2007-07-08 16:03:48Z mrglavas $
+ */
+@SuppressWarnings("all")
+public class DatatypeFactoryImpl extends DatatypeFactory {
+
+    /**
+     * <p>Public constructor is empty..</p>
+     * 
+     * <p>Use {@link DatatypeFactory#newInstance()} to create a <code>DatatypeFactory</code>.</p>
+     */
+    public DatatypeFactoryImpl() {}
+
+    /**
+     * <p>Obtain a new instance of a <code>Duration</code>
+     * specifying the <code>Duration</code> as its string representation, "PnYnMnDTnHnMnS",
+     * as defined in XML Schema 1.0 section 3.2.6.1.</p>
+     * 
+     * <p>XML Schema Part 2: Datatypes, 3.2.6 duration, defines <code>duration</code> as:</p>
+     * <blockquote>
+     * duration represents a duration of time.
+     * The value space of duration is a six-dimensional space where the coordinates designate the
+     * Gregorian year, month, day, hour, minute, and second components defined in Section 5.5.3.2 of [ISO 8601], respectively.
+     * These components are ordered in their significance by their order of appearance i.e. as
+     * year, month, day, hour, minute, and second. 
+     * </blockquote>
+     * <p>All six values are set and availabe from the created {@link Duration}</p>
+     * 
+     * <p>The XML Schema specification states that values can be of an arbitrary size.
+     * Implementations may chose not to or be incapable of supporting arbitrarily large and/or small values.
+     * An {@link UnsupportedOperationException} will be thrown with a message indicating implementation limits
+     * if implementation capacities are exceeded.</p>
+     * 
+     * @param lexicalRepresentation <code>String</code> representation of a <code>Duration</code>.
+     * 
+     * @return New <code>Duration</code> created from parsing the <code>lexicalRepresentation</code>.
+     * 
+     * @throws IllegalArgumentException If <code>lexicalRepresentation</code> is not a valid representation of a <code>Duration</code>.
+     * @throws UnsupportedOperationException If implementation cannot support requested values.
+     * @throws NullPointerException if <code>lexicalRepresentation</code> is <code>null</code>.
+     */
+    public Duration newDuration(final String lexicalRepresentation) {
+
+        return new DurationImpl(lexicalRepresentation);
+    }
+
+    /**
+     * <p>Obtain a new instance of a <code>Duration</code>
+     * specifying the <code>Duration</code> as milliseconds.</p>
+     * 
+     * <p>XML Schema Part 2: Datatypes, 3.2.6 duration, defines <code>duration</code> as:</p>
+     * <blockquote>
+     * duration represents a duration of time.
+     * The value space of duration is a six-dimensional space where the coordinates designate the
+     * Gregorian year, month, day, hour, minute, and second components defined in Section 5.5.3.2 of [ISO 8601], respectively.
+     * These components are ordered in their significance by their order of appearance i.e. as
+     * year, month, day, hour, minute, and second. 
+     * </blockquote>
+     * <p>All six values are set by computing their values from the specified milliseconds
+     * and are availabe using the <code>get</code> methods of  the created {@link Duration}.
+     * The values conform to and are defined by:</p>
+     * <ul>
+     *   <li>ISO 8601:2000(E) Section 5.5.3.2 Alternative format</li>
+     *   <li><a href="http://www.w3.org/TR/xmlschema-2/#isoformats">
+     *     W3C XML Schema 1.0 Part 2, Appendix D, ISO 8601 Date and Time Formats</a>
+     *   </li>
+     *   <li>{@link XMLGregorianCalendar}  Date/Time Datatype Field Mapping Between XML Schema 1.0 and Java Representation</li>
+     * </ul>
+     * 
+     * <p>The default start instance is defined by {@link GregorianCalendar}'s use of the start of the epoch: i.e.,
+     * {@link java.util.Calendar#YEAR} = 1970,
+     * {@link java.util.Calendar#MONTH} = {@link java.util.Calendar#JANUARY},
+     * {@link java.util.Calendar#DATE} = 1, etc.
+     * This is important as there are variations in the Gregorian Calendar,
+     * e.g. leap years have different days in the month = {@link java.util.Calendar#FEBRUARY}
+     * so the result of {@link Duration#getMonths()} and {@link Duration#getDays()} can be influenced.</p> 
+     * 
+     * @param durationInMilliseconds Duration in milliseconds to create.
+     * 
+     * @return New <code>Duration</code> representing <code>durationInMilliseconds</code>.
+     */
+    public Duration newDuration(final long durationInMilliseconds) {
+
+        return new DurationImpl(durationInMilliseconds);
+    }
+
+    /**
+     * <p>Obtain a new instance of a <code>Duration</code>
+     * specifying the <code>Duration</code> as isPositive, years, months, days, hours, minutes, seconds.</p>
+     * 
+     * <p>The XML Schema specification states that values can be of an arbitrary size.
+     * Implementations may chose not to or be incapable of supporting arbitrarily large and/or small values.
+     * An {@link UnsupportedOperationException} will be thrown with a message indicating implementation limits
+     * if implementation capacities are exceeded.</p>
+     * 
+     * @param isPositive Set to <code>false</code> to create a negative duration. When the length
+     *   of the duration is zero, this parameter will be ignored.
+     * @param years of this <code>Duration</code>
+     * @param months of this <code>Duration</code>
+     * @param days of this <code>Duration</code>
+     * @param hours of this <code>Duration</code>
+     * @param minutes of this <code>Duration</code>
+     * @param seconds of this <code>Duration</code>
+     * 
+     * @return New <code>Duration</code> created from the specified values.
+     * 
+     * @throws IllegalArgumentException If values are not a valid representation of a <code>Duration</code>.
+     * @throws UnsupportedOperationException If implementation cannot support requested values.
+     * @throws NullPointerException If any values are <code>null</code>.
+     * 
+     * @see #newDuration(boolean isPositive, BigInteger years, BigInteger months, BigInteger days,
+     *   BigInteger hours, BigInteger minutes, BigDecimal seconds)
+     */
+    public Duration newDuration(
+            final boolean isPositive,
+            final BigInteger years,
+            final BigInteger months,
+            final BigInteger days,
+            final BigInteger hours,
+            final BigInteger minutes,
+            final BigDecimal seconds) {
+
+        return new DurationImpl(
+                isPositive,
+                years,
+                months,
+                days,
+                hours,
+                minutes,
+                seconds
+        );
+    }
+
+    /**
+     * <p>Create a new instance of an <code>XMLGregorianCalendar</code>.</p>
+     * 
+     * <p>All date/time datatype fields set to {@link DatatypeConstants#FIELD_UNDEFINED} or null.</p>
+     * 
+     * @return New <code>XMLGregorianCalendar</code> with all date/time datatype fields set to
+     *   {@link DatatypeConstants#FIELD_UNDEFINED} or null.
+     */
+    public XMLGregorianCalendar newXMLGregorianCalendar() {
+
+        return new XMLGregorianCalendarImpl();
+    }
+
+    /**
+     * <p>Create a new XMLGregorianCalendar by parsing the String as a lexical representation.</p>
+     * 
+     * <p>Parsing the lexical string representation is defined in 
+     * <a href="http://www.w3.org/TR/xmlschema-2/#dateTime-order">XML Schema 1.0 Part 2, Section 3.2.[7-14].1,
+     * <em>Lexical Representation</em>.</a></p>
+     * 
+     * <p>The string representation may not have any leading and trailing whitespaces.</p>
+     * 
+     * <p>The parsing is done field by field so that
+     * the following holds for any lexically correct String x:</p>
+     * <pre>
+     * newXMLGregorianCalendar(x).toXMLFormat().equals(x)
+     * </pre>
+     * <p>Except for the noted lexical/canonical representation mismatches
+     * listed in <a href="http://www.w3.org/2001/05/xmlschema-errata#e2-45">
+     * XML Schema 1.0 errata, Section 3.2.7.2</a>.</p>
+     * 
+     * @param lexicalRepresentation Lexical representation of one the eight XML Schema date/time datatypes.
+     * 
+     * @return <code>XMLGregorianCalendar</code> created from the <code>lexicalRepresentation</code>.
+     * 
+     * @throws IllegalArgumentException If the <code>lexicalRepresentation</code> is not a valid <code>XMLGregorianCalendar</code>.
+     * @throws NullPointerException If <code>lexicalRepresentation</code> is <code>null</code>.
+     */
+    public XMLGregorianCalendar newXMLGregorianCalendar(final String lexicalRepresentation) {
+
+        return new XMLGregorianCalendarImpl(lexicalRepresentation);
+    }
+
+    /**
+     * <p>Create an <code>XMLGregorianCalendar</code> from a {@link GregorianCalendar}.</p> 
+     *
+     * <table border="2" rules="all" cellpadding="2">
+     *   <thead>
+     *     <tr>
+     *       <th align="center" colspan="2">
+     *          Field by Field Conversion from
+     *          {@link GregorianCalendar} to an {@link XMLGregorianCalendar} 
+     *       </th>
+     *     </tr>
+     *     <tr>
+     *        <th><code>java.util.GregorianCalendar</code> field</th>
+     *        <th><code>javax.xml.datatype.XMLGregorianCalendar</code> field</th>
+     *     </tr>
+     *   </thead>
+     *   <tbody>
+     *     <tr>
+     *       <td><code>ERA == GregorianCalendar.BC ? -YEAR : YEAR</code></td>
+     *       <td>{@link XMLGregorianCalendar#setYear(int year)}</td>
+     *     </tr>
+     *     <tr>
+     *       <td><code>MONTH + 1</code></td>
+     *       <td>{@link XMLGregorianCalendar#setMonth(int month)}</td>
+     *     </tr>
+     *     <tr>
+     *       <td><code>DAY_OF_MONTH</code></td>
+     *       <td>{@link XMLGregorianCalendar#setDay(int day)}</td>
+     *     </tr>
+     *     <tr>
+     *       <td><code>HOUR_OF_DAY, MINUTE, SECOND, MILLISECOND</code></td>
+     *       <td>{@link XMLGregorianCalendar#setTime(int hour, int minute, int second, BigDecimal fractional)}</td>
+     *     </tr>
+     *     <tr>
+     *       <td>
+     *         <code>(ZONE_OFFSET + DST_OFFSET) / (60*1000)</code><br/>
+     *         <em>(in minutes)</em>
+     *       </td>
+     *       <td>{@link XMLGregorianCalendar#setTimezone(int offset)}<sup><em>*</em></sup>
+     *       </td>
+     *     </tr>
+     *   </tbody>
+     * </table>
+     * <p><em>*</em>conversion loss of information. It is not possible to represent 
+     * a <code>java.util.GregorianCalendar</code> daylight savings timezone id in the 
+     * XML Schema 1.0 date/time datatype representation.</p>
+     * 
+     * <p>To compute the return value's <code>TimeZone</code> field,
+     * <ul>
+     * <li>when <code>this.getTimezone() != FIELD_UNDEFINED</code>,
+     * create a <code>java.util.TimeZone</code> with a custom timezone id 
+     * using the <code>this.getTimezone()</code>.</li>
+     * <li>else use the <code>GregorianCalendar</code> default timezone value 
+     * for the host is defined as specified by 
+     * <code>java.util.TimeZone.getDefault()</code>.</li></p>     
+     *
+     * @param cal <code>java.util.GregorianCalendar</code> used to create <code>XMLGregorianCalendar</code>
+     * 
+     * @return <code>XMLGregorianCalendar</code> created from <code>java.util.GregorianCalendar</code>
+     *  
+     * @throws NullPointerException If <code>cal</code> is <code>null</code>.
+     */
+    public XMLGregorianCalendar newXMLGregorianCalendar(final GregorianCalendar cal) {
+
+        return new XMLGregorianCalendarImpl(cal);
+    }
+
+    /**
+     * <p>Constructor of value spaces that a
+     * <code>java.util.GregorianCalendar</code> instance would need to convert to an
+     * <code>XMLGregorianCalendar</code> instance.</p>
+     *    
+     * <p><code>XMLGregorianCalendar eon</code> and 
+     * <code>fractionalSecond</code> are set to <code>null</code></p>
+     *
+     * <p>A {@link DatatypeConstants#FIELD_UNDEFINED} value indicates that field isnot set.</p>
+     * 
+     * @param year of <code>XMLGregorianCalendar</code> to be created.
+     * @param month of <code>XMLGregorianCalendar</code> to be created.
+     * @param day of <code>XMLGregorianCalendar</code> to be created.
+     * @param hour of <code>XMLGregorianCalendar</code> to be created.
+     * @param minute of <code>XMLGregorianCalendar</code> to be created.
+     * @param second of <code>XMLGregorianCalendar</code> to be created.
+     * @param millisecond of <code>XMLGregorianCalendar</code> to be created.
+     * @param timezone of <code>XMLGregorianCalendar</code> to be created.
+     * 
+     * @return <code>XMLGregorianCalendar</code> created from specified values.
+     * 
+     * @throws IllegalArgumentException If any individual parameter's value is outside the maximum value constraint for the field
+     *   as determined by the Date/Time Data Mapping table in {@link XMLGregorianCalendar}
+     *   or if the composite values constitute an invalid <code>XMLGregorianCalendar</code> instance
+     *   as determined by {@link XMLGregorianCalendar#isValid()}.
+     */
+    public XMLGregorianCalendar newXMLGregorianCalendar(
+            final int year,
+            final int month,
+            final int day,
+            final int hour,
+            final int minute,
+            final int second,
+            final int millisecond,
+            final int timezone) {
+        return XMLGregorianCalendarImpl.createDateTime(
+                year, 
+                month, 
+                day, 
+                hour, 
+                minute, 
+                second, 
+                millisecond, 
+                timezone);
+    }
+
+    /**
+     * <p>Constructor allowing for complete value spaces allowed by 
+     * W3C XML Schema 1.0 recommendation for xsd:dateTime and related 
+     * builtin datatypes. Note that <code>year</code> parameter supports
+     * arbitrarily large numbers and fractionalSecond has infinite 
+     * precision.</p>
+     * 
+     * @param year of <code>XMLGregorianCalendar</code> to be created.
+     * @param month of <code>XMLGregorianCalendar</code> to be created.
+     * @param day of <code>XMLGregorianCalendar</code> to be created.
+     * @param hour of <code>XMLGregorianCalendar</code> to be created.
+     * @param minute of <code>XMLGregorianCalendar</code> to be created.
+     * @param second of <code>XMLGregorianCalendar</code> to be created.
+     * @param fractionalSecond of <code>XMLGregorianCalendar</code> to be created.
+     * @param timezone of <code>XMLGregorianCalendar</code> to be created.
+     * 
+     * @return <code>XMLGregorianCalendar</code> created from specified values.
+     * 
+     * @throws IllegalArgumentException If any individual parameter's value is outside the maximum value constraint for the field
+     *   as determined by the Date/Time Data Mapping table in {@link XMLGregorianCalendar}
+     *   or if the composite values constitute an invalid <code>XMLGregorianCalendar</code> instance
+     *   as determined by {@link XMLGregorianCalendar#isValid()}.
+     * @throws NullPointerException If any parameters are <code>null</code>.
+     * 
+     */
+    public XMLGregorianCalendar newXMLGregorianCalendar(
+            final BigInteger year,
+            final int month,
+            final int day,
+            final int hour,
+            final int minute,
+            final int second,
+            final BigDecimal fractionalSecond,
+            final int timezone) {
+
+        return new XMLGregorianCalendarImpl(
+                year,
+                month,
+                day,
+                hour,
+                minute,
+                second,
+                fractionalSecond,
+                timezone
+        );
+    }
+}


[17/24] jena git commit: JENA-1537: Remove dependency on Xerces. Import needed code

Posted by an...@apache.org.
http://git-wip-us.apache.org/repos/asf/jena/blob/c9a7e646/jena-core/src/main/java/org/apache/jena/ext/xerces/impl/dv/xs/XSSimpleTypeDecl.java
----------------------------------------------------------------------
diff --git a/jena-core/src/main/java/org/apache/jena/ext/xerces/impl/dv/xs/XSSimpleTypeDecl.java b/jena-core/src/main/java/org/apache/jena/ext/xerces/impl/dv/xs/XSSimpleTypeDecl.java
new file mode 100644
index 0000000..512449d
--- /dev/null
+++ b/jena-core/src/main/java/org/apache/jena/ext/xerces/impl/dv/xs/XSSimpleTypeDecl.java
@@ -0,0 +1,3562 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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.jena.ext.xerces.impl.dv.xs;
+
+import java.math.BigInteger;
+import java.util.AbstractList;
+import java.util.Locale;
+import java.util.StringTokenizer;
+import java.util.Vector;
+
+import org.apache.jena.ext.xerces.impl.Constants;
+import org.apache.jena.ext.xerces.impl.dv.*;
+import org.apache.jena.ext.xerces.impl.xpath.regex.RegularExpression;
+import org.apache.jena.ext.xerces.impl.xs.SchemaSymbols;
+import org.apache.jena.ext.xerces.impl.xs.util.ObjectListImpl;
+import org.apache.jena.ext.xerces.impl.xs.util.ShortListImpl;
+import org.apache.jena.ext.xerces.impl.xs.util.StringListImpl;
+import org.apache.jena.ext.xerces.impl.xs.util.XSObjectListImpl;
+import org.apache.jena.ext.xerces.util.XMLChar;
+import org.apache.jena.ext.xerces.xni.NamespaceContext;
+import org.apache.jena.ext.xerces.xs.*;
+import org.apache.jena.ext.xerces.xs.datatypes.ObjectList;
+import org.w3c.dom.TypeInfo;
+
+/**
+ * @xerces.internal
+ *  
+ * @author Sandy Gao, IBM
+ * @author Neeraj Bajaj, Sun Microsystems, inc.
+ *
+ * @version $Id: XSSimpleTypeDecl.java 1026362 2010-10-22 15:15:18Z sandygao $
+ */
+@SuppressWarnings("all")
+public class XSSimpleTypeDecl implements XSSimpleType, TypeInfo {
+
+    protected static final short DV_STRING        = PRIMITIVE_STRING;
+    protected static final short DV_BOOLEAN       = PRIMITIVE_BOOLEAN;
+    protected static final short DV_DECIMAL       = PRIMITIVE_DECIMAL;
+    protected static final short DV_FLOAT         = PRIMITIVE_FLOAT;
+    protected static final short DV_DOUBLE        = PRIMITIVE_DOUBLE;
+    protected static final short DV_DURATION      = PRIMITIVE_DURATION;
+    protected static final short DV_DATETIME      = PRIMITIVE_DATETIME;
+    protected static final short DV_TIME          = PRIMITIVE_TIME;
+    protected static final short DV_DATE          = PRIMITIVE_DATE;
+    protected static final short DV_GYEARMONTH    = PRIMITIVE_GYEARMONTH;
+    protected static final short DV_GYEAR         = PRIMITIVE_GYEAR;
+    protected static final short DV_GMONTHDAY     = PRIMITIVE_GMONTHDAY;
+    protected static final short DV_GDAY          = PRIMITIVE_GDAY;
+    protected static final short DV_GMONTH        = PRIMITIVE_GMONTH;
+    protected static final short DV_HEXBINARY     = PRIMITIVE_HEXBINARY;
+    protected static final short DV_BASE64BINARY  = PRIMITIVE_BASE64BINARY;
+    protected static final short DV_ANYURI        = PRIMITIVE_ANYURI;
+    protected static final short DV_QNAME         = PRIMITIVE_QNAME;
+    protected static final short DV_PRECISIONDECIMAL = PRIMITIVE_PRECISIONDECIMAL;
+    protected static final short DV_NOTATION      = PRIMITIVE_NOTATION;
+
+    protected static final short DV_ANYSIMPLETYPE = 0;
+    protected static final short DV_ID            = DV_NOTATION + 1;
+    protected static final short DV_IDREF         = DV_NOTATION + 2;
+    protected static final short DV_ENTITY        = DV_NOTATION + 3;
+    protected static final short DV_INTEGER       = DV_NOTATION + 4;
+    protected static final short DV_LIST          = DV_NOTATION + 5;
+    protected static final short DV_UNION         = DV_NOTATION + 6;
+    protected static final short DV_YEARMONTHDURATION = DV_NOTATION + 7;
+    protected static final short DV_DAYTIMEDURATION	= DV_NOTATION + 8;
+    protected static final short DV_ANYATOMICTYPE = DV_NOTATION + 9;
+
+    private static final TypeValidator[] gDVs = {
+        new AnySimpleDV(),
+        new StringDV(),
+        new BooleanDV(),
+        new DecimalDV(),
+        new FloatDV(),
+        new DoubleDV(),
+        new DurationDV(),
+        new DateTimeDV(),
+        new TimeDV(),
+        new DateDV(),
+        new YearMonthDV(),
+        new YearDV(),
+        new MonthDayDV(),
+        new DayDV(),
+        new MonthDV(),
+        new HexBinaryDV(),
+        new Base64BinaryDV(),
+        new AnyURIDV(),
+        null, //new QNameDV(), // QName datatype not supported (or relevant) to RDF / Apache Jena.
+        new PrecisionDecimalDV(), // XML Schema 1.1 type
+        null, //new QNameDV(),   // notation use the same one as qname
+        new IDDV(),
+        new IDREFDV(),
+        new EntityDV(),
+        new IntegerDV(),
+        new ListDV(),
+        new UnionDV(),
+        new YearMonthDurationDV(), // XML Schema 1.1 type
+        new DayTimeDurationDV(), // XML Schema 1.1 type
+        new AnyAtomicDV() // XML Schema 1.1 type
+    };
+
+    static final short NORMALIZE_NONE = 0;
+    static final short NORMALIZE_TRIM = 1;
+    static final short NORMALIZE_FULL = 2;
+    static final short[] fDVNormalizeType = {
+        NORMALIZE_NONE, //AnySimpleDV(),
+        NORMALIZE_FULL, //StringDV(),
+        NORMALIZE_TRIM, //BooleanDV(),
+        NORMALIZE_TRIM, //DecimalDV(),
+        NORMALIZE_TRIM, //FloatDV(),
+        NORMALIZE_TRIM, //DoubleDV(),
+        NORMALIZE_TRIM, //DurationDV(),
+        NORMALIZE_TRIM, //DateTimeDV(),
+        NORMALIZE_TRIM, //TimeDV(),
+        NORMALIZE_TRIM, //DateDV(),
+        NORMALIZE_TRIM, //YearMonthDV(),
+        NORMALIZE_TRIM, //YearDV(),
+        NORMALIZE_TRIM, //MonthDayDV(),
+        NORMALIZE_TRIM, //DayDV(),
+        NORMALIZE_TRIM, //MonthDV(),
+        NORMALIZE_TRIM, //HexBinaryDV(),
+        NORMALIZE_NONE, //Base64BinaryDV(),  // Base64 know how to deal with spaces
+        NORMALIZE_TRIM, //AnyURIDV(),
+        NORMALIZE_TRIM, //QNameDV(),
+        NORMALIZE_TRIM, //PrecisionDecimalDV() (Schema 1.1)
+        NORMALIZE_TRIM, //QNameDV(),   // notation
+        NORMALIZE_TRIM, //IDDV(),
+        NORMALIZE_TRIM, //IDREFDV(),
+        NORMALIZE_TRIM, //EntityDV(),
+        NORMALIZE_TRIM, //IntegerDV(),
+        NORMALIZE_FULL, //ListDV(),
+        NORMALIZE_NONE, //UnionDV(),
+        NORMALIZE_TRIM, //YearMonthDurationDV() (Schema 1.1)
+        NORMALIZE_TRIM, //DayTimeDurationDV() (Schema 1.1)
+        NORMALIZE_NONE, //AnyAtomicDV() (Schema 1.1)
+    };
+
+    static final short SPECIAL_PATTERN_NONE     = 0;
+    static final short SPECIAL_PATTERN_NMTOKEN  = 1;
+    static final short SPECIAL_PATTERN_NAME     = 2;
+    static final short SPECIAL_PATTERN_NCNAME   = 3;
+
+    static final String[] SPECIAL_PATTERN_STRING   = {
+        "NONE", "NMTOKEN", "Name", "NCName"
+    };
+
+    static final String[] WS_FACET_STRING = {
+        "preserve", "replace", "collapse"
+    };
+
+    static final String URI_SCHEMAFORSCHEMA = "http://www.w3.org/2001/XMLSchema";
+    static final String ANY_TYPE = "anyType";
+
+    // XML Schema 1.1 type constants
+    public static final short YEARMONTHDURATION_DT      = 46;
+    public static final short DAYTIMEDURATION_DT        = 47;   
+    public static final short PRECISIONDECIMAL_DT       = 48;
+    public static final short ANYATOMICTYPE_DT          = 49;
+
+    // DOM Level 3 TypeInfo Derivation Method constants
+    static final int DERIVATION_ANY = 0;
+    static final int DERIVATION_RESTRICTION = 1;
+    static final int DERIVATION_EXTENSION = 2;
+    static final int DERIVATION_UNION = 4;
+    static final int DERIVATION_LIST = 8;
+
+    static final ValidationContext fEmptyContext = new ValidationContext() {
+        @Override
+        public boolean needFacetChecking() {
+            return true;
+        }
+        @Override
+        public boolean needExtraChecking() {
+            return false;
+        }
+        @Override
+        public boolean needToNormalize() {
+            return true;
+        }
+        @Override
+        public boolean useNamespaces () {
+            return true;
+        }
+        @Override
+        public boolean isEntityDeclared (String name) {
+            return false;
+        }
+        @Override
+        public boolean isEntityUnparsed (String name) {
+            return false;
+        }
+        @Override
+        public boolean isIdDeclared (String name) {
+            return false;
+        }
+        @Override
+        public void addId(String name) {
+        }
+        @Override
+        public void addIdRef(String name) {
+        }
+        @Override
+        public String getSymbol (String symbol) {
+            return symbol.intern();
+        }
+        @Override
+        public String getURI(String prefix) {
+            return null;
+        }
+        @Override
+        public Locale getLocale() {
+            return Locale.getDefault();
+        }
+    };
+
+    protected static TypeValidator[] getGDVs() {
+        return gDVs.clone();
+    }
+    private TypeValidator[] fDVs = gDVs;
+    protected void setDVs(TypeValidator[] dvs) {
+        fDVs = dvs;
+    }
+    
+    // this will be true if this is a static XSSimpleTypeDecl
+    // and hence must remain immutable (i.e., applyFacets
+    // may not be permitted to have any effect).
+    private boolean fIsImmutable = false;
+
+    private XSSimpleTypeDecl fItemType;
+    private XSSimpleTypeDecl[] fMemberTypes;
+    // The most specific built-in type kind.
+    private short fBuiltInKind;
+
+    private String fTypeName;
+    private String fTargetNamespace;
+    private short fFinalSet = 0;
+    private XSSimpleTypeDecl fBase;
+    private short fVariety = -1;
+    private short fValidationDV = -1;
+
+    private short fFacetsDefined = 0;
+    private short fFixedFacet = 0;
+
+    //for constraining facets
+    private short fWhiteSpace = 0;
+    private int fLength = -1;
+    private int fMinLength = -1;
+    private int fMaxLength = -1;
+    private int fTotalDigits = -1;
+    private int fFractionDigits = -1;
+    private Vector fPattern;
+    private Vector fPatternStr;
+    private ValidatedInfo[] fEnumeration;
+    private int fEnumerationSize;
+    private ShortList fEnumerationTypeList;
+    private ObjectList fEnumerationItemTypeList;
+    private StringList fLexicalPattern;
+    private StringList fLexicalEnumeration;
+    private ObjectList fActualEnumeration;
+    private Object fMaxInclusive;
+    private Object fMaxExclusive;
+    private Object fMinExclusive;
+    private Object fMinInclusive;
+
+    // annotations for constraining facets
+    public XSAnnotation lengthAnnotation;
+    public XSAnnotation minLengthAnnotation;
+    public XSAnnotation maxLengthAnnotation;
+    public XSAnnotation whiteSpaceAnnotation;
+    public XSAnnotation totalDigitsAnnotation;
+    public XSAnnotation fractionDigitsAnnotation;
+    public XSObjectListImpl patternAnnotations;
+    public XSObjectList enumerationAnnotations;
+    public XSAnnotation maxInclusiveAnnotation;
+    public XSAnnotation maxExclusiveAnnotation;
+    public XSAnnotation minInclusiveAnnotation;
+    public XSAnnotation minExclusiveAnnotation;
+
+    // facets as objects
+    private XSObjectListImpl fFacets;
+
+    // enumeration and pattern facets
+    private XSObjectListImpl fMultiValueFacets;
+
+    // simpleType annotations
+    private XSObjectList fAnnotations = null;
+
+    private short fPatternType = SPECIAL_PATTERN_NONE;
+
+    // for fundamental facets
+    private short fOrdered;
+    private boolean fFinite;
+    private boolean fBounded;
+    private boolean fNumeric;
+    
+    // The namespace schema information item corresponding to the target namespace 
+    // of the simple type definition, if it is globally declared; or null otherwise.
+    private XSNamespaceItem fNamespaceItem = null;
+
+    // default constructor
+    public XSSimpleTypeDecl(){}
+
+    //Create a new built-in primitive types (and id/idref/entity/integer/yearMonthDuration)
+    protected XSSimpleTypeDecl(XSSimpleTypeDecl base, String name, short validateDV,
+            short ordered, boolean bounded, boolean finite,
+            boolean numeric, boolean isImmutable, short builtInKind) {
+        fIsImmutable = isImmutable;
+        fBase = base;
+        fTypeName = name;
+        fTargetNamespace = URI_SCHEMAFORSCHEMA;
+        // To simplify the code for anySimpleType, we treat it as an atomic type
+        fVariety = VARIETY_ATOMIC;
+        fValidationDV = validateDV;
+        fFacetsDefined = FACET_WHITESPACE;
+        if (validateDV == DV_ANYSIMPLETYPE ||
+            validateDV == DV_ANYATOMICTYPE ||
+            validateDV == DV_STRING) {
+            fWhiteSpace = WS_PRESERVE;
+        } 
+        else {
+            fWhiteSpace = WS_COLLAPSE;
+            fFixedFacet = FACET_WHITESPACE;
+        }
+        this.fOrdered = ordered;
+        this.fBounded = bounded;
+        this.fFinite = finite;
+        this.fNumeric = numeric;
+        fAnnotations = null;
+
+        // Specify the build in kind for this primitive type
+        fBuiltInKind = builtInKind;
+    }
+
+    //Create a new simple type for restriction for built-in types
+    protected XSSimpleTypeDecl(XSSimpleTypeDecl base, String name, String uri, short finalSet, boolean isImmutable,
+            XSObjectList annotations, short builtInKind) {
+        this(base, name, uri, finalSet, isImmutable, annotations);
+        // Specify the build in kind for this built-in type
+        fBuiltInKind = builtInKind;
+    }
+
+    //Create a new simple type for restriction.
+    protected XSSimpleTypeDecl(XSSimpleTypeDecl base, String name, String uri, short finalSet, boolean isImmutable,
+            XSObjectList annotations) {
+        fBase = base;
+        fTypeName = name;
+        fTargetNamespace = uri;
+        fFinalSet = finalSet;
+        fAnnotations = annotations;
+
+        fVariety = fBase.fVariety;
+        fValidationDV = fBase.fValidationDV;
+        switch (fVariety) {
+            case VARIETY_ATOMIC:
+                break;
+            case VARIETY_LIST:
+                fItemType = fBase.fItemType;
+                break;
+            case VARIETY_UNION:
+                fMemberTypes = fBase.fMemberTypes;
+                break;
+        }
+
+        // always inherit facets from the base.
+        // in case a type is created, but applyFacets is not called
+        fLength = fBase.fLength;
+        fMinLength = fBase.fMinLength;
+        fMaxLength = fBase.fMaxLength;
+        fPattern = fBase.fPattern;
+        fPatternStr = fBase.fPatternStr;
+        fEnumeration = fBase.fEnumeration;
+        fEnumerationSize = fBase.fEnumerationSize;
+        fWhiteSpace = fBase.fWhiteSpace;
+        fMaxExclusive = fBase.fMaxExclusive;
+        fMaxInclusive = fBase.fMaxInclusive;
+        fMinExclusive = fBase.fMinExclusive;
+        fMinInclusive = fBase.fMinInclusive;
+        fTotalDigits = fBase.fTotalDigits;
+        fFractionDigits = fBase.fFractionDigits;
+        fPatternType = fBase.fPatternType;
+        fFixedFacet = fBase.fFixedFacet;
+        fFacetsDefined = fBase.fFacetsDefined;
+
+        // always inherit facet annotations in case applyFacets is not called.
+        lengthAnnotation = fBase.lengthAnnotation;
+        minLengthAnnotation = fBase.minLengthAnnotation;
+        maxLengthAnnotation = fBase.maxLengthAnnotation;
+        patternAnnotations = fBase.patternAnnotations;
+        enumerationAnnotations = fBase.enumerationAnnotations;
+        whiteSpaceAnnotation = fBase.whiteSpaceAnnotation;
+        maxExclusiveAnnotation = fBase.maxExclusiveAnnotation;
+        maxInclusiveAnnotation = fBase.maxInclusiveAnnotation;
+        minExclusiveAnnotation = fBase.minExclusiveAnnotation;
+        minInclusiveAnnotation = fBase.minInclusiveAnnotation;
+        totalDigitsAnnotation = fBase.totalDigitsAnnotation;
+        fractionDigitsAnnotation = fBase.fractionDigitsAnnotation;
+
+        //we also set fundamental facets information in case applyFacets is not called.
+        calcFundamentalFacets();
+        fIsImmutable = isImmutable;
+
+        // Inherit from the base type
+        fBuiltInKind = base.fBuiltInKind;
+    }
+
+    //Create a new simple type for list.
+    protected XSSimpleTypeDecl(String name, String uri, short finalSet, XSSimpleTypeDecl itemType, boolean isImmutable,
+            XSObjectList annotations) {
+        fBase = fAnySimpleType;
+        fTypeName = name;
+        fTargetNamespace = uri;
+        fFinalSet = finalSet;
+        fAnnotations = annotations;
+
+        fVariety = VARIETY_LIST;
+        fItemType = itemType;
+        fValidationDV = DV_LIST;
+        fFacetsDefined = FACET_WHITESPACE;
+        fFixedFacet = FACET_WHITESPACE;
+        fWhiteSpace = WS_COLLAPSE;
+
+        //setting fundamental facets
+        calcFundamentalFacets();
+        fIsImmutable = isImmutable;
+
+        // Values of this type are lists
+        fBuiltInKind = XSConstants.LIST_DT;
+    }
+
+    //Create a new simple type for union.
+    protected XSSimpleTypeDecl(String name, String uri, short finalSet, XSSimpleTypeDecl[] memberTypes,
+            XSObjectList annotations) {
+        fBase = fAnySimpleType;
+        fTypeName = name;
+        fTargetNamespace = uri;
+        fFinalSet = finalSet;
+        fAnnotations = annotations;
+
+        fVariety = VARIETY_UNION;
+        fMemberTypes = memberTypes;
+        fValidationDV = DV_UNION;
+        // even for union, we set whitespace to something
+        // this will never be used, but we can use fFacetsDefined to check
+        // whether applyFacets() is allwwed: it's not allowed
+        // if fFacetsDefined != 0
+        fFacetsDefined = FACET_WHITESPACE;
+        fWhiteSpace = WS_COLLAPSE;
+
+        //setting fundamental facets
+        calcFundamentalFacets();
+        // none of the schema-defined types are unions, so just set
+        // fIsImmutable to false.
+        fIsImmutable = false;
+
+        // No value can be of this type, so it's unavailable.
+        fBuiltInKind = XSConstants.UNAVAILABLE_DT;
+    }
+
+    //set values for restriction.
+    protected XSSimpleTypeDecl setRestrictionValues(XSSimpleTypeDecl base, String name, String uri, short finalSet,
+            XSObjectList annotations) {
+        //decline to do anything if the object is immutable.
+        if(fIsImmutable) return null;
+        fBase = base;
+        fAnonymous = false;
+        fTypeName = name;
+        fTargetNamespace = uri;
+        fFinalSet = finalSet;
+        fAnnotations = annotations;
+
+        fVariety = fBase.fVariety;
+        fValidationDV = fBase.fValidationDV;
+        switch (fVariety) {
+            case VARIETY_ATOMIC:
+                break;
+            case VARIETY_LIST:
+                fItemType = fBase.fItemType;
+                break;
+            case VARIETY_UNION:
+                fMemberTypes = fBase.fMemberTypes;
+                break;
+        }
+
+        // always inherit facets from the base.
+        // in case a type is created, but applyFacets is not called
+        fLength = fBase.fLength;
+        fMinLength = fBase.fMinLength;
+        fMaxLength = fBase.fMaxLength;
+        fPattern = fBase.fPattern;
+        fPatternStr = fBase.fPatternStr;
+        fEnumeration = fBase.fEnumeration;
+        fEnumerationSize = fBase.fEnumerationSize;
+        fWhiteSpace = fBase.fWhiteSpace;
+        fMaxExclusive = fBase.fMaxExclusive;
+        fMaxInclusive = fBase.fMaxInclusive;
+        fMinExclusive = fBase.fMinExclusive;
+        fMinInclusive = fBase.fMinInclusive;
+        fTotalDigits = fBase.fTotalDigits;
+        fFractionDigits = fBase.fFractionDigits;
+        fPatternType = fBase.fPatternType;
+        fFixedFacet = fBase.fFixedFacet;
+        fFacetsDefined = fBase.fFacetsDefined;
+
+        //we also set fundamental facets information in case applyFacets is not called.
+        calcFundamentalFacets();
+
+        // Inherit from the base type
+        fBuiltInKind = base.fBuiltInKind;
+
+        return this;
+    }
+
+    //set values for list.
+    protected XSSimpleTypeDecl setListValues(String name, String uri, short finalSet, XSSimpleTypeDecl itemType,
+            XSObjectList annotations) {
+        //decline to do anything if the object is immutable.
+        if(fIsImmutable) return null;
+        fBase = fAnySimpleType;
+        fAnonymous = false;
+        fTypeName = name;
+        fTargetNamespace = uri;
+        fFinalSet = finalSet;
+        fAnnotations = annotations;
+
+        fVariety = VARIETY_LIST;
+        fItemType = itemType;
+        fValidationDV = DV_LIST;
+        fFacetsDefined = FACET_WHITESPACE;
+        fFixedFacet = FACET_WHITESPACE;
+        fWhiteSpace = WS_COLLAPSE;
+
+        //setting fundamental facets
+        calcFundamentalFacets();
+
+        // Values of this type are lists
+        fBuiltInKind = XSConstants.LIST_DT;
+
+        return this;
+    }
+
+    //set values for union.
+    protected XSSimpleTypeDecl setUnionValues(String name, String uri, short finalSet, XSSimpleTypeDecl[] memberTypes,
+            XSObjectList annotations) {
+        //decline to do anything if the object is immutable.
+        if(fIsImmutable) return null;
+        fBase = fAnySimpleType;
+        fAnonymous = false;
+        fTypeName = name;
+        fTargetNamespace = uri;
+        fFinalSet = finalSet;
+        fAnnotations = annotations;
+
+        fVariety = VARIETY_UNION;
+        fMemberTypes = memberTypes;
+        fValidationDV = DV_UNION;
+        // even for union, we set whitespace to something
+        // this will never be used, but we can use fFacetsDefined to check
+        // whether applyFacets() is allwwed: it's not allowed
+        // if fFacetsDefined != 0
+        fFacetsDefined = FACET_WHITESPACE;
+        fWhiteSpace = WS_COLLAPSE;
+
+        //setting fundamental facets
+        calcFundamentalFacets();
+
+        // No value can be of this type, so it's unavailable.
+        fBuiltInKind = XSConstants.UNAVAILABLE_DT;
+
+        return this;
+    }
+
+    @Override
+    public short getType () {
+        return XSConstants.TYPE_DEFINITION;
+    }
+
+    @Override
+    public short getTypeCategory () {
+        return SIMPLE_TYPE;
+    }
+
+    @Override
+    public String getName() {
+        return getAnonymous()?null:fTypeName;
+    }
+
+    @Override
+    public String getTypeName() {
+        return fTypeName;
+    }
+
+    @Override
+    public String getNamespace() {
+        return fTargetNamespace;
+    }
+
+    @Override
+    public short getFinal(){
+        return fFinalSet;
+    }
+
+    @Override
+    public boolean isFinal(short derivation) {
+        return (fFinalSet & derivation) != 0;
+    }
+
+    @Override
+    public XSTypeDefinition getBaseType(){
+        return fBase;
+    }
+
+    @Override
+    public boolean getAnonymous() {
+        return fAnonymous || (fTypeName == null);
+    }
+
+    @Override
+    public short getVariety(){
+        // for anySimpleType, return absent variaty
+        return fValidationDV == DV_ANYSIMPLETYPE ? VARIETY_ABSENT : fVariety;
+    }
+
+    @Override
+    public boolean isIDType(){
+        switch (fVariety) {
+            case VARIETY_ATOMIC:
+                return fValidationDV == DV_ID;
+            case VARIETY_LIST:
+                return fItemType.isIDType();
+            case VARIETY_UNION:
+                for (int i = 0; i < fMemberTypes.length; i++) {
+                    if (fMemberTypes[i].isIDType())
+                        return true;
+                }
+        }
+        return false;
+    }
+
+    @Override
+    public short getWhitespace() throws DatatypeException{
+        if (fVariety == VARIETY_UNION) {
+            throw new DatatypeException("dt-whitespace", new Object[]{fTypeName});
+        }
+        return fWhiteSpace;
+    }
+
+    @Override
+    public short getPrimitiveKind() {
+        if (fVariety == VARIETY_ATOMIC && fValidationDV != DV_ANYSIMPLETYPE) {
+            if (fValidationDV == DV_ID || fValidationDV == DV_IDREF || fValidationDV == DV_ENTITY) {
+                return DV_STRING;
+            }
+            else if (fValidationDV == DV_INTEGER) {
+                return DV_DECIMAL;
+            }
+            else if (Constants.SCHEMA_1_1_SUPPORT && (fValidationDV == DV_YEARMONTHDURATION || fValidationDV == DV_DAYTIMEDURATION)) {
+                return DV_DURATION;
+            }
+            else {
+                return fValidationDV;
+            }
+        }
+        else {
+            // REVISIT: error situation. runtime exception?
+            return (short)0;
+        }
+    }
+
+    /**
+     * Returns the closest built-in type category this type represents or
+     * derived from. For example, if this simple type is a built-in derived
+     * type integer the <code>INTEGER_DV</code> is returned.
+     */
+    @Override
+    public short getBuiltInKind() {
+        return this.fBuiltInKind;
+    }
+
+    /**
+     * If variety is <code>atomic</code> the primitive type definition (a
+     * built-in primitive datatype definition or the simple ur-type
+     * definition) is available, otherwise <code>null</code>.
+     */
+    @Override
+    public XSSimpleTypeDefinition getPrimitiveType() {
+        if (fVariety == VARIETY_ATOMIC && fValidationDV != DV_ANYSIMPLETYPE) {
+            XSSimpleTypeDecl pri = this;
+            // recursively get base, until we reach anySimpleType
+            while (pri.fBase != fAnySimpleType)
+                pri = pri.fBase;
+            return pri;
+        }
+        else {
+            // REVISIT: error situation. runtime exception?
+            return null;
+        }
+    }
+
+    /**
+     * If variety is <code>list</code> the item type definition (an atomic or
+     * union simple type definition) is available, otherwise
+     * <code>null</code>.
+     */
+    @Override
+    public XSSimpleTypeDefinition getItemType() {
+        if (fVariety == VARIETY_LIST) {
+            return fItemType;
+        }
+        else {
+            // REVISIT: error situation. runtime exception?
+            return null;
+        }
+    }
+
+    /**
+     * If variety is <code>union</code> the list of member type definitions (a
+     * non-empty sequence of simple type definitions) is available,
+     * otherwise an empty <code>XSObjectList</code>.
+     */
+    @Override
+    public XSObjectList getMemberTypes() {
+        if (fVariety == VARIETY_UNION) {
+            return new XSObjectListImpl(fMemberTypes, fMemberTypes.length);
+        }
+        else {
+            return XSObjectListImpl.EMPTY_LIST;
+        }
+    }
+
+    /**
+     * If <restriction> is chosen
+     */
+    @Override
+    public void applyFacets(XSFacets facets, short presentFacet, short fixedFacet, ValidationContext context)
+    throws InvalidDatatypeFacetException {
+        if (context == null) {
+            context = fEmptyContext;
+        }
+        applyFacets(facets, presentFacet, fixedFacet, SPECIAL_PATTERN_NONE, context);
+    }
+
+    /**
+     * built-in derived types by restriction
+     */
+    void applyFacets1(XSFacets facets, short presentFacet, short fixedFacet) {
+
+        try {
+            applyFacets(facets, presentFacet, fixedFacet, SPECIAL_PATTERN_NONE, fDummyContext);
+        } catch (InvalidDatatypeFacetException e) {
+            // should never gets here, internel error
+            throw new RuntimeException("internal error");
+        }
+        // we've now applied facets; so lock this object:
+        fIsImmutable = true;
+    }
+
+    /**
+     * built-in derived types by restriction
+     */
+    void applyFacets1(XSFacets facets, short presentFacet, short fixedFacet, short patternType) {
+
+        try {
+            applyFacets(facets, presentFacet, fixedFacet, patternType, fDummyContext);
+        } catch (InvalidDatatypeFacetException e) {
+            // should never gets here, internel error
+            throw new RuntimeException("internal error");
+        }
+        // we've now applied facets; so lock this object:
+        fIsImmutable = true;
+    }
+
+    /**
+     * If <restriction> is chosen, or built-in derived types by restriction
+     */
+    void applyFacets(XSFacets facets, short presentFacet, short fixedFacet, short patternType, ValidationContext context)
+    throws InvalidDatatypeFacetException {
+
+        // if the object is immutable, should not apply facets...
+        if(fIsImmutable) return;
+        ValidatedInfo tempInfo = new ValidatedInfo();
+
+        // clear facets. because we always inherit facets in the constructor
+        // REVISIT: in fact, we don't need to clear them.
+        // we can convert 5 string values (4 bounds + 1 enum) to actual values,
+        // store them somewhere, then do facet checking at once, instead of
+        // going through the following steps. (lots of checking are redundant:
+        // for example, ((presentFacet & FACET_XXX) != 0))
+
+        fFacetsDefined = 0;
+        fFixedFacet = 0;
+
+        int result = 0 ;
+
+        // step 1: parse present facets
+        short allowedFacet = fDVs[fValidationDV].getAllowedFacets();
+
+        // length
+        if ((presentFacet & FACET_LENGTH) != 0) {
+            if ((allowedFacet & FACET_LENGTH) == 0) {
+                reportError("cos-applicable-facets", new Object[]{"length", fTypeName});
+            } else {
+                fLength = facets.length;
+                lengthAnnotation = facets.lengthAnnotation;
+                fFacetsDefined |= FACET_LENGTH;
+                if ((fixedFacet & FACET_LENGTH) != 0)
+                    fFixedFacet |= FACET_LENGTH;
+            }
+        }
+        // minLength
+        if ((presentFacet & FACET_MINLENGTH) != 0) {
+            if ((allowedFacet & FACET_MINLENGTH) == 0) {
+                reportError("cos-applicable-facets", new Object[]{"minLength", fTypeName});
+            } else {
+                fMinLength = facets.minLength;
+                minLengthAnnotation = facets.minLengthAnnotation;
+                fFacetsDefined |= FACET_MINLENGTH;
+                if ((fixedFacet & FACET_MINLENGTH) != 0)
+                    fFixedFacet |= FACET_MINLENGTH;
+            }
+        }
+        // maxLength
+        if ((presentFacet & FACET_MAXLENGTH) != 0) {
+            if ((allowedFacet & FACET_MAXLENGTH) == 0) {
+                reportError("cos-applicable-facets", new Object[]{"maxLength", fTypeName});
+            } else {
+                fMaxLength = facets.maxLength;
+                maxLengthAnnotation = facets.maxLengthAnnotation;
+                fFacetsDefined |= FACET_MAXLENGTH;
+                if ((fixedFacet & FACET_MAXLENGTH) != 0)
+                    fFixedFacet |= FACET_MAXLENGTH;
+            }
+        }
+        // pattern
+        if ((presentFacet & FACET_PATTERN) != 0) {
+            if ((allowedFacet & FACET_PATTERN) == 0) {
+                reportError("cos-applicable-facets", new Object[]{"pattern", fTypeName});
+            } else {
+                patternAnnotations = facets.patternAnnotations;
+                RegularExpression regex = null;
+                try {
+                    regex = new RegularExpression(facets.pattern, "X", context.getLocale());
+                } catch (Exception e) {
+                    reportError("InvalidRegex", new Object[]{facets.pattern, e.getLocalizedMessage()});
+                }
+                if (regex != null) {
+                    fPattern = new Vector();
+                    fPattern.addElement(regex);
+                    fPatternStr = new Vector();
+                    fPatternStr.addElement(facets.pattern);
+                    fFacetsDefined |= FACET_PATTERN;
+                    if ((fixedFacet & FACET_PATTERN) != 0)
+                        fFixedFacet |= FACET_PATTERN;
+                }
+            }
+        }
+
+        // whiteSpace
+        if ((presentFacet & FACET_WHITESPACE) != 0) {
+            if ((allowedFacet & FACET_WHITESPACE) == 0) {
+                reportError("cos-applicable-facets", new Object[]{"whiteSpace", fTypeName});
+            } else {
+                fWhiteSpace = facets.whiteSpace;
+                whiteSpaceAnnotation = facets.whiteSpaceAnnotation;
+                fFacetsDefined |= FACET_WHITESPACE;
+                if ((fixedFacet & FACET_WHITESPACE) != 0)
+                    fFixedFacet |= FACET_WHITESPACE;
+            }
+        }
+        // enumeration
+        if ((presentFacet & FACET_ENUMERATION) != 0) {
+            if ((allowedFacet & FACET_ENUMERATION) == 0) {
+                reportError("cos-applicable-facets", new Object[]{"enumeration", fTypeName});
+            } else {
+                Vector enumVals = facets.enumeration;
+                int size = enumVals.size();
+                fEnumeration = new ValidatedInfo[size];
+                Vector enumNSDecls = facets.enumNSDecls;
+                ValidationContextImpl ctx = new ValidationContextImpl(context);
+                enumerationAnnotations = facets.enumAnnotations;
+                fEnumerationSize = 0;
+                for (int i = 0; i < size; i++) {
+                    if (enumNSDecls != null)
+                        ctx.setNSContext((NamespaceContext)enumNSDecls.elementAt(i));
+                    try {
+                        ValidatedInfo info = getActualEnumValue((String)enumVals.elementAt(i), ctx, null);
+                        // check 4.3.5.c0 must: enumeration values from the value space of base
+                        fEnumeration[fEnumerationSize++] = info;
+                    } catch (InvalidDatatypeValueException ide) {
+                        reportError("enumeration-valid-restriction", new Object[]{enumVals.elementAt(i), this.getBaseType().getName()});
+                    }
+                }
+                fFacetsDefined |= FACET_ENUMERATION;
+                if ((fixedFacet & FACET_ENUMERATION) != 0)
+                    fFixedFacet |= FACET_ENUMERATION;
+            }
+        }
+
+        // maxInclusive
+        if ((presentFacet & FACET_MAXINCLUSIVE) != 0) {
+            if ((allowedFacet & FACET_MAXINCLUSIVE) == 0) {
+                reportError("cos-applicable-facets", new Object[]{"maxInclusive", fTypeName});
+            } else {
+                maxInclusiveAnnotation = facets.maxInclusiveAnnotation;
+                try {
+                    fMaxInclusive = fBase.getActualValue(facets.maxInclusive, context, tempInfo, true);
+                    fFacetsDefined |= FACET_MAXINCLUSIVE;
+                    if ((fixedFacet & FACET_MAXINCLUSIVE) != 0)
+                        fFixedFacet |= FACET_MAXINCLUSIVE;
+                } catch (InvalidDatatypeValueException ide) {
+                    reportError(ide.getKey(), ide.getArgs());
+                    reportError("FacetValueFromBase", new Object[]{fTypeName, facets.maxInclusive,
+                            "maxInclusive", fBase.getName()});
+                }
+
+                // check against fixed value in base
+                if (((fBase.fFacetsDefined & FACET_MAXINCLUSIVE) != 0)) {
+                    if ((fBase.fFixedFacet & FACET_MAXINCLUSIVE) != 0) {
+                        if (fDVs[fValidationDV].compare(fMaxInclusive, fBase.fMaxInclusive) != 0)
+                            reportError( "FixedFacetValue", new Object[]{"maxInclusive", fMaxInclusive, fBase.fMaxInclusive, fTypeName});
+                    }
+                }
+                // maxInclusive from base
+                try {
+                    fBase.validate(context, tempInfo);
+                } catch (InvalidDatatypeValueException ide) {
+                    reportError(ide.getKey(), ide.getArgs());
+                    reportError("FacetValueFromBase", new Object[]{fTypeName, facets.maxInclusive,
+                            "maxInclusive", fBase.getName()});
+                }
+            }
+        }
+
+        // maxExclusive
+        boolean needCheckBase = true;
+        if ((presentFacet & FACET_MAXEXCLUSIVE) != 0) {
+            if ((allowedFacet & FACET_MAXEXCLUSIVE) == 0) {
+                reportError("cos-applicable-facets", new Object[]{"maxExclusive", fTypeName});
+            } else {
+                maxExclusiveAnnotation = facets.maxExclusiveAnnotation;
+                try {
+                    fMaxExclusive = fBase.getActualValue(facets.maxExclusive, context, tempInfo, true);
+                    fFacetsDefined |= FACET_MAXEXCLUSIVE;
+                    if ((fixedFacet & FACET_MAXEXCLUSIVE) != 0)
+                        fFixedFacet |= FACET_MAXEXCLUSIVE;
+                } catch (InvalidDatatypeValueException ide) {
+                    reportError(ide.getKey(), ide.getArgs());
+                    reportError("FacetValueFromBase", new Object[]{fTypeName, facets.maxExclusive,
+                            "maxExclusive", fBase.getName()});
+                }
+
+                // check against fixed value in base
+                if (((fBase.fFacetsDefined & FACET_MAXEXCLUSIVE) != 0)) {
+                    result = fDVs[fValidationDV].compare(fMaxExclusive, fBase.fMaxExclusive);
+                    if ((fBase.fFixedFacet & FACET_MAXEXCLUSIVE) != 0 && result != 0) {
+                        reportError( "FixedFacetValue", new Object[]{"maxExclusive", facets.maxExclusive, fBase.fMaxExclusive, fTypeName});
+                    }
+                    if (result == 0) {
+                        needCheckBase = false;
+                    }
+                }
+                // maxExclusive from base
+                if (needCheckBase) {
+                    try {
+                        fBase.validate(context, tempInfo);
+                    } catch (InvalidDatatypeValueException ide) {
+                        reportError(ide.getKey(), ide.getArgs());
+                        reportError("FacetValueFromBase", new Object[]{fTypeName, facets.maxExclusive,
+                                "maxExclusive", fBase.getName()});
+                    }
+                }
+                // If maxExclusive == base.maxExclusive, then we only need to check
+                // maxExclusive <= base.maxInclusive
+                else if (((fBase.fFacetsDefined & FACET_MAXINCLUSIVE) != 0)) {
+                    if (fDVs[fValidationDV].compare(fMaxExclusive, fBase.fMaxInclusive) > 0) {
+                        reportError( "maxExclusive-valid-restriction.2", new Object[]{facets.maxExclusive, fBase.fMaxInclusive});
+                    }
+                }
+            }
+        }
+        // minExclusive
+        needCheckBase = true;
+        if ((presentFacet & FACET_MINEXCLUSIVE) != 0) {
+            if ((allowedFacet & FACET_MINEXCLUSIVE) == 0) {
+                reportError("cos-applicable-facets", new Object[]{"minExclusive", fTypeName});
+            } else {
+                minExclusiveAnnotation = facets.minExclusiveAnnotation;
+                try {
+                    fMinExclusive = fBase.getActualValue(facets.minExclusive, context, tempInfo, true);
+                    fFacetsDefined |= FACET_MINEXCLUSIVE;
+                    if ((fixedFacet & FACET_MINEXCLUSIVE) != 0)
+                        fFixedFacet |= FACET_MINEXCLUSIVE;
+                } catch (InvalidDatatypeValueException ide) {
+                    reportError(ide.getKey(), ide.getArgs());
+                    reportError("FacetValueFromBase", new Object[]{fTypeName, facets.minExclusive,
+                            "minExclusive", fBase.getName()});
+                }
+
+                // check against fixed value in base
+                if (((fBase.fFacetsDefined & FACET_MINEXCLUSIVE) != 0)) {
+                    result = fDVs[fValidationDV].compare(fMinExclusive, fBase.fMinExclusive);
+                    if ((fBase.fFixedFacet & FACET_MINEXCLUSIVE) != 0 && result != 0) {
+                        reportError( "FixedFacetValue", new Object[]{"minExclusive", facets.minExclusive, fBase.fMinExclusive, fTypeName});
+                    }
+                    if (result == 0) {
+                        needCheckBase = false;
+                    }
+                }
+                // minExclusive from base
+                if (needCheckBase) {
+                    try {
+                        fBase.validate(context, tempInfo);
+                    } catch (InvalidDatatypeValueException ide) {
+                        reportError(ide.getKey(), ide.getArgs());
+                        reportError("FacetValueFromBase", new Object[]{fTypeName, facets.minExclusive,
+                                "minExclusive", fBase.getName()});
+                    }
+                }
+                // If minExclusive == base.minExclusive, then we only need to check
+                // minExclusive >= base.minInclusive
+                else if (((fBase.fFacetsDefined & FACET_MININCLUSIVE) != 0)) {
+                    if (fDVs[fValidationDV].compare(fMinExclusive, fBase.fMinInclusive) < 0) {
+                        reportError( "minExclusive-valid-restriction.3", new Object[]{facets.minExclusive, fBase.fMinInclusive});
+                    }
+                }
+            }
+        }
+        // minInclusive
+        if ((presentFacet & FACET_MININCLUSIVE) != 0) {
+            if ((allowedFacet & FACET_MININCLUSIVE) == 0) {
+                reportError("cos-applicable-facets", new Object[]{"minInclusive", fTypeName});
+            } else {
+                minInclusiveAnnotation = facets.minInclusiveAnnotation;
+                try {
+                    fMinInclusive = fBase.getActualValue(facets.minInclusive, context, tempInfo, true);
+                    fFacetsDefined |= FACET_MININCLUSIVE;
+                    if ((fixedFacet & FACET_MININCLUSIVE) != 0)
+                        fFixedFacet |= FACET_MININCLUSIVE;
+                } catch (InvalidDatatypeValueException ide) {
+                    reportError(ide.getKey(), ide.getArgs());
+                    reportError("FacetValueFromBase", new Object[]{fTypeName, facets.minInclusive,
+                            "minInclusive", fBase.getName()});
+                }
+
+                // check against fixed value in base
+                if (((fBase.fFacetsDefined & FACET_MININCLUSIVE) != 0)) {
+                    if ((fBase.fFixedFacet & FACET_MININCLUSIVE) != 0) {
+                        if (fDVs[fValidationDV].compare(fMinInclusive, fBase.fMinInclusive) != 0)
+                            reportError( "FixedFacetValue", new Object[]{"minInclusive", facets.minInclusive, fBase.fMinInclusive, fTypeName});
+                    }
+                }
+                // minInclusive from base
+                try {
+                    fBase.validate(context, tempInfo);
+                } catch (InvalidDatatypeValueException ide) {
+                    reportError(ide.getKey(), ide.getArgs());
+                    reportError("FacetValueFromBase", new Object[]{fTypeName, facets.minInclusive,
+                            "minInclusive", fBase.getName()});
+                }
+            }
+        }
+
+        // totalDigits
+        if ((presentFacet & FACET_TOTALDIGITS) != 0) {
+            if ((allowedFacet & FACET_TOTALDIGITS) == 0) {
+                reportError("cos-applicable-facets", new Object[]{"totalDigits", fTypeName});
+            } else {
+                totalDigitsAnnotation = facets.totalDigitsAnnotation;
+                fTotalDigits = facets.totalDigits;
+                fFacetsDefined |= FACET_TOTALDIGITS;
+                if ((fixedFacet & FACET_TOTALDIGITS) != 0)
+                    fFixedFacet |= FACET_TOTALDIGITS;
+            }
+        }
+        // fractionDigits
+        if ((presentFacet & FACET_FRACTIONDIGITS) != 0) {
+            if ((allowedFacet & FACET_FRACTIONDIGITS) == 0) {
+                reportError("cos-applicable-facets", new Object[]{"fractionDigits", fTypeName});
+            } else {
+                fFractionDigits = facets.fractionDigits;
+                fractionDigitsAnnotation = facets.fractionDigitsAnnotation;
+                fFacetsDefined |= FACET_FRACTIONDIGITS;
+                if ((fixedFacet & FACET_FRACTIONDIGITS) != 0)
+                    fFixedFacet |= FACET_FRACTIONDIGITS;
+            }
+        }
+
+        // token type: internal use, so do less checking
+        if (patternType != SPECIAL_PATTERN_NONE) {
+            fPatternType = patternType;
+        }
+
+        // step 2: check facets against each other: length, bounds
+        if(fFacetsDefined != 0) {
+
+            // check 4.3.2.c1 must: minLength <= maxLength
+            if(((fFacetsDefined & FACET_MINLENGTH ) != 0 ) && ((fFacetsDefined & FACET_MAXLENGTH) != 0))
+            {
+                if(fMinLength > fMaxLength)
+                    reportError("minLength-less-than-equal-to-maxLength", new Object[]{Integer.toString(fMinLength), Integer.toString(fMaxLength), fTypeName});
+            }
+
+            // check 4.3.8.c1 error: maxInclusive + maxExclusive
+            if (((fFacetsDefined & FACET_MAXEXCLUSIVE) != 0) && ((fFacetsDefined & FACET_MAXINCLUSIVE) != 0)) {
+                reportError( "maxInclusive-maxExclusive", new Object[]{fMaxInclusive, fMaxExclusive, fTypeName});
+            }
+
+            // check 4.3.9.c1 error: minInclusive + minExclusive
+            if (((fFacetsDefined & FACET_MINEXCLUSIVE) != 0) && ((fFacetsDefined & FACET_MININCLUSIVE) != 0)) {
+                reportError("minInclusive-minExclusive", new Object[]{fMinInclusive, fMinExclusive, fTypeName});
+            }
+
+            // check 4.3.7.c1 must: minInclusive <= maxInclusive
+            if (((fFacetsDefined &  FACET_MAXINCLUSIVE) != 0) && ((fFacetsDefined & FACET_MININCLUSIVE) != 0)) {
+                result = fDVs[fValidationDV].compare(fMinInclusive, fMaxInclusive);
+                if (result != -1 && result != 0)
+                    reportError("minInclusive-less-than-equal-to-maxInclusive", new Object[]{fMinInclusive, fMaxInclusive, fTypeName});
+            }
+
+            // check 4.3.8.c2 must: minExclusive <= maxExclusive ??? minExclusive < maxExclusive
+            if (((fFacetsDefined & FACET_MAXEXCLUSIVE) != 0) && ((fFacetsDefined & FACET_MINEXCLUSIVE) != 0)) {
+                result = fDVs[fValidationDV].compare(fMinExclusive, fMaxExclusive);
+                if (result != -1 && result != 0)
+                    reportError( "minExclusive-less-than-equal-to-maxExclusive", new Object[]{fMinExclusive, fMaxExclusive, fTypeName});
+            }
+
+            // check 4.3.9.c2 must: minExclusive < maxInclusive
+            if (((fFacetsDefined & FACET_MAXINCLUSIVE) != 0) && ((fFacetsDefined & FACET_MINEXCLUSIVE) != 0)) {
+                if (fDVs[fValidationDV].compare(fMinExclusive, fMaxInclusive) != -1)
+                    reportError( "minExclusive-less-than-maxInclusive", new Object[]{fMinExclusive, fMaxInclusive, fTypeName});
+            }
+
+            // check 4.3.10.c1 must: minInclusive < maxExclusive
+            if (((fFacetsDefined & FACET_MAXEXCLUSIVE) != 0) && ((fFacetsDefined & FACET_MININCLUSIVE) != 0)) {
+                if (fDVs[fValidationDV].compare(fMinInclusive, fMaxExclusive) != -1)
+                    reportError( "minInclusive-less-than-maxExclusive", new Object[]{fMinInclusive, fMaxExclusive, fTypeName});
+            }
+
+            // check 4.3.12.c1 must: fractionDigits <= totalDigits
+            if (((fFacetsDefined & FACET_FRACTIONDIGITS) != 0) &&
+                    ((fFacetsDefined & FACET_TOTALDIGITS) != 0)) {
+                if (fFractionDigits > fTotalDigits)
+                    reportError( "fractionDigits-totalDigits", new Object[]{Integer.toString(fFractionDigits), Integer.toString(fTotalDigits), fTypeName});
+            }
+
+            // step 3: check facets against base
+            // check 4.3.1.c1 error: length & (fBase.maxLength | fBase.minLength)
+            if((fFacetsDefined & FACET_LENGTH) != 0 ){
+                if ((fBase.fFacetsDefined & FACET_MINLENGTH) != 0 &&
+                        fLength < fBase.fMinLength) {
+                    // length, fBase.minLength and fBase.maxLength defined
+                    reportError("length-minLength-maxLength.1.1", new Object[]{fTypeName, Integer.toString(fLength), Integer.toString(fBase.fMinLength)});
+                }
+                if ((fBase.fFacetsDefined & FACET_MAXLENGTH) != 0 &&
+                        fLength > fBase.fMaxLength) {
+                    // length and fBase.maxLength defined
+                    reportError("length-minLength-maxLength.2.1", new Object[]{fTypeName, Integer.toString(fLength), Integer.toString(fBase.fMaxLength)});
+                }
+                if ( (fBase.fFacetsDefined & FACET_LENGTH) != 0 ) {
+                    // check 4.3.1.c2 error: length != fBase.length
+                    if ( fLength != fBase.fLength )
+                        reportError( "length-valid-restriction", new Object[]{Integer.toString(fLength), Integer.toString(fBase.fLength), fTypeName});
+                }
+            }
+
+            // check 4.3.1.c1 error: fBase.length & (maxLength | minLength)
+            if((fBase.fFacetsDefined & FACET_LENGTH) != 0 || (fFacetsDefined & FACET_LENGTH) != 0){
+                if ((fFacetsDefined & FACET_MINLENGTH) != 0){
+                    if (fBase.fLength < fMinLength) {
+                        // fBase.length, minLength and maxLength defined
+                        reportError("length-minLength-maxLength.1.1", new Object[]{fTypeName, Integer.toString(fBase.fLength), Integer.toString(fMinLength)});
+                    }
+                    if ((fBase.fFacetsDefined & FACET_MINLENGTH) == 0){ 
+                        reportError("length-minLength-maxLength.1.2.a", new Object[]{fTypeName});  
+                    }
+                    if (fMinLength != fBase.fMinLength){
+                        reportError("length-minLength-maxLength.1.2.b", new Object[]{fTypeName, Integer.toString(fMinLength), Integer.toString(fBase.fMinLength)}); 
+                    }
+                }
+                if ((fFacetsDefined & FACET_MAXLENGTH) != 0){
+                    if (fBase.fLength > fMaxLength) {
+                        // fBase.length, minLength and maxLength defined
+                        reportError("length-minLength-maxLength.2.1", new Object[]{fTypeName, Integer.toString(fBase.fLength), Integer.toString(fMaxLength)});
+                    }
+                    if ((fBase.fFacetsDefined & FACET_MAXLENGTH) == 0){ 
+                        reportError("length-minLength-maxLength.2.2.a", new Object[]{fTypeName});  
+                    }
+                    if (fMaxLength != fBase.fMaxLength){
+                        reportError("length-minLength-maxLength.2.2.b", new Object[]{fTypeName, Integer.toString(fMaxLength), Integer.toString(fBase.fBase.fMaxLength)}); 
+                    }
+                }
+            }
+
+            // check 4.3.2.c1 must: minLength <= fBase.maxLength
+            if ( ((fFacetsDefined & FACET_MINLENGTH ) != 0 ) ) {
+                if ( (fBase.fFacetsDefined & FACET_MAXLENGTH ) != 0 ) {
+                    if ( fMinLength > fBase.fMaxLength ) {
+                        reportError("minLength-less-than-equal-to-maxLength", new Object[]{Integer.toString(fMinLength), Integer.toString(fBase.fMaxLength), fTypeName});
+                    }
+                }
+                else if ( (fBase.fFacetsDefined & FACET_MINLENGTH) != 0 ) {
+                    if ( (fBase.fFixedFacet & FACET_MINLENGTH) != 0 && fMinLength != fBase.fMinLength ) {
+                        reportError( "FixedFacetValue", new Object[]{"minLength", Integer.toString(fMinLength), Integer.toString(fBase.fMinLength), fTypeName});
+                    }
+
+                    // check 4.3.2.c2 error: minLength < fBase.minLength
+                    if ( fMinLength < fBase.fMinLength ) {
+                        reportError( "minLength-valid-restriction", new Object[]{Integer.toString(fMinLength), Integer.toString(fBase.fMinLength), fTypeName});
+                    }
+                }
+            }
+
+
+            // check 4.3.2.c1 must: maxLength < fBase.minLength
+            if ( ((fFacetsDefined & FACET_MAXLENGTH ) != 0 ) && ((fBase.fFacetsDefined & FACET_MINLENGTH ) != 0 )) {
+                if ( fMaxLength < fBase.fMinLength) {
+                    reportError("minLength-less-than-equal-to-maxLength", new Object[]{Integer.toString(fBase.fMinLength), Integer.toString(fMaxLength)});
+                }
+            }
+
+            // check 4.3.3.c1 error: maxLength > fBase.maxLength
+            if ( (fFacetsDefined & FACET_MAXLENGTH) != 0 ) {
+                if ( (fBase.fFacetsDefined & FACET_MAXLENGTH) != 0 ){
+                    if(( (fBase.fFixedFacet & FACET_MAXLENGTH) != 0 )&& fMaxLength != fBase.fMaxLength ) {
+                        reportError( "FixedFacetValue", new Object[]{"maxLength", Integer.toString(fMaxLength), Integer.toString(fBase.fMaxLength), fTypeName});
+                    }
+                    if ( fMaxLength > fBase.fMaxLength ) {
+                        reportError( "maxLength-valid-restriction", new Object[]{Integer.toString(fMaxLength), Integer.toString(fBase.fMaxLength), fTypeName});
+                    }
+                }
+            }
+
+            /*          // check 4.3.7.c2 error:
+			 // maxInclusive > fBase.maxInclusive
+			  // maxInclusive >= fBase.maxExclusive
+			   // maxInclusive < fBase.minInclusive
+			    // maxInclusive <= fBase.minExclusive
+
+			     if (((fFacetsDefined & FACET_MAXINCLUSIVE) != 0)) {
+			     if (((fBase.fFacetsDefined & FACET_MAXINCLUSIVE) != 0)) {
+			     result = fDVs[fValidationDV].compare(fMaxInclusive, fBase.fMaxInclusive);
+			     if ((fBase.fFixedFacet & FACET_MAXINCLUSIVE) != 0 && result != 0) {
+			     reportError( "FixedFacetValue", new Object[]{"maxInclusive", fMaxInclusive, fBase.fMaxInclusive, fTypeName});
+			     }
+			     if (result != -1 && result != 0) {
+			     reportError( "maxInclusive-valid-restriction.1", new Object[]{fMaxInclusive, fBase.fMaxInclusive, fTypeName});
+			     }
+			     }
+			     if (((fBase.fFacetsDefined & FACET_MAXEXCLUSIVE) != 0) &&
+			     fDVs[fValidationDV].compare(fMaxInclusive, fBase.fMaxExclusive) != -1){
+			     reportError( "maxInclusive-valid-restriction.1", new Object[]{fMaxInclusive, fBase.fMaxExclusive, fTypeName});
+			     }
+
+			     if ((( fBase.fFacetsDefined & FACET_MININCLUSIVE) != 0)) {
+			     result = fDVs[fValidationDV].compare(fMaxInclusive, fBase.fMinInclusive);
+			     if (result != 1 && result != 0) {
+			     reportError( "maxInclusive-valid-restriction.1", new Object[]{fMaxInclusive, fBase.fMinInclusive, fTypeName});
+			     }
+			     }
+
+			     if ((( fBase.fFacetsDefined & FACET_MINEXCLUSIVE) != 0) &&
+			     fDVs[fValidationDV].compare(fMaxInclusive, fBase.fMinExclusive ) != 1)
+			     reportError( "maxInclusive-valid-restriction.1", new Object[]{fMaxInclusive, fBase.fMinExclusive, fTypeName});
+			     }
+
+			     // check 4.3.8.c3 error:
+			      // maxExclusive > fBase.maxExclusive
+			       // maxExclusive > fBase.maxInclusive
+			        // maxExclusive <= fBase.minInclusive
+			         // maxExclusive <= fBase.minExclusive
+			          if (((fFacetsDefined & FACET_MAXEXCLUSIVE) != 0)) {
+			          if ((( fBase.fFacetsDefined & FACET_MAXEXCLUSIVE) != 0)) {
+			          result= fDVs[fValidationDV].compare(fMaxExclusive, fBase.fMaxExclusive);
+			          if ((fBase.fFixedFacet & FACET_MAXEXCLUSIVE) != 0 &&  result != 0) {
+			          reportError( "FixedFacetValue", new Object[]{"maxExclusive", fMaxExclusive, fBase.fMaxExclusive, fTypeName});
+			          }
+			          if (result != -1 && result != 0) {
+			          reportError( "maxExclusive-valid-restriction.1", new Object[]{fMaxExclusive, fBase.fMaxExclusive, fTypeName});
+			          }
+			          }
+
+			          if ((( fBase.fFacetsDefined & FACET_MAXINCLUSIVE) != 0)) {
+			          result= fDVs[fValidationDV].compare(fMaxExclusive, fBase.fMaxInclusive);
+			          if (result != -1 && result != 0) {
+			          reportError( "maxExclusive-valid-restriction.2", new Object[]{fMaxExclusive, fBase.fMaxInclusive, fTypeName});
+			          }
+			          }
+
+			          if ((( fBase.fFacetsDefined & FACET_MINEXCLUSIVE) != 0) &&
+			          fDVs[fValidationDV].compare(fMaxExclusive, fBase.fMinExclusive ) != 1)
+			          reportError( "maxExclusive-valid-restriction.3", new Object[]{fMaxExclusive, fBase.fMinExclusive, fTypeName});
+
+			          if ((( fBase.fFacetsDefined & FACET_MININCLUSIVE) != 0) &&
+			          fDVs[fValidationDV].compare(fMaxExclusive, fBase.fMinInclusive) != 1)
+			          reportError( "maxExclusive-valid-restriction.4", new Object[]{fMaxExclusive, fBase.fMinInclusive, fTypeName});
+			          }
+
+			          // check 4.3.9.c3 error:
+			           // minExclusive < fBase.minExclusive
+			            // minExclusive > fBase.maxInclusive
+			             // minExclusive < fBase.minInclusive
+			              // minExclusive >= fBase.maxExclusive
+			               if (((fFacetsDefined & FACET_MINEXCLUSIVE) != 0)) {
+			               if ((( fBase.fFacetsDefined & FACET_MINEXCLUSIVE) != 0)) {
+			               result= fDVs[fValidationDV].compare(fMinExclusive, fBase.fMinExclusive);
+			               if ((fBase.fFixedFacet & FACET_MINEXCLUSIVE) != 0 && result != 0) {
+			               reportError( "FixedFacetValue", new Object[]{"minExclusive", fMinExclusive, fBase.fMinExclusive, fTypeName});
+			               }
+			               if (result != 1 && result != 0) {
+			               reportError( "minExclusive-valid-restriction.1", new Object[]{fMinExclusive, fBase.fMinExclusive, fTypeName});
+			               }
+			               }
+
+			               if ((( fBase.fFacetsDefined & FACET_MAXINCLUSIVE) != 0)) {
+			               result=fDVs[fValidationDV].compare(fMinExclusive, fBase.fMaxInclusive);
+
+			               if (result != -1 && result != 0) {
+			               reportError( "minExclusive-valid-restriction.2", new Object[]{fMinExclusive, fBase.fMaxInclusive, fTypeName});
+			               }
+			               }
+
+			               if ((( fBase.fFacetsDefined & FACET_MININCLUSIVE) != 0)) {
+			               result = fDVs[fValidationDV].compare(fMinExclusive, fBase.fMinInclusive);
+
+			               if (result != 1 && result != 0) {
+			               reportError( "minExclusive-valid-restriction.3", new Object[]{fMinExclusive, fBase.fMinInclusive, fTypeName});
+			               }
+			               }
+
+			               if ((( fBase.fFacetsDefined & FACET_MAXEXCLUSIVE) != 0) &&
+			               fDVs[fValidationDV].compare(fMinExclusive, fBase.fMaxExclusive) != -1)
+			               reportError( "minExclusive-valid-restriction.4", new Object[]{fMinExclusive, fBase.fMaxExclusive, fTypeName});
+			               }
+
+			               // check 4.3.10.c2 error:
+			                // minInclusive < fBase.minInclusive
+			                 // minInclusive > fBase.maxInclusive
+			                  // minInclusive <= fBase.minExclusive
+			                   // minInclusive >= fBase.maxExclusive
+			                    if (((fFacetsDefined & FACET_MININCLUSIVE) != 0)) {
+			                    if (((fBase.fFacetsDefined & FACET_MININCLUSIVE) != 0)) {
+			                    result = fDVs[fValidationDV].compare(fMinInclusive, fBase.fMinInclusive);
+
+			                    if ((fBase.fFixedFacet & FACET_MININCLUSIVE) != 0 && result != 0) {
+			                    reportError( "FixedFacetValue", new Object[]{"minInclusive", fMinInclusive, fBase.fMinInclusive, fTypeName});
+			                    }
+			                    if (result != 1 && result != 0) {
+			                    reportError( "minInclusive-valid-restriction.1", new Object[]{fMinInclusive, fBase.fMinInclusive, fTypeName});
+			                    }
+			                    }
+			                    if ((( fBase.fFacetsDefined & FACET_MAXINCLUSIVE) != 0)) {
+			                    result=fDVs[fValidationDV].compare(fMinInclusive, fBase.fMaxInclusive);
+			                    if (result != -1 && result != 0) {
+			                    reportError( "minInclusive-valid-restriction.2", new Object[]{fMinInclusive, fBase.fMaxInclusive, fTypeName});
+			                    }
+			                    }
+			                    if ((( fBase.fFacetsDefined & FACET_MINEXCLUSIVE) != 0) &&
+			                    fDVs[fValidationDV].compare(fMinInclusive, fBase.fMinExclusive ) != 1)
+			                    reportError( "minInclusive-valid-restriction.3", new Object[]{fMinInclusive, fBase.fMinExclusive, fTypeName});
+			                    if ((( fBase.fFacetsDefined & FACET_MAXEXCLUSIVE) != 0) &&
+			                    fDVs[fValidationDV].compare(fMinInclusive, fBase.fMaxExclusive) != -1)
+			                    reportError( "minInclusive-valid-restriction.4", new Object[]{fMinInclusive, fBase.fMaxExclusive, fTypeName});
+			                    }
+             */
+            // check 4.3.11.c1 error: totalDigits > fBase.totalDigits
+            if (((fFacetsDefined & FACET_TOTALDIGITS) != 0)) {
+                if ((( fBase.fFacetsDefined & FACET_TOTALDIGITS) != 0)) {
+                    if ((fBase.fFixedFacet & FACET_TOTALDIGITS) != 0 && fTotalDigits != fBase.fTotalDigits) {
+                        reportError("FixedFacetValue", new Object[]{"totalDigits", Integer.toString(fTotalDigits), Integer.toString(fBase.fTotalDigits), fTypeName});
+                    }
+                    if (fTotalDigits > fBase.fTotalDigits) {
+                        reportError( "totalDigits-valid-restriction", new Object[]{Integer.toString(fTotalDigits), Integer.toString(fBase.fTotalDigits), fTypeName});
+                    }
+                }
+            }
+
+            // check 4.3.12.c1 must: fractionDigits <= base.totalDigits
+            if ((fFacetsDefined & FACET_FRACTIONDIGITS) != 0) {
+                if ((fBase.fFacetsDefined & FACET_TOTALDIGITS) != 0) {
+                    if (fFractionDigits > fBase.fTotalDigits)
+                        reportError( "fractionDigits-totalDigits", new Object[]{Integer.toString(fFractionDigits), Integer.toString(fTotalDigits), fTypeName});
+                }
+            }
+
+            // check 4.3.12.c2 error: fractionDigits > fBase.fractionDigits
+            // check fixed value for fractionDigits
+            if (((fFacetsDefined & FACET_FRACTIONDIGITS) != 0)) {
+                if ((( fBase.fFacetsDefined & FACET_FRACTIONDIGITS) != 0)) {
+                    if (((fBase.fFixedFacet & FACET_FRACTIONDIGITS) != 0 && fFractionDigits != fBase.fFractionDigits) ||
+                            (fValidationDV == DV_INTEGER && fFractionDigits != 0)) {
+                        reportError("FixedFacetValue", new Object[]{"fractionDigits", Integer.toString(fFractionDigits), Integer.toString(fBase.fFractionDigits), fTypeName});
+                    }
+                    if (fFractionDigits > fBase.fFractionDigits) {
+                        reportError( "fractionDigits-valid-restriction", new Object[]{Integer.toString(fFractionDigits), Integer.toString(fBase.fFractionDigits), fTypeName});
+                    }
+                }
+                else if (fValidationDV == DV_INTEGER && fFractionDigits != 0) {
+                    reportError("FixedFacetValue", new Object[]{"fractionDigits", Integer.toString(fFractionDigits), "0", fTypeName});
+                }
+            }
+
+            // check 4.3.6.c1 error:
+            // (whiteSpace = preserve || whiteSpace = replace) && fBase.whiteSpace = collapese or
+            // whiteSpace = preserve && fBase.whiteSpace = replace
+
+            if ( (fFacetsDefined & FACET_WHITESPACE) != 0 && (fBase.fFacetsDefined & FACET_WHITESPACE) != 0 ){
+                if ( (fBase.fFixedFacet & FACET_WHITESPACE) != 0 &&  fWhiteSpace != fBase.fWhiteSpace ) {
+                    reportError( "FixedFacetValue", new Object[]{"whiteSpace", whiteSpaceValue(fWhiteSpace), whiteSpaceValue(fBase.fWhiteSpace), fTypeName});
+                }
+
+                if ( fWhiteSpace == WS_PRESERVE &&  fBase.fWhiteSpace == WS_COLLAPSE ){
+                    reportError( "whiteSpace-valid-restriction.1", new Object[]{fTypeName, "preserve"});
+                }
+                if ( fWhiteSpace == WS_REPLACE &&  fBase.fWhiteSpace == WS_COLLAPSE ){
+                    reportError( "whiteSpace-valid-restriction.1", new Object[]{fTypeName, "replace"});
+                }
+                if ( fWhiteSpace == WS_PRESERVE &&  fBase.fWhiteSpace == WS_REPLACE ){
+                    reportError( "whiteSpace-valid-restriction.2", new Object[]{fTypeName});
+                }
+            }
+        }//fFacetsDefined != null
+
+        // step 4: inherit other facets from base (including fTokeyType)
+
+        // inherit length
+        if ( (fFacetsDefined & FACET_LENGTH) == 0  && (fBase.fFacetsDefined & FACET_LENGTH) != 0 ) {
+            fFacetsDefined |= FACET_LENGTH;
+            fLength = fBase.fLength;
+            lengthAnnotation = fBase.lengthAnnotation;
+        }
+        // inherit minLength
+        if ( (fFacetsDefined & FACET_MINLENGTH) == 0 && (fBase.fFacetsDefined & FACET_MINLENGTH) != 0 ) {
+            fFacetsDefined |= FACET_MINLENGTH;
+            fMinLength = fBase.fMinLength;
+            minLengthAnnotation = fBase.minLengthAnnotation;
+        }
+        // inherit maxLength
+        if ((fFacetsDefined & FACET_MAXLENGTH) == 0 &&  (fBase.fFacetsDefined & FACET_MAXLENGTH) != 0 ) {
+            fFacetsDefined |= FACET_MAXLENGTH;
+            fMaxLength = fBase.fMaxLength;
+            maxLengthAnnotation = fBase.maxLengthAnnotation;
+        }
+        // inherit pattern
+        if ( (fBase.fFacetsDefined & FACET_PATTERN) != 0 ) {
+            if ((fFacetsDefined & FACET_PATTERN) == 0) {
+                fFacetsDefined |= FACET_PATTERN;
+                fPattern = fBase.fPattern;
+                fPatternStr = fBase.fPatternStr;
+                patternAnnotations = fBase.patternAnnotations;
+            }
+            else {
+                for (int i = fBase.fPattern.size()-1; i >= 0; --i) {
+                    fPattern.addElement(fBase.fPattern.elementAt(i));
+                    fPatternStr.addElement(fBase.fPatternStr.elementAt(i));
+                }
+                if (fBase.patternAnnotations != null) {
+                    if (patternAnnotations != null) {
+                        for (int i = fBase.patternAnnotations.getLength()-1; i >= 0; --i) {
+                            patternAnnotations.addXSObject(fBase.patternAnnotations.item(i));
+                        }
+                    }
+                    else {
+                        patternAnnotations = fBase.patternAnnotations;
+                    }
+                }
+            }
+        }
+        // inherit whiteSpace
+        if ( (fFacetsDefined & FACET_WHITESPACE) == 0 &&  (fBase.fFacetsDefined & FACET_WHITESPACE) != 0 ) {
+            fFacetsDefined |= FACET_WHITESPACE;
+            fWhiteSpace = fBase.fWhiteSpace;
+            whiteSpaceAnnotation = fBase.whiteSpaceAnnotation;
+        }
+        // inherit enumeration
+        if ((fFacetsDefined & FACET_ENUMERATION) == 0 && (fBase.fFacetsDefined & FACET_ENUMERATION) != 0) {
+            fFacetsDefined |= FACET_ENUMERATION;
+            fEnumeration = fBase.fEnumeration;
+            fEnumerationSize = fBase.fEnumerationSize;
+            enumerationAnnotations = fBase.enumerationAnnotations;
+        }
+        // inherit maxExclusive
+        if ((( fBase.fFacetsDefined & FACET_MAXEXCLUSIVE) != 0) &&
+                !((fFacetsDefined & FACET_MAXEXCLUSIVE) != 0) && !((fFacetsDefined & FACET_MAXINCLUSIVE) != 0)) {
+            fFacetsDefined |= FACET_MAXEXCLUSIVE;
+            fMaxExclusive = fBase.fMaxExclusive;
+            maxExclusiveAnnotation = fBase.maxExclusiveAnnotation;
+        }
+        // inherit maxInclusive
+        if ((( fBase.fFacetsDefined & FACET_MAXINCLUSIVE) != 0) &&
+                !((fFacetsDefined & FACET_MAXEXCLUSIVE) != 0) && !((fFacetsDefined & FACET_MAXINCLUSIVE) != 0)) {
+            fFacetsDefined |= FACET_MAXINCLUSIVE;
+            fMaxInclusive = fBase.fMaxInclusive;
+            maxInclusiveAnnotation = fBase.maxInclusiveAnnotation;
+        }
+        // inherit minExclusive
+        if ((( fBase.fFacetsDefined & FACET_MINEXCLUSIVE) != 0) &&
+                !((fFacetsDefined & FACET_MINEXCLUSIVE) != 0) && !((fFacetsDefined & FACET_MININCLUSIVE) != 0)) {
+            fFacetsDefined |= FACET_MINEXCLUSIVE;
+            fMinExclusive = fBase.fMinExclusive;
+            minExclusiveAnnotation = fBase.minExclusiveAnnotation;
+        }
+        // inherit minExclusive
+        if ((( fBase.fFacetsDefined & FACET_MININCLUSIVE) != 0) &&
+                !((fFacetsDefined & FACET_MINEXCLUSIVE) != 0) && !((fFacetsDefined & FACET_MININCLUSIVE) != 0)) {
+            fFacetsDefined |= FACET_MININCLUSIVE;
+            fMinInclusive = fBase.fMinInclusive;
+            minInclusiveAnnotation = fBase.minInclusiveAnnotation;
+        }
+        // inherit totalDigits
+        if ((( fBase.fFacetsDefined & FACET_TOTALDIGITS) != 0) &&
+                !((fFacetsDefined & FACET_TOTALDIGITS) != 0)) {
+            fFacetsDefined |= FACET_TOTALDIGITS;
+            fTotalDigits = fBase.fTotalDigits;
+            totalDigitsAnnotation = fBase.totalDigitsAnnotation;
+        }
+        // inherit fractionDigits
+        if ((( fBase.fFacetsDefined & FACET_FRACTIONDIGITS) != 0)
+                && !((fFacetsDefined & FACET_FRACTIONDIGITS) != 0)) {
+            fFacetsDefined |= FACET_FRACTIONDIGITS;
+            fFractionDigits = fBase.fFractionDigits;
+            fractionDigitsAnnotation = fBase.fractionDigitsAnnotation;
+        }
+        //inherit tokeytype
+        if ((fPatternType == SPECIAL_PATTERN_NONE ) && (fBase.fPatternType != SPECIAL_PATTERN_NONE)) {
+            fPatternType = fBase.fPatternType ;
+        }
+
+        // step 5: mark fixed values
+        fFixedFacet |= fBase.fFixedFacet;
+
+        //step 6: setting fundamental facets
+        calcFundamentalFacets();
+
+    } //applyFacets()
+
+    /**
+     * validate a value, and return the compiled form
+     */
+    @Override
+    public Object validate(String content, ValidationContext context, ValidatedInfo validatedInfo) throws InvalidDatatypeValueException {
+
+        if (context == null)
+            context = fEmptyContext;
+
+        if (validatedInfo == null)
+            validatedInfo = new ValidatedInfo();
+        else
+            validatedInfo.memberType = null;
+
+        // first normalize string value, and convert it to actual value
+        boolean needNormalize = context==null||context.needToNormalize();
+        Object ob = getActualValue(content, context, validatedInfo, needNormalize);
+
+        validate(context, validatedInfo);
+
+        return ob;
+
+    }
+
+    protected ValidatedInfo getActualEnumValue(String lexical, ValidationContext ctx, ValidatedInfo info)
+    throws InvalidDatatypeValueException {
+        return fBase.validateWithInfo(lexical, ctx, info);
+    }
+
+    /**
+     * validate a value, and return the compiled form
+     */
+    public ValidatedInfo validateWithInfo(String content, ValidationContext context, ValidatedInfo validatedInfo) throws InvalidDatatypeValueException {
+
+        if (context == null)
+            context = fEmptyContext;
+
+        if (validatedInfo == null)
+            validatedInfo = new ValidatedInfo();
+        else
+            validatedInfo.memberType = null;
+
+        // first normalize string value, and convert it to actual value
+        boolean needNormalize = context==null||context.needToNormalize();
+        getActualValue(content, context, validatedInfo, needNormalize);
+
+        validate(context, validatedInfo);
+
+        return validatedInfo;
+
+    }
+
+    /**
+     * validate a value, and return the compiled form
+     */
+    @Override
+    public Object validate(Object content, ValidationContext context, ValidatedInfo validatedInfo) throws InvalidDatatypeValueException {
+
+        if (context == null)
+            context = fEmptyContext;
+
+        if (validatedInfo == null)
+            validatedInfo = new ValidatedInfo();
+        else
+            validatedInfo.memberType = null;
+
+        // first normalize string value, and convert it to actual value
+        boolean needNormalize = context==null||context.needToNormalize();
+        Object ob = getActualValue(content, context, validatedInfo, needNormalize);
+
+        validate(context, validatedInfo);
+
+        return ob;
+
+    }
+
+    /**
+     * validate an actual value against this DV
+     *
+     * @param context       the validation context
+     * @param validatedInfo used to provide the actual value and member types
+     */
+    @Override
+    public void validate(ValidationContext context, ValidatedInfo validatedInfo)
+        throws InvalidDatatypeValueException {
+
+        if (context == null)
+            context = fEmptyContext;
+
+        // then validate the actual value against the facets
+        if (context.needFacetChecking() &&
+                (fFacetsDefined != 0 && fFacetsDefined != FACET_WHITESPACE)) {
+            checkFacets(validatedInfo);
+        }
+
+        // now check extra rules: for ID/IDREF/ENTITY
+        if (context.needExtraChecking()) {
+            checkExtraRules(context, validatedInfo);
+        }
+
+    }
+
+    private void checkFacets(ValidatedInfo validatedInfo) throws InvalidDatatypeValueException {
+
+        Object ob = validatedInfo.actualValue;
+        String content = validatedInfo.normalizedValue;
+        short type = validatedInfo.actualValueType;
+        ShortList itemType = validatedInfo.itemValueTypes;
+
+        // For QName and NOTATION types, we don't check length facets
+        if (fValidationDV != DV_QNAME && fValidationDV != DV_NOTATION) {
+            int length = fDVs[fValidationDV].getDataLength(ob);
+
+            // maxLength
+            if ( (fFacetsDefined & FACET_MAXLENGTH) != 0 ) {
+                if ( length > fMaxLength ) {
+                    throw new InvalidDatatypeValueException("cvc-maxLength-valid",
+                            new Object[]{content, Integer.toString(length), Integer.toString(fMaxLength), fTypeName});
+                }
+            }
+
+            //minLength
+            if ( (fFacetsDefined & FACET_MINLENGTH) != 0 ) {
+                if ( length < fMinLength ) {
+                    throw new InvalidDatatypeValueException("cvc-minLength-valid",
+                            new Object[]{content, Integer.toString(length), Integer.toString(fMinLength), fTypeName});
+                }
+            }
+
+            //length
+            if ( (fFacetsDefined & FACET_LENGTH) != 0 ) {
+                if ( length != fLength ) {
+                    throw new InvalidDatatypeValueException("cvc-length-valid",
+                            new Object[]{content, Integer.toString(length), Integer.toString(fLength), fTypeName});
+                }
+            }
+        }
+
+        //enumeration
+        if ( ((fFacetsDefined & FACET_ENUMERATION) != 0 ) ) {
+            boolean present = false;
+            final int enumSize = fEnumerationSize;
+            final short primitiveType1 = convertToPrimitiveKind(type);
+            for (int i = 0; i < enumSize; i++) {
+                final short primitiveType2 = convertToPrimitiveKind(fEnumeration[i].actualValueType);
+                if ((primitiveType1 == primitiveType2 ||
+                        primitiveType1 == XSConstants.ANYSIMPLETYPE_DT && primitiveType2 == XSConstants.STRING_DT ||
+                        primitiveType1 == XSConstants.STRING_DT && primitiveType2 == XSConstants.ANYSIMPLETYPE_DT)
+                        && fEnumeration[i].actualValue.equals(ob)) {
+                    if (primitiveType1 == XSConstants.LIST_DT || primitiveType1 == XSConstants.LISTOFUNION_DT) {
+                        ShortList enumItemType = fEnumeration[i].itemValueTypes;
+                        final int typeList1Length = itemType != null ? itemType.getLength() : 0;
+                        final int typeList2Length = enumItemType != null ? enumItemType.getLength() : 0;
+                        if (typeList1Length == typeList2Length) {
+                            int j;
+                            for (j = 0; j < typeList1Length; ++j) {
+                                final short primitiveItem1 = convertToPrimitiveKind(itemType.item(j));
+                                final short primitiveItem2 = convertToPrimitiveKind(enumItemType.item(j));
+                                if (primitiveItem1 != primitiveItem2) {
+                                    if (primitiveItem1 == XSConstants.ANYSIMPLETYPE_DT && primitiveItem2 == XSConstants.STRING_DT ||
+                                            primitiveItem1 == XSConstants.STRING_DT && primitiveItem2 == XSConstants.ANYSIMPLETYPE_DT) {
+                                        continue;
+                                    }
+                                    break;
+                                }
+                            }
+                            if (j == typeList1Length) {
+                                present = true;
+                                break;
+                            }
+                        }
+                    }
+                    else {
+                        present = true;
+                        break;
+                    }
+                }
+            }
+            if(!present){
+                StringBuffer sb = new StringBuffer();
+                appendEnumString(sb);
+                throw new InvalidDatatypeValueException("cvc-enumeration-valid",
+                        new Object [] {content, sb.toString()});
+            }
+        }
+
+        //fractionDigits
+        if ((fFacetsDefined & FACET_FRACTIONDIGITS) != 0) {
+            int scale = fDVs[fValidationDV].getFractionDigits(ob);
+            if (scale > fFractionDigits) {
+                throw new InvalidDatatypeValueException("cvc-fractionDigits-valid",
+                        new Object[] {content, Integer.toString(scale), Integer.toString(fFractionDigits)});
+            }
+        }
+
+        //totalDigits
+        if ((fFacetsDefined & FACET_TOTALDIGITS)!=0) {
+            int totalDigits = fDVs[fValidationDV].getTotalDigits(ob);
+            if (totalDigits > fTotalDigits) {
+                throw new InvalidDatatypeValueException("cvc-totalDigits-valid",
+                        new Object[] {content, Integer.toString(totalDigits), Integer.toString(fTotalDigits)});
+            }
+        }
+
+        int compare;
+
+        //maxinclusive
+        if ( (fFacetsDefined & FACET_MAXINCLUSIVE) != 0 ) {
+            compare = fDVs[fValidationDV].compare(ob, fMaxInclusive);
+            if (compare != -1 && compare != 0) {
+                throw new InvalidDatatypeValueException("cvc-maxInclusive-valid",
+                        new Object[] {content, fMaxInclusive, fTypeName});
+            }
+        }
+
+        //maxExclusive
+        if ( (fFacetsDefined & FACET_MAXEXCLUSIVE) != 0 ) {
+            compare = fDVs[fValidationDV].compare(ob, fMaxExclusive );
+            if (compare != -1) {
+                throw new InvalidDatatypeValueException("cvc-maxExclusive-valid",
+                        new Object[] {content, fMaxExclusive, fTypeName});
+            }
+        }
+
+        //minInclusive
+        if ( (fFacetsDefined & FACET_MININCLUSIVE) != 0 ) {
+            compare = fDVs[fValidationDV].compare(ob, fMinInclusive);
+            if (compare != 1 && compare != 0) {
+                throw new InvalidDatatypeValueException("cvc-minInclusive-valid",
+                        new Object[] {content, fMinInclusive, fTypeName});
+            }
+        }
+
+        //minExclusive
+        if ( (fFacetsDefined & FACET_MINEXCLUSIVE) != 0 ) {
+            compare = fDVs[fValidationDV].compare(ob, fMinExclusive);
+            if (compare != 1) {
+                throw new InvalidDatatypeValueException("cvc-minExclusive-valid",
+                        new Object[] {content, fMinExclusive, fTypeName});
+            }
+        }
+
+    }
+
+    private void checkExtraRules(ValidationContext context, ValidatedInfo validatedInfo) throws InvalidDatatypeValueException {
+
+        Object ob = validatedInfo.actualValue;
+
+        if (fVariety == VARIETY_ATOMIC) {
+
+            fDVs[fValidationDV].checkExtraRules(ob, context);
+
+        } else if (fVariety == VARIETY_LIST) {
+
+            ListDV.ListData values = (ListDV.ListData)ob;
+            XSSimpleType memberType = validatedInfo.memberType;
+            int len = values.getLength();
+            try {
+                if (fItemType.fVariety == VARIETY_UNION) {
+                    XSSimpleTypeDecl[] memberTypes = (XSSimpleTypeDecl[])validatedInfo.memberTypes;
+                    for (int i = len-1; i >= 0; i--) {
+                        validatedInfo.actualValue = values.item(i);
+                        validatedInfo.memberType = memberTypes[i];
+                        fItemType.checkExtraRules(context, validatedInfo);
+                    }
+                } else { // (fVariety == VARIETY_ATOMIC)
+                    for (int i = len-1; i >= 0; i--) {
+                        validatedInfo.actualValue = values.item(i);
+                        fItemType.checkExtraRules(context, validatedInfo);
+                    }
+                }
+            }
+            finally {
+                validatedInfo.actualValue = values;
+                validatedInfo.memberType = memberType;
+            }
+
+        } else { // (fVariety == VARIETY_UNION)
+
+            ((XSSimpleTypeDecl)validatedInfo.memberType).checkExtraRules(context, validatedInfo);
+
+        }
+
+    }// checkExtraRules()
+
+    //we can still return object for internal use.
+    private Object getActualValue(Object content, ValidationContext context,
+            ValidatedInfo validatedInfo, boolean needNormalize)
+    throws InvalidDatatypeValueException{
+
+        String nvalue;
+        if (needNormalize) {
+            nvalue = normalize(content, fWhiteSpace);
+        } else {
+            nvalue = content.toString();
+        }
+        if ( (fFacetsDefined & FACET_PATTERN ) != 0 ) {
+            RegularExpression regex;
+            for (int idx = fPattern.size()-1; idx >= 0; idx--) {
+                regex = (RegularExpression)fPattern.elementAt(idx);
+                if (!regex.matches(nvalue)){
+                    throw new InvalidDatatypeValueException("cvc-pattern-valid",
+                            new Object[]{content,
+                            fPatternStr.elementAt(idx),
+
+                            fTypeName});
+                }
+            }
+        }
+
+        if (fVariety == VARIETY_ATOMIC) {
+
+            // validate special kinds of token, in place of old pattern matching
+            if (fPatternType != SPECIAL_PATTERN_NONE) {
+
+                boolean seenErr = false;
+                if (fPatternType == SPECIAL_PATTERN_NMTOKEN) {
+                    // PATTERN "\\c+"
+                    seenErr = !XMLChar.isValidNmtoken(nvalue);
+                }
+                else if (fPatternType == SPECIAL_PATTERN_NAME) {
+                    // PATTERN "\\i\\c*"
+                    seenErr = !XMLChar.isValidName(nvalue);
+                }
+                else if (fPatternType == SPECIAL_PATTERN_NCNAME) {
+                    // PATTERN "[\\i-[:]][\\c-[:]]*"
+                    seenErr = !XMLChar.isValidNCName(nvalue);
+                }
+                if (seenErr) {
+                    throw new InvalidDatatypeValueException("cvc-datatype-valid.1.2.1",
+                            new Object[]{nvalue, SPECIAL_PATTERN_STRING[fPatternType]});
+                }
+            }
+
+            validatedInfo.normalizedValue = nvalue;
+            Object avalue = fDVs[fValidationDV].getActualValue(nvalue, context);
+            validatedInfo.actualValue = avalue;
+            validatedInfo.actualValueType = fBuiltInKind;
+            validatedInfo.actualType = this;
+
+            return avalue;
+
+        } else if (fVariety == VARIETY_LIST) {
+
+            StringTokenizer parsedList = new StringTokenizer(nvalue, " ");
+            int countOfTokens = parsedList.countTokens() ;
+            Object[] avalue = new Object[countOfTokens];
+            boolean isUnion = fItemType.getVariety() == VARIETY_UNION;
+            short[] itemTypes = new short[isUnion ? countOfTokens : 1];
+            if (!isUnion)
+                itemTypes[0] = fItemType.fBuiltInKind;
+            XSSimpleTypeDecl[] memberTypes = new XSSimpleTypeDecl[countOfTokens];
+            for(int i = 0 ; i < countOfTokens ; i ++){
+                // we can't call fItemType.validate(), otherwise checkExtraRules()
+                // will be called twice: once in fItemType.validate, once in
+                // validate method of this type.
+                // so we take two steps to get the actual value:
+                // 1. fItemType.getActualValue()
+                // 2. fItemType.chekcFacets()
+                avalue[i] = fItemType.getActualValue(parsedList.nextToken(), context, validatedInfo, false);
+                if (context.needFacetChecking() &&
+                        (fItemType.fFacetsDefined != 0 && fItemType.fFacetsDefined != FACET_WHITESPACE)) {
+                    fItemType.checkFacets(validatedInfo);
+                }
+                memberTypes[i] = (XSSimpleTypeDecl)validatedInfo.memberType;
+                if (isUnion)
+                    itemTypes[i] = memberTypes[i].fBuiltInKind;
+            }
+
+            ListDV.ListData v = new ListDV.ListData(avalue);
+            validatedInfo.actualValue = v;
+            validatedInfo.actualValueType = isUnion ? XSConstants.LISTOFUNION_DT : XSConstants.LIST_DT;
+            validatedInfo.memberType = null;
+            validatedInfo.memberTypes = memberTypes;
+            validatedInfo.itemValueTypes = new ShortListImpl(itemTypes, itemTypes.length);
+            validatedInfo.normalizedValue = nvalue;
+            // Need to set it here or it will become the item type
+            validatedInfo.actualType = this;
+
+            return v;
+
+        } else { // (fVariety == VARIETY_UNION)
+            final Object _content = (fMemberTypes.length > 1 && content != null) ? content.toString() : content;
+            for (int i = 0; i < fMemberTypes.length; i++) {
+                try {
+                    // we can't call fMemberType[i].validate(), otherwise checkExtraRules()
+                    // will be called twice: once in fMemberType[i].validate, once in
+                    // validate method of this type.
+                    // so we take two steps to get the actual value:
+                    // 1. fMemberType[i].getActualValue()
+                    // 2. fMemberType[i].chekcFacets()
+                    Object aValue = fMemberTypes[i].getActualValue(_content, context, validatedInfo, true);
+                    if (context.needFacetChecking() &&
+                            (fMemberTypes[i].fFacetsDefined != 0 && fMemberTypes[i].fFacetsDefined != FACET_WHITESPACE)) {
+                        fMemberTypes[i].checkFacets(validatedInfo);
+                    }
+                    validatedInfo.memberType = fMemberTypes[i];
+                    // Need to set it here or it will become the member type
+                    validatedInfo.actualType = this;
+                    return aValue;
+                } catch(InvalidDatatypeValueException invalidValue) {
+                }
+            }
+            StringBuffer typesBuffer = new StringBuffer();
+            XSSimpleTypeDecl decl;
+            for(int i = 0;i < fMemberTypes.length; i++) {
+                if(i != 0)
+                    typesBuffer.append(" | ");
+                decl = fMemberTypes[i];
+                if(decl.fTargetNamespace != null) {
+                    typesBuffer.append('{');
+                    typesBuffer.append(decl.fTargetNamespace);
+                    typesBuffer.append('}');
+    

<TRUNCATED>

[21/24] jena git commit: JENA-1537: Remove dependency on Xerces. Import needed code

Posted by an...@apache.org.
http://git-wip-us.apache.org/repos/asf/jena/blob/c9a7e646/jena-core/src/main/java/org/apache/jena/ext/xerces/impl/dv/ObjectFactory.java
----------------------------------------------------------------------
diff --git a/jena-core/src/main/java/org/apache/jena/ext/xerces/impl/dv/ObjectFactory.java b/jena-core/src/main/java/org/apache/jena/ext/xerces/impl/dv/ObjectFactory.java
new file mode 100644
index 0000000..e96a9af
--- /dev/null
+++ b/jena-core/src/main/java/org/apache/jena/ext/xerces/impl/dv/ObjectFactory.java
@@ -0,0 +1,546 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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.jena.ext.xerces.impl.dv;
+
+import java.io.BufferedReader;
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.InputStreamReader;
+import java.util.Properties;
+
+/**
+ * This class is duplicated for each JAXP subpackage so keep it in sync.
+ * It is package private and therefore is not exposed as part of the JAXP
+ * API.
+ * <p>
+ * This code is designed to implement the JAXP 1.1 spec pluggability
+ * feature and is designed to run on JDK version 1.1 and
+ * later, and to compile on JDK 1.2 and onward.
+ * The code also runs both as part of an unbundled jar file and
+ * when bundled as part of the JDK.
+ * <p>
+ * 
+ * @xerces.internal 
+ *
+ * @version $Id: ObjectFactory.java 924307 2010-03-17 14:36:05Z mrglavas $
+ */
+@SuppressWarnings("all")
+final class ObjectFactory {
+
+    //
+    // Constants
+    //
+
+    // name of default properties file to look for in JDK's jre/lib directory
+    private static final String DEFAULT_PROPERTIES_FILENAME = "xerces.properties";
+
+    /** Set to true for debugging */
+    private static final boolean DEBUG = isDebugEnabled();
+
+    /**
+     * Default columns per line.
+     */
+    private static final int DEFAULT_LINE_LENGTH = 80;
+
+    /** cache the contents of the xerces.properties file.
+     *  Until an attempt has been made to read this file, this will
+     * be null; if the file does not exist or we encounter some other error
+     * during the read, this will be empty.
+     */
+    private static Properties fXercesProperties = null;
+
+    /***
+     * Cache the time stamp of the xerces.properties file so
+     * that we know if it's been modified and can invalidate
+     * the cache when necessary.
+     */
+    private static long fLastModified = -1;
+
+    //
+    // static methods
+    //
+
+    /**
+     * Finds the implementation Class object in the specified order.  The
+     * specified order is the following:
+     * <ol>
+     *  <li>query the system property using <code>System.getProperty</code>
+     *  <li>read <code>META-INF/services/<i>factoryId</i></code> file
+     *  <li>use fallback classname
+     * </ol>
+     *
+     * @return Class object of factory, never null
+     *
+     * @param factoryId             Name of the factory to find, same as
+     *                              a property name
+     * @param fallbackClassName     Implementation class name, if nothing else
+     *                              is found.  Use null to mean no fallback.
+     *
+     * @exception ObjectFactory.ConfigurationError
+     */
+    static Object createObject(String factoryId, String fallbackClassName)
+        throws ConfigurationError {
+        return createObject(factoryId, null, fallbackClassName);
+    } // createObject(String,String):Object
+
+    /**
+     * Finds the implementation Class object in the specified order.  The
+     * specified order is the following:
+     * <ol>
+     *  <li>query the system property using <code>System.getProperty</code>
+     *  <li>read <code>$java.home/lib/<i>propertiesFilename</i></code> file
+     *  <li>read <code>META-INF/services/<i>factoryId</i></code> file
+     *  <li>use fallback classname
+     * </ol>
+     *
+     * @return Class object of factory, never null
+     *
+     * @param factoryId             Name of the factory to find, same as
+     *                              a property name
+     * @param propertiesFilename The filename in the $java.home/lib directory
+     *                           of the properties file.  If none specified,
+     *                           ${java.home}/lib/xerces.properties will be used.
+     * @param fallbackClassName     Implementation class name, if nothing else
+     *                              is found.  Use null to mean no fallback.
+     *
+     * @exception ObjectFactory.ConfigurationError
+     */
+    static Object createObject(String factoryId,
+                                      String propertiesFilename,
+                                      String fallbackClassName)
+        throws ConfigurationError
+    {
+        if (DEBUG) debugPrintln("debug is on");
+
+        ClassLoader cl = findClassLoader();
+
+        // Use the system property first
+        try {
+            String systemProp = SecuritySupport.getSystemProperty(factoryId);
+            if (systemProp != null && systemProp.length() > 0) {
+                if (DEBUG) debugPrintln("found system property, value=" + systemProp);
+                return newInstance(systemProp, cl, true);
+            }
+        } catch (SecurityException se) {
+            // Ignore and continue w/ next location
+        }
+
+        // Try to read from propertiesFilename, or $java.home/lib/xerces.properties
+        String factoryClassName = null;
+        // no properties file name specified; use $JAVA_HOME/lib/xerces.properties:
+        if (propertiesFilename == null) {
+            File propertiesFile = null;
+            boolean propertiesFileExists = false;
+            try {
+                String javah = SecuritySupport.getSystemProperty("java.home");
+                propertiesFilename = javah + File.separator +
+                    "lib" + File.separator + DEFAULT_PROPERTIES_FILENAME;
+                propertiesFile = new File(propertiesFilename);
+                propertiesFileExists = SecuritySupport.getFileExists(propertiesFile);
+            } catch (SecurityException e) {
+                // try again...
+                fLastModified = -1;
+                fXercesProperties = null;
+            }
+            
+            synchronized (ObjectFactory.class) {
+                boolean loadProperties = false;
+                FileInputStream fis = null;
+                try {
+                    // file existed last time
+                    if(fLastModified >= 0) {
+                        if(propertiesFileExists &&
+                                (fLastModified < (fLastModified = SecuritySupport.getLastModified(propertiesFile)))) {
+                            loadProperties = true;
+                        } else {
+                            // file has stopped existing...
+                            if(!propertiesFileExists) {
+                                fLastModified = -1;
+                                fXercesProperties = null;
+                            } // else, file wasn't modified!
+                        }
+                    } else {
+                        // file has started to exist:
+                        if(propertiesFileExists) {
+                            loadProperties = true;
+                            fLastModified = SecuritySupport.getLastModified(propertiesFile);
+                        } // else, nothing's changed
+                    }
+                    if(loadProperties) {
+                        // must never have attempted to read xerces.properties before (or it's outdeated)
+                        fXercesProperties = new Properties();
+                        fis = SecuritySupport.getFileInputStream(propertiesFile);
+                        fXercesProperties.load(fis);
+                    }
+                } catch (Exception x) {
+                    fXercesProperties = null;
+                    fLastModified = -1;
+                    // assert(x instanceof FileNotFoundException
+                    //        || x instanceof SecurityException)
+                    // In both cases, ignore and continue w/ next location
+                }
+                finally {
+                    // try to close the input stream if one was opened.
+                    if (fis != null) {
+                        try {
+                            fis.close();
+                        }
+                        // Ignore the exception.
+                        catch (IOException exc) {}
+                    }
+                }
+            }
+            if(fXercesProperties != null) {
+                factoryClassName = fXercesProperties.getProperty(factoryId);
+            }
+        } else {
+            FileInputStream fis = null;
+            try {
+                fis = SecuritySupport.getFileInputStream(new File(propertiesFilename));
+                Properties props = new Properties();
+                props.load(fis);
+                factoryClassName = props.getProperty(factoryId);
+            } catch (Exception x) {
+                // assert(x instanceof FileNotFoundException
+                //        || x instanceof SecurityException)
+                // In both cases, ignore and continue w/ next location
+            }
+            finally {
+                // try to close the input stream if one was opened.
+                if (fis != null) {
+                    try {
+                        fis.close();
+                    }
+                    // Ignore the exception.
+                    catch (IOException exc) {}
+                }
+            }
+        }
+        if (factoryClassName != null) {
+            if (DEBUG) debugPrintln("found in " + propertiesFilename + ", value=" + factoryClassName);
+            return newInstance(factoryClassName, cl, true);
+        }
+
+        // Try Jar Service Provider Mechanism
+        Object provider = findJarServiceProvider(factoryId);
+        if (provider != null) {
+            return provider;
+        }
+
+        if (fallbackClassName == null) {
+            throw new ConfigurationError(
+                "Provider for " + factoryId + " cannot be found", null);
+        }
+
+        if (DEBUG) debugPrintln("using fallback, value=" + fallbackClassName);
+        return newInstance(fallbackClassName, cl, true);
+    } // createObject(String,String,String):Object
+
+    //
+    // Private static methods
+    //
+    
+    /** Returns true if debug has been enabled. */
+    private static boolean isDebugEnabled() {
+        try {
+            String val = SecuritySupport.getSystemProperty("xerces.debug");
+            // Allow simply setting the prop to turn on debug
+            return (val != null && (!"false".equals(val)));
+        } 
+        catch (SecurityException se) {}
+        return false;
+    } // isDebugEnabled()
+
+    /** Prints a message to standard error if debugging is enabled. */
+    private static void debugPrintln(String msg) {
+        if (DEBUG) {
+            System.err.println("XERCES: " + msg);
+        }
+    } // debugPrintln(String)
+
+    /**
+     * Figure out which ClassLoader to use.  For JDK 1.2 and later use
+     * the context ClassLoader.
+     */
+    static ClassLoader findClassLoader()
+        throws ConfigurationError
+    {
+        // Figure out which ClassLoader to use for loading the provider
+        // class.  If there is a Context ClassLoader then use it.
+        ClassLoader context = SecuritySupport.getContextClassLoader();
+        ClassLoader system = SecuritySupport.getSystemClassLoader();
+
+        ClassLoader chain = system;
+        while (true) {
+            if (context == chain) {
+                // Assert: we are on JDK 1.1 or we have no Context ClassLoader
+                // or any Context ClassLoader in chain of system classloader
+                // (including extension ClassLoader) so extend to widest
+                // ClassLoader (always look in system ClassLoader if Xerces
+                // is in boot/extension/system classpath and in current
+                // ClassLoader otherwise); normal classloaders delegate
+                // back to system ClassLoader first so this widening doesn't
+                // change the fact that context ClassLoader will be consulted
+                ClassLoader current = ObjectFactory.class.getClassLoader();
+
+                chain = system;
+                while (true) {
+                    if (current == chain) {
+                        // Assert: Current ClassLoader in chain of
+                        // boot/extension/system ClassLoaders
+                        return system;
+                    }
+                    if (chain == null) {
+                        break;
+                    }
+                    chain = SecuritySupport.getParentClassLoader(chain);
+                }
+
+                // Assert: Current ClassLoader not in chain of
+                // boot/extension/system ClassLoaders
+                return current;
+            }
+
+            if (chain == null) {
+                // boot ClassLoader reached
+                break;
+            }
+
+            // Check for any extension ClassLoaders in chain up to
+            // boot ClassLoader
+            chain = SecuritySupport.getParentClassLoader(chain);
+        };
+
+        // Assert: Context ClassLoader not in chain of
+        // boot/extension/system ClassLoaders
+        return context;
+    } // findClassLoader():ClassLoader
+
+    /**
+     * Create an instance of a class using the specified ClassLoader
+     */
+    static Object newInstance(String className, ClassLoader cl,
+                                      boolean doFallback)
+        throws ConfigurationError
+    {
+        // assert(className != null);
+        try{
+            Class providerClass = findProviderClass(className, cl, doFallback);
+            Object instance = providerClass.newInstance();
+            if (DEBUG) debugPrintln("created new instance of " + providerClass +
+                   " using ClassLoader: " + cl);
+            return instance;
+        } catch (ClassNotFoundException x) {
+            throw new ConfigurationError(
+                "Provider " + className + " not found", x);
+        } catch (Exception x) {
+            throw new ConfigurationError(
+                "Provider " + className + " could not be instantiated: " + x,
+                x);
+        }
+    }
+
+    /**
+     * Find a Class using the specified ClassLoader
+     */
+    static Class findProviderClass(String className, ClassLoader cl,
+                                      boolean doFallback)
+        throws ClassNotFoundException, ConfigurationError
+    {
+        //throw security exception if the calling thread is not allowed to access the package
+        //restrict the access to package as speicified in java.security policy
+        SecurityManager security = System.getSecurityManager();
+        if (security != null) {
+            final int lastDot = className.lastIndexOf(".");
+            String packageName = className;
+            if (lastDot != -1) packageName = className.substring(0, lastDot);
+            security.checkPackageAccess(packageName);
+        }
+        Class providerClass;
+        if (cl == null) {
+            // XXX Use the bootstrap ClassLoader.  There is no way to
+            // load a class using the bootstrap ClassLoader that works
+            // in both JDK 1.1 and Java 2.  However, this should still
+            // work b/c the following should be true:
+            //
+            // (cl == null) iff current ClassLoader == null
+            //
+            // Thus Class.forName(String) will use the current
+            // ClassLoader which will be the bootstrap ClassLoader.
+            providerClass = Class.forName(className);
+        } else {
+            try {
+                providerClass = cl.loadClass(className);
+            } catch (ClassNotFoundException x) {
+                if (doFallback) {
+                    // Fall back to current classloader
+                    ClassLoader current = ObjectFactory.class.getClassLoader();
+                    if (current == null) {
+                        providerClass = Class.forName(className);
+                    } else if (cl != current) {
+                        cl = current;
+                        providerClass = cl.loadClass(className);
+                    } else {
+                        throw x;
+                    }
+                } else {
+                    throw x;
+                }
+            }
+        }
+
+        return providerClass;
+    }
+
+    /*
+     * Try to find provider using Jar Service Provider Mechanism
+     *
+     * @return instance of provider class if found or null
+     */
+    private static Object findJarServiceProvider(String factoryId)
+        throws ConfigurationError
+    {
+        String serviceId = "META-INF/services/" + factoryId;
+        InputStream is = null;
+
+        // First try the Context ClassLoader
+        ClassLoader cl = findClassLoader();
+
+        is = SecuritySupport.getResourceAsStream(cl, serviceId);
+
+        // If no provider found then try the current ClassLoader
+        if (is == null) {
+            ClassLoader current = ObjectFactory.class.getClassLoader();
+            if (cl != current) {
+                cl = current;
+                is = SecuritySupport.getResourceAsStream(cl, serviceId);
+            }
+        }
+
+        if (is == null) {
+            // No provider found
+            return null;
+        }
+
+        if (DEBUG) debugPrintln("found jar resource=" + serviceId +
+               " using ClassLoader: " + cl);
+
+        // Read the service provider name in UTF-8 as specified in
+        // the jar spec.  Unfortunately this fails in Microsoft
+        // VJ++, which does not implement the UTF-8
+        // encoding. Theoretically, we should simply let it fail in
+        // that case, since the JVM is obviously broken if it
+        // doesn't support such a basic standard.  But since there
+        // are still some users attempting to use VJ++ for
+        // development, we have dropped in a fallback which makes a
+        // second attempt using the platform's default encoding. In
+        // VJ++ this is apparently ASCII, which is a subset of
+        // UTF-8... and since the strings we'll be reading here are
+        // also primarily limited to the 7-bit ASCII range (at
+        // least, in English versions), this should work well
+        // enough to keep us on the air until we're ready to
+        // officially decommit from VJ++. [Edited comment from
+        // jkesselm]
+        BufferedReader rd;
+        try {
+            rd = new BufferedReader(new InputStreamReader(is, "UTF-8"), DEFAULT_LINE_LENGTH);
+        } catch (java.io.UnsupportedEncodingException e) {
+            rd = new BufferedReader(new InputStreamReader(is), DEFAULT_LINE_LENGTH);
+        }
+
+        String factoryClassName = null;
+        try {
+            // XXX Does not handle all possible input as specified by the
+            // Jar Service Provider specification
+            factoryClassName = rd.readLine();
+        } catch (IOException x) {
+            // No provider found
+            return null;
+        }
+        finally {
+            try {
+                // try to close the reader.
+                rd.close();
+            }
+            // Ignore the exception.
+            catch (IOException exc) {}
+        }
+
+        if (factoryClassName != null &&
+            ! "".equals(factoryClassName)) {
+            if (DEBUG) debugPrintln("found in resource, value="
+                   + factoryClassName);
+
+            // Note: here we do not want to fall back to the current
+            // ClassLoader because we want to avoid the case where the
+            // resource file was found using one ClassLoader and the
+            // provider class was instantiated using a different one.
+            return newInstance(factoryClassName, cl, false);
+        }
+
+        // No provider found
+        return null;
+    }
+
+    //
+    // Classes
+    //
+
+    /**
+     * A configuration error.
+     */
+    static final class ConfigurationError
+        extends Error {
+
+        /** Serialization version. */
+        static final long serialVersionUID = 8521878292694272124L;
+        
+        //
+        // Data
+        //
+
+        /** Exception. */
+        private Exception exception;
+
+        //
+        // Constructors
+        //
+
+        /**
+         * Construct a new instance with the specified detail string and
+         * exception.
+         */
+        ConfigurationError(String msg, Exception x) {
+            super(msg);
+            this.exception = x;
+        } // <init>(String,Exception)
+
+        //
+        // methods
+        //
+
+        /** Returns the exception associated to this error. */
+        Exception getException() {
+            return exception;
+        } // getException():Exception
+
+    } // class ConfigurationError
+
+} // class ObjectFactory

http://git-wip-us.apache.org/repos/asf/jena/blob/c9a7e646/jena-core/src/main/java/org/apache/jena/ext/xerces/impl/dv/SchemaDVFactory.java
----------------------------------------------------------------------
diff --git a/jena-core/src/main/java/org/apache/jena/ext/xerces/impl/dv/SchemaDVFactory.java b/jena-core/src/main/java/org/apache/jena/ext/xerces/impl/dv/SchemaDVFactory.java
new file mode 100644
index 0000000..6295737
--- /dev/null
+++ b/jena-core/src/main/java/org/apache/jena/ext/xerces/impl/dv/SchemaDVFactory.java
@@ -0,0 +1,145 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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.jena.ext.xerces.impl.dv;
+
+import org.apache.jena.ext.xerces.util.SymbolHash;
+import org.apache.jena.ext.xerces.xs.XSObjectList;
+
+/**
+ * Defines a factory API that enables applications to <p>
+ * 1. to get the instance of specified SchemaDVFactory implementation <p>
+ * 2. to create/return built-in schema simple types <p>
+ * 3. to create user defined simple types. <p>
+ *
+ * Implementations of this abstract class can be used to get built-in simple
+ * types and create user-defined simle types. <p>
+ *
+ * The implementation should store the built-in datatypes in static data, so
+ * that they can be shared by multiple parser instance, and multiple threads.
+ * 
+ * @xerces.internal 
+ *
+ * @author Sandy Gao, IBM
+ *
+ * @version $Id: SchemaDVFactory.java 558582 2007-07-23 02:05:04Z mrglavas $
+ */
+public abstract class SchemaDVFactory {
+
+    private static final String DEFAULT_FACTORY_CLASS = "org.apache.jena.ext.xerces.impl.dv.xs.SchemaDVFactoryImpl";
+
+    /**
+     * Get a default instance of SchemaDVFactory implementation.
+     *
+     * @return  an instance of SchemaDVFactory implementation
+     * @exception DVFactoryException  cannot create an instance of the specified
+     *                                class name or the default class name
+     */
+    public static final SchemaDVFactory getInstance() throws DVFactoryException {
+        return getInstance(DEFAULT_FACTORY_CLASS);
+    } //getInstance():  SchemaDVFactory
+
+
+    /**
+     * Get an instance of SchemaDVFactory implementation.
+     *
+     * @param factoryClass   name of the schema factory implementation to instantiate.
+     * @return  an instance of SchemaDVFactory implementation
+     * @exception DVFactoryException  cannot create an instance of the specified
+     *                                class name or the default class name
+     */
+    public static final SchemaDVFactory getInstance(String factoryClass) throws DVFactoryException {
+        try {
+            // if the class name is not specified, use the default one
+            return (SchemaDVFactory)(ObjectFactory.newInstance(
+                factoryClass, ObjectFactory.findClassLoader(), true));
+        } 
+        catch (ClassCastException e4) {
+            throw new DVFactoryException("Schema factory class " + factoryClass + " does not extend from SchemaDVFactory.");
+        }
+    }
+
+    // can't create a new object of this class
+    protected SchemaDVFactory() {}
+
+    /**
+     * Get a built-in simple type of the given name
+     * REVISIT: its still not decided within the Schema WG how to define the
+     *          ur-types and if all simple types should be derived from a
+     *          complex type, so as of now we ignore the fact that anySimpleType
+     *          is derived from anyType, and pass 'null' as the base of
+     *          anySimpleType. It needs to be changed as per the decision taken.
+     *
+     * @param name  the name of the datatype
+     * @return      the datatype validator of the given name
+     */
+    public abstract XSSimpleType getBuiltInType(String name);
+
+    /**
+     * get all built-in simple types, which are stored in a SymbolHash keyed by
+     * the name
+     *
+     * @return      a SymbolHash which contains all built-in simple types
+     */
+    public abstract SymbolHash getBuiltInTypes();
+
+    /**
+     * Create a new simple type which is derived by restriction from another
+     * simple type.
+     *
+     * @param name              name of the new type, could be null
+     * @param targetNamespace   target namespace of the new type, could be null
+     * @param finalSet          value of "final"
+     * @param base              base type of the new type
+     * @param annotations       set of annotations
+     * @return                  the newly created simple type
+     */
+    public abstract XSSimpleType createTypeRestriction(String name, String targetNamespace,
+                                                       short finalSet, XSSimpleType base,
+                                                       XSObjectList annotations);
+
+    /**
+     * Create a new simple type which is derived by list from another simple
+     * type.
+     *
+     * @param name              name of the new type, could be null
+     * @param targetNamespace   target namespace of the new type, could be null
+     * @param finalSet          value of "final"
+     * @param itemType          item type of the list type
+     * @param annotations       set of annotations
+     * @return                  the newly created simple type
+     */
+    public abstract XSSimpleType createTypeList(String name, String targetNamespace,
+                                                short finalSet, XSSimpleType itemType,
+                                                XSObjectList annotations);
+
+    /**
+     * Create a new simple type which is derived by union from a list of other
+     * simple types.
+     *
+     * @param name              name of the new type, could be null
+     * @param targetNamespace   target namespace of the new type, could be null
+     * @param finalSet          value of "final"
+     * @param memberTypes       member types of the union type
+     * @param annotations       set of annotations
+     * @return                  the newly created simple type
+     */
+    public abstract XSSimpleType createTypeUnion(String name, String targetNamespace,
+                                                 short finalSet, XSSimpleType[] memberTypes,
+                                                 XSObjectList annotations);
+
+}

http://git-wip-us.apache.org/repos/asf/jena/blob/c9a7e646/jena-core/src/main/java/org/apache/jena/ext/xerces/impl/dv/SecuritySupport.java
----------------------------------------------------------------------
diff --git a/jena-core/src/main/java/org/apache/jena/ext/xerces/impl/dv/SecuritySupport.java b/jena-core/src/main/java/org/apache/jena/ext/xerces/impl/dv/SecuritySupport.java
new file mode 100644
index 0000000..4d04cab
--- /dev/null
+++ b/jena-core/src/main/java/org/apache/jena/ext/xerces/impl/dv/SecuritySupport.java
@@ -0,0 +1,150 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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.jena.ext.xerces.impl.dv;
+
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.FileNotFoundException;
+import java.io.InputStream;
+import java.security.AccessController;
+import java.security.PrivilegedAction;
+import java.security.PrivilegedActionException;
+import java.security.PrivilegedExceptionAction;
+
+/**
+ * This class is duplicated for each subpackage so keep it in sync.
+ * It is package private and therefore is not exposed as part of any API.
+ * 
+ * @xerces.internal
+ * 
+ * @version $Id: SecuritySupport.java 950361 2010-06-02 04:12:35Z mrglavas $
+ */
+@SuppressWarnings("all")
+final class SecuritySupport {
+
+    static ClassLoader getContextClassLoader() {
+        return (ClassLoader)
+        AccessController.doPrivileged(new PrivilegedAction() {
+            @Override
+            public Object run() {
+                ClassLoader cl = null;
+                try {
+                    cl = Thread.currentThread().getContextClassLoader();
+                } catch (SecurityException ex) { }
+                return cl;
+            }
+        });
+    }
+    
+    static ClassLoader getSystemClassLoader() {
+        return (ClassLoader)
+        AccessController.doPrivileged(new PrivilegedAction() {
+            @Override
+            public Object run() {
+                ClassLoader cl = null;
+                try {
+                    cl = ClassLoader.getSystemClassLoader();
+                } catch (SecurityException ex) {}
+                return cl;
+            }
+        });
+    }
+    
+    static ClassLoader getParentClassLoader(final ClassLoader cl) {
+        return (ClassLoader)
+        AccessController.doPrivileged(new PrivilegedAction() {
+            @Override
+            public Object run() {
+                ClassLoader parent = null;
+                try {
+                    parent = cl.getParent();
+                } catch (SecurityException ex) {}
+                
+                // eliminate loops in case of the boot
+                // ClassLoader returning itself as a parent
+                return (parent == cl) ? null : parent;
+            }
+        });
+    }
+    
+    static String getSystemProperty(final String propName) {
+        return (String)
+        AccessController.doPrivileged(new PrivilegedAction() {
+            @Override
+            public Object run() {
+                return System.getProperty(propName);
+            }
+        });
+    }
+    
+    static FileInputStream getFileInputStream(final File file)
+    throws FileNotFoundException
+    {
+        try {
+            return (FileInputStream)
+            AccessController.doPrivileged(new PrivilegedExceptionAction() {
+                @Override
+                public Object run() throws FileNotFoundException {
+                    return new FileInputStream(file);
+                }
+            });
+        } catch (PrivilegedActionException e) {
+            throw (FileNotFoundException)e.getException();
+        }
+    }
+    
+    static InputStream getResourceAsStream(final ClassLoader cl,
+            final String name)
+    {
+        return (InputStream)
+        AccessController.doPrivileged(new PrivilegedAction() {
+            @Override
+            public Object run() {
+                InputStream ris;
+                if (cl == null) {
+                    ris = ClassLoader.getSystemResourceAsStream(name);
+                } else {
+                    ris = cl.getResourceAsStream(name);
+                }
+                return ris;
+            }
+        });
+    }
+    
+    static boolean getFileExists(final File f) {
+        return ((Boolean)
+                AccessController.doPrivileged(new PrivilegedAction() {
+                    @Override
+                    public Object run() {
+                        return f.exists() ? Boolean.TRUE : Boolean.FALSE;
+                    }
+                })).booleanValue();
+    }
+    
+    static long getLastModified(final File f) {
+        return ((Long)
+                AccessController.doPrivileged(new PrivilegedAction() {
+                    @Override
+                    public Object run() {
+                        return new Long(f.lastModified());
+                    }
+                })).longValue();
+    }
+    
+    private SecuritySupport () {}
+}

http://git-wip-us.apache.org/repos/asf/jena/blob/c9a7e646/jena-core/src/main/java/org/apache/jena/ext/xerces/impl/dv/ValidatedInfo.java
----------------------------------------------------------------------
diff --git a/jena-core/src/main/java/org/apache/jena/ext/xerces/impl/dv/ValidatedInfo.java b/jena-core/src/main/java/org/apache/jena/ext/xerces/impl/dv/ValidatedInfo.java
new file mode 100644
index 0000000..bf612e0
--- /dev/null
+++ b/jena-core/src/main/java/org/apache/jena/ext/xerces/impl/dv/ValidatedInfo.java
@@ -0,0 +1,239 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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.jena.ext.xerces.impl.dv;
+
+import org.apache.jena.ext.xerces.impl.xs.util.ShortListImpl;
+import org.apache.jena.ext.xerces.impl.xs.util.XSObjectListImpl;
+import org.apache.jena.ext.xerces.xs.*;
+
+/**
+ * Class to get the information back after content is validated. This info
+ * would be filled by validate().
+ * 
+ * @xerces.internal 
+ *
+ * @author Neeraj Bajaj, Sun Microsystems, inc.
+ *
+ * @version $Id: ValidatedInfo.java 1026362 2010-10-22 15:15:18Z sandygao $
+ */
+public class ValidatedInfo implements XSValue {
+
+    /**
+     * The normalized value of a string value
+     */
+    public String normalizedValue;
+
+    /**
+     * The actual value from a string value (QName, Boolean, etc.)
+     * An array of Objects if the type is a list.
+     */
+    public Object actualValue;
+
+    /**
+     * The type of the actual value. It's one of the _DT constants
+     * defined in XSConstants.java. The value is used to indicate
+     * the most specific built-in type.
+     * (i.e. short instead of decimal or integer).
+     */
+    public short actualValueType;
+
+    /**
+     * The declared type of the value.
+     */
+    public XSSimpleType actualType;
+
+    /**
+     * If the type is a union type, then the member type which
+     * actually validated the string value.
+     */
+    public XSSimpleType memberType;
+
+    /**
+     * If
+     * 1. the type is a union type where one of the member types is a list, or
+     *    if the type is a list; and
+     * 2. the item type of the list is a union type
+     * then an array of member types used to validate the values.
+     */
+    public XSSimpleType[] memberTypes;
+
+    /**
+     * In the case the value is a list or a list of unions, this value
+     * indicates the type(s) of the items in the list.
+     * For a normal list, the length of the array is 1; for list of unions,
+     * the length of the array is the same as the length of the list.
+     */
+    public ShortList itemValueTypes;
+
+    /**
+     * reset the state of this object
+     */
+    public void reset() {
+        this.normalizedValue = null;
+        this.actualValue = null;
+        this.actualValueType = XSConstants.UNAVAILABLE_DT;
+        this.actualType = null;
+        this.memberType = null;
+        this.memberTypes = null;
+        this.itemValueTypes = null;
+    }
+    
+    /**
+     * Return a string representation of the value. If there is an actual
+     * value, use toString; otherwise, use the normalized value.
+     */
+    public String stringValue() {
+        if (actualValue == null) {
+            return normalizedValue;
+        }
+        else {
+            return actualValue.toString();
+        }
+    }
+    
+    /**
+     * Returns true if the two ValidatedInfo objects can be compared in the same
+     * value space.
+     */
+    public static boolean isComparable(ValidatedInfo info1, ValidatedInfo info2) {
+        final short primitiveType1 = convertToPrimitiveKind(info1.actualValueType);
+        final short primitiveType2 = convertToPrimitiveKind(info2.actualValueType);
+        if (primitiveType1 != primitiveType2) {    
+            return (primitiveType1 == XSConstants.ANYSIMPLETYPE_DT && primitiveType2 == XSConstants.STRING_DT ||
+                    primitiveType1 == XSConstants.STRING_DT && primitiveType2 == XSConstants.ANYSIMPLETYPE_DT);
+        }
+        else if (primitiveType1 == XSConstants.LIST_DT || primitiveType1 == XSConstants.LISTOFUNION_DT) {
+            final ShortList typeList1 = info1.itemValueTypes;
+            final ShortList typeList2 = info2.itemValueTypes;
+            final int typeList1Length = typeList1 != null ? typeList1.getLength() : 0;
+            final int typeList2Length = typeList2 != null ? typeList2.getLength() : 0;
+            if (typeList1Length != typeList2Length) {
+                return false;
+            }
+            for (int i = 0; i < typeList1Length; ++i) {
+                final short primitiveItem1 = convertToPrimitiveKind(typeList1.item(i));
+                final short primitiveItem2 = convertToPrimitiveKind(typeList2.item(i));
+                if (primitiveItem1 != primitiveItem2) {
+                    if (primitiveItem1 == XSConstants.ANYSIMPLETYPE_DT && primitiveItem2 == XSConstants.STRING_DT ||
+                        primitiveItem1 == XSConstants.STRING_DT && primitiveItem2 == XSConstants.ANYSIMPLETYPE_DT) {
+                        continue;
+                    }
+                    return false;
+                }
+            }
+        }
+        return true;
+    }
+    
+    /**
+     * Returns the primitive type of the given type.
+     * @param valueType A value type as defined in XSConstants.
+     * @return The primitive type from which valueType was derived.
+     */
+    private static short convertToPrimitiveKind(short valueType) {
+        /** Primitive datatypes. */
+        if (valueType <= XSConstants.NOTATION_DT) {
+            return valueType;
+        }
+        /** Types derived from string. */
+        if (valueType <= XSConstants.ENTITY_DT) {
+            return XSConstants.STRING_DT;
+        }
+        /** Types derived from decimal. */
+        if (valueType <= XSConstants.POSITIVEINTEGER_DT) {
+            return XSConstants.DECIMAL_DT;
+        }
+        /** Other types. */
+        return valueType;
+    }
+
+    // XSValue methods
+    
+    @Override
+    public Object getActualValue() {
+        return actualValue;
+    }
+
+    @Override
+    public short getActualValueType() {
+        return actualValueType;
+    }
+
+    @Override
+    public ShortList getListValueTypes() {
+        return itemValueTypes == null ? ShortListImpl.EMPTY_LIST : itemValueTypes;
+    }
+
+    @Override
+    public XSObjectList getMemberTypeDefinitions() {
+        if (memberTypes == null) {
+            return XSObjectListImpl.EMPTY_LIST;
+        }
+        return new XSObjectListImpl(memberTypes, memberTypes.length);
+    }
+
+    @Override
+    public String getNormalizedValue() {
+        return normalizedValue;
+    }
+
+    @Override
+    public XSSimpleTypeDefinition getTypeDefinition() {
+        return actualType;
+    }
+    
+    @Override
+    public XSSimpleTypeDefinition getMemberTypeDefinition() {
+        return memberType;
+    }
+
+    public void copyFrom(XSValue o) {
+        if (o == null) {
+            reset();
+        }
+        else if (o instanceof ValidatedInfo) {
+            ValidatedInfo other = (ValidatedInfo)o;
+            normalizedValue = other.normalizedValue;
+            actualValue = other.actualValue;
+            actualValueType = other.actualValueType;
+            actualType = other.actualType;
+            memberType = other.memberType;
+            memberTypes = other.memberTypes;
+            itemValueTypes = other.itemValueTypes;
+        }
+        else {
+            normalizedValue = o.getNormalizedValue();
+            actualValue = o.getActualValue();
+            actualValueType = o.getActualValueType();
+            actualType = (XSSimpleType)o.getTypeDefinition();
+            memberType = (XSSimpleType)o.getMemberTypeDefinition();
+            XSSimpleType realType = memberType == null ? actualType : memberType;
+            if (realType != null && realType.getBuiltInKind() == XSConstants.LISTOFUNION_DT) {
+                XSObjectList members = o.getMemberTypeDefinitions();
+                memberTypes = new XSSimpleType[members.getLength()];
+                for (int i = 0; i < members.getLength(); i++) {
+                    memberTypes[i] = (XSSimpleType)members.get(i);
+                }
+            }
+            else {
+                memberTypes = null;
+            }
+            itemValueTypes = o.getListValueTypes();
+        }
+    }
+}

http://git-wip-us.apache.org/repos/asf/jena/blob/c9a7e646/jena-core/src/main/java/org/apache/jena/ext/xerces/impl/dv/ValidationContext.java
----------------------------------------------------------------------
diff --git a/jena-core/src/main/java/org/apache/jena/ext/xerces/impl/dv/ValidationContext.java b/jena-core/src/main/java/org/apache/jena/ext/xerces/impl/dv/ValidationContext.java
new file mode 100644
index 0000000..1ee5542
--- /dev/null
+++ b/jena-core/src/main/java/org/apache/jena/ext/xerces/impl/dv/ValidationContext.java
@@ -0,0 +1,63 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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.jena.ext.xerces.impl.dv;
+
+import java.util.Locale;
+
+/**
+ * ValidationContext has all the information required for the
+ * validation of: id, idref, entity, notation, qname
+ * 
+ * @xerces.internal 
+ *
+ * @author Sandy Gao, IBM
+ * @version $Id: ValidationContext.java 713638 2008-11-13 04:42:18Z mrglavas $
+ */
+public interface ValidationContext {
+    // whether to validate against facets
+    public boolean needFacetChecking();
+
+    // whether to do extra id/idref/entity checking
+    public boolean needExtraChecking();
+
+    // whether we need to normalize the value that is passed!
+    public boolean needToNormalize();
+
+    // are namespaces relevant in this context?
+    public boolean useNamespaces();
+
+    // entity
+    public boolean isEntityDeclared (String name);
+    public boolean isEntityUnparsed (String name);
+
+    // id
+    public boolean isIdDeclared (String name);
+    public void    addId(String name);
+
+    // idref
+    public void addIdRef(String name);
+
+    // get symbol from symbol table
+    public String getSymbol (String symbol);
+
+    // qname
+    public String getURI(String prefix);
+    
+    // Locale
+    public Locale getLocale();
+}

http://git-wip-us.apache.org/repos/asf/jena/blob/c9a7e646/jena-core/src/main/java/org/apache/jena/ext/xerces/impl/dv/XSFacets.java
----------------------------------------------------------------------
diff --git a/jena-core/src/main/java/org/apache/jena/ext/xerces/impl/dv/XSFacets.java b/jena-core/src/main/java/org/apache/jena/ext/xerces/impl/dv/XSFacets.java
new file mode 100644
index 0000000..7cc4b9a
--- /dev/null
+++ b/jena-core/src/main/java/org/apache/jena/ext/xerces/impl/dv/XSFacets.java
@@ -0,0 +1,135 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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.jena.ext.xerces.impl.dv;
+
+import java.util.Vector;
+
+import org.apache.jena.ext.xerces.impl.xs.util.XSObjectListImpl;
+import org.apache.jena.ext.xerces.xs.XSAnnotation;
+import org.apache.jena.ext.xerces.xs.XSObjectList;
+
+/**
+ * The class used to pass all facets to {@link XSSimpleType#applyFacets}.
+ *
+ * @xerces.internal 
+ *
+ * @author Sandy Gao, IBM
+ *
+ * @version $Id: XSFacets.java 699892 2008-09-28 21:08:27Z mrglavas $
+ */
+@SuppressWarnings("all")
+public class XSFacets {
+
+    /**
+     * value of length facet.
+     */
+    public int length;
+
+    /**
+     * value of minLength facet.
+     */
+    public int minLength;
+
+    /**
+     * value of maxLength facet.
+     */
+    public int maxLength;
+
+    /**
+     * value of whiteSpace facet.
+     */
+    public short whiteSpace;
+
+    /**
+     * value of totalDigits facet.
+     */
+    public int totalDigits;
+
+    /**
+     * value of fractionDigits facet.
+     */
+    public int fractionDigits;
+
+    /**
+     * string containing value of pattern facet, for multiple patterns values
+     * are ORed together.
+     */
+    public String pattern;
+
+    /**
+     * Vector containing values of Enumeration facet, as String's.
+     */
+    public Vector enumeration;
+
+    /**
+     * An array parallel to "Vector enumeration". It contains namespace context
+     * of each enumeration value. Elements of this vector are NamespaceContext
+     * objects.
+     */
+    public Vector enumNSDecls;
+
+    /**
+     * value of maxInclusive facet.
+     */
+    public String maxInclusive;
+
+    /**
+     * value of maxExclusive facet.
+     */
+    public String maxExclusive;
+
+    /**
+     * value of minInclusive facet.
+     */
+    public String minInclusive;
+
+    /**
+     * value of minExclusive facet.
+     */
+    public String minExclusive;
+    
+    
+   
+    public XSAnnotation lengthAnnotation;
+    public XSAnnotation minLengthAnnotation;
+    public XSAnnotation maxLengthAnnotation;
+    public XSAnnotation whiteSpaceAnnotation;
+    public XSAnnotation totalDigitsAnnotation;
+    public XSAnnotation fractionDigitsAnnotation;
+    public XSObjectListImpl patternAnnotations;
+    public XSObjectList enumAnnotations;
+    public XSAnnotation maxInclusiveAnnotation;
+    public XSAnnotation maxExclusiveAnnotation;
+    public XSAnnotation minInclusiveAnnotation;
+    public XSAnnotation minExclusiveAnnotation;
+    
+    public void reset(){
+        lengthAnnotation = null;
+        minLengthAnnotation = null;
+        maxLengthAnnotation = null;
+        whiteSpaceAnnotation = null;
+        totalDigitsAnnotation = null;
+        fractionDigitsAnnotation = null;
+        patternAnnotations = null;
+        enumAnnotations = null;
+        maxInclusiveAnnotation = null;
+        maxExclusiveAnnotation = null;
+        minInclusiveAnnotation = null;
+        minExclusiveAnnotation = null;
+    }
+}

http://git-wip-us.apache.org/repos/asf/jena/blob/c9a7e646/jena-core/src/main/java/org/apache/jena/ext/xerces/impl/dv/XSSimpleType.java
----------------------------------------------------------------------
diff --git a/jena-core/src/main/java/org/apache/jena/ext/xerces/impl/dv/XSSimpleType.java b/jena-core/src/main/java/org/apache/jena/ext/xerces/impl/dv/XSSimpleType.java
new file mode 100644
index 0000000..5a4d26a
--- /dev/null
+++ b/jena-core/src/main/java/org/apache/jena/ext/xerces/impl/dv/XSSimpleType.java
@@ -0,0 +1,201 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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.jena.ext.xerces.impl.dv;
+
+import org.apache.jena.ext.xerces.xs.XSSimpleTypeDefinition;
+
+/**
+ * This interface <code>XSSimpleType</code> represents the simple type
+ * definition of schema component and defines methods to query the information
+ * contained.
+ * Any simple type (atomic, list or union) will implement this interface.
+ * It inherits from <code>XSTypeDecl</code>.
+ *
+ * @xerces.internal 
+ *
+ * @author Sandy Gao, IBM
+ *
+ * @version $Id: XSSimpleType.java 446751 2006-09-15 21:54:06Z mrglavas $
+ */
+public interface XSSimpleType extends XSSimpleTypeDefinition {
+
+    /**
+     * constants defined for the values of 'whitespace' facet.
+     * see <a href='http://www.w3.org/TR/xmlschema-2/#dt-whiteSpace'> XML Schema
+     * Part 2: Datatypes </a>
+     */
+    /** preserve the white spaces */
+    public static final short WS_PRESERVE = 0;
+    /** replace the white spaces */
+    public static final short WS_REPLACE  = 1;
+    /** collapse the white spaces */
+    public static final short WS_COLLAPSE = 2;
+
+    /**
+     * Constant defined for the primitive built-in simple tpyes.
+     * see <a href='http://www.w3.org/TR/xmlschema-2/#built-in-primitive-datatypes'>
+     * XML Schema Part 2: Datatypes </a>
+     */
+    /** "string" type */
+    public static final short PRIMITIVE_STRING        = 1;
+    /** "boolean" type */
+    public static final short PRIMITIVE_BOOLEAN       = 2;
+    /** "decimal" type */
+    public static final short PRIMITIVE_DECIMAL       = 3;
+    /** "float" type */
+    public static final short PRIMITIVE_FLOAT         = 4;
+    /** "double" type */
+    public static final short PRIMITIVE_DOUBLE        = 5;
+    /** "duration" type */
+    public static final short PRIMITIVE_DURATION      = 6;
+    /** "dataTime" type */
+    public static final short PRIMITIVE_DATETIME      = 7;
+    /** "time" type */
+    public static final short PRIMITIVE_TIME          = 8;
+    /** "date" type */
+    public static final short PRIMITIVE_DATE          = 9;
+    /** "gYearMonth" type */
+    public static final short PRIMITIVE_GYEARMONTH    = 10;
+    /** "gYear" type */
+    public static final short PRIMITIVE_GYEAR         = 11;
+    /** "gMonthDay" type */
+    public static final short PRIMITIVE_GMONTHDAY     = 12;
+    /** "gDay" type */
+    public static final short PRIMITIVE_GDAY          = 13;
+    /** "gMonth" type */
+    public static final short PRIMITIVE_GMONTH        = 14;
+    /** "hexBinary" type */
+    public static final short PRIMITIVE_HEXBINARY     = 15;
+    /** "base64Binary" type */
+    public static final short PRIMITIVE_BASE64BINARY  = 16;
+    /** "anyURI" type */
+    public static final short PRIMITIVE_ANYURI        = 17;
+    /** "QName" type */
+    public static final short PRIMITIVE_QNAME         = 18;
+    /** "precisionDecimal" type */
+    public static final short PRIMITIVE_PRECISIONDECIMAL = 19;
+    /** "NOTATION" type */
+    public static final short PRIMITIVE_NOTATION      = 20;
+
+    /**
+     * return an ID representing the built-in primitive base type.
+     * REVISIT: This method is (currently) for internal use only.
+     *          the constants returned from this method are not finalized yet.
+     *          the names and values might change in the further.
+     *
+     * @return   an ID representing the built-in primitive base type
+     */
+    public short getPrimitiveKind();
+
+    /**
+     * validate a given string against this simple type.
+     *
+     * @param content       the string value that needs to be validated
+     * @param context       the validation context
+     * @param validatedInfo used to store validation result
+     *
+     * @return              the actual value (QName, Boolean) of the string value
+     */
+    public Object validate(String content, ValidationContext context, ValidatedInfo validatedInfo)
+        throws InvalidDatatypeValueException;
+
+    /**
+     * validate a given string value, represented by content.toString().
+     * note that if content is a StringBuffer, for performance reasons,
+     * it's possible that the content of the string buffer is modified.
+     *
+     * @param content       the string value that needs to be validated
+     * @param context       the validation context
+     * @param validatedInfo used to store validation result
+     *
+     * @return              the actual value (QName, Boolean) of the string value
+     */
+    public Object validate(Object content, ValidationContext context, ValidatedInfo validatedInfo)
+        throws InvalidDatatypeValueException;
+
+    /**
+     * Validate an actual value against this simple type.
+     *
+     * @param context       the validation context
+     * @param validatedInfo used to provide the actual value and member types
+     * @exception InvalidDatatypeValueException  exception for invalid values.
+     */
+    public void validate(ValidationContext context, ValidatedInfo validatedInfo)
+        throws InvalidDatatypeValueException;
+
+    /**
+     * If this type is created from restriction, then some facets can be applied
+     * to the simple type. <code>XSFacets</code> is used to pass the value of
+     * different facets.
+     *
+     * @param facets        the value of all the facets
+     * @param presentFacet  bit combination value of the costraining facet
+     *                      constants which are present.
+     * @param fixedFacet    bit combination value of the costraining facet
+     *                      constants which are fixed.
+     * @param context       the validation context
+     * @exception InvalidDatatypeFacetException  exception for invalid facet values.
+     */
+    public void applyFacets(XSFacets facets, short presentFacet, short fixedFacet, ValidationContext context)
+        throws InvalidDatatypeFacetException;
+
+    /**
+     * Check whether two actual values are equal.
+     *
+     * @param value1  the first value
+     * @param value2  the second value
+     * @return        true if the two value are equal
+     */
+    public boolean isEqual(Object value1, Object value2);
+
+    /**
+     * Check the order of the two actual values. (May not be supported by all
+     * simple types.
+     * REVISIT: Andy believes that a compare() method is necessary.
+     *          I don't see the necessity for schema (the only place where we
+     *          need to compare two values is to check min/maxIn/Exclusive
+     *          facets, but we only need a private method for this case.)
+     *          But Andy thinks XPATH potentially needs this compare() method.
+     *
+     * @param value1  the first value
+     * @prarm value2  the second value
+     * @return        > 0 if value1 > value2
+     *                = 0 if value1 == value2
+     *                < = if value1 < value2
+     */
+    //public short compare(Object value1, Object value2);
+
+    /**
+     * Check whether this type is or is derived from ID.
+     * REVISIT: this method makes ID special, which is not a good design.
+     *          but since ID is not a primitive, there doesn't seem to be a
+     *          clean way of doing it except to define special method like this.
+     *
+     * @return  whether this simple type is or is derived from ID.
+     */
+    public boolean isIDType();
+
+    /**
+     * Return the whitespace corresponding to this datatype.
+     * 
+     * @return valid values are WS_PRESERVE, WS_REPLACE, WS_COLLAPSE.
+     * @exception DatatypeException
+     *                   union datatypes don't have whitespace facet associated with them
+     */
+    public short getWhitespace() throws DatatypeException;
+}

http://git-wip-us.apache.org/repos/asf/jena/blob/c9a7e646/jena-core/src/main/java/org/apache/jena/ext/xerces/impl/dv/util/Base64.java
----------------------------------------------------------------------
diff --git a/jena-core/src/main/java/org/apache/jena/ext/xerces/impl/dv/util/Base64.java b/jena-core/src/main/java/org/apache/jena/ext/xerces/impl/dv/util/Base64.java
new file mode 100644
index 0000000..5b13f5b
--- /dev/null
+++ b/jena-core/src/main/java/org/apache/jena/ext/xerces/impl/dv/util/Base64.java
@@ -0,0 +1,305 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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.jena.ext.xerces.impl.dv.util;
+
+/**
+ * This class provides encode/decode for RFC 2045 Base64 as
+ * defined by RFC 2045, N. Freed and N. Borenstein.
+ * RFC 2045: Multipurpose Internet Mail Extensions (MIME)
+ * Part One: Format of Internet Message Bodies. Reference
+ * 1996 Available at: http://www.ietf.org/rfc/rfc2045.txt
+ * This class is used by XML Schema binary format validation
+ *
+ * This implementation does not encode/decode streaming
+ * data. You need the data that you will encode/decode
+ * already on a byte arrray.
+ *
+ * @xerces.internal 
+ *
+ * @author Jeffrey Rodriguez
+ * @author Sandy Gao
+ * @version $Id: Base64.java 446747 2006-09-15 21:46:20Z mrglavas $
+ */
+public final class  Base64 {
+
+    static private final int  BASELENGTH         = 128;
+    static private final int  LOOKUPLENGTH       = 64;
+    static private final int  TWENTYFOURBITGROUP = 24;
+    static private final int  EIGHTBIT           = 8;
+    static private final int  SIXTEENBIT         = 16;
+    static private final int  SIXBIT             = 6;
+    static private final int  FOURBYTE           = 4;
+    static private final int  SIGN               = -128;
+    static private final char PAD                = '=';
+    static private final boolean fDebug          = false;
+    static final private byte [] base64Alphabet        = new byte[BASELENGTH];
+    static final private char [] lookUpBase64Alphabet  = new char[LOOKUPLENGTH];
+
+    static {
+
+        for (int i = 0; i < BASELENGTH; ++i) {
+            base64Alphabet[i] = -1;
+        }
+        for (int i = 'Z'; i >= 'A'; i--) {
+            base64Alphabet[i] = (byte) (i-'A');
+        }
+        for (int i = 'z'; i>= 'a'; i--) {
+            base64Alphabet[i] = (byte) ( i-'a' + 26);
+        }
+
+        for (int i = '9'; i >= '0'; i--) {
+            base64Alphabet[i] = (byte) (i-'0' + 52);
+        }
+
+        base64Alphabet['+']  = 62;
+        base64Alphabet['/']  = 63;
+
+        for (int i = 0; i<=25; i++)
+            lookUpBase64Alphabet[i] = (char)('A'+i);
+
+        for (int i = 26,  j = 0; i<=51; i++, j++)
+            lookUpBase64Alphabet[i] = (char)('a'+ j);
+
+        for (int i = 52,  j = 0; i<=61; i++, j++)
+            lookUpBase64Alphabet[i] = (char)('0' + j);
+        lookUpBase64Alphabet[62] = '+';
+        lookUpBase64Alphabet[63] = '/';
+
+    }
+
+    protected static boolean isWhiteSpace(char octect) {
+        return (octect == 0x20 || octect == 0xd || octect == 0xa || octect == 0x9);
+    }
+
+    protected static boolean isPad(char octect) {
+        return (octect == PAD);
+    }
+
+    protected static boolean isData(char octect) {
+        return (octect < BASELENGTH && base64Alphabet[octect] != -1);
+    }
+
+    protected static boolean isBase64(char octect) {
+        return (isWhiteSpace(octect) || isPad(octect) || isData(octect));
+    }
+
+    /**
+     * Encodes hex octects into Base64
+     *
+     * @param binaryData Array containing binaryData
+     * @return Encoded Base64 array
+     */
+    public static String encode(byte[] binaryData) {
+
+        if (binaryData == null)
+            return null;
+
+        int      lengthDataBits    = binaryData.length*EIGHTBIT;
+        if (lengthDataBits == 0) {
+            return "";
+        }
+        
+        int      fewerThan24bits   = lengthDataBits%TWENTYFOURBITGROUP;
+        int      numberTriplets    = lengthDataBits/TWENTYFOURBITGROUP;
+        int      numberQuartet     = fewerThan24bits != 0 ? numberTriplets+1 : numberTriplets;
+        char     encodedData[]     = null;
+
+        encodedData = new char[numberQuartet*4];
+
+        byte k=0, l=0, b1=0,b2=0,b3=0;
+
+        int encodedIndex = 0;
+        int dataIndex   = 0;
+        if (fDebug) {
+            System.out.println("number of triplets = " + numberTriplets );
+        }
+
+        for (int i=0; i<numberTriplets; i++) {
+            b1 = binaryData[dataIndex++];
+            b2 = binaryData[dataIndex++];
+            b3 = binaryData[dataIndex++];
+
+            if (fDebug) {
+                System.out.println( "b1= " + b1 +", b2= " + b2 + ", b3= " + b3 );
+            }
+
+            l  = (byte)(b2 & 0x0f);
+            k  = (byte)(b1 & 0x03);
+
+            byte val1 = ((b1 & SIGN)==0)?(byte)(b1>>2):(byte)((b1)>>2^0xc0);
+
+            byte val2 = ((b2 & SIGN)==0)?(byte)(b2>>4):(byte)((b2)>>4^0xf0);
+            byte val3 = ((b3 & SIGN)==0)?(byte)(b3>>6):(byte)((b3)>>6^0xfc);
+
+            if (fDebug) {
+                System.out.println( "val2 = " + val2 );
+                System.out.println( "k4   = " + (k<<4));
+                System.out.println( "vak  = " + (val2 | (k<<4)));
+            }
+
+            encodedData[encodedIndex++] = lookUpBase64Alphabet[ val1 ];
+            encodedData[encodedIndex++] = lookUpBase64Alphabet[ val2 | ( k<<4 )];
+            encodedData[encodedIndex++] = lookUpBase64Alphabet[ (l <<2 ) | val3 ];
+            encodedData[encodedIndex++] = lookUpBase64Alphabet[ b3 & 0x3f ];
+        }
+
+        // form integral number of 6-bit groups
+        if (fewerThan24bits == EIGHTBIT) {
+            b1 = binaryData[dataIndex];
+            k = (byte) ( b1 &0x03 );
+            if (fDebug) {
+                System.out.println("b1=" + b1);
+                System.out.println("b1<<2 = " + (b1>>2) );
+            }
+            byte val1 = ((b1 & SIGN)==0)?(byte)(b1>>2):(byte)((b1)>>2^0xc0);
+            encodedData[encodedIndex++] = lookUpBase64Alphabet[ val1 ];
+            encodedData[encodedIndex++] = lookUpBase64Alphabet[ k<<4 ];
+            encodedData[encodedIndex++] = PAD;
+            encodedData[encodedIndex++] = PAD;
+        } else if (fewerThan24bits == SIXTEENBIT) {
+            b1 = binaryData[dataIndex];
+            b2 = binaryData[dataIndex +1 ];
+            l = ( byte ) ( b2 &0x0f );
+            k = ( byte ) ( b1 &0x03 );
+
+            byte val1 = ((b1 & SIGN)==0)?(byte)(b1>>2):(byte)((b1)>>2^0xc0);
+            byte val2 = ((b2 & SIGN)==0)?(byte)(b2>>4):(byte)((b2)>>4^0xf0);
+
+            encodedData[encodedIndex++] = lookUpBase64Alphabet[ val1 ];
+            encodedData[encodedIndex++] = lookUpBase64Alphabet[ val2 | ( k<<4 )];
+            encodedData[encodedIndex++] = lookUpBase64Alphabet[ l<<2 ];
+            encodedData[encodedIndex++] = PAD;
+        }
+
+        return new String(encodedData);
+    }
+
+    /**
+     * Decodes Base64 data into octects
+     *
+     * @param encoded string containing Base64 data
+     * @return Array containind decoded data.
+     */
+    public static byte[] decode(String encoded) {
+
+        if (encoded == null)
+            return null;
+
+        char[] base64Data = encoded.toCharArray();
+        // remove white spaces
+        int len = removeWhiteSpace(base64Data);
+        
+        if (len%FOURBYTE != 0) {
+            return null;//should be divisible by four
+        }
+
+        int      numberQuadruple    = (len/FOURBYTE );
+
+        if (numberQuadruple == 0)
+            return new byte[0];
+
+        byte     decodedData[]      = null;
+        byte     b1=0,b2=0,b3=0,b4=0;
+        char     d1=0,d2=0,d3=0,d4=0;
+
+        int i = 0;
+        int encodedIndex = 0;
+        int dataIndex    = 0;
+        decodedData      = new byte[ (numberQuadruple)*3];
+
+        for (; i<numberQuadruple-1; i++) {
+
+            if (!isData( (d1 = base64Data[dataIndex++]) )||
+                !isData( (d2 = base64Data[dataIndex++]) )||
+                !isData( (d3 = base64Data[dataIndex++]) )||
+                !isData( (d4 = base64Data[dataIndex++]) ))
+                return null;//if found "no data" just return null
+
+            b1 = base64Alphabet[d1];
+            b2 = base64Alphabet[d2];
+            b3 = base64Alphabet[d3];
+            b4 = base64Alphabet[d4];
+
+            decodedData[encodedIndex++] = (byte)(  b1 <<2 | b2>>4 ) ;
+            decodedData[encodedIndex++] = (byte)(((b2 & 0xf)<<4 ) |( (b3>>2) & 0xf) );
+            decodedData[encodedIndex++] = (byte)( b3<<6 | b4 );
+        }
+
+        if (!isData( (d1 = base64Data[dataIndex++]) ) ||
+            !isData( (d2 = base64Data[dataIndex++]) )) {
+            return null;//if found "no data" just return null
+        }
+
+        b1 = base64Alphabet[d1];
+        b2 = base64Alphabet[d2];
+
+        d3 = base64Data[dataIndex++];
+        d4 = base64Data[dataIndex++];
+        if (!isData( (d3 ) ) ||
+            !isData( (d4 ) )) {//Check if they are PAD characters
+            if (isPad( d3 ) && isPad( d4)) {               //Two PAD e.g. 3c[Pad][Pad]
+                if ((b2 & 0xf) != 0)//last 4 bits should be zero
+                    return null;
+                byte[] tmp = new byte[ i*3 + 1 ];
+                System.arraycopy( decodedData, 0, tmp, 0, i*3 );
+                tmp[encodedIndex]   = (byte)(  b1 <<2 | b2>>4 ) ;
+                return tmp;
+            } else if (!isPad( d3) && isPad(d4)) {               //One PAD  e.g. 3cQ[Pad]
+                b3 = base64Alphabet[ d3 ];
+                if ((b3 & 0x3 ) != 0)//last 2 bits should be zero
+                    return null;
+                byte[] tmp = new byte[ i*3 + 2 ];
+                System.arraycopy( decodedData, 0, tmp, 0, i*3 );
+                tmp[encodedIndex++] = (byte)(  b1 <<2 | b2>>4 );
+                tmp[encodedIndex]   = (byte)(((b2 & 0xf)<<4 ) |( (b3>>2) & 0xf) );
+                return tmp;
+            } else {
+                return null;//an error  like "3c[Pad]r", "3cdX", "3cXd", "3cXX" where X is non data
+            }
+        } else { //No PAD e.g 3cQl
+            b3 = base64Alphabet[ d3 ];
+            b4 = base64Alphabet[ d4 ];
+            decodedData[encodedIndex++] = (byte)(  b1 <<2 | b2>>4 ) ;
+            decodedData[encodedIndex++] = (byte)(((b2 & 0xf)<<4 ) |( (b3>>2) & 0xf) );
+            decodedData[encodedIndex++] = (byte)( b3<<6 | b4 );
+
+        }
+
+        return decodedData;
+    }
+
+    /**
+     * remove WhiteSpace from MIME containing encoded Base64 data.
+     * 
+     * @param data  the byte array of base64 data (with WS)
+     * @return      the new length
+     */
+    protected static int removeWhiteSpace(char[] data) {
+        if (data == null)
+            return 0;
+
+        // count characters that's not whitespace
+        int newSize = 0;
+        int len = data.length;
+        for (int i = 0; i < len; i++) {
+            if (!isWhiteSpace(data[i]))
+                data[newSize++] = data[i];
+        }
+        return newSize;
+    }
+}

http://git-wip-us.apache.org/repos/asf/jena/blob/c9a7e646/jena-core/src/main/java/org/apache/jena/ext/xerces/impl/dv/util/ByteListImpl.java
----------------------------------------------------------------------
diff --git a/jena-core/src/main/java/org/apache/jena/ext/xerces/impl/dv/util/ByteListImpl.java b/jena-core/src/main/java/org/apache/jena/ext/xerces/impl/dv/util/ByteListImpl.java
new file mode 100644
index 0000000..5ce96f9
--- /dev/null
+++ b/jena-core/src/main/java/org/apache/jena/ext/xerces/impl/dv/util/ByteListImpl.java
@@ -0,0 +1,112 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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.jena.ext.xerces.impl.dv.util;
+
+import java.util.AbstractList;
+
+import org.apache.jena.ext.xerces.xs.XSException;
+import org.apache.jena.ext.xerces.xs.datatypes.ByteList;
+
+/**
+ * Implementation of <code>org.apache.xerces.xs.datatypes.ByteList</code>.
+ *
+ * @xerces.internal 
+ * 
+ * @author Ankit Pasricha, IBM
+ * 
+ * @version $Id: ByteListImpl.java 1024038 2010-10-18 22:06:35Z sandygao $
+ */
+@SuppressWarnings("all")
+public class ByteListImpl extends AbstractList implements ByteList {
+
+    // actually data stored in a byte array
+    protected final byte[] data;
+    
+    // canonical representation of the data
+    protected String canonical;
+    
+    public ByteListImpl(byte[] data) {
+        this.data = data;
+    }
+    
+    /**
+     * The number of <code>byte</code>s in the list. The range of 
+     * valid child object indices is 0 to <code>length-1</code> inclusive. 
+     */
+    public int getLength() {
+        return data.length;
+    }
+
+    /**
+     * Checks if the <code>byte</code> <code>item</code> is a 
+     * member of this list. 
+     * @param item  <code>byte</code> whose presence in this list 
+     *   is to be tested. 
+     * @return  True if this list contains the <code>byte</code> 
+     *   <code>item</code>. 
+     */
+    public boolean contains(byte item) {
+        for (int i = 0; i < data.length; ++i) {
+            if (data[i] == item) {
+                return true;
+            }
+        }
+        return false;
+    }
+
+    /**
+     * Returns the <code>index</code>th item in the collection. The index 
+     * starts at 0. 
+     * @param index  index into the collection. 
+     * @return  The <code>byte</code> at the <code>index</code>th 
+     *   position in the <code>ByteList</code>. 
+     * @exception XSException
+     *   INDEX_SIZE_ERR: if <code>index</code> is greater than or equal to the 
+     *   number of objects in the list.
+     */
+    public byte item(int index) 
+        throws XSException {
+        
+        if(index < 0 || index > data.length - 1) {
+            throw new XSException(XSException.INDEX_SIZE_ERR, null);
+        }
+        return data[index];
+    }
+    
+    /*
+     * List methods
+     */
+
+    public Object get(int index) {
+        if (index >= 0 && index < data.length) {
+            return new Byte(data[index]);
+        }
+        throw new IndexOutOfBoundsException("Index: " + index);
+    }
+
+    public int size() {
+        return getLength();
+    }
+    
+    public byte[] toByteArray() {
+        byte[] ret = new byte[data.length];
+        System.arraycopy(data, 0, ret, 0, data.length);
+        return ret;
+    }
+}
+

http://git-wip-us.apache.org/repos/asf/jena/blob/c9a7e646/jena-core/src/main/java/org/apache/jena/ext/xerces/impl/dv/util/HexBin.java
----------------------------------------------------------------------
diff --git a/jena-core/src/main/java/org/apache/jena/ext/xerces/impl/dv/util/HexBin.java b/jena-core/src/main/java/org/apache/jena/ext/xerces/impl/dv/util/HexBin.java
new file mode 100644
index 0000000..4dce68b
--- /dev/null
+++ b/jena-core/src/main/java/org/apache/jena/ext/xerces/impl/dv/util/HexBin.java
@@ -0,0 +1,113 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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.jena.ext.xerces.impl.dv.util;
+
+/**
+ * format validation
+ *
+ * This class encodes/decodes hexadecimal data
+ * 
+ * @xerces.internal  
+ * 
+ * @author Jeffrey Rodriguez
+ * @version $Id: HexBin.java 446747 2006-09-15 21:46:20Z mrglavas $
+ */
+public final class  HexBin {
+    static private final int  BASELENGTH   = 128;
+    static private final int  LOOKUPLENGTH = 16;
+    static final private byte [] hexNumberTable    = new byte[BASELENGTH];
+    static final private char [] lookUpHexAlphabet = new char[LOOKUPLENGTH];
+
+
+    static {
+        for (int i = 0; i < BASELENGTH; i++ ) {
+            hexNumberTable[i] = -1;
+        }
+        for ( int i = '9'; i >= '0'; i--) {
+            hexNumberTable[i] = (byte) (i-'0');
+        }
+        for ( int i = 'F'; i>= 'A'; i--) {
+            hexNumberTable[i] = (byte) ( i-'A' + 10 );
+        }
+        for ( int i = 'f'; i>= 'a'; i--) {
+           hexNumberTable[i] = (byte) ( i-'a' + 10 );
+        }
+
+        for(int i = 0; i<10; i++ ) {
+            lookUpHexAlphabet[i] = (char)('0'+i);
+        }
+        for(int i = 10; i<=15; i++ ) {
+            lookUpHexAlphabet[i] = (char)('A'+i -10);
+        }
+    }
+
+    /**
+     * Encode a byte array to hex string
+     *
+     * @param binaryData array of byte to encode
+     * @return return encoded string
+     */
+    static public String encode(byte[] binaryData) {
+        if (binaryData == null)
+            return null;
+        int lengthData   = binaryData.length;
+        int lengthEncode = lengthData * 2;
+        char[] encodedData = new char[lengthEncode];
+        int temp;
+        for (int i = 0; i < lengthData; i++) {
+            temp = binaryData[i];
+            if (temp < 0)
+                temp += 256;
+            encodedData[i*2] = lookUpHexAlphabet[temp >> 4];
+            encodedData[i*2+1] = lookUpHexAlphabet[temp & 0xf];
+        }
+        return new String(encodedData);
+    }
+
+    /**
+     * Decode hex string to a byte array
+     *
+     * @param encoded encoded string
+     * @return return array of byte to encode
+     */
+    static public byte[] decode(String encoded) {
+        if (encoded == null)
+            return null;
+        int lengthData = encoded.length();
+        if (lengthData % 2 != 0)
+            return null;
+
+        char[] binaryData = encoded.toCharArray();
+        int lengthDecode = lengthData / 2;
+        byte[] decodedData = new byte[lengthDecode];
+        byte temp1, temp2;
+        char tempChar;
+        for( int i = 0; i<lengthDecode; i++ ){
+            tempChar = binaryData[i*2];
+            temp1 = (tempChar < BASELENGTH) ? hexNumberTable[tempChar] : -1;
+            if (temp1 == -1)
+                return null;
+            tempChar = binaryData[i*2+1];
+            temp2 = (tempChar < BASELENGTH) ? hexNumberTable[tempChar] : -1;
+            if (temp2 == -1)
+                return null;
+            decodedData[i] = (byte)((temp1 << 4) | temp2);
+        }
+        return decodedData;
+    }
+}


[14/24] jena git commit: JENA-1537: Remove dependency on Xerces. Import needed code

Posted by an...@apache.org.
http://git-wip-us.apache.org/repos/asf/jena/blob/c9a7e646/jena-core/src/main/java/org/apache/jena/ext/xerces/impl/xpath/regex/RegexParser.java
----------------------------------------------------------------------
diff --git a/jena-core/src/main/java/org/apache/jena/ext/xerces/impl/xpath/regex/RegexParser.java b/jena-core/src/main/java/org/apache/jena/ext/xerces/impl/xpath/regex/RegexParser.java
new file mode 100644
index 0000000..ff9be7c
--- /dev/null
+++ b/jena-core/src/main/java/org/apache/jena/ext/xerces/impl/xpath/regex/RegexParser.java
@@ -0,0 +1,1230 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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.jena.ext.xerces.impl.xpath.regex;
+
+import java.util.Locale;
+import java.util.MissingResourceException;
+import java.util.ResourceBundle;
+import java.util.Vector;
+
+/**
+ * A Regular Expression Parser.
+ * 
+ * @xerces.internal
+ *
+ * @version $Id: RegexParser.java 1033661 2010-11-10 19:31:44Z knoaman $
+ */
+@SuppressWarnings("all")
+class RegexParser {
+    static final int T_CHAR = 0;
+    static final int T_EOF = 1;
+    static final int T_OR = 2;                  // '|'
+    static final int T_STAR = 3;                // '*'
+    static final int T_PLUS = 4;                // '+'
+    static final int T_QUESTION = 5;            // '?'
+    static final int T_LPAREN = 6;              // '('
+    static final int T_RPAREN = 7;              // ')'
+    static final int T_DOT = 8;                 // '.'
+    static final int T_LBRACKET = 9;            // '['
+    static final int T_BACKSOLIDUS = 10;        // '\'
+    static final int T_CARET = 11;              // '^'
+    static final int T_DOLLAR = 12;             // '$'
+    static final int T_LPAREN2 = 13;            // '(?:'
+    static final int T_LOOKAHEAD = 14;          // '(?='
+    static final int T_NEGATIVELOOKAHEAD = 15;  // '(?!'
+    static final int T_LOOKBEHIND = 16;         // '(?<='
+    static final int T_NEGATIVELOOKBEHIND = 17; // '(?<!'
+    static final int T_INDEPENDENT = 18;        // '(?>'
+    static final int T_SET_OPERATIONS = 19;     // '(?['
+    static final int T_POSIX_CHARCLASS_START = 20; // '[:' in a character class
+    static final int T_COMMENT = 21;            // '(?#'
+    static final int T_MODIFIERS = 22;          // '(?' [\-,a-z,A-Z]
+    static final int T_CONDITION = 23;          // '(?('
+    static final int T_XMLSCHEMA_CC_SUBTRACTION = 24; // '-[' in a character class
+
+    static class ReferencePosition {
+        int refNumber;
+        int position;
+        ReferencePosition(int n, int pos) {
+            this.refNumber = n;
+            this.position = pos;
+        }
+    }
+
+    int offset;
+    String regex;
+    int regexlen;
+    int options;
+    ResourceBundle resources;
+    int chardata;
+    int nexttoken;
+    static protected final int S_NORMAL = 0;
+    static protected final int S_INBRACKETS = 1;
+    static protected final int S_INXBRACKETS = 2;
+    int context = S_NORMAL;
+    int parenOpened = 1;
+    int parennumber = 1;
+    boolean hasBackReferences;
+    Vector references = null;
+
+    public RegexParser() {
+        this.setLocale(Locale.getDefault());
+    }
+    public RegexParser(Locale locale) {
+        this.setLocale(locale);
+    }
+
+    public void setLocale(Locale locale) {
+        try {
+            if (locale != null) {
+                this.resources = ResourceBundle.getBundle("org.apache.jena.ext.xerces.impl.xpath.regex.message", locale);
+            }
+            else {
+                this.resources = ResourceBundle.getBundle("org.apache.jena.ext.xerces.impl.xpath.regex.message");
+            }
+        } 
+        catch (MissingResourceException mre) {
+            throw new RuntimeException("Installation Problem???  Couldn't load messages: "
+                                       + mre.getMessage());
+        }
+    }
+
+    final ParseException ex(String key, int loc) {
+        return new ParseException(this.resources.getString(key), loc);
+    }
+
+    protected final boolean isSet(int flag) {
+        return (this.options & flag) == flag;
+    }
+
+    synchronized Token parse(String regex, int options) throws ParseException {
+        this.options = options;
+        this.offset = 0;
+        this.setContext(S_NORMAL);
+        this.parennumber = 1;
+        this.parenOpened = 1;
+        this.hasBackReferences = false;
+        this.regex = regex;
+        if (this.isSet(RegularExpression.EXTENDED_COMMENT))
+            this.regex = REUtil.stripExtendedComment(this.regex);
+        this.regexlen = this.regex.length();
+
+
+        this.next();
+        Token ret = this.parseRegex();
+        if (this.offset != this.regexlen)
+            throw ex("parser.parse.1", this.offset);
+        if (this.references != null) {
+            for (int i = 0;  i < this.references.size();  i ++) {
+                ReferencePosition position = (ReferencePosition)this.references.elementAt(i);
+                if (this.parennumber <= position.refNumber)
+                    throw ex("parser.parse.2", position.position);
+            }
+            this.references.removeAllElements();
+        }
+        return ret;
+    }
+
+    /*
+    public RegularExpression createRegex(String regex, int options) throws ParseException {
+        Token tok = this.parse(regex, options);
+        return new RegularExpression(regex, tok, this.parennumber, this.hasBackReferences, options);
+    }
+    */
+
+    protected final void setContext(int con) {
+        this.context = con;
+    }
+
+    final int read() {
+        return this.nexttoken;
+    }
+
+    final void next() {
+        if (this.offset >= this.regexlen) {
+            this.chardata = -1;
+            this.nexttoken = T_EOF;
+            return;
+        }
+
+        int ret;
+        int ch = this.regex.charAt(this.offset++);
+        this.chardata = ch;
+
+        if (this.context == S_INBRACKETS) {
+            // In a character class, this.chardata has one character, that is to say,
+            // a pair of surrogates is composed and stored to this.chardata.
+            switch (ch) {
+              case '\\':
+                ret = T_BACKSOLIDUS;
+                if (this.offset >= this.regexlen)
+                    throw ex("parser.next.1", this.offset-1);
+                this.chardata = this.regex.charAt(this.offset++);
+                break;
+
+              case '-':
+                // Allow character class subtraction (regardless of whether we are in
+                // XML Schema mode or not)
+                if (this.offset < this.regexlen && this.regex.charAt(this.offset) == '[') {
+                    this.offset++;
+                    ret = T_XMLSCHEMA_CC_SUBTRACTION;
+                } else
+                    ret = T_CHAR;
+                break;
+
+              case '[':
+                if (!this.isSet(RegularExpression.XMLSCHEMA_MODE)
+                    && this.offset < this.regexlen && this.regex.charAt(this.offset) == ':') {
+                    this.offset++;
+                    ret = T_POSIX_CHARCLASS_START;
+                    break;
+                } // Through down
+              default:
+                if (REUtil.isHighSurrogate(ch) && this.offset < this.regexlen) {
+                    int low = this.regex.charAt(this.offset);
+                    if (REUtil.isLowSurrogate(low)) {
+                        this.chardata = REUtil.composeFromSurrogates(ch, low);
+                        this.offset ++;
+                    }
+                }
+                ret = T_CHAR;
+            }
+            this.nexttoken = ret;
+            return;
+        }
+
+        switch (ch) {
+          case '|': ret = T_OR;             break;
+          case '*': ret = T_STAR;           break;
+          case '+': ret = T_PLUS;           break;
+          case '?': ret = T_QUESTION;       break;
+          case ')': ret = T_RPAREN;         break;
+          case '.': ret = T_DOT;            break;
+          case '[': ret = T_LBRACKET;       break;
+          case '^':
+              if (this.isSet(RegularExpression.XMLSCHEMA_MODE)) {
+                  ret = T_CHAR;
+              }
+              else {
+                  ret = T_CARET;
+              }
+              break;
+          case '$': 
+              if (this.isSet(RegularExpression.XMLSCHEMA_MODE)) {
+                  ret = T_CHAR;
+              }
+              else {
+                  ret = T_DOLLAR;
+              }
+              break;
+          case '(':
+            ret = T_LPAREN;
+            if (this.offset >= this.regexlen)
+                break;
+            if (this.regex.charAt(this.offset) != '?')
+                break;
+            if (++this.offset >= this.regexlen)
+                throw ex("parser.next.2", this.offset-1);
+            ch = this.regex.charAt(this.offset++);
+            switch (ch) {
+              case ':':  ret = T_LPAREN2;            break;
+              case '=':  ret = T_LOOKAHEAD;          break;
+              case '!':  ret = T_NEGATIVELOOKAHEAD;  break;
+              case '[':  ret = T_SET_OPERATIONS;     break;
+              case '>':  ret = T_INDEPENDENT;        break;
+              case '<':
+                if (this.offset >= this.regexlen)
+                    throw ex("parser.next.2", this.offset-3);
+                ch = this.regex.charAt(this.offset++);
+                if (ch == '=') {
+                    ret = T_LOOKBEHIND;
+                } else if (ch == '!') {
+                    ret = T_NEGATIVELOOKBEHIND;
+                } else
+                    throw ex("parser.next.3", this.offset-3);
+                break;
+              case '#':
+                while (this.offset < this.regexlen) {
+                    ch = this.regex.charAt(this.offset++);
+                    if (ch == ')')  break;
+                }
+                if (ch != ')')
+                    throw ex("parser.next.4", this.offset-1);
+                ret = T_COMMENT;
+                break;
+              default:
+                if (ch == '-' || 'a' <= ch && ch <= 'z' || 'A' <= ch && ch <= 'Z') {// Options
+                    this.offset --;
+                    ret = T_MODIFIERS;
+                    break;
+                } else if (ch == '(') {         // conditional
+                    ret = T_CONDITION;          // this.offsets points the next of '('.
+                    break;
+                }
+                throw ex("parser.next.2", this.offset-2);
+            }
+            break;
+            
+          case '\\':
+            ret = T_BACKSOLIDUS;
+            if (this.offset >= this.regexlen)
+                throw ex("parser.next.1", this.offset-1);
+            this.chardata = this.regex.charAt(this.offset++);
+            break;
+
+          default:
+            ret = T_CHAR;
+        }
+        this.nexttoken = ret;
+    }
+
+    /**
+     * regex ::= term (`|` term)*
+     * term ::= factor+
+     * factor ::= ('^' | '$' | '\A' | '\Z' | '\z' | '\b' | '\B' | '\<' | '\>'
+     *            | atom (('*' | '+' | '?' | minmax ) '?'? )?)
+     *            | '(?=' regex ')'  | '(?!' regex ')'  | '(?&lt;=' regex ')'  | '(?&lt;!' regex ')'
+     * atom ::= char | '.' | range | '(' regex ')' | '(?:' regex ')' | '\' [0-9]
+     *          | '\w' | '\W' | '\d' | '\D' | '\s' | '\S' | category-block 
+     */
+    Token parseRegex() throws ParseException {
+        Token tok = this.parseTerm();
+        Token parent = null;
+        while (this.read() == T_OR) {
+            this.next();                    // '|'
+            if (parent == null) {
+                parent = Token.createUnion();
+                parent.addChild(tok);
+                tok = parent;
+            }
+            tok.addChild(this.parseTerm());
+        }
+        return tok;
+    }
+
+    /**
+     * term ::= factor+
+     */
+    Token parseTerm() throws ParseException {
+        int ch = this.read();
+        if (ch == T_OR || ch == T_RPAREN || ch == T_EOF) {
+            return Token.createEmpty();
+        } else {
+            Token tok = this.parseFactor();
+            Token concat = null;
+            while ((ch = this.read()) != T_OR && ch != T_RPAREN && ch != T_EOF) {
+                if (concat == null) {
+                    concat = Token.createConcat();
+                    concat.addChild(tok);
+                    tok = concat;
+                }
+                concat.addChild(this.parseFactor());
+                //tok = Token.createConcat(tok, this.parseFactor());
+            }
+            return tok;
+        }
+    }
+
+    // ----------------------------------------------------------------
+
+    Token processCaret() throws ParseException {
+        this.next();
+        return Token.token_linebeginning;
+    }
+    Token processDollar() throws ParseException {
+        this.next();
+        return Token.token_lineend;
+    }
+    Token processLookahead() throws ParseException {
+        this.next();
+        Token tok = Token.createLook(Token.LOOKAHEAD, this.parseRegex());
+        if (this.read() != T_RPAREN)  throw ex("parser.factor.1", this.offset-1);
+        this.next();                            // ')'
+        return tok;
+    }
+    Token processNegativelookahead() throws ParseException {
+        this.next();
+        Token tok = Token.createLook(Token.NEGATIVELOOKAHEAD, this.parseRegex());
+        if (this.read() != T_RPAREN)  throw ex("parser.factor.1", this.offset-1);
+        this.next();                            // ')'
+        return tok;
+    }
+    Token processLookbehind() throws ParseException {
+        this.next();
+        Token tok = Token.createLook(Token.LOOKBEHIND, this.parseRegex());
+        if (this.read() != T_RPAREN)  throw ex("parser.factor.1", this.offset-1);
+        this.next();                            // ')'
+        return tok;
+    }
+    Token processNegativelookbehind() throws ParseException {
+        this.next();
+        Token tok = Token.createLook(Token.NEGATIVELOOKBEHIND, this.parseRegex());
+        if (this.read() != T_RPAREN)  throw ex("parser.factor.1", this.offset-1);
+        this.next();                    // ')'
+        return tok;
+    }
+    Token processBacksolidus_A() throws ParseException {
+        this.next();
+        return Token.token_stringbeginning;
+    }
+    Token processBacksolidus_Z() throws ParseException {
+        this.next();
+        return Token.token_stringend2;
+    }
+    Token processBacksolidus_z() throws ParseException {
+        this.next();
+        return Token.token_stringend;
+    }
+    Token processBacksolidus_b() throws ParseException {
+        this.next();
+        return Token.token_wordedge;
+    }
+    Token processBacksolidus_B() throws ParseException {
+        this.next();
+        return Token.token_not_wordedge;
+    }
+    Token processBacksolidus_lt() throws ParseException {
+        this.next();
+        return Token.token_wordbeginning;
+    }
+    Token processBacksolidus_gt() throws ParseException {
+        this.next();
+        return Token.token_wordend;
+    }
+    Token processStar(Token tok) throws ParseException {
+        this.next();
+        if (this.read() == T_QUESTION) {
+            this.next();
+            return Token.createNGClosure(tok);
+        } else
+            return Token.createClosure(tok);
+    }
+    Token processPlus(Token tok) throws ParseException {
+        // X+ -> XX*
+        this.next();
+        if (this.read() == T_QUESTION) {
+            this.next();
+            return Token.createConcat(tok, Token.createNGClosure(tok));
+        } else
+            return Token.createConcat(tok, Token.createClosure(tok));
+    }
+    Token processQuestion(Token tok) throws ParseException {
+        // X? -> X|
+        this.next();
+        Token par = Token.createUnion();
+        if (this.read() == T_QUESTION) {
+            this.next();
+            par.addChild(Token.createEmpty());
+            par.addChild(tok);
+        } else {
+            par.addChild(tok);
+            par.addChild(Token.createEmpty());
+        }
+        return par;
+    }
+    boolean checkQuestion(int off) {
+        return off < this.regexlen && this.regex.charAt(off) == '?';
+    }
+    Token processParen() throws ParseException {
+        this.next();
+        int p = this.parenOpened++;
+        Token tok = Token.createParen(this.parseRegex(), p);
+        if (this.read() != T_RPAREN)  throw ex("parser.factor.1", this.offset-1);
+        this.parennumber++;
+        this.next();                            // Skips ')'
+        return tok;
+    }
+    Token processParen2() throws ParseException {
+        this.next();
+        Token tok = Token.createParen(this.parseRegex(), 0);
+        if (this.read() != T_RPAREN)  throw ex("parser.factor.1", this.offset-1);
+        this.next();                            // Skips ')'
+        return tok;
+    }
+    Token processCondition() throws ParseException {
+                                                // this.offset points the next of '('
+        if (this.offset+1 >= this.regexlen)  throw ex("parser.factor.4", this.offset);
+                                                // Parses a condition.
+        int refno = -1;
+        Token condition = null;
+        int ch = this.regex.charAt(this.offset);
+        if ('1' <= ch && ch <= '9') {
+            refno = ch-'0';
+            int finalRefno = refno;
+            
+            if (this.parennumber <= refno)
+                throw ex("parser.parse.2", this.offset);
+
+            while (this.offset + 1 < this.regexlen) {
+                ch = this.regex.charAt(this.offset + 1);
+                if ('0' <= ch && ch <= '9') {
+                    refno = (refno * 10) + (ch - '0');
+                    if (refno < this.parennumber) {
+                        finalRefno= refno;
+                        ++this.offset;
+                    }
+                    else {
+                        break;
+                    }
+                }
+                else {
+                    break;
+                }
+            }
+
+            this.hasBackReferences = true;
+            if (this.references == null)  this.references = new Vector();
+            this.references.addElement(new ReferencePosition(finalRefno, this.offset));
+            this.offset ++;
+            if (this.regex.charAt(this.offset) != ')')  throw ex("parser.factor.1", this.offset);
+            this.offset ++;
+        } else {
+            if (ch == '?')  this.offset --; // Points '('.
+            this.next();
+            condition = this.parseFactor();
+            switch (condition.type) {
+              case Token.LOOKAHEAD:
+              case Token.NEGATIVELOOKAHEAD:
+              case Token.LOOKBEHIND:
+              case Token.NEGATIVELOOKBEHIND:
+                break;
+              case Token.ANCHOR:
+                if (this.read() != T_RPAREN)  throw ex("parser.factor.1", this.offset-1);
+                break;
+              default:
+                throw ex("parser.factor.5", this.offset);
+            }
+        }
+                                                // Parses yes/no-patterns.
+        this.next();
+        Token yesPattern = this.parseRegex();
+        Token noPattern = null;
+        if (yesPattern.type == Token.UNION) {
+            if (yesPattern.size() != 2)  throw ex("parser.factor.6", this.offset);
+            noPattern = yesPattern.getChild(1);
+            yesPattern = yesPattern.getChild(0);
+        }
+        if (this.read() != T_RPAREN)  throw ex("parser.factor.1", this.offset-1);
+        this.next();
+        return Token.createCondition(refno, condition, yesPattern, noPattern);
+    }
+    Token processModifiers() throws ParseException {
+                                                // this.offset points the next of '?'.
+                                                // modifiers ::= [imsw]* ('-' [imsw]*)? ':'
+        int add = 0, mask = 0, ch = -1;
+        while (this.offset < this.regexlen) {
+            ch = this.regex.charAt(this.offset);
+            int v = REUtil.getOptionValue(ch);
+            if (v == 0)  break;                 // '-' or ':'?
+            add |= v;
+            this.offset ++;
+        }
+        if (this.offset >= this.regexlen)  throw ex("parser.factor.2", this.offset-1);
+        if (ch == '-') {
+            this.offset ++;
+            while (this.offset < this.regexlen) {
+                ch = this.regex.charAt(this.offset);
+                int v = REUtil.getOptionValue(ch);
+                if (v == 0)  break;             // ':'?
+                mask |= v;
+                this.offset ++;
+            }
+            if (this.offset >= this.regexlen)  throw ex("parser.factor.2", this.offset-1);
+        }
+        Token tok;
+        if (ch == ':') {
+            this.offset ++;
+            this.next();
+            tok = Token.createModifierGroup(this.parseRegex(), add, mask);
+            if (this.read() != T_RPAREN)  throw ex("parser.factor.1", this.offset-1);
+            this.next();
+        } else if (ch == ')') {                 // such as (?-i)
+            this.offset ++;
+            this.next();
+            tok = Token.createModifierGroup(this.parseRegex(), add, mask);
+        } else
+            throw ex("parser.factor.3", this.offset);
+
+        return tok;
+    }
+    Token processIndependent() throws ParseException {
+        this.next();
+        Token tok = Token.createLook(Token.INDEPENDENT, this.parseRegex());
+        if (this.read() != T_RPAREN)  throw ex("parser.factor.1", this.offset-1);
+        this.next();                            // Skips ')'
+        return tok;
+    }
+    Token processBacksolidus_c() throws ParseException {
+        int ch2;                                // Must be in 0x0040-0x005f
+        if (this.offset >= this.regexlen
+            || ((ch2 = this.regex.charAt(this.offset++)) & 0xffe0) != 0x0040)
+            throw ex("parser.atom.1", this.offset-1);
+        this.next();
+        return Token.createChar(ch2-0x40);
+    }
+    Token processBacksolidus_C() throws ParseException {
+        throw ex("parser.process.1", this.offset);
+    }
+    Token processBacksolidus_i() throws ParseException {
+        Token tok = Token.createChar('i');
+        this.next();
+        return tok;
+    }
+    Token processBacksolidus_I() throws ParseException {
+        throw ex("parser.process.1", this.offset);
+    }
+    Token processBacksolidus_g() throws ParseException {
+        this.next();
+        return Token.getGraphemePattern();
+    }
+    Token processBacksolidus_X() throws ParseException {
+        this.next();
+        return Token.getCombiningCharacterSequence();
+    }
+    Token processBackreference() throws ParseException {
+        int refnum = this.chardata-'0';
+        int finalRefnum = refnum;
+
+        if (this.parennumber <= refnum)
+            throw ex("parser.parse.2", this.offset-2);
+
+        while  (this.offset < this.regexlen) {
+            final int ch = this.regex.charAt(this.offset);
+            if ('0' <= ch && ch <= '9') {
+                refnum = (refnum * 10) + (ch - '0');
+                if (refnum < this.parennumber) {
+                    ++this.offset;
+                    finalRefnum = refnum;
+                    this.chardata = ch;
+                }
+                else {
+                    break;
+                }
+            }
+            else {
+                break;
+            }
+        }
+
+        Token tok = Token.createBackReference(finalRefnum);
+        this.hasBackReferences = true;
+        if (this.references == null)  this.references = new Vector();
+        this.references.addElement(new ReferencePosition(finalRefnum, this.offset-2));
+        this.next();
+        return tok;
+    }
+
+    // ----------------------------------------------------------------
+
+    /**
+     * factor ::= ('^' | '$' | '\A' | '\Z' | '\z' | '\b' | '\B' | '\<' | '\>'
+     *            | atom (('*' | '+' | '?' | minmax ) '?'? )?)
+     *            | '(?=' regex ')'  | '(?!' regex ')'  | '(?&lt;=' regex ')'  | '(?&lt;!' regex ')'
+     *            | '(?#' [^)]* ')'
+     * minmax ::= '{' min (',' max?)? '}'
+     * min ::= [0-9]+
+     * max ::= [0-9]+
+     */
+    Token parseFactor() throws ParseException {        
+        int ch = this.read();
+        Token tok;
+        switch (ch) {
+          case T_CARET:         return this.processCaret();
+          case T_DOLLAR:        return this.processDollar();
+          case T_LOOKAHEAD:     return this.processLookahead();
+          case T_NEGATIVELOOKAHEAD: return this.processNegativelookahead();
+          case T_LOOKBEHIND:    return this.processLookbehind();
+          case T_NEGATIVELOOKBEHIND: return this.processNegativelookbehind();
+
+          case T_COMMENT:
+            this.next();
+            return Token.createEmpty();
+
+          case T_BACKSOLIDUS:
+            switch (this.chardata) {
+              case 'A': return this.processBacksolidus_A();
+              case 'Z': return this.processBacksolidus_Z();
+              case 'z': return this.processBacksolidus_z();
+              case 'b': return this.processBacksolidus_b();
+              case 'B': return this.processBacksolidus_B();
+              case '<': return this.processBacksolidus_lt();
+              case '>': return this.processBacksolidus_gt();
+            }
+                                                // through down
+        }
+        tok = this.parseAtom();
+        ch = this.read();
+        switch (ch) {
+          case T_STAR:  return this.processStar(tok);
+          case T_PLUS:  return this.processPlus(tok);
+          case T_QUESTION: return this.processQuestion(tok);
+          case T_CHAR:
+            if (this.chardata == '{' && this.offset < this.regexlen) {
+
+                int off = this.offset;          // this.offset -> next of '{'
+                int min = 0, max = -1;
+
+                if ((ch = this.regex.charAt(off++)) >= '0' && ch <= '9') {
+
+                    min = ch -'0';
+                    while (off < this.regexlen
+                           && (ch = this.regex.charAt(off++)) >= '0' && ch <= '9') {
+                        min = min*10 +ch-'0';
+                        if (min < 0)
+                            throw ex("parser.quantifier.5", this.offset);
+                    }
+                }
+                else {
+                    throw ex("parser.quantifier.1", this.offset);
+                }
+
+                max = min;
+                if (ch == ',') {
+
+                   if (off >= this.regexlen) {
+                       throw ex("parser.quantifier.3", this.offset);
+                   }
+                   else if ((ch = this.regex.charAt(off++)) >= '0' && ch <= '9') {                       
+
+                        max = ch -'0';       // {min,max}
+                        while (off < this.regexlen
+                               && (ch = this.regex.charAt(off++)) >= '0'
+                               && ch <= '9') {
+                            max = max*10 +ch-'0';
+                            if (max < 0)
+                                throw ex("parser.quantifier.5", this.offset);
+                        }
+
+                        if (min > max)
+                            throw ex("parser.quantifier.4", this.offset);
+                   }
+                   else { // assume {min,}
+                        max = -1;           
+                    }
+                }
+
+               if (ch != '}')
+                   throw ex("parser.quantifier.2", this.offset);
+
+               if (this.checkQuestion(off)) {  // off -> next of '}'
+                    tok = Token.createNGClosure(tok);
+                    this.offset = off+1;
+                } else {
+                    tok = Token.createClosure(tok);
+                    this.offset = off;
+                }
+
+                tok.setMin(min);
+                tok.setMax(max);
+                //System.err.println("CLOSURE: "+min+", "+max);
+                this.next();
+            }
+        }
+        return tok;
+    }
+
+    /**
+     * atom ::= char | '.' | char-class | '(' regex ')' | '(?:' regex ')' | '\' [0-9]
+     *          | '\w' | '\W' | '\d' | '\D' | '\s' | '\S' | category-block
+     *          | '(?>' regex ')'
+     * char ::= '\\' | '\' [efnrt] | bmp-code | character-1
+     */
+    Token parseAtom() throws ParseException {
+        int ch = this.read();
+        Token tok = null;
+        switch (ch) {
+          case T_LPAREN:        return this.processParen();
+          case T_LPAREN2:       return this.processParen2(); // '(?:'
+          case T_CONDITION:     return this.processCondition(); // '(?('
+          case T_MODIFIERS:     return this.processModifiers(); // (?modifiers ... )
+          case T_INDEPENDENT:   return this.processIndependent();
+          case T_DOT:
+            this.next();                    // Skips '.'
+            tok = Token.token_dot;
+            break;
+
+            /**
+             * char-class ::= '[' ( '^'? range ','?)+ ']'
+             * range ::= '\d' | '\w' | '\s' | category-block | range-char
+             *           | range-char '-' range-char
+             * range-char ::= '\[' | '\]' | '\\' | '\' [,-efnrtv] | bmp-code | character-2
+             * bmp-char ::= '\' 'u' [0-9a-fA-F] [0-9a-fA-F] [0-9a-fA-F] [0-9a-fA-F]
+             */
+          case T_LBRACKET:      return this.parseCharacterClass(true);
+          case T_SET_OPERATIONS: return this.parseSetOperations();
+
+          case T_BACKSOLIDUS:
+            switch (this.chardata) {
+              case 'd':  case 'D':
+              case 'w':  case 'W':
+              case 's':  case 'S':
+                tok = this.getTokenForShorthand(this.chardata);
+                this.next();
+                return tok;
+
+              case 'e':  case 'f':  case 'n':  case 'r':
+              case 't':  case 'u':  case 'v':  case 'x':
+                {
+                    int ch2 = this.decodeEscaped();
+                    if (ch2 < 0x10000) {
+                        tok = Token.createChar(ch2);
+                    } else {
+                        tok = Token.createString(REUtil.decomposeToSurrogates(ch2));
+                    }
+                }
+                break;
+
+              case 'c': return this.processBacksolidus_c();
+              case 'C': return this.processBacksolidus_C();
+              case 'i': return this.processBacksolidus_i();
+              case 'I': return this.processBacksolidus_I();
+              case 'g': return this.processBacksolidus_g();
+              case 'X': return this.processBacksolidus_X();
+              case '1':  case '2':  case '3':  case '4':
+              case '5':  case '6':  case '7':  case '8':  case '9':
+                return this.processBackreference();
+
+              case 'P':
+              case 'p':
+                int pstart = this.offset;
+                tok = processBacksolidus_pP(this.chardata);
+                if (tok == null)  throw this.ex("parser.atom.5", pstart);
+                break;
+
+              default:
+                tok = Token.createChar(this.chardata);
+            }
+            this.next();
+            break;
+
+          case T_CHAR:
+            if (this.chardata == ']' || this.chardata == '{' || this.chardata == '}')
+                throw this.ex("parser.atom.4", this.offset-1);
+            tok = Token.createChar(this.chardata);
+            int high = this.chardata;
+            this.next();
+            if (REUtil.isHighSurrogate(high)
+                && this.read() == T_CHAR && REUtil.isLowSurrogate(this.chardata)) {
+                char[] sur = new char[2];
+                sur[0] = (char)high;
+                sur[1] = (char)this.chardata;
+                tok = Token.createParen(Token.createString(new String(sur)), 0);
+                this.next();
+            }
+            break;
+
+          default:
+            throw this.ex("parser.atom.4", this.offset-1);
+        }
+        return tok;
+    }
+
+    protected RangeToken processBacksolidus_pP(int c) throws ParseException {
+
+        this.next();
+        if (this.read() != T_CHAR || this.chardata != '{')
+            throw this.ex("parser.atom.2", this.offset-1);
+
+        // handle category escape
+        boolean positive = c == 'p';
+        int namestart = this.offset;
+        int nameend = this.regex.indexOf('}', namestart);
+
+        if (nameend < 0)
+            throw this.ex("parser.atom.3", this.offset);
+
+        String pname = this.regex.substring(namestart, nameend);
+        this.offset = nameend+1;
+
+        return Token.getRange(pname, positive, this.isSet(RegularExpression.XMLSCHEMA_MODE));
+    }
+
+    int processCIinCharacterClass(RangeToken tok, int c) {
+        return this.decodeEscaped();
+    }
+
+    /**
+     * char-class ::= '[' ( '^'? range ','?)+ ']'
+     * range ::= '\d' | '\w' | '\s' | category-block | range-char
+     *           | range-char '-' range-char
+     * range-char ::= '\[' | '\]' | '\\' | '\' [,-efnrtv] | bmp-code | character-2
+     * bmp-code ::= '\' 'u' [0-9a-fA-F] [0-9a-fA-F] [0-9a-fA-F] [0-9a-fA-F]
+     */
+    protected RangeToken parseCharacterClass(boolean useNrange) throws ParseException {
+        this.setContext(S_INBRACKETS);
+        this.next();                            // '['
+        boolean nrange = false;
+        RangeToken base = null;
+        RangeToken tok;
+        if (this.read() == T_CHAR && this.chardata == '^') {
+            nrange = true;
+            this.next();                        // '^'
+            if (useNrange) {
+                tok = Token.createNRange();
+            } else {
+                base = Token.createRange();
+                base.addRange(0, Token.UTF16_MAX);
+                tok = Token.createRange();
+            }
+        } else {
+            tok = Token.createRange();
+        }
+        int type;
+        boolean firstloop = true;
+        while ((type = this.read()) != T_EOF) {
+            if (type == T_CHAR && this.chardata == ']' && !firstloop)
+                break;
+            int c = this.chardata;
+            boolean end = false;
+            if (type == T_BACKSOLIDUS) {
+                switch (c) {
+                  case 'd':  case 'D':
+                  case 'w':  case 'W':
+                  case 's':  case 'S':
+                    tok.mergeRanges(this.getTokenForShorthand(c));
+                    end = true;
+                    break;
+
+                  case 'i':  case 'I':
+                  case 'c':  case 'C':
+                    c = this.processCIinCharacterClass(tok, c);
+                    if (c < 0)  end = true;
+                    break;
+                    
+                  case 'p':
+                  case 'P':
+                    int pstart = this.offset;
+                    RangeToken tok2 = this.processBacksolidus_pP(c);
+                    if (tok2 == null)  throw this.ex("parser.atom.5", pstart);
+                    tok.mergeRanges(tok2);
+                    end = true;
+                    break;
+
+                  default:
+                    c = this.decodeEscaped();
+                } // \ + c
+            } // backsolidus
+                                                // POSIX Character class such as [:alnum:]
+            else if (type == T_POSIX_CHARCLASS_START) {
+                int nameend = this.regex.indexOf(':', this.offset);
+                if (nameend < 0) throw this.ex("parser.cc.1", this.offset);
+                boolean positive = true;
+                if (this.regex.charAt(this.offset) == '^') {
+                    this.offset ++;
+                    positive = false;
+                }
+                String name = this.regex.substring(this.offset, nameend);
+                RangeToken range = Token.getRange(name, positive,
+                                                  this.isSet(RegularExpression.XMLSCHEMA_MODE));
+                if (range == null)  throw this.ex("parser.cc.3", this.offset);
+                tok.mergeRanges(range);
+                end = true;
+                if (nameend+1 >= this.regexlen || this.regex.charAt(nameend+1) != ']')
+                    throw this.ex("parser.cc.1", nameend);
+                this.offset = nameend+2;
+            }
+            else if (type == T_XMLSCHEMA_CC_SUBTRACTION && !firstloop) {
+                if (nrange) {
+                    nrange = false;
+                    if (useNrange) {
+                        tok = (RangeToken) Token.complementRanges(tok);
+                    }
+                    else {
+                        base.subtractRanges(tok);
+                        tok = base;
+                    }
+                }
+                RangeToken range2 = this.parseCharacterClass(false);
+                tok.subtractRanges(range2);
+                if (this.read() != T_CHAR || this.chardata != ']') {
+                    throw this.ex("parser.cc.5", this.offset);
+                }
+                break;                          // Exit this loop
+            }
+            this.next();
+            if (!end) {                         // if not shorthands...
+                if (this.read() != T_CHAR || this.chardata != '-') { // Here is no '-'.
+                    if (!this.isSet(RegularExpression.IGNORE_CASE) || c > 0xffff) {
+                        tok.addRange(c, c);
+                    }
+                    else {
+                        addCaseInsensitiveChar(tok, c);
+                    }
+                }
+                else if (type == T_XMLSCHEMA_CC_SUBTRACTION) {
+                    throw this.ex("parser.cc.8", this.offset-1);
+                }
+                else {
+                    this.next(); // Skips '-'
+                    if ((type = this.read()) == T_EOF)  throw this.ex("parser.cc.2", this.offset);
+                    if (type == T_CHAR && this.chardata == ']') {
+                        if (!this.isSet(RegularExpression.IGNORE_CASE) || c > 0xffff) {
+                            tok.addRange(c, c);
+                        }
+                        else {
+                            addCaseInsensitiveChar(tok, c);
+                        }
+                        tok.addRange('-', '-');
+                    } else {
+                        int rangeend = this.chardata;
+                        if (type == T_BACKSOLIDUS) {
+                            rangeend = this.decodeEscaped();
+                        }
+                        this.next();
+                        if (c > rangeend) {
+                            throw this.ex("parser.ope.3", this.offset-1);
+                        }
+                        if (!this.isSet(RegularExpression.IGNORE_CASE) ||
+                                (c > 0xffff && rangeend > 0xffff)) {
+                            tok.addRange(c, rangeend);
+                        }
+                        else {
+                            addCaseInsensitiveCharRange(tok, c, rangeend);
+                        }
+                    }
+                }
+            }
+            if (this.isSet(RegularExpression.SPECIAL_COMMA)
+                && this.read() == T_CHAR && this.chardata == ',') {
+                this.next();
+            }
+            firstloop = false;
+        }
+        if (this.read() == T_EOF) {
+            throw this.ex("parser.cc.2", this.offset);
+        }
+        
+        if (!useNrange && nrange) {
+            base.subtractRanges(tok);
+            tok = base;
+        }
+        tok.sortRanges();
+        tok.compactRanges();
+        this.setContext(S_NORMAL);
+        this.next();                    // Skips ']'
+
+        return tok;
+    }
+
+    /**
+     * '(?[' ... ']' (('-' | '+' | '&') '[' ... ']')? ')'
+     */
+    protected RangeToken parseSetOperations() throws ParseException {
+        RangeToken tok = this.parseCharacterClass(false);
+        int type;
+        while ((type = this.read()) != T_RPAREN) {
+            int ch = this.chardata;
+            if (type == T_CHAR && (ch == '-' || ch == '&')
+                || type == T_PLUS) {
+                this.next();
+                if (this.read() != T_LBRACKET) throw ex("parser.ope.1", this.offset-1);
+                RangeToken t2 = this.parseCharacterClass(false);
+                if (type == T_PLUS)
+                    tok.mergeRanges(t2);
+                else if (ch == '-')
+                    tok.subtractRanges(t2);
+                else if (ch == '&')
+                    tok.intersectRanges(t2);
+                else
+                    throw new RuntimeException("ASSERT");
+            } else {
+                throw ex("parser.ope.2", this.offset-1);
+            }
+        }
+        this.next();
+        return tok;
+    }
+
+    Token getTokenForShorthand(int ch) {
+        Token tok;
+        switch (ch) {
+          case 'd':
+            tok = this.isSet(RegularExpression.USE_UNICODE_CATEGORY)
+                ? Token.getRange("Nd", true) : Token.token_0to9;
+            break;
+          case 'D':
+            tok = this.isSet(RegularExpression.USE_UNICODE_CATEGORY)
+                ? Token.getRange("Nd", false) : Token.token_not_0to9;
+            break;
+          case 'w':
+            tok = this.isSet(RegularExpression.USE_UNICODE_CATEGORY)
+                ? Token.getRange("IsWord", true) : Token.token_wordchars;
+            break;
+          case 'W':
+            tok = this.isSet(RegularExpression.USE_UNICODE_CATEGORY)
+                ? Token.getRange("IsWord", false) : Token.token_not_wordchars;
+            break;
+          case 's':
+            tok = this.isSet(RegularExpression.USE_UNICODE_CATEGORY)
+                ? Token.getRange("IsSpace", true) : Token.token_spaces;
+            break;
+          case 'S':
+            tok = this.isSet(RegularExpression.USE_UNICODE_CATEGORY)
+                ? Token.getRange("IsSpace", false) : Token.token_not_spaces;
+            break;
+
+          default:
+            throw new RuntimeException("Internal Error: shorthands: \\u"+Integer.toString(ch, 16));
+        }
+        return tok;
+    }
+
+    /**
+     */
+    int decodeEscaped() throws ParseException {
+        if (this.read() != T_BACKSOLIDUS)  throw ex("parser.next.1", this.offset-1);
+        int c = this.chardata;
+        switch (c) {
+          case 'e':  c = 0x1b;  break; // ESCAPE U+001B
+          case 'f':  c = '\f';  break; // FORM FEED U+000C
+          case 'n':  c = '\n';  break; // LINE FEED U+000A
+          case 'r':  c = '\r';  break; // CRRIAGE RETURN U+000D
+          case 't':  c = '\t';  break; // HORIZONTAL TABULATION U+0009
+          //case 'v':  c = 0x0b;  break; // VERTICAL TABULATION U+000B
+          case 'x':
+            this.next();
+            if (this.read() != T_CHAR)  throw ex("parser.descape.1", this.offset-1);
+            if (this.chardata == '{') {
+                int v1 = 0;
+                int uv = 0;
+                do {
+                    this.next();
+                    if (this.read() != T_CHAR)  throw ex("parser.descape.1", this.offset-1);
+                    if ((v1 = hexChar(this.chardata)) < 0)
+                        break;
+                    if (uv > uv*16) throw ex("parser.descape.2", this.offset-1);
+                    uv = uv*16+v1;
+                } while (true);
+                if (this.chardata != '}')  throw ex("parser.descape.3", this.offset-1);
+                if (uv > Token.UTF16_MAX)  throw ex("parser.descape.4", this.offset-1);
+                c = uv;
+            } else {
+                int v1 = 0;
+                if (this.read() != T_CHAR || (v1 = hexChar(this.chardata)) < 0)
+                    throw ex("parser.descape.1", this.offset-1);
+                int uv = v1;
+                this.next();
+                if (this.read() != T_CHAR || (v1 = hexChar(this.chardata)) < 0)
+                    throw ex("parser.descape.1", this.offset-1);
+                uv = uv*16+v1;
+                c = uv;
+            }
+            break;
+
+          case 'u':
+            int v1 = 0;
+            this.next();
+            if (this.read() != T_CHAR || (v1 = hexChar(this.chardata)) < 0)
+                throw ex("parser.descape.1", this.offset-1);
+            int uv = v1;
+            this.next();
+            if (this.read() != T_CHAR || (v1 = hexChar(this.chardata)) < 0)
+                throw ex("parser.descape.1", this.offset-1);
+            uv = uv*16+v1;
+            this.next();
+            if (this.read() != T_CHAR || (v1 = hexChar(this.chardata)) < 0)
+                throw ex("parser.descape.1", this.offset-1);
+            uv = uv*16+v1;
+            this.next();
+            if (this.read() != T_CHAR || (v1 = hexChar(this.chardata)) < 0)
+                throw ex("parser.descape.1", this.offset-1);
+            uv = uv*16+v1;
+            c = uv;
+            break;
+
+          case 'v':
+            this.next();
+            if (this.read() != T_CHAR || (v1 = hexChar(this.chardata)) < 0)
+                throw ex("parser.descape.1", this.offset-1);
+            uv = v1;
+            this.next();
+            if (this.read() != T_CHAR || (v1 = hexChar(this.chardata)) < 0)
+                throw ex("parser.descape.1", this.offset-1);
+            uv = uv*16+v1;
+            this.next();
+            if (this.read() != T_CHAR || (v1 = hexChar(this.chardata)) < 0)
+                throw ex("parser.descape.1", this.offset-1);
+            uv = uv*16+v1;
+            this.next();
+            if (this.read() != T_CHAR || (v1 = hexChar(this.chardata)) < 0)
+                throw ex("parser.descape.1", this.offset-1);
+            uv = uv*16+v1;
+            this.next();
+            if (this.read() != T_CHAR || (v1 = hexChar(this.chardata)) < 0)
+                throw ex("parser.descape.1", this.offset-1);
+            uv = uv*16+v1;
+            this.next();
+            if (this.read() != T_CHAR || (v1 = hexChar(this.chardata)) < 0)
+                throw ex("parser.descape.1", this.offset-1);
+            uv = uv*16+v1;
+            if (uv > Token.UTF16_MAX)  throw ex("parser.descappe.4", this.offset-1);
+            c = uv;
+            break;
+          case 'A':
+          case 'Z':
+          case 'z':
+            throw ex("parser.descape.5", this.offset-2);
+          default:
+        }
+        return c;
+    }
+
+    static private final int hexChar(int ch) {
+        if (ch < '0')  return -1;
+        if (ch > 'f')  return -1;
+        if (ch <= '9')  return ch-'0';
+        if (ch < 'A')  return -1;
+        if (ch <= 'F')  return ch-'A'+10;
+        if (ch < 'a')  return -1;
+        return ch-'a'+10;
+    }
+    
+    static protected final void addCaseInsensitiveChar(RangeToken tok, int c) {
+        final int[] caseMap = CaseInsensitiveMap.get(c);
+        tok.addRange(c, c);
+        
+        if (caseMap != null) {
+            for (int i=0; i<caseMap.length; i+=2) {
+                tok.addRange(caseMap[i], caseMap[i]);
+            }
+        }
+
+    }
+    
+    static protected final void addCaseInsensitiveCharRange(RangeToken tok, int start, int end) {
+        int[] caseMap;
+        int r1, r2;
+        if (start <= end) {
+            r1 = start;
+            r2 = end;
+        } else {
+            r1 = end;
+            r2 = start;
+        }
+
+        tok.addRange(r1, r2);
+        for (int ch = r1;  ch <= r2;  ch++) {
+            caseMap = CaseInsensitiveMap.get(ch);
+            if (caseMap != null) {
+                for (int i=0; i<caseMap.length; i+=2) {
+                    tok.addRange(caseMap[i], caseMap[i]);
+                }
+            }
+        }
+    }
+}


[02/24] jena git commit: JENA-1537: Remove dependency on Xerces. Import needed code

Posted by an...@apache.org.
http://git-wip-us.apache.org/repos/asf/jena/blob/c9a7e646/jena-core/src/main/resources/org/apache/jena/ext/xerces/impl/msg/XMLSchemaMessages.properties
----------------------------------------------------------------------
diff --git a/jena-core/src/main/resources/org/apache/jena/ext/xerces/impl/msg/XMLSchemaMessages.properties b/jena-core/src/main/resources/org/apache/jena/ext/xerces/impl/msg/XMLSchemaMessages.properties
new file mode 100644
index 0000000..cd8765d
--- /dev/null
+++ b/jena-core/src/main/resources/org/apache/jena/ext/xerces/impl/msg/XMLSchemaMessages.properties
@@ -0,0 +1,320 @@
+#
+# Licensed to the Apache Software Foundation (ASF) under one or more
+# contributor license agreements.  See the NOTICE file distributed with
+# this work for additional information regarding copyright ownership.
+# The ASF licenses this file to You 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.
+#
+
+# This file contains error and warning messages related to XML Schema
+# The messages are arranged in key and value tuples in a ListResourceBundle.
+#
+# @version $Id: XMLSchemaMessages.properties 806363 2009-08-20 21:18:48Z mrglavas $
+
+        BadMessageKey = The error message corresponding to the message key can not be found.
+        FormatFailed = An internal error occurred while formatting the following message:\n
+
+# For internal use
+
+        Internal-Error = Internal error: {0}.
+        dt-whitespace = Whitespace facet value is not available for the union simpleType ''{0}''
+        GrammarConflict = One of the grammar(s) returned from the user's grammar pool is in conflict with another grammar.
+
+# Identity constraints
+
+        AbsentKeyValue = cvc-identity-constraint.4.2.1.a: Element \"{0}\" has no value for the key \"{1}\".
+        DuplicateField = Duplicate match in scope for field \"{0}\".
+        DuplicateKey = cvc-identity-constraint.4.2.2: Duplicate key value [{0}] declared for identity constraint \"{2}\" of element \"{1}\".
+        DuplicateUnique = cvc-identity-constraint.4.1: Duplicate unique value [{0}] declared for identity constraint \"{2}\" of element \"{1}\".
+        FieldMultipleMatch = cvc-identity-constraint.3: Field \"{0}\" of identity constraint \"{1}\" matches more than one value within the scope of its selector; fields must match unique values.
+        FixedDiffersFromActual = The content of this element is not equivalent to the value of the \"fixed\" attribute in the element's declaration in the schema.
+        KeyMatchesNillable = cvc-identity-constraint.4.2.3: Element \"{0}\" has the key \"{1}\" which matches an element which has nillable set to true.
+        KeyNotEnoughValues = cvc-identity-constraint.4.2.1.b: Not enough values specified for <key name=\"{1}\"> identity constraint specified for element \"{0}\".
+        KeyNotFound = cvc-identity-constraint.4.3: Key ''{0}'' with value ''{1}'' not found for identity constraint of element ''{2}''.
+        KeyRefOutOfScope = Identity Constraint error:  identity constraint \"{0}\" has a keyref which refers to a key or unique that is out of scope.
+        KeyRefReferNotFound = Key reference declaration \"{0}\" refers to unknown key with name \"{1}\".
+        UnknownField = Internal identity constraint error; unknown field \"{0}\" for identity constraint \"{2}\" specified for element \"{1}\".
+
+# Ideally, we should only use the following error keys, not the ones under
+# "Identity constraints". And we should cover all of the following errors.
+
+#validation (3.X.4)
+
+        cvc-attribute.3 = cvc-attribute.3: The value ''{2}'' of attribute ''{1}'' on element ''{0}'' is not valid with respect to its type, ''{3}''.
+        cvc-attribute.4 = cvc-attribute.4: The value ''{2}'' of attribute ''{1}'' on element ''{0}'' is not valid with respect to its fixed '{'value constraint'}'. The attribute must have a value of ''{3}''.
+        cvc-complex-type.2.1 = cvc-complex-type.2.1: Element ''{0}'' must have no character or element information item [children], because the type''s content type is empty.
+        cvc-complex-type.2.2 = cvc-complex-type.2.2: Element ''{0}'' must have no element [children], and the value must be valid.
+        cvc-complex-type.2.3 = cvc-complex-type.2.3: Element ''{0}'' cannot have character [children], because the type''s content type is element-only.
+        cvc-complex-type.2.4.a = cvc-complex-type.2.4.a: Invalid content was found starting with element ''{0}''. One of ''{1}'' is expected.
+        cvc-complex-type.2.4.b = cvc-complex-type.2.4.b: The content of element ''{0}'' is not complete. One of ''{1}'' is expected.
+        cvc-complex-type.2.4.c = cvc-complex-type.2.4.c: The matching wildcard is strict, but no declaration can be found for element ''{0}''.
+        cvc-complex-type.2.4.d = cvc-complex-type.2.4.d: Invalid content was found starting with element ''{0}''. No child element is expected at this point.
+        cvc-complex-type.2.4.e = cvc-complex-type.2.4.e: ''{0}'' can occur a maximum of ''{2}'' times in the current sequence. This limit was exceeded. At this point one of ''{1}'' is expected.
+        cvc-complex-type.2.4.f = cvc-complex-type.2.4.f: ''{0}'' can occur a maximum of ''{1}'' times in the current sequence. This limit was exceeded. No child element is expected at this point.
+        cvc-complex-type.2.4.g = cvc-complex-type.2.4.g: Invalid content was found starting with element ''{0}''. ''{1}'' is expected to occur a minimum of ''{2}'' times in the current sequence. One more instance is required to satisfy this constraint.
+        cvc-complex-type.2.4.h = cvc-complex-type.2.4.h: Invalid content was found starting with element ''{0}''. ''{1}'' is expected to occur a minimum of ''{2}'' times in the current sequence. ''{3}'' more instances are required to satisfy this constraint.
+        cvc-complex-type.2.4.i = cvc-complex-type.2.4.i: The content of element ''{0}'' is not complete. ''{1}'' is expected to occur a minimum of ''{2}'' times. One more instance is required to satisfy this constraint.
+        cvc-complex-type.2.4.j = cvc-complex-type.2.4.j: The content of element ''{0}'' is not complete. ''{1}'' is expected to occur a minimum of ''{2}'' times. ''{3}'' more instances are required to satisfy this constraint.
+        cvc-complex-type.3.1 = cvc-complex-type.3.1: Value ''{2}'' of attribute ''{1}'' of element ''{0}'' is not valid with respect to the corresponding attribute use. Attribute ''{1}'' has a fixed value of ''{3}''.
+        cvc-complex-type.3.2.1 = cvc-complex-type.3.2.1: Element ''{0}'' does not have an attribute wildcard for attribute ''{1}''.
+        cvc-complex-type.3.2.2 = cvc-complex-type.3.2.2: Attribute ''{1}'' is not allowed to appear in element ''{0}''.
+        cvc-complex-type.4 = cvc-complex-type.4: Attribute ''{1}'' must appear on element ''{0}''.
+        cvc-complex-type.5.1 = cvc-complex-type.5.1: In element ''{0}'', attribute ''{1}'' is a Wild ID. But there is already a Wild ID ''{2}''. There can be only one.
+        cvc-complex-type.5.2 = cvc-complex-type.5.2: In element ''{0}'', attribute ''{1}'' is a Wild ID. But there is already an attribute ''{2}'' derived from ID among the '{'attribute uses'}'.
+        cvc-datatype-valid.1.2.1 = cvc-datatype-valid.1.2.1: ''{0}'' is not a valid value for ''{1}''.
+        cvc-datatype-valid.1.2.2 = cvc-datatype-valid.1.2.2: ''{0}'' is not a valid value of list type ''{1}''.
+        cvc-datatype-valid.1.2.3 = cvc-datatype-valid.1.2.3: ''{0}'' is not a valid value of union type ''{1}''.
+        cvc-elt.1.a = cvc-elt.1.a: Cannot find the declaration of element ''{0}''.
+        cvc-elt.1.b = cvc-elt.1.b: The name of the element does not match the name of the element declaration. Saw ''{0}''. Expected ''{1}''.
+        cvc-elt.2 = cvc-elt.2: The value of '{'abstract'}' in the element declaration for ''{0}'' must be false.
+        cvc-elt.3.1 = cvc-elt.3.1: Attribute ''{1}'' must not appear on element ''{0}'', because the '{'nillable'}' property of ''{0}'' is false.
+        cvc-elt.3.2.1 = cvc-elt.3.2.1: Element ''{0}'' cannot have character or element information [children], because ''{1}'' is specified.
+        cvc-elt.3.2.2 = cvc-elt.3.2.2: There must be no fixed '{'value constraint'}' for element ''{0}'', because ''{1}'' is specified.
+        cvc-elt.4.1 = cvc-elt.4.1: The value ''{2}'' of attribute ''{1}'' of element ''{0}'' is not a valid QName.
+        cvc-elt.4.2 = cvc-elt.4.2: Cannot resolve ''{1}'' to a type definition for element ''{0}''.
+        cvc-elt.4.3 = cvc-elt.4.3: Type ''{1}'' is not validly derived from the type definition, ''{2}'', of element ''{0}''.
+        cvc-elt.5.1.1 = cvc-elt.5.1.1: '{'value constraint'}' ''{2}'' of element ''{0}'' is not a valid default value for type ''{1}''.
+        cvc-elt.5.2.2.1 = cvc-elt.5.2.2.1: Element ''{0}'' must have no element information item [children].
+        cvc-elt.5.2.2.2.1 = cvc-elt.5.2.2.2.1: The value ''{1}'' of element ''{0}'' does not match the fixed '{'value constraint'}' value ''{2}''.
+        cvc-elt.5.2.2.2.2 = cvc-elt.5.2.2.2.2: The value ''{1}'' of element ''{0}'' does not match the '{'value constraint'}' value ''{2}''.
+        cvc-enumeration-valid = cvc-enumeration-valid: Value ''{0}'' is not facet-valid with respect to enumeration ''{1}''. It must be a value from the enumeration.
+        cvc-fractionDigits-valid = cvc-fractionDigits-valid: Value ''{0}'' has {1} fraction digits, but the number of fraction digits has been limited to {2}.
+        cvc-id.1 = cvc-id.1: There is no ID/IDREF binding for IDREF ''{0}''.
+        cvc-id.2 = cvc-id.2: There are multiple occurrences of ID value ''{0}''.
+        cvc-id.3 = cvc-id.3: A field of identity constraint ''{0}'' matched element ''{1}'', but this element does not have a simple type.
+        cvc-length-valid = cvc-length-valid: Value ''{0}'' with length = ''{1}'' is not facet-valid with respect to length ''{2}'' for type ''{3}''.
+        cvc-maxExclusive-valid = cvc-maxExclusive-valid: Value ''{0}'' is not facet-valid with respect to maxExclusive ''{1}'' for type ''{2}''.
+        cvc-maxInclusive-valid = cvc-maxInclusive-valid: Value ''{0}'' is not facet-valid with respect to maxInclusive ''{1}'' for type ''{2}''.
+        cvc-maxLength-valid = cvc-maxLength-valid: Value ''{0}'' with length = ''{1}'' is not facet-valid with respect to maxLength ''{2}'' for type ''{3}''.
+        cvc-minExclusive-valid = cvc-minExclusive-valid: Value ''{0}'' is not facet-valid with respect to minExclusive ''{1}'' for type ''{2}''.
+        cvc-minInclusive-valid = cvc-minInclusive-valid: Value ''{0}'' is not facet-valid with respect to minInclusive ''{1}'' for type ''{2}''.
+        cvc-minLength-valid = cvc-minLength-valid: Value ''{0}'' with length = ''{1}'' is not facet-valid with respect to minLength ''{2}'' for type ''{3}''.
+        cvc-pattern-valid = cvc-pattern-valid: Value ''{0}'' is not facet-valid with respect to pattern ''{1}'' for type ''{2}''.
+        cvc-totalDigits-valid = cvc-totalDigits-valid: Value ''{0}'' has {1} total digits, but the number of total digits has been limited to {2}.
+        cvc-type.1 = cvc-type.1: The type definition ''{0}'' was not found.
+        cvc-type.2 = cvc-type.2: The type definition cannot be abstract for element {0}.
+        cvc-type.3.1.1 = cvc-type.3.1.1: Element ''{0}'' is a simple type, so it cannot have attributes, excepting those whose namespace name is identical to ''http://www.w3.org/2001/XMLSchema-instance'' and whose [local name] is one of ''type'', ''nil'', ''schemaLocation'' or ''noNamespaceSchemaLocation''. However, the attribute, ''{1}'' was found.
+        cvc-type.3.1.2 = cvc-type.3.1.2: Element ''{0}'' is a simple type, so it must have no element information item [children].
+        cvc-type.3.1.3 = cvc-type.3.1.3: The value ''{1}'' of element ''{0}'' is not valid.
+
+#schema valid (3.X.3)
+
+        schema_reference.4 = schema_reference.4: Failed to read schema document ''{0}'', because 1) could not find the document; 2) the document could not be read; 3) the root element of the document is not <xsd:schema>.
+        src-annotation = src-annotation: <annotation> elements can only contain <appinfo> and <documentation> elements, but ''{0}'' was found.
+        src-attribute.1 = src-attribute.1: The properties ''default'' and ''fixed'' cannot both be present in attribute declaration ''{0}''. Use only one of them.
+        src-attribute.2 = src-attribute.2: : The property ''default'' is present in attribute ''{0}'', so the value of ''use'' must be ''optional''.
+        src-attribute.3.1 = src-attribute.3.1: One of 'ref' or 'name' must be present in a local attribute declaration.
+        src-attribute.3.2 = src-attribute.3.2: The content must match (annotation?) for the attribute reference ''{0}''.
+        src-attribute.4 = src-attribute.4: Attribute ''{0}'' has both a ''type'' attribute and an anonymous ''simpleType'' child. Only one of these is allowed for an attribute.
+        src-attribute_group.2 = src-attribute_group.2: The intersection of wildcards is not expressible for attribute group ''{0}''.
+        src-attribute_group.3 = src-attribute_group.3: Circular definitions detected for attribute group ''{0}''. Recursively following attribute group references eventually leads back to itself.
+        src-ct.1 = src-ct.1: Complex Type Definition Representation Error for type ''{0}''.  When <complexContent> is used, the base type must be a complexType. ''{1}'' is a simpleType.
+        src-ct.2.1 = src-ct.2.1: Complex Type Definition Representation Error for type ''{0}''.  When <simpleContent> is used, the base type must be a complexType whose content type is simple, or, only if restriction is specified, a complex type with mixed content and emptiable particle, or, only if extension is specified, a simple type. ''{1}'' satisfies none of these conditions.
+        src-ct.2.2 = src-ct.2.2: Complex Type Definition Representation Error for type ''{0}''.  When a complexType with simpleContent restricts a complexType with mixed content and emptiable particle, then there must be a <simpleType> among the children of <restriction>.
+        src-ct.4 = src-ct.4: Complex Type Definition Representation Error for type ''{0}''. The intersection of wildcards is not expressible.
+        src-ct.5 = src-ct.5: Complex Type Definition Representation Error for type ''{0}''. The union of wildcards is not expressible.
+        src-element.1 = src-element.1: The properties ''default'' and ''fixed'' cannot both be present in element declaration ''{0}''. Use only one of them.
+        src-element.2.1 = src-element.2.1: : One of 'ref' or 'name' must be present in a local element declaration.
+        src-element.2.2 = src-element.2.2: Since ''{0}'' contains the ''ref'' attribute, its content must match (annotation?). However, ''{1}'' was found.
+        src-element.3 = src-element.3: Element ''{0}'' has both a ''type'' attribute and a ''anonymous type'' child. Only one of these is allowed for an element.
+        src-import.1.1 = src-import.1.1: The namespace attribute ''{0}'' of an <import> element information item must not be the same as the targetNamespace of the schema it exists in.
+        src-import.1.2 = src-import.1.2: If the namespace attribute is not present on an <import> element information item then the enclosing schema must have a targetNamespace.
+        src-import.2 = src-import.2: The root element of document ''{0}'' has to have the namespace name ''http://www.w3.org/2001/XMLSchema'' and the local name ''schema''.
+        src-import.3.1 = src-import.3.1: The namespace attribute, ''{0}'', of an <import> element information item must be identical to the targetNamespace attribute, ''{1}'', of the imported document.
+        src-import.3.2 = src-import.3.2: An <import> element information item that had no namespace attribute was found, so the imported document cannot have a targetNamespace attribute. However, the targetNamespace ''{1}'' was found in the imported document.
+        src-include.1 = src-include.1: The root element of document ''{0}'' has to have the namespace name ''http://www.w3.org/2001/XMLSchema'' and the local name ''schema''.
+        src-include.2.1 = src-include.2.1: The targetNamespace of the referenced schema, currently ''{1}'', must be identical to that of the including schema, currently ''{0}''.
+        src-redefine.2 = src-redefine.2: The root element of document ''{0}'' has to have the namespace name ''http://www.w3.org/2001/XMLSchema'' and the local name ''schema''.
+        src-redefine.3.1 = src-redefine.3.1: The targetNamespace of the referenced schema, currently ''{1}'', must be identical to that of the redefining schema, currently ''{0}''.
+        src-redefine.5.a.a = src-redefine.5.a.a: No non-annotation children of <simpleType> were found. <simpleType> children of <redefine> elements must have <restriction> descendants, with 'base' attributes that refer to themselves.
+        src-redefine.5.a.b = src-redefine.5.a.b: ''{0}'' is not a valid child element. <simpleType> children of <redefine> elements must have <restriction> descendants, with ''base'' attributes that refer to themselves.
+        src-redefine.5.a.c = src-redefine.5.a.c: ''{0}'' does not have a ''base'' attribute that refers to the redefined element, ''{1}''. <simpleType> children of <redefine> elements must have <restriction> descendants, with ''base'' attributes that refer to themselves.
+        src-redefine.5.b.a = src-redefine.5.b.a: No non-annotation children of <complexType> were found. <complexType> children of <redefine> elements must have <extension> or <restriction> descendants, with 'base' attributes that refer to themselves.
+        src-redefine.5.b.b = src-redefine.5.b.b: No non-annotation grandchildren of <complexType> were found. <complexType> children of <redefine> elements must have <extension> or <restriction> descendants, with 'base' attributes that refer to themselves.
+        src-redefine.5.b.c = src-redefine.5.b.c: ''{0}'' is not a valid grandchild element. <complexType> children of <redefine> elements must have <extension> or <restriction> descendants, with ''base'' attributes that refer to themselves.
+        src-redefine.5.b.d = src-redefine.5.b.d: ''{0}'' does not have a ''base'' attribute that refers to the redefined element, ''{1}''. <complexType> children of <redefine> elements must have <extension> or <restriction> descendants, with ''base'' attributes that refer to themselves.
+        src-redefine.6.1.1 = src-redefine.6.1.1:  If a group child of a <redefine> element contains a group referring itself, it must have exactly 1; this one has ''{0}''.
+        src-redefine.6.1.2 = src-redefine.6.1.2:  The group ''{0}'', which contains a reference to a group being redefined, must have ''minOccurs'' = ''maxOccurs'' = 1.
+        src-redefine.6.2.1 = src-redefine.6.2.1: No group in the redefined schema has a name matching ''{0}''.
+        src-redefine.6.2.2 = src-redefine.6.2.2: Group ''{0}'' does not properly restrict the group it redefines; constraint violated:  ''{1}''.
+        src-redefine.7.1 = src-redefine.7.1:  If an attributeGroup child of a <redefine> element contains an attributeGroup referring itself, it must have exactly 1; this one has {0}.
+        src-redefine.7.2.1 = src-redefine.7.2.1: No attributeGroup in the redefined schema has a name matching ''{0}''.
+        src-redefine.7.2.2 = src-redefine.7.2.2: AttributeGroup ''{0}'' does not properly restrict the attributeGroup it redefines; constraint violated:  ''{1}''.
+        src-resolve = src-resolve: Cannot resolve the name ''{0}'' to a(n) ''{1}'' component.
+        src-resolve.4.1 = src-resolve.4.1: Error resolving component ''{2}''. It was detected that ''{2}'' has no namespace, but components with no target namespace are not referenceable from schema document ''{0}''. If ''{2}'' is intended to have a namespace, perhaps a prefix needs to be provided. If it is intended that ''{2}'' has no namespace, then an ''import'' without a "namespace" attribute should be added to ''{0}''.
+        src-resolve.4.2 = src-resolve.4.2: Error resolving component ''{2}''. It was detected that ''{2}'' is in namespace ''{1}'', but components from this namespace are not referenceable from schema document ''{0}''. If this is the incorrect namespace, perhaps the prefix of ''{2}'' needs to be changed. If this is the correct namespace, then an appropriate ''import'' tag should be added to ''{0}''.
+        src-simple-type.2.a = src-simple-type.2.a: A <restriction> element was found that has both a base [attribute] and a <simpleType> element among its [children]. Only one is allowed.
+        src-simple-type.2.b = src-simple-type.2.b: A <restriction> element was found that has neither a base [attribute] nor a <simpleType> element among its [children]. One is required.
+        src-simple-type.3.a = src-simple-type.3.a: A <list> element was found that has both an itemType [attribute] and a <simpleType> element among its [children]. Only one is allowed.
+        src-simple-type.3.b = src-simple-type.3.b: A <list> element was found that has neither an itemType [attribute] nor a <simpleType> element among its [children]. One is required.
+        src-single-facet-value = src-single-facet-value: The facet ''{0}'' is defined more than once.
+        src-union-memberTypes-or-simpleTypes = src-union-memberTypes-or-simpleTypes: A <union> element must have either a non-empty memberTypes [attribute] or at least one <simpleType> element among its [children].
+
+#constraint valid (3.X.6)
+
+        ag-props-correct.2 = ag-props-correct.2: Error for attribute group ''{0}''.  Duplicate attribute uses with the same name and target namespace are specified.  Name of duplicate attribute use is ''{1}''.
+        ag-props-correct.3 = ag-props-correct.3: Error for attribute group ''{0}''.  Two attribute declarations, ''{1}'' and ''{2}'' have types which are derived from ID.
+        a-props-correct.2 = a-props-correct.2: Invalid value constraint value ''{1}'' in attribute ''{0}''.
+        a-props-correct.3 = a-props-correct.3: Attribute ''{0}'' cannot use ''fixed'' or ''default'', because the attribute''s '{'type definition'}' is ID, or is derived from ID.
+        au-props-correct.2 = au-props-correct.2: In the attribute declaration of ''{0}'', a fixed value of ''{1}'' was specified. So if the attribute use referring to ''{0}'' also has a '{'value constraint'}', it must be fixed and its value must be ''{1}''.
+        cos-all-limited.1.2 = cos-all-limited.1.2: An 'all' model group must appear in a particle with '{'min occurs'}' = '{'max occurs'}' = 1, and that particle must be part of a pair which constitutes the '{'content type'}' of a complex type definition.
+        cos-all-limited.2 = cos-all-limited.2: The '{'max occurs'}' of an element in an ''all'' model group must be 0 or 1. The value ''{0}'' for element ''{1}'' is invalid.
+        cos-applicable-facets = cos-applicable-facets: Facet ''{0}'' is not allowed by type {1}.
+        cos-ct-extends.1.1 = cos-ct-extends.1.1: Type ''{0}'' was derived by extension from type ''{1}''.  However, the ''final'' attribute of ''{1}'' forbids derivation by extension.
+        cos-ct-extends.1.4.3.2.2.1.a = cos-ct-extends.1.4.3.2.2.1.a: The content type of a derived type and that of its base must both be mixed or both be element-only. Type ''{0}'' is element only, but its base type is not.
+        cos-ct-extends.1.4.3.2.2.1.b = cos-ct-extends.1.4.3.2.2.1.b: The content type of a derived type and that of its base must both be mixed or both be element-only. Type ''{0}'' is mixed, but its base type is not.
+        cos-element-consistent = cos-element-consistent: Error for type ''{0}''. Multiple elements with name ''{1}'', with different types, appear in the model group.
+        cos-list-of-atomic = cos-list-of-atomic: In the definition of list type ''{0}'', type ''{1}'' is an invalid list element type because it is not atomic (''{1}'' is either a list type, or a union type which contains a list).
+        cos-nonambig = cos-nonambig: {0} and {1} (or elements from their substitution group) violate \"Unique Particle Attribution\". During validation against this schema, ambiguity would be created for those two particles.
+        cos-particle-restrict.a = cos-particle-restrict.a: Derived particle is empty, and base is not emptiable.
+        cos-particle-restrict.b = cos-particle-restrict.b: Base particle is empty, but derived particle is not.
+        cos-particle-restrict.2 = cos-particle-restrict.2: Forbidden particle restriction: ''{0}''.
+        cos-st-restricts.1.1 = cos-st-restricts.1.1: The type ''{1}'' is atomic, so its '{'base type definition'}', ''{0}'', must be an atomic simple type definition or a built-in primitive datatype.
+        cos-st-restricts.2.1 = cos-st-restricts.2.1: In the definition of list type ''{0}'', type ''{1}'' is an invalid item type because it is either a list type, or a union type that contains a list.
+        cos-st-restricts.2.3.1.1 = cos-st-restricts.2.3.1.1: The '{'final'}' component of the '{'item type definition'}', ''{0}'', contains ''list''. This means that ''{0}'' cannot be used as an item type for list type ''{1}''.
+        cos-st-restricts.3.3.1.1 = cos-st-restricts.3.3.1.1: The '{'final'}' component of the '{'member type definitions'}', ''{0}'', contains ''union''. This means that ''{0}'' cannot be used as an member type for union type ''{1}''.
+        cos-valid-default.2.1 = cos-valid-default.2.1: Element ''{0}'' has a value constraint and must have a mixed or simple content model.
+        cos-valid-default.2.2.2 = cos-valid-default.2.2.2: Since element ''{0}'' has a '{'value constraint'}' and its type definition has mixed '{'content type'}', then the particle of the '{'content type'}' must be emptiable.
+        c-props-correct.2 = c-props-correct.2: Cardinality of Fields for keyref ''{0}'' and key ''{1}'' must match each other.
+        ct-props-correct.3 = ct-props-correct.3: Circular definitions detected for complex type ''{0}''. This means that ''{0}'' is contained in its own type hierarchy, which is an error.
+        ct-props-correct.4 = ct-props-correct.4: Error for type ''{0}''. Duplicate attribute uses with the same name and target namespace are specified.  Name of duplicate attribute use is ''{1}''.
+        ct-props-correct.5 = ct-props-correct.5: Error for type ''{0}''. Two attribute declarations, ''{1}'' and ''{2}'' have types which are derived from ID.
+        derivation-ok-restriction.1 = derivation-ok-restriction.1: Type ''{0}'' was derived by restriction from type ''{1}''.  However, ''{1}'' has a '{'final'}' property that forbids derivation by restriction.
+        derivation-ok-restriction.2.1.1 = derivation-ok-restriction.2.1.1: Error for type ''{0}''.  The attribute use ''{1}'' in this type has a ''use'' value of ''{2}'', which is inconsistent with the value of ''required'' in a matching attribute use in the base type.
+        derivation-ok-restriction.2.1.2 = derivation-ok-restriction.2.1.2: Error for type ''{0}''.  The attribute use ''{1}'' in this type has type ''{2}'', which is not validly derived from ''{3}'', the type of the matching attribute use in the base type.
+        derivation-ok-restriction.2.1.3.a = derivation-ok-restriction.2.1.3.a: Error for type ''{0}''.  The attribute use ''{1}'' in this type has an effective value constraint which is not fixed, and the effective value constraint of the matching attribute use in the base type is fixed.
+        derivation-ok-restriction.2.1.3.b = derivation-ok-restriction.2.1.3.b: Error for type ''{0}''.  The attribute use ''{1}'' in this type has an effective value constraint fixed with a value of ''{2}'', which is not consistent with the value of ''{3}'' for the fixed effective value constraint of the matching attribute use in the base type.
+        derivation-ok-restriction.2.2.a = derivation-ok-restriction.2.2.a: Error for type ''{0}''.  The attribute use ''{1}'' in this type does not have a matching attribute use in the base, and the base type does not have a wildcard attribute.
+        derivation-ok-restriction.2.2.b = derivation-ok-restriction.2.2.b: Error for type ''{0}''.  The attribute use ''{1}'' in this type does not have a matching attribute use in the base, and the wildcard in the base type does not allow the namespace ''{2}'' of this attribute use.
+        derivation-ok-restriction.3 = derivation-ok-restriction.3: Error for type ''{0}''.  The attribute use ''{1}'' in the base type has REQUIRED as true, but there is no matching attribute use in the derived type.
+        derivation-ok-restriction.4.1 = derivation-ok-restriction.4.1: Error for type ''{0}''.  The derivation has an attribute wildcard, but the base does not have one.
+        derivation-ok-restriction.4.2 = derivation-ok-restriction.4.2: Error for type ''{0}''.  The wildcard in the derivation is not a valid wildcard subset of the one in the base.
+        derivation-ok-restriction.4.3 = derivation-ok-restriction.4.3: Error for type ''{0}''.  The process contents of the wildcard in the derivation ({1}) is weaker than that in the base ({2}).
+        derivation-ok-restriction.5.2.2.1 = derivation-ok-restriction.5.2.2.1: Error for type ''{0}''.  The simple content type of this type, ''{1}'', is not a valid restriction of the simple content type of the base, ''{2}''.
+        derivation-ok-restriction.5.3.2 = derivation-ok-restriction.5.3.2: Error for type ''{0}''.  The content type of this type is empty, but the content type of the base, ''{1}'', is not empty or emptiable.
+        derivation-ok-restriction.5.4.1.2 = derivation-ok-restriction.5.4.1.2: Error for type ''{0}''.  The content type of this type is mixed, but the content type of the base, ''{1}'', is not.
+        derivation-ok-restriction.5.4.2 = derivation-ok-restriction.5.4.2: Error for type ''{0}''.  The particle of the type is not a valid restriction of the particle of the base.
+        enumeration-required-notation = enumeration-required-notation: The NOTATION type, ''{0}'' used by {2} ''{1}'', must have an enumeration facet value which specifies the notation elements used by this type.
+        enumeration-valid-restriction = enumeration-valid-restriction: Enumeration value ''{0}'' is not in the value space of the base type, {1}.
+        e-props-correct.2 = e-props-correct.2: Invalid value constraint value ''{1}'' in element ''{0}''.
+        e-props-correct.4 = e-props-correct.4: The '{'type definition'}' of element ''{0}'' is not validly derived from the '{'type definition'}' of the substitutionHead ''{1}'', or the '{'substitution group exclusions'}' property of ''{1}'' does not allow this derivation.
+        e-props-correct.5 = e-props-correct.5: A '{'value constraint'}' must not be present on element ''{0}'', because the element''s '{'type definition'}' or '{'type definition'}'''s '{'content type'}' is ID, or is derived from ID.
+        e-props-correct.6 = e-props-correct.6: Circular substitution group detected for element ''{0}''.
+        fractionDigits-valid-restriction = fractionDigits-valid-restriction: In the definition of {2}, the value ''{0}'' for the facet ''fractionDigits'' is invalid, because it must be <= the value for ''fractionDigits'' which was set to ''{1}'' in one of the ancestor types.
+        fractionDigits-totalDigits = fractionDigits-totalDigits: In the definition of {2}, the value ''{0}'' for the facet ''fractionDigits'' is invalid, because the value must be <= the value for ''totalDigits'' which is ''{1}''.
+        length-minLength-maxLength.1.1 = length-minLength-maxLength.1.1: For type {0}, it is an error for the value of length ''{1}'' to be less than the value of minLength ''{2}''.
+        length-minLength-maxLength.1.2.a = length-minLength-maxLength.1.2.a: For type {0}, it is an error for the base to not have a minLength facet if the current restriction has the minLength facet and the current restriction or base has the length facet. 
+        length-minLength-maxLength.1.2.b = length-minLength-maxLength.1.2.b: For type {0}, it is an error for the current minLength ''{1}'' to not equal the base minLength ''{2}''.
+        length-minLength-maxLength.2.1 = length-minLength-maxLength.2.1: For type {0}, it is an error for the value of length ''{1}'' to be greater than the value of maxLength ''{2}''. 
+        length-minLength-maxLength.2.2.a = length-minLength-maxLength.2.2.a: For type {0}, it is an error for the base to not have a maxLength facet if the current restriction has the maxLength facet and the current restriction or base has the length facet. 
+        length-minLength-maxLength.2.2.b = length-minLength-maxLength.2.2.b: For type {0}, it is an error for the current maxLength ''{1}'' to not equal the base maxLength ''{2}''.        
+        length-valid-restriction = length-valid-restriction: Error for type ''{2}''. The value of length = ''{0}'' must be = the value of that of the base type ''{1}''.
+        maxExclusive-valid-restriction.1 = maxExclusive-valid-restriction.1: Error for type ''{2}''. The maxExclusive value =''{0}'' must be <= maxExclusive of the base type ''{1}''.
+        maxExclusive-valid-restriction.2 = maxExclusive-valid-restriction.2: Error for type ''{2}''. The maxExclusive value =''{0}'' must be <= maxInclusive of the base type ''{1}''.
+        maxExclusive-valid-restriction.3 = maxExclusive-valid-restriction.3: Error for type ''{2}''. The maxExclusive value =''{0}'' must be > minInclusive of the base type ''{1}''.
+        maxExclusive-valid-restriction.4 = maxExclusive-valid-restriction.4: Error for type ''{2}''. The maxExclusive value =''{0}'' must be > minExclusive of the base type ''{1}''.
+        maxInclusive-maxExclusive = maxInclusive-maxExclusive: It is an error for both maxInclusive and maxExclusive to be specified for the same datatype. In {2}, maxInclusive = ''{0}'' and maxExclusive = ''{1}''.
+        maxInclusive-valid-restriction.1 = maxInclusive-valid-restriction.1: Error for type ''{2}''. The maxInclusive value =''{0}'' must be <= maxInclusive of the base type ''{1}''.
+        maxInclusive-valid-restriction.2 = maxInclusive-valid-restriction.2: Error for type ''{2}''. The maxInclusive value =''{0}'' must be < maxExclusive of the base type ''{1}''.
+        maxInclusive-valid-restriction.3 = maxInclusive-valid-restriction.3: Error for type ''{2}''. The maxInclusive value =''{0}'' must be >= minInclusive of the base type ''{1}''.
+        maxInclusive-valid-restriction.4 = maxInclusive-valid-restriction.4: Error for type ''{2}''. The maxInclusive value =''{0}'' must be > minExclusive of the base type ''{1}''.
+        maxLength-valid-restriction = maxLength-valid-restriction: In the definition of {2}, maxLength value = ''{0}'' must be <= that of the base type ''{1}''.
+        mg-props-correct.2 = mg-props-correct.2: Circular definitions detected for group ''{0}''. Recursively following the '{'term'}' values of the particles leads to a particle whose '{'term'}' is the group itself.
+        minExclusive-less-than-equal-to-maxExclusive = minExclusive-less-than-equal-to-maxExclusive: In the definition of {2}, minExclusive value = ''{0}'' must be <= maxExclusive value = ''{1}''.
+        minExclusive-less-than-maxInclusive = minExclusive-less-than-maxInclusive: In the definition of {2}, minExclusive value = ''{0}'' must be < maxInclusive value = ''{1}''.
+        minExclusive-valid-restriction.1 = minExclusive-valid-restriction.1: Error for type ''{2}''. The minExclusive value =''{0}'' must be >= minExclusive of the base type ''{1}''.
+        minExclusive-valid-restriction.2 = minExclusive-valid-restriction.2: Error for type ''{2}''. The minExclusive value =''{0}'' must be <= maxInclusive of the base type ''{1}''.
+        minExclusive-valid-restriction.3 = minExclusive-valid-restriction.3: Error for type ''{2}''. The minExclusive value =''{0}'' must be >= minInclusive of the base type ''{1}''.
+        minExclusive-valid-restriction.4 = minExclusive-valid-restriction.4: Error for type ''{2}''. The minExclusive value =''{0}'' must be < maxExclusive of the base type ''{1}''.
+        minInclusive-less-than-equal-to-maxInclusive = minInclusive-less-than-equal-to-maxInclusive: In the definition of {2}, minInclusive value = ''{0}'' must be <= maxInclusive value = ''{1}''.
+        minInclusive-less-than-maxExclusive = minInclusive-less-than-maxExclusive: In the definition of {2}, minInclusive value = ''{0}'' must be < maxExclusive value = ''{1}''.
+        minInclusive-minExclusive = minInclusive-minExclusive: It is an error for both minInclusive and minExclusive to be specified for the same datatype. In {2}, minInclusive = ''{0}'' and minExclusive = ''{1}''.
+        minInclusive-valid-restriction.1 = minInclusive-valid-restriction.1: Error for type ''{2}''. The minInclusive value =''{0}'' must be >= minInclusive of the base type ''{1}''.
+        minInclusive-valid-restriction.2 = minInclusive-valid-restriction.2: Error for type ''{2}''. The minInclusive value =''{0}'' must be <= maxInclusive of the base type ''{1}''.
+        minInclusive-valid-restriction.3 = minInclusive-valid-restriction.3: Error for type ''{2}''. The minInclusive value =''{0}'' must be > minExclusive of the base type ''{1}''.
+        minInclusive-valid-restriction.4 = minInclusive-valid-restriction.4: Error for type ''{2}''. The minInclusive value =''{0}'' must be < maxExclusive of the base type ''{1}''.
+        minLength-less-than-equal-to-maxLength = minLength-less-than-equal-to-maxLength: In the definition of {2}, value of minLength = ''{0}'' must be < value of maxLength = ''{1}''.
+        minLength-valid-restriction = minLength-valid-restriction: In the definition of {2}, minLength = ''{0}'' must be >= than that of the base type, ''{1}''.
+        no-xmlns = no-xmlns: The {name} of an attribute declaration must not match 'xmlns'.
+        no-xsi = no-xsi: The '{'target namespace'}' of an attribute declaration must not match ''{0}''.
+        p-props-correct.2.1 = p-props-correct.2.1: In the declaration of ''{0}'', the value of ''minOccurs'' is ''{1}'', but it must not be greater than the value of ''maxOccurs'', which is ''{2}''.
+        rcase-MapAndSum.1 = rcase-MapAndSum.1: There is not a complete functional mapping between the particles.
+        rcase-MapAndSum.2 = rcase-MapAndSum.2: Group''s occurrence range, ({0},{1}), is not a valid restriction of base group''s occurrence range, ({2},{3}).
+        rcase-NameAndTypeOK.1 = rcase-NameAndTypeOK.1: Elements have names and target namespaces which are not the same:  Element ''{0}'' in namespace ''{1}'' and element ''{2}'' in namespace ''{3}''.
+        rcase-NameAndTypeOK.2 = rcase-NameAndTypeOK.2: Error for the particle whose '{'term'}' is the element declaration ''{0}''. The element declaration''s '{'nillable'}' is true, but the corresponding particle in the base type has an element declaration whose '{'nillable'}' is false.
+        rcase-NameAndTypeOK.3 = rcase-NameAndTypeOK.3: Error for the particle whose '{'term'}' is the element declaration ''{0}''. Its occurrence range, ({1},{2}), is not a valid restriction of the range, ({3},{4}), of the corresponding particle in the base type.
+        rcase-NameAndTypeOK.4.a = rcase-NameAndTypeOK.4.a: Element ''{0}'' is not fixed, but the corresponding element in the base type is fixed with value ''{1}''.
+        rcase-NameAndTypeOK.4.b = rcase-NameAndTypeOK.4.b: Element ''{0}'' is fixed with value ''{1}'', but the corresponding element in the base type is fixed with value ''{2}''.
+        rcase-NameAndTypeOK.5 = rcase-NameAndTypeOK.5: Identity constraints for element ''{0}'' are not a subset of those in base.
+        rcase-NameAndTypeOK.6 = rcase-NameAndTypeOK.6: The disallowed substitutions for element ''{0}'' are not a superset of those in the base.
+        rcase-NameAndTypeOK.7 = rcase-NameAndTypeOK.7: The type of element ''{0}'', ''{1}'', is not derived from the type of the base element, ''{2}''.
+        rcase-NSCompat.1 = rcase-NSCompat.1: Element ''{0}'' has a namespace ''{1}'' which is not allowed by the wildcard in the base.
+        rcase-NSCompat.2 = rcase-NSCompat.2: Error for the particle whose '{'term'}' is the element declaration ''{0}''. Its occurrence range, ({1},{2}), is not a valid restriction of the range, ({3},{4}), of the corresponding particle in the base type.
+        rcase-NSRecurseCheckCardinality.1 = rcase-NSRecurseCheckCardinality.1: There is not a complete functional mapping between the particles.
+        rcase-NSRecurseCheckCardinality.2 = rcase-NSRecurseCheckCardinality.2: Group''s occurrence range, ({0},{1}), is not a valid restriction of base wildcard''s range, ({2},{3}).
+        rcase-NSSubset.1 = rcase-NSSubset.1: Wildcard is not a subset of corresponding wildcard in base.
+        rcase-NSSubset.2 = rcase-NSSubset.2: Wildcard''s occurrence range, ({0},{1}), is not a valid restriction of that in the base, ({2},{3}),.
+        rcase-NSSubset.3 = rcase-NSSubset.3: Wildcard''s process contents, ''{0}'', is weaker than that in the base, ''{1}''.
+        rcase-Recurse.1 = rcase-Recurse.1: Group''s occurrence range, ({0},{1}), is not a valid restriction of base group''s occurrence range, ({2},{3}).
+        rcase-Recurse.2 = rcase-Recurse.2: There is not a complete functional mapping between the particles.
+        rcase-RecurseLax.1 = rcase-RecurseLax.1: Group''s occurrence range, ({0},{1}), is not a valid restriction of base group''s occurrence range, ({2},{3}).
+        rcase-RecurseLax.2 = rcase-RecurseLax.2: There is not a complete functional mapping between the particles.
+        rcase-RecurseUnordered.1 = rcase-RecurseUnordered.1: Group''s occurrence range, ({0},{1}), is not a valid restriction of base group''s occurrence range, ({2},{3}).
+        rcase-RecurseUnordered.2 = rcase-RecurseUnordered.2: There is not a complete functional mapping between the particles.
+#        We're using sch-props-correct.2 instead of the old src-redefine.1
+#        src-redefine.1 = src-redefine.1: The component ''{0}'' is begin redefined, but its corresponding component isn't in the schema document being redefined (with namespace ''{2}''), but in a different document, with namespace ''{1}''.
+        sch-props-correct.2 = sch-props-correct.2: A schema cannot contain two global components with the same name; this schema contains two occurrences of ''{0}''.
+        st-props-correct.2 = st-props-correct.2: Circular definitions have been detected for simple type ''{0}''. This means that ''{0}'' is contained in its own type hierarchy, which is an error.
+        st-props-correct.3 = st-props-correct.3: Error for type ''{0}''. The value of '{'final'}' of the '{'base type definition'}', ''{1}'', forbids derivation by restriction.
+        totalDigits-valid-restriction = totalDigits-valid-restriction: In the definition of {2}, the value ''{0}'' for the facet ''totalDigits'' is invalid, because it must be <= the value for ''totalDigits'' which was set to ''{1}'' in one of the ancestor types.
+        whiteSpace-valid-restriction.1 = whiteSpace-valid-restriction.1: In the definition of {0}, the value ''{1}'' for the facet ''whitespace'' is invalid, because the value for ''whitespace'' has been set to ''collapse'' in one of the ancestor types.
+        whiteSpace-valid-restriction.2 = whiteSpace-valid-restriction.2: In the definition of {0}, the value ''preserve'' for the facet ''whitespace'' is invalid, because the value for ''whitespace'' has been set to ''replace'' in one of the ancestor types.
+
+#schema for Schemas
+
+        s4s-att-invalid-value = s4s-att-invalid-value: Invalid attribute value for ''{1}'' in element ''{0}''. Recorded reason: {2}
+        s4s-att-must-appear = s4s-att-must-appear: Attribute ''{1}'' must appear in element ''{0}''.
+        s4s-att-not-allowed = s4s-att-not-allowed: Attribute ''{1}'' cannot appear in element ''{0}''.
+        s4s-elt-invalid = s4s-elt-invalid: Element ''{0}'' is not a valid element in a schema document.
+        s4s-elt-must-match.1 = s4s-elt-must-match.1: The content of ''{0}'' must match {1}. A problem was found starting at: {2}.
+        s4s-elt-must-match.2 = s4s-elt-must-match.2: The content of ''{0}'' must match {1}. Not enough elements were found.
+        # the "invalid-content" messages provide less information than the "must-match" counterparts above. They're used for complex types when providing a "match" would be an information dump
+        s4s-elt-invalid-content.1 = s4s-elt-invalid-content.1: The content of ''{0}'' is invalid.  Element ''{1}'' is invalid, misplaced, or occurs too often.
+        s4s-elt-invalid-content.2 = s4s-elt-invalid-content.2: The content of ''{0}'' is invalid.  Element ''{1}'' cannot be empty.
+        s4s-elt-invalid-content.3 = s4s-elt-invalid-content.3: Elements of type ''{0}'' cannot appear after declarations as children of a <schema> element.
+        s4s-elt-schema-ns = s4s-elt-schema-ns: The namespace of element ''{0}'' must be from the schema namespace, ''http://www.w3.org/2001/XMLSchema''.
+        s4s-elt-character = s4s-elt-character: Non-whitespace characters are not allowed in schema elements other than ''xs:appinfo'' and ''xs:documentation''. Saw ''{0}''.
+
+# codes not defined by the spec
+
+        c-fields-xpaths = c-fields-xpaths: The field value = ''{0}'' is not valid.
+        c-general-xpath = c-general-xpath: The expression ''{0}'' is not valid with respect to the XPath subset supported by XML Schema.
+        c-general-xpath-ns = c-general-xpath-ns: A namespace prefix in XPath expression ''{0}'' was not bound to a namespace.
+        c-selector-xpath = c-selector-xpath: The selector value = ''{0}'' is not valid; selector xpaths cannot contain attributes.
+        EmptyTargetNamespace = EmptyTargetNamespace: In schema document ''{0}'', the value of the ''targetNamespace'' attribute cannot be an empty string.
+        FacetValueFromBase = FacetValueFromBase: In the declaration of type ''{0}'', value ''{1}'' of facet ''{2}'' must be from the value space of the base type, ''{3}''.
+        FixedFacetValue = FixedFacetValue: In the definition of {3}, the value ''{1}'' for the facet ''{0}'' is invalid, because the value for ''{0}'' has been set to ''{2}'' in one of the ancestor types, and '{'fixed'}' = true.
+        InvalidRegex = InvalidRegex: Pattern value ''{0}'' is not a valid regular expression. The reported error was: ''{1}''.
+        maxOccurLimit = Current configuration of the parser doesn''t allow the expansion of a content model for a complex type to contain more than {0} nodes.
+        PublicSystemOnNotation = PublicSystemOnNotation: At least one of 'public' and 'system' must appear in element 'notation'.
+        SchemaLocation = SchemaLocation: schemaLocation value = ''{0}'' must have even number of URI''s.
+        TargetNamespace.1 = TargetNamespace.1: Expecting namespace ''{0}'', but the target namespace of the schema document is ''{1}''.
+        TargetNamespace.2 = TargetNamespace.2: Expecting no namespace, but the schema document has a target namespace of ''{1}''.
+        UndeclaredEntity = UndeclaredEntity: Entity ''{0}'' is not declared.
+        UndeclaredPrefix = UndeclaredPrefix: Cannot resolve ''{0}'' as a QName: the prefix ''{1}'' is not declared.
+
+# JAXP 1.2 schema source property errors
+
+        jaxp12-schema-source-type.1 = The ''http://java.sun.com/xml/jaxp/properties/schemaSource'' property cannot have a value of type ''{0}''. Possible types of the value supported are String, File, InputStream, InputSource or an array of these types.
+        jaxp12-schema-source-type.2 = The ''http://java.sun.com/xml/jaxp/properties/schemaSource'' property cannot have an array value of type ''{0}''. Possible types of the array supported are Object, String, File, InputStream and InputSource.
+        jaxp12-schema-source-ns = When using an array of Objects as the value of the 'http://java.sun.com/xml/jaxp/properties/schemaSource' property, it is illegal to have two schemas that share the same target namespace.
+        

http://git-wip-us.apache.org/repos/asf/jena/blob/c9a7e646/jena-core/src/main/resources/org/apache/jena/ext/xerces/impl/msg/XMLSerializerMessages.properties
----------------------------------------------------------------------
diff --git a/jena-core/src/main/resources/org/apache/jena/ext/xerces/impl/msg/XMLSerializerMessages.properties b/jena-core/src/main/resources/org/apache/jena/ext/xerces/impl/msg/XMLSerializerMessages.properties
new file mode 100644
index 0000000..5a86e03
--- /dev/null
+++ b/jena-core/src/main/resources/org/apache/jena/ext/xerces/impl/msg/XMLSerializerMessages.properties
@@ -0,0 +1,50 @@
+#
+# Licensed to the Apache Software Foundation (ASF) under one or more
+# contributor license agreements.  See the NOTICE file distributed with
+# this work for additional information regarding copyright ownership.
+# The ASF licenses this file to You 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.
+#
+
+# This file stores error messages for the Xerces XML
+# serializer.  Many DOM Load/Save error messages also 
+# live here, since the serializer largely implements that package.
+#
+# As usual with properties files, the messages are arranged in
+# key/value tuples.
+# 
+# @version $Id: XMLSerializerMessages.properties 595211 2007-11-15 05:28:12Z mrglavas $
+
+    BadMessageKey = The error message corresponding to the message key can not be found.
+    FormatFailed = An internal error occurred while formatting the following message:\n
+
+    ArgumentIsNull = Argument ''{0}'' is null.
+    NoWriterSupplied = No writer supplied for serializer.
+    MethodNotSupported = The method ''{0}'' is not supported by this factory.
+    ResetInMiddle = The serializer may not be reset in the middle of serialization.
+    Internal = Internal error: element state is zero.
+    NoName = There is no rawName and localName is null.
+    ElementQName = The element name ''{0}'' is not a QName.
+    ElementPrefix = Element ''{0}'' does not belong to any namespace: prefix could be undeclared or bound to some namespace.
+    AttributeQName = The attribute name ''{0}'' is not a QName.
+    AttributePrefix = Attribute ''{0}'' does not belong to any namespace: prefix could be undeclared or bound to some namespace.
+    InvalidNSDecl = Namespace declaration syntax is incorrect: {0}.
+    EndingCDATA = The character sequence \"]]>\" must not appear in content unless used to mark the end of a CDATA section.
+    SplittingCDATA = Splitting a CDATA section containing the CDATA section termination marker \"]]>\".
+    ResourceNotFound = The resource ''{0}'' could not be found.
+    ResourceNotLoaded = The resource ''{0}'' could not be loaded. {1}
+    SerializationStopped =  Serialization stopped at user request.
+
+    # DOM Level 3 load and save messages
+    no-output-specified = no-output-specified: The output destination for data to be written to was null.
+    unsupported-encoding = unsupported-encoding: An unsupported encoding is encountered.
+    unable-to-serialize-node = unable-to-serialize-node: The node could not be serialized.

http://git-wip-us.apache.org/repos/asf/jena/blob/c9a7e646/jena-core/src/main/resources/org/apache/jena/ext/xerces/impl/msg/XPointerMessages.properties
----------------------------------------------------------------------
diff --git a/jena-core/src/main/resources/org/apache/jena/ext/xerces/impl/msg/XPointerMessages.properties b/jena-core/src/main/resources/org/apache/jena/ext/xerces/impl/msg/XPointerMessages.properties
new file mode 100644
index 0000000..cdd4c6e
--- /dev/null
+++ b/jena-core/src/main/resources/org/apache/jena/ext/xerces/impl/msg/XPointerMessages.properties
@@ -0,0 +1,44 @@
+#
+# Licensed to the Apache Software Foundation (ASF) under one or more
+# contributor license agreements.  See the NOTICE file distributed with
+# this work for additional information regarding copyright ownership.
+# The ASF licenses this file to You 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.
+#
+
+# This file stores localized messages for the Xerces XPointer implementation.
+#
+# The messages are arranged in key and value tuples in a ListResourceBundle.
+#
+# @version $Id: XPointerMessages.properties 595211 2007-11-15 05:28:12Z mrglavas $
+
+# Messages for message reporting
+BadMessageKey = The error message corresponding to the message key can not be found.
+FormatFailed = An internal error occurred while formatting the following message:\n  
+
+# XPointer Framework Error Messages
+XPointerProcessingError = XPointerProcessingError: An error occurred while processing the XPointer expression.
+InvalidXPointerToken = InvalidXPointerToken: The XPointer expression contains the invalid token ''{0}''
+InvalidXPointerExpression = InvalidXPointerExpression: The XPointer expression ''{0}'' is invalid.
+MultipleShortHandPointers = MultipleShortHandPointers:  The XPointer expression ''{0}'' is invalid.  It has more than one ShortHand Pointer. 
+SchemeDataNotFollowedByCloseParenthesis = SchemeDataNotFollowedByCloseParenthesis: The XPointer expression ''{0}'' is invalid.  The SchemeData was not followed by a '')'' character. 
+SchemeUnsupported = SchemeUnsupported: The XPointer scheme ''{0}'' is not supported.
+InvalidShortHandPointer = InvalidShortHandPointer: The NCName of the ShortHand Pointer ''{0}'' is invalid.
+UnbalancedParenthesisInXPointerExpression = UnbalancedParenthesisInXPointerExpression: The XPointer expression ''{0}'' is invalid.  The number of open parenthesis ''{1}'' is not equal to the number of close parenthesis ''{2}''.
+InvalidSchemeDataInXPointer = InvalidSchemeDataInXPointer: The XPointer expression ''{0}'' contains invalid SchemeData.
+
+# XPointer Element Scheme Error Messages
+InvalidElementSchemeToken = InvalidElementSchemeToken: The element() scheme XPointer expression contains the invalid token ''{0}''
+InvalidElementSchemeXPointer = InvalidElementSchemeXPointer: The Element Scheme XPointer expression ''{0}'' is invalid.
+XPointerElementSchemeProcessingError = XPointerElementSchemeProcessingError: An error occurred while processing the XPointer element() Scheme expression.
+InvalidNCNameInElementSchemeData = InvalidNCNameInElementSchemeData: The element() Scheme contains a ShortHand Pointer ''{0}'' with an invalid NCName.
+InvalidChildSequenceCharacter = InvalidChildSequenceCharacter: The element() Scheme contains an invalid child sequence character ''{0}''. 
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/jena/blob/c9a7e646/jena-core/src/main/resources/org/apache/jena/ext/xerces/impl/xpath/regex/message.properties
----------------------------------------------------------------------
diff --git a/jena-core/src/main/resources/org/apache/jena/ext/xerces/impl/xpath/regex/message.properties b/jena-core/src/main/resources/org/apache/jena/ext/xerces/impl/xpath/regex/message.properties
new file mode 100644
index 0000000..ee5d50d
--- /dev/null
+++ b/jena-core/src/main/resources/org/apache/jena/ext/xerces/impl/xpath/regex/message.properties
@@ -0,0 +1,58 @@
+#
+# Licensed to the Apache Software Foundation (ASF) under one or more
+# contributor license agreements.  See the NOTICE file distributed with
+# this work for additional information regarding copyright ownership.
+# The ASF licenses this file to You 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.
+#
+
+# @version $Id: message.properties 595212 2007-11-15 05:28:57Z mrglavas $
+
+parser.parse.1=Wrong character.
+parser.parse.2=Invalid reference number.
+parser.next.1=A character is required after \\.
+parser.next.2='?' is not expected.  '(?:' or '(?=' or '(?!' or '(?<' or '(?#' or '(?>'?
+parser.next.3='(?<=' or '(?<!' is expected.
+parser.next.4=A comment is not terminated.
+parser.factor.1=')' is expected.
+parser.factor.2=Unexpected end of the pattern in a modifier group.
+parser.factor.3=':' is expected.
+parser.factor.4=Unexpected end of the pattern in a conditional group.
+parser.factor.5=A back reference or an anchor or a lookahead or a lookbehind is expected in a conditional pattern.
+parser.factor.6=There are more than three choices in a conditional group.
+parser.atom.1=A character in U+0040-U+005f must follow \\c.
+parser.atom.2=A '{' is required before a character category.
+parser.atom.3=A property name is not closed by '}'.
+parser.atom.4=Unexpected meta character.
+parser.atom.5=Unknown property.
+parser.cc.1=A POSIX character class must be closed by ':]'.
+parser.cc.2=Unexpected end of the pattern in a character class.
+parser.cc.3=Unknown name for a POSIX character class.
+parser.cc.4='-' is invalid here.
+parser.cc.5=']' is expected.
+parser.cc.6='[' is invalid in a character class.  Write '\\['.
+parser.cc.7=']' is invalid in a character class.  Write '\\]'.
+parser.cc.8='-' is an invalid character range. Write '\\-'.
+parser.ope.1='[' is expected.
+parser.ope.2=')' or '-[' or '+[' or '&[' is expected.
+parser.ope.3=The range end code point is less than the start code point.
+parser.descape.1=Invalid Unicode hex notation.
+parser.descape.2=Overflow in a hex notation.
+parser.descape.3='\\x{' must be closed by '}'.
+parser.descape.4=Invalid Unicode code point.
+parser.descape.5=An anchor must not be here.
+parser.process.1=This expression is not supported in the current option setting.
+parser.quantifier.1=Invalid quantifier. A digit is expected.
+parser.quantifier.2=Invalid quantifier. Invalid quantity or a '}' is missing.
+parser.quantifier.3=Invalid quantifier. A digit or '}' is expected.
+parser.quantifier.4=Invalid quantifier. A min quantity must be <= a max quantity.
+parser.quantifier.5=Invalid quantifier. A quantity value overflow.

http://git-wip-us.apache.org/repos/asf/jena/blob/c9a7e646/jena-core/src/main/resources/org/apache/jena/ext/xerces/impl/xpath/regex/message_fr.properties
----------------------------------------------------------------------
diff --git a/jena-core/src/main/resources/org/apache/jena/ext/xerces/impl/xpath/regex/message_fr.properties b/jena-core/src/main/resources/org/apache/jena/ext/xerces/impl/xpath/regex/message_fr.properties
new file mode 100644
index 0000000..6c1e840
--- /dev/null
+++ b/jena-core/src/main/resources/org/apache/jena/ext/xerces/impl/xpath/regex/message_fr.properties
@@ -0,0 +1,58 @@
+#
+# Licensed to the Apache Software Foundation (ASF) under one or more
+# contributor license agreements.  See the NOTICE file distributed with
+# this work for additional information regarding copyright ownership.
+# The ASF licenses this file to You 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.
+#
+
+# @version $Id: message_fr.properties 595212 2007-11-15 05:28:57Z mrglavas $
+
+parser.parse.1=Caract\u00e8re erron\u00e9.
+parser.parse.2=Num\u00e9ro de r\u00e9f\u00e9rence non valide.
+parser.next.1=Un caract\u00e8re est requis apr\u00e8s \\.
+parser.next.2='?' n'est pas attendu.  '(?:', '(?=', '(?!', '(?<', '(?#', '(?>'?
+parser.next.3='(?<=' ou '(?<!' est attendu.
+parser.next.4=Commentaire sans caract\u00e8re de terminaison.
+parser.factor.1=')' attendu.
+parser.factor.2=Fin du mod\u00e8le attendue dans un groupe de modificateurs.
+parser.factor.3=':' attendu.
+parser.factor.4=Fin du mod\u00e8le inattendue dans un groupe conditionnel.
+parser.factor.5=Un mod\u00e8le conditionnel doit contenir un renvoi, une ancre, une lecture anticip\u00e9e ou une lecture diff\u00e9r\u00e9e.
+parser.factor.6=Un groupe conditionnel comporte plus de trois choix.
+parser.atom.1=Un caract\u00e8re de U+0040-U+005f doit suivre \\c.
+parser.atom.2=Une accolade ('{') est obligatoire devant une cat\u00e9gorie de caract\u00e8res.
+parser.atom.3=Un nom de propri\u00e9t\u00e9 n'est pas ferm\u00e9 par '}'.
+parser.atom.4=M\u00e9ta-caract\u00e8re inattendu.
+parser.atom.5=Propri\u00e9t\u00e9 inconnue.
+parser.cc.1=Une classe de caract\u00e8res POSIX doit \u00eatre ferm\u00e9e par ':]'.
+parser.cc.2=Fin du mod\u00e8le inattendue dans une classe de caract\u00e8res.
+parser.cc.3=Nom inconnu pour une classe de caract\u00e8res POSIX.
+parser.cc.4='-' n'est pas valide ici.
+parser.cc.5=']' est attendu.
+parser.cc.6='[' n'est pas valide dans une classe de caract\u00e8res.  Ecrire '\\['.
+parser.cc.7=']' n'est pas valide dans une classe de caract\u00e8res.  Ecrire '\\['.
+parser.cc.8='-' n'est pas valide dans un intervalle de caract\u00e8res. Ecrire '\\-'.
+parser.ope.1='[' est attendu.
+parser.ope.2=')', '-[', '+[' ou '&[' est attendu.
+parser.ope.3=Le point de code final doit \u00eatre inf\u00e9rieur au point de code initial dans l'intervalle.
+parser.descape.1=Notation hexad\u00e9cimale Unicode non valide.
+parser.descape.2=D\u00e9passement d'une notation hexad\u00e9cimale.
+parser.descape.3='\\x{' doit \u00eatre ferm\u00e9 par '}'.
+parser.descape.4=Point de code Unicode non valide.
+parser.descape.5=Une ancre ne doit pas figurer ici.
+parser.process.1=Cette expression n'est pas prise en charge dans le param\u00e8tre d'option courant.
+parser.quantifier.1=Quantifieur non valide. Valeur num\u00e9rique requise.
+parser.quantifier.2=Quantifieur non valide. Quantit\u00e9 non valide ou '}' manquant.
+parser.quantifier.3=Quantifieur non valide. Nombre ou '}' obligatoire.
+parser.quantifier.4=Quantifieur non valide. Une quantit\u00e9 minimale doit \u00eatre <= \u00e0 une quantit\u00e9 maximale.
+parser.quantifier.5=Quantifieur non valide. D\u00e9passement de quantit\u00e9.

http://git-wip-us.apache.org/repos/asf/jena/blob/c9a7e646/jena-core/src/main/resources/org/apache/jena/ext/xerces/impl/xpath/regex/message_ja.properties
----------------------------------------------------------------------
diff --git a/jena-core/src/main/resources/org/apache/jena/ext/xerces/impl/xpath/regex/message_ja.properties b/jena-core/src/main/resources/org/apache/jena/ext/xerces/impl/xpath/regex/message_ja.properties
new file mode 100644
index 0000000..043e5fa
--- /dev/null
+++ b/jena-core/src/main/resources/org/apache/jena/ext/xerces/impl/xpath/regex/message_ja.properties
@@ -0,0 +1,58 @@
+#
+# Licensed to the Apache Software Foundation (ASF) under one or more
+# contributor license agreements.  See the NOTICE file distributed with
+# this work for additional information regarding copyright ownership.
+# The ASF licenses this file to You 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.
+#
+
+# @version $Id: message_ja.properties 595212 2007-11-15 05:28:57Z mrglavas $
+
+parser.parse.1=\u4e0d\u5f53\u306a\u6587\u5b57\u3002
+parser.parse.2=\u7121\u52b9\u306a\u53c2\u7167\u756a\u53f7\u3002
+parser.next.1=\\ \u306e\u5f8c\u306b\u6587\u5b57\u304c\u5fc5\u8981\u3067\u3059\u3002
+parser.next.2='?' \u306f\u671f\u5f85\u3055\u308c\u3066\u3044\u307e\u305b\u3093\u3002'(?:' \u307e\u305f\u306f '(?=' \u307e\u305f\u306f '(?!' \u307e\u305f\u306f '(?<' \u307e\u305f\u306f '(?#' \u307e\u305f\u306f '(?>'?
+parser.next.3='(?<=' \u307e\u305f\u306f '(?<!' \u304c\u671f\u5f85\u3055\u308c\u3066\u3044\u307e\u3059\u3002
+parser.next.4=\u30b3\u30e1\u30f3\u30c8\u304c\u7d42\u7d50\u3057\u3066\u3044\u307e\u305b\u3093\u3002
+parser.factor.1=')' \u304c\u671f\u5f85\u3055\u308c\u3066\u3044\u307e\u3059\u3002
+parser.factor.2=\u4fee\u98fe\u5b50\u30b0\u30eb\u30fc\u30d7\u5185\u3067\u30d1\u30bf\u30fc\u30f3\u306e\u4e88\u671f\u3057\u306a\u3044\u7d42\u4e86\u3002
+parser.factor.3=':' \u304c\u671f\u5f85\u3055\u308c\u3066\u3044\u307e\u3059\u3002
+parser.factor.4=\u6761\u4ef6\u4ed8\u304d\u30b0\u30eb\u30fc\u30d7\u5185\u3067\u30d1\u30bf\u30fc\u30f3\u306e\u4e88\u671f\u3057\u306a\u3044\u7d42\u4e86\u3002
+parser.factor.5=\u6761\u4ef6\u4ed8\u304d\u30d1\u30bf\u30fc\u30f3\u3067\u306f\u9006\u53c2\u7167\u307e\u305f\u306f\u30a2\u30f3\u30ab\u30fc\u307e\u305f\u306f\u5148\u8aad\u307f\u304c\u671f\u5f85\u3055\u308c\u3066\u3044\u307e\u3059\u3002
+parser.factor.6=\u6761\u4ef6\u4ed8\u304d\u30b0\u30eb\u30fc\u30d7\u306b 3 \u3064\u3092\u8d85\u3048\u308b\u9078\u629e\u9805\u76ee\u304c\u3042\u308a\u307e\u3059\u3002
+parser.atom.1=\u5f8c\u306b \\c \u304c\u5fc5\u8981\u306a\u6587\u5b57\u304c U+0040-U+005f \u306b\u3042\u308a\u307e\u3059\u3002
+parser.atom.2=\u6587\u5b57\u30ab\u30c6\u30b4\u30ea\u30fc\u306e\u524d\u306b '{' \u304c\u5fc5\u8981\u3067\u3059\u3002
+parser.atom.3=\u30d7\u30ed\u30d1\u30c6\u30a3\u30fc\u540d\u304c '}' \u3067\u9589\u3058\u3089\u308c\u3066\u3044\u307e\u305b\u3093\u3002
+parser.atom.4=\u4e88\u671f\u3057\u306a\u3044\u30e1\u30bf\u6587\u5b57\u3002
+parser.atom.5=\u4e0d\u660e\u306a\u30d7\u30ed\u30d1\u30c6\u30a3\u30fc\u3002
+parser.cc.1=POSIX \u6587\u5b57\u30af\u30e9\u30b9\u306f ':]' \u3067\u9589\u3058\u3089\u308c\u3066\u3044\u306a\u3051\u308c\u3070\u306a\u308a\u307e\u305b\u3093\u3002
+parser.cc.2=\u6587\u5b57\u30af\u30e9\u30b9\u5185\u3067\u30d1\u30bf\u30fc\u30f3\u306e\u4e88\u671f\u3057\u306a\u3044\u7d42\u4e86\u3002
+parser.cc.3=POSIX \u6587\u5b57\u30af\u30e9\u30b9\u306e\u540d\u524d\u304c\u4e0d\u660e\u3067\u3059\u3002
+parser.cc.4='-' \u306f\u3053\u3053\u3067\u306f\u7121\u52b9\u3067\u3059\u3002
+parser.cc.5=']' \u304c\u671f\u5f85\u3055\u308c\u3066\u3044\u307e\u3059\u3002
+parser.cc.6='[' \u306f\u6587\u5b57\u30af\u30e9\u30b9\u5185\u3067\u306f\u7121\u52b9\u3067\u3059\u3002'\\[' \u3068\u66f8\u3044\u3066\u304f\u3060\u3055\u3044\u3002
+parser.cc.7=']' \u306f\u6587\u5b57\u30af\u30e9\u30b9\u5185\u3067\u306f\u7121\u52b9\u3067\u3059\u3002'\\]' \u3068\u66f8\u3044\u3066\u304f\u3060\u3055\u3044\u3002
+parser.cc.8='-' \u306f\u7121\u52b9\u306a\u6587\u5b57\u7bc4\u56f2\u3067\u3059\u3002'\\-' \u3068\u66f8\u3044\u3066\u304f\u3060\u3055\u3044\u3002
+parser.ope.1='[' \u304c\u671f\u5f85\u3055\u308c\u3066\u3044\u307e\u3059\u3002
+parser.ope.2=')' \u307e\u305f\u306f '-[' \u307e\u305f\u306f '+[' \u307e\u305f\u306f '&[' \u304c\u671f\u5f85\u3055\u308c\u3066\u3044\u307e\u3059\u3002
+parser.ope.3=\u7bc4\u56f2\u7d42\u4e86\u30b3\u30fc\u30c9\u30fb\u30dd\u30a4\u30f3\u30c8\u304c\u958b\u59cb\u30b3\u30fc\u30c9\u30fb\u30dd\u30a4\u30f3\u30c8\u3088\u308a\u5c0f\u3055\u3044\u5024\u306b\u306a\u3063\u3066\u3044\u307e\u3059\u3002
+parser.descape.1=\u7121\u52b9\u306a Unicode 16 \u9032\u8868\u8a18\u3002
+parser.descape.2=16 \u9032\u8868\u8a18\u3067\u30aa\u30fc\u30d0\u30fc\u30d5\u30ed\u30fc\u3002
+parser.descape.3='\\x{' \u306f '}' \u3067\u9589\u3058\u3089\u308c\u3066\u3044\u306a\u3051\u308c\u3070\u306a\u308a\u307e\u305b\u3093\u3002
+parser.descape.4=\u7121\u52b9\u306a Unicode \u30b3\u30fc\u30c9\u30fb\u30dd\u30a4\u30f3\u30c8\u3002
+parser.descape.5=\u3053\u3053\u306b\u30a2\u30f3\u30ab\u30fc\u304c\u3042\u3063\u3066\u306f\u306a\u308a\u307e\u305b\u3093\u3002
+parser.process.1=\u3053\u306e\u5f0f\u306f\u73fe\u5728\u306e\u30aa\u30d7\u30b7\u30e7\u30f3\u8a2d\u5b9a\u3067\u306f\u30b5\u30dd\u30fc\u30c8\u3055\u308c\u307e\u305b\u3093\u3002
+parser.quantifier.1=\u6570\u91cf\u8a5e\u304c\u7121\u52b9\u3067\u3059\u3002\u6570\u5b57\u304c\u671f\u5f85\u3055\u308c\u3066\u3044\u307e\u3059\u3002
+parser.quantifier.2=\u6570\u91cf\u8a5e\u304c\u7121\u52b9\u3067\u3059\u3002\u6570\u91cf\u304c\u7121\u52b9\u304b\u3001\u307e\u305f\u306f '}' \u304c\u3042\u308a\u307e\u305b\u3093\u3002
+parser.quantifier.3=\u6570\u91cf\u8a5e\u304c\u7121\u52b9\u3067\u3059\u3002\u6570\u5b57\u307e\u305f\u306f '}' \u304c\u671f\u5f85\u3055\u308c\u3066\u3044\u307e\u3059\u3002
+parser.quantifier.4=\u6570\u91cf\u8a5e\u304c\u7121\u52b9\u3067\u3059\u3002\u6700\u5c0f\u6570\u91cf\u306f\u6700\u5927\u6570\u91cf\u4ee5\u4e0b\u3067\u306a\u3051\u308c\u3070\u306a\u308a\u307e\u305b\u3093\u3002
+parser.quantifier.5=\u6570\u91cf\u8a5e\u304c\u7121\u52b9\u3067\u3059\u3002\u6570\u91cf\u5024\u304c\u30aa\u30fc\u30d0\u30fc\u30d5\u30ed\u30fc\u3057\u3066\u3044\u307e\u3059\u3002

http://git-wip-us.apache.org/repos/asf/jena/blob/c9a7e646/jena-core/src/test/java/org/apache/jena/graph/test/TestTypedLiterals.java
----------------------------------------------------------------------
diff --git a/jena-core/src/test/java/org/apache/jena/graph/test/TestTypedLiterals.java b/jena-core/src/test/java/org/apache/jena/graph/test/TestTypedLiterals.java
index 57a320d..4b66077 100644
--- a/jena-core/src/test/java/org/apache/jena/graph/test/TestTypedLiterals.java
+++ b/jena-core/src/test/java/org/apache/jena/graph/test/TestTypedLiterals.java
@@ -20,8 +20,6 @@ package org.apache.jena.graph.test;
 
 import static org.apache.jena.graph.NodeFactory.createLiteral;
 
-import java.io.FileReader;
-import java.io.IOException;
 import java.math.BigDecimal ;
 import java.math.BigInteger ;
 import java.text.SimpleDateFormat ;
@@ -161,65 +159,68 @@ public class TestTypedLiterals extends TestCase {
         } catch (DatatypeFormatException e) {}
         assertEquals("Extract xml tag", l1.isWellFormedXML(), false);
     }
-    
-    /**
-     * Test user defined data types.
-     * This is based on a corrected, modified version of an early DAML+OIL example
-     * but is not specific to DAML+OIL.
-     */
-    public void testUserDefined() throws IOException {
-        String uri = "http://www.daml.org/2001/03/daml+oil-ex-dt";
-        String filename = "testing/xsd/daml+oil-ex-dt.xsd";
-        TypeMapper tm = TypeMapper.getInstance();
-        List<String> typenames = XSDDatatype.loadUserDefined(uri, new FileReader(filename), null, tm);
-        assertIteratorValues(typenames.iterator(), new Object[] {
-            uri + "#XSDEnumerationHeight",
-            uri + "#over12",
-            uri + "#over17",
-            uri + "#over59",
-            uri + "#clothingsize"   });
-        
-        // Check the string restriction
-        RDFDatatype heightType = tm.getSafeTypeByName(uri + "#XSDEnumerationHeight");
-        checkLegalLiteral("short", heightType, String.class, "short");
-        checkLegalLiteral("tall", heightType, String.class, "tall");
-        checkIllegalLiteral("shortish", heightType);
 
-        // Check the numeric restriction
-        RDFDatatype over12Type = tm.getSafeTypeByName(uri + "#over12");
-        checkLegalLiteral("15", over12Type, Integer.class, 15 );
-        checkIllegalLiteral("12", over12Type);
-        
-        // Check the union type
-        RDFDatatype clothingsize = tm.getSafeTypeByName(uri + "#clothingsize");
-        checkLegalLiteral("42", clothingsize, Integer.class, 42 );
-        checkLegalLiteral("short", clothingsize, String.class, "short");
-        
-        // Check use of isValidLiteral for base versus derived combinations
-        LiteralLabel iOver12 = m.createTypedLiteral("13", over12Type).asNode().getLiteral();
-        LiteralLabel iDecimal14 = m.createTypedLiteral("14", XSDDatatype.XSDdecimal).asNode().getLiteral();
-        LiteralLabel iDecimal10 = m.createTypedLiteral("10", XSDDatatype.XSDdecimal).asNode().getLiteral();
-        LiteralLabel iString = m.createTypedLiteral("15", XSDDatatype.XSDstring).asNode().getLiteral();
-        LiteralLabel iPlain = m.createLiteral("foo").asNode().getLiteral();
-        
-        assertTrue(over12Type.isValidLiteral(iOver12));
-        assertTrue(over12Type.isValidLiteral(iDecimal14));
-        assertTrue( ! over12Type.isValidLiteral(iDecimal10));
-        assertTrue( ! over12Type.isValidLiteral(iString));
-        assertTrue( ! over12Type.isValidLiteral(iPlain));
-        
-        assertTrue(XSDDatatype.XSDdecimal.isValidLiteral(iOver12));
-        assertTrue(XSDDatatype.XSDdecimal.isValidLiteral(iDecimal14));
-        assertTrue(XSDDatatype.XSDdecimal.isValidLiteral(iDecimal10));
-        assertTrue( ! XSDDatatype.XSDdecimal.isValidLiteral(iString));
-        assertTrue( ! XSDDatatype.XSDdecimal.isValidLiteral(iPlain));
-        
-        assertTrue(XSDDatatype.XSDstring.isValidLiteral(iString));
-        assertTrue(XSDDatatype.XSDstring.isValidLiteral(iPlain));
-        assertTrue( ! XSDDatatype.XSDstring.isValidLiteral(iOver12));
-        assertTrue( ! XSDDatatype.XSDstring.isValidLiteral(iDecimal10));
-        assertTrue( ! XSDDatatype.XSDstring.isValidLiteral(iDecimal14));
-    }
+    // Removal of Apach Xerces : JENA-1537.
+    // No XSDDatatype.loadUserDefineds
+    
+//    /**
+//     * Test user defined data types.
+//     * This is based on a corrected, modified version of an early DAML+OIL example
+//     * but is not specific to DAML+OIL.
+//     */
+//    public void testUserDefined() throws IOException {
+//        String uri = "http://www.daml.org/2001/03/daml+oil-ex-dt";
+//        String filename = "testing/xsd/daml+oil-ex-dt.xsd";
+//        TypeMapper tm = TypeMapper.getInstance();
+//        List<String> typenames = XSDDatatype.loadUserDefined(uri, new FileReader(filename), null, tm);
+//        assertIteratorValues(typenames.iterator(), new Object[] {
+//            uri + "#XSDEnumerationHeight",
+//            uri + "#over12",
+//            uri + "#over17",
+//            uri + "#over59",
+//            uri + "#clothingsize"   });
+//        
+//        // Check the string restriction
+//        RDFDatatype heightType = tm.getSafeTypeByName(uri + "#XSDEnumerationHeight");
+//        checkLegalLiteral("short", heightType, String.class, "short");
+//        checkLegalLiteral("tall", heightType, String.class, "tall");
+//        checkIllegalLiteral("shortish", heightType);
+//
+//        // Check the numeric restriction
+//        RDFDatatype over12Type = tm.getSafeTypeByName(uri + "#over12");
+//        checkLegalLiteral("15", over12Type, Integer.class, 15 );
+//        checkIllegalLiteral("12", over12Type);
+//        
+//        // Check the union type
+//        RDFDatatype clothingsize = tm.getSafeTypeByName(uri + "#clothingsize");
+//        checkLegalLiteral("42", clothingsize, Integer.class, 42 );
+//        checkLegalLiteral("short", clothingsize, String.class, "short");
+//        
+//        // Check use of isValidLiteral for base versus derived combinations
+//        LiteralLabel iOver12 = m.createTypedLiteral("13", over12Type).asNode().getLiteral();
+//        LiteralLabel iDecimal14 = m.createTypedLiteral("14", XSDDatatype.XSDdecimal).asNode().getLiteral();
+//        LiteralLabel iDecimal10 = m.createTypedLiteral("10", XSDDatatype.XSDdecimal).asNode().getLiteral();
+//        LiteralLabel iString = m.createTypedLiteral("15", XSDDatatype.XSDstring).asNode().getLiteral();
+//        LiteralLabel iPlain = m.createLiteral("foo").asNode().getLiteral();
+//        
+//        assertTrue(over12Type.isValidLiteral(iOver12));
+//        assertTrue(over12Type.isValidLiteral(iDecimal14));
+//        assertTrue( ! over12Type.isValidLiteral(iDecimal10));
+//        assertTrue( ! over12Type.isValidLiteral(iString));
+//        assertTrue( ! over12Type.isValidLiteral(iPlain));
+//        
+//        assertTrue(XSDDatatype.XSDdecimal.isValidLiteral(iOver12));
+//        assertTrue(XSDDatatype.XSDdecimal.isValidLiteral(iDecimal14));
+//        assertTrue(XSDDatatype.XSDdecimal.isValidLiteral(iDecimal10));
+//        assertTrue( ! XSDDatatype.XSDdecimal.isValidLiteral(iString));
+//        assertTrue( ! XSDDatatype.XSDdecimal.isValidLiteral(iPlain));
+//        
+//        assertTrue(XSDDatatype.XSDstring.isValidLiteral(iString));
+//        assertTrue(XSDDatatype.XSDstring.isValidLiteral(iPlain));
+//        assertTrue( ! XSDDatatype.XSDstring.isValidLiteral(iOver12));
+//        assertTrue( ! XSDDatatype.XSDstring.isValidLiteral(iDecimal10));
+//        assertTrue( ! XSDDatatype.XSDstring.isValidLiteral(iDecimal14));
+//    }
     
     public void testXMLLiteral() {
     	Literal ll;

http://git-wip-us.apache.org/repos/asf/jena/blob/c9a7e646/jena-core/src/test/java/org/apache/jena/rdfxml/xmlinput/MoreTests.java
----------------------------------------------------------------------
diff --git a/jena-core/src/test/java/org/apache/jena/rdfxml/xmlinput/MoreTests.java b/jena-core/src/test/java/org/apache/jena/rdfxml/xmlinput/MoreTests.java
index 4ace50c..771edde 100644
--- a/jena-core/src/test/java/org/apache/jena/rdfxml/xmlinput/MoreTests.java
+++ b/jena-core/src/test/java/org/apache/jena/rdfxml/xmlinput/MoreTests.java
@@ -19,7 +19,6 @@
 package org.apache.jena.rdfxml.xmlinput;
 
 import java.io.* ;
-import java.nio.charset.Charset ;
 
 import junit.framework.Test ;
 import junit.framework.TestCase ;
@@ -120,44 +119,50 @@ public class MoreTests extends TestCase implements RDFErrorHandler,
         }
     }
 
-	public void testLatin1() throws IOException {
-		Model m = createMemModel();
-		RDFReader rdr = m.getReader();
-		InputStream r = new FileInputStream(
-				"testing/arp/i18n/latin1.rdf");
-		
-		rdr.setErrorHandler(this);
-		expected = new int[] { WARN_NONCANONICAL_IANA_NAME };
-		rdr.read(m, r, "http://example.org/");
-		checkExpected();
-	}
-	public void testARPMacRoman() throws IOException {
-		Model m = createMemModel();
-		RDFReader rdr = m.getReader();
-		InputStream r = new FileInputStream(
-				"testing/arp/i18n/macroman.rdf");
-		
-		rdr.setErrorHandler(this);
-		expected = new int[] { WARN_UNSUPPORTED_ENCODING, WARN_NON_IANA_ENCODING };
-		expected[Charset.isSupported("MacRoman")?0:1]=0;
-//		 Only one of the warnings is expected, which depends on Java version
-		
-		rdr.read(m, r, "http://example.org/");
-		checkExpected();
-	}
-	public void testARPMacArabic() throws IOException {
-		Model m = createMemModel();
-		RDFReader rdr = m.getReader();
-		InputStream r = new FileInputStream(
-				"testing/arp/i18n/arabic-macarabic.rdf");
-		
-		rdr.setErrorHandler(this);
-		expected = new int[] { WARN_UNSUPPORTED_ENCODING, WARN_NON_IANA_ENCODING };
-		expected[Charset.isSupported("MacArabic")?0:1]=0;
-//		 Only one of the warnings is expected, which depends on Java version
-		rdr.read(m, r, "http://example.org/");
-		checkExpected();
-	}
+    // JENA-1537
+    // Character encoding checks removed due to lack of support in JDK XML parser APIs.  
+//	public void testLatin1() throws IOException {
+//		Model m = createMemModel();
+//		RDFReader rdr = m.getReader();
+//		InputStream r = new FileInputStream(
+//				"testing/arp/i18n/latin1.rdf");
+//		
+//		rdr.setErrorHandler(this);
+//		expected = new int[] { WARN_NONCANONICAL_IANA_NAME };
+//		rdr.read(m, r, "http://example.org/");
+//		checkExpected();
+//	}
+	
+	// JENA-1537
+    // Character encoding checks removed due to lack of support in JDK XML parser APIs.  
+	
+//	public void testARPMacRoman() throws IOException {
+//		Model m = createMemModel();
+//		RDFReader rdr = m.getReader();
+//		InputStream r = new FileInputStream(
+//				"testing/arp/i18n/macroman.rdf");
+//		
+//		rdr.setErrorHandler(this);
+//		expected = new int[] { WARN_UNSUPPORTED_ENCODING, WARN_NON_IANA_ENCODING };
+//		expected[Charset.isSupported("MacRoman")?0:1]=0;
+////		 Only one of the warnings is expected, which depends on Java version
+//		
+//		rdr.read(m, r, "http://example.org/");
+//		checkExpected();
+//	}
+//	public void testARPMacArabic() throws IOException {
+//		Model m = createMemModel();
+//		RDFReader rdr = m.getReader();
+//		InputStream r = new FileInputStream(
+//				"testing/arp/i18n/arabic-macarabic.rdf");
+//		
+//		rdr.setErrorHandler(this);
+//		expected = new int[] { WARN_UNSUPPORTED_ENCODING, WARN_NON_IANA_ENCODING };
+//		expected[Charset.isSupported("MacArabic")?0:1]=0;
+////		 Only one of the warnings is expected, which depends on Java version
+//		rdr.read(m, r, "http://example.org/");
+//		checkExpected();
+//	}
 	
 
 	public void testEncodingMismatch1() throws IOException {
@@ -253,16 +258,20 @@ public class MoreTests extends TestCase implements RDFErrorHandler,
 		subTestEncodingMismatch2(r);
 	}
 
-	public void testEncodingMismatch3() throws IOException {
-	    try ( FileInputStream fin = new FileInputStream("testing/wg/rdf-charmod-literals/test001.rdf") ;
-	          InputStreamReader r = new InputStreamReader(fin,"MS950")) {
-	        subTestEncodingMismatch2(r);
-	    }catch (java.io.UnsupportedEncodingException e) {
-	        System.err
-	        .println("WARNING: Encoding mismatch3 test not executed on platform without MS950 encoding.");
-	        return;
-	    }
-	}
+	
+	// JENA-1537
+    // Character encoding checks removed due to lack of support in JDK XML parser APIs.  
+
+//	public void testEncodingMismatch3() throws IOException {
+//	    try ( FileInputStream fin = new FileInputStream("testing/wg/rdf-charmod-literals/test001.rdf") ;
+//	          InputStreamReader r = new InputStreamReader(fin,"MS950")) {
+//	        subTestEncodingMismatch2(r);
+//	    }catch (java.io.UnsupportedEncodingException e) {
+//	        System.err
+//	        .println("WARNING: Encoding mismatch3 test not executed on platform without MS950 encoding.");
+//	        return;
+//	    }
+//	}
 
 	private void subTestEncodingMismatch2(InputStreamReader r) {
 		if (r.getEncoding().startsWith("UTF")) {

http://git-wip-us.apache.org/repos/asf/jena/blob/c9a7e646/jena-core/src/test/java/org/apache/jena/rdfxml/xmlinput/SAX2RDFMoreTests.java
----------------------------------------------------------------------
diff --git a/jena-core/src/test/java/org/apache/jena/rdfxml/xmlinput/SAX2RDFMoreTests.java b/jena-core/src/test/java/org/apache/jena/rdfxml/xmlinput/SAX2RDFMoreTests.java
index 05a7e70..18539c9 100644
--- a/jena-core/src/test/java/org/apache/jena/rdfxml/xmlinput/SAX2RDFMoreTests.java
+++ b/jena-core/src/test/java/org/apache/jena/rdfxml/xmlinput/SAX2RDFMoreTests.java
@@ -26,13 +26,11 @@ import junit.framework.TestCase;
 import org.apache.jena.rdf.model.Model ;
 import org.apache.jena.rdf.model.ModelFactory ;
 import org.apache.jena.rdf.model.RDFReader ;
-import org.apache.jena.rdfxml.xmlinput.SAX2Model ;
-import org.apache.jena.rdfxml.xmlinput.SAX2RDF ;
 import org.apache.jena.rdfxml.xmlinput.SAX2RDFTest.RDFEHArray ;
-import org.apache.xerces.parsers.SAXParser;
 import org.xml.sax.InputSource;
 import org.xml.sax.SAXParseException;
 import org.xml.sax.XMLReader;
+import org.xml.sax.helpers.XMLReaderFactory;
 
 public class SAX2RDFMoreTests extends TestCase {
 	public SAX2RDFMoreTests(String nm) {
@@ -52,9 +50,8 @@ public class SAX2RDFMoreTests extends TestCase {
 	    RDFEHArray eh2 = new RDFEHArray();
 
 	    try ( InputStream in = new FileInputStream("testing/wg/rdfms-xmllang/test003.rdf") ) {
-	        XMLReader saxParser = new SAXParser();
-	        SAX2Model handler = SAX2Model.create("http://example.org/", m2,
-	            "fr");
+	        XMLReader saxParser = XMLReaderFactory.createXMLReader();
+	        SAX2Model handler = SAX2Model.create("http://example.org/", m2, "fr");
 	        SAX2RDF.installHandlers(saxParser, handler);
 	        handler.setErrorHandler(eh2);
 

http://git-wip-us.apache.org/repos/asf/jena/blob/c9a7e646/jena-core/src/test/java/org/apache/jena/rdfxml/xmlinput/SAX2RDFTest.java
----------------------------------------------------------------------
diff --git a/jena-core/src/test/java/org/apache/jena/rdfxml/xmlinput/SAX2RDFTest.java b/jena-core/src/test/java/org/apache/jena/rdfxml/xmlinput/SAX2RDFTest.java
index 437be8a..809bb8a 100644
--- a/jena-core/src/test/java/org/apache/jena/rdfxml/xmlinput/SAX2RDFTest.java
+++ b/jena-core/src/test/java/org/apache/jena/rdfxml/xmlinput/SAX2RDFTest.java
@@ -34,11 +34,11 @@ import org.apache.jena.rdf.model.RDFErrorHandler ;
 import org.apache.jena.rdf.model.RDFReader ;
 import org.apache.jena.rdfxml.xmlinput.SAX2Model ;
 import org.apache.jena.rdfxml.xmlinput.SAX2RDF ;
-import org.apache.xerces.parsers.SAXParser;
 import org.xml.sax.InputSource;
 import org.xml.sax.SAXException;
 import org.xml.sax.SAXParseException;
 import org.xml.sax.XMLReader;
+import org.xml.sax.helpers.XMLReaderFactory;
 
 public class SAX2RDFTest extends TestCase {
 
@@ -1259,11 +1259,10 @@ public class SAX2RDFTest extends TestCase {
 		for (int i = 0; i < eh.v.size(); i++) {
 			assertEquals("Error " + i + " different.", a[i], a2[i]);
 		}
-
 	}
 
 	void loadXMLModel(Model m2, InputStream in, RDFEHArray eh2) throws SAXException, IOException {
-		XMLReader saxParser = new SAXParser();
+		XMLReader saxParser = XMLReaderFactory.createXMLReader();
 		SAX2Model handler = SAX2Model.create(base, m2);
 		SAX2RDF.installHandlers(saxParser, handler);
 		handler.setErrorHandler(eh2);

http://git-wip-us.apache.org/repos/asf/jena/blob/c9a7e646/jena-core/src/test/java/org/apache/jena/rdfxml/xmlinput/states/TestARPStates.java
----------------------------------------------------------------------
diff --git a/jena-core/src/test/java/org/apache/jena/rdfxml/xmlinput/states/TestARPStates.java b/jena-core/src/test/java/org/apache/jena/rdfxml/xmlinput/states/TestARPStates.java
index 3fa9742..29a0e0f 100644
--- a/jena-core/src/test/java/org/apache/jena/rdfxml/xmlinput/states/TestARPStates.java
+++ b/jena-core/src/test/java/org/apache/jena/rdfxml/xmlinput/states/TestARPStates.java
@@ -34,7 +34,7 @@ public class TestARPStates extends TestCase {
 
     public static TestSuite suite() {
         TestSuite rslt = new TestSuite();
-        rslt.setName("ARP state machine");
+        //rslt.setName("ARP state machine");
         Map<String, TestSuite> tests = new HashMap<>();
         try ( LineNumberReader r = new LineNumberReader(new FileReader(TestData.dataFile)) ) {
             while (true) {

http://git-wip-us.apache.org/repos/asf/jena/blob/c9a7e646/jena-core/src/test/java/org/apache/jena/rdfxml/xmloutput/TestMacEncodings.java
----------------------------------------------------------------------
diff --git a/jena-core/src/test/java/org/apache/jena/rdfxml/xmloutput/TestMacEncodings.java b/jena-core/src/test/java/org/apache/jena/rdfxml/xmloutput/TestMacEncodings.java
index c9547ea..bf12c12 100644
--- a/jena-core/src/test/java/org/apache/jena/rdfxml/xmloutput/TestMacEncodings.java
+++ b/jena-core/src/test/java/org/apache/jena/rdfxml/xmloutput/TestMacEncodings.java
@@ -40,10 +40,12 @@ public class TestMacEncodings  extends ModelTestBase
 	public TestMacEncodings( String name )
 		{ super( name ); }
 			
-	public static TestSuite suite()
+	// JENA-1537
+	// Character encoding checks removed due to lack of support in JDK XML parser APIs.  
+	public static TestSuite inactive_suite()
     	{ 
 	    TestSuite suite = new TestSuite( TestMacEncodings.class );
-        suite.setName("Encodings (particular MacRoman etc.)");
+        suite.setName("Encodings - particular MacRoman etc.");
 
         try {
             OutputStream out = new ByteArrayOutputStream();


[22/24] jena git commit: JENA-1537: Remove dependency on Xerces. Import needed code

Posted by an...@apache.org.
JENA-1537: Remove dependency on Xerces. Import needed code


Project: http://git-wip-us.apache.org/repos/asf/jena/repo
Commit: http://git-wip-us.apache.org/repos/asf/jena/commit/c9a7e646
Tree: http://git-wip-us.apache.org/repos/asf/jena/tree/c9a7e646
Diff: http://git-wip-us.apache.org/repos/asf/jena/diff/c9a7e646

Branch: refs/heads/master
Commit: c9a7e646be45d44f26b44e51187487f12f182b89
Parents: 52377b8
Author: Andy Seaborne <an...@apache.org>
Authored: Mon Apr 30 18:26:05 2018 +0100
Committer: Andy Seaborne <an...@apache.org>
Committed: Tue May 1 08:51:34 2018 +0100

----------------------------------------------------------------------
 apache-jena-osgi/jena-osgi/pom.xml              |   21 +-
 .../org/apache/jena/sparql/expr/NodeValue.java  |   70 +-
 .../apache/jena/sparql/expr/RegexXerces.java    |    7 +-
 jena-cmds/src/main/java/jena/schemagen.java     |    2 +-
 jena-core/pom.xml                               |    5 -
 .../apache/jena/datatypes/xsd/XSDDatatype.java  |  173 +-
 .../jena/ext/xerces/DatatypeFactoryInst.java    |   32 +
 .../apache/jena/ext/xerces/impl/Constants.java  |  694 ++++
 .../apache/jena/ext/xerces/impl/Version.java    |   37 +
 .../jena/ext/xerces/impl/dv/DTDDVFactory.java   |   86 +
 .../ext/xerces/impl/dv/DVFactoryException.java  |   40 +
 .../ext/xerces/impl/dv/DatatypeException.java   |  106 +
 .../ext/xerces/impl/dv/DatatypeValidator.java   |   42 +
 .../impl/dv/InvalidDatatypeFacetException.java  |   47 +
 .../impl/dv/InvalidDatatypeValueException.java  |   46 +
 .../jena/ext/xerces/impl/dv/ObjectFactory.java  |  546 +++
 .../ext/xerces/impl/dv/SchemaDVFactory.java     |  145 +
 .../ext/xerces/impl/dv/SecuritySupport.java     |  150 +
 .../jena/ext/xerces/impl/dv/ValidatedInfo.java  |  239 ++
 .../ext/xerces/impl/dv/ValidationContext.java   |   63 +
 .../jena/ext/xerces/impl/dv/XSFacets.java       |  135 +
 .../jena/ext/xerces/impl/dv/XSSimpleType.java   |  201 +
 .../jena/ext/xerces/impl/dv/util/Base64.java    |  305 ++
 .../ext/xerces/impl/dv/util/ByteListImpl.java   |  112 +
 .../jena/ext/xerces/impl/dv/util/HexBin.java    |  113 +
 .../xerces/impl/dv/xs/AbstractDateTimeDV.java   | 1107 ++++++
 .../jena/ext/xerces/impl/dv/xs/AnyAtomicDV.java |   43 +
 .../jena/ext/xerces/impl/dv/xs/AnySimpleDV.java |   45 +
 .../jena/ext/xerces/impl/dv/xs/AnyURIDV.java    |  170 +
 .../ext/xerces/impl/dv/xs/Base64BinaryDV.java   |   92 +
 .../ext/xerces/impl/dv/xs/BaseDVFactory.java    |  248 ++
 .../xerces/impl/dv/xs/BaseSchemaDVFactory.java  |  326 ++
 .../jena/ext/xerces/impl/dv/xs/BooleanDV.java   |   50 +
 .../jena/ext/xerces/impl/dv/xs/DateDV.java      |   96 +
 .../jena/ext/xerces/impl/dv/xs/DateTimeDV.java  |   95 +
 .../jena/ext/xerces/impl/dv/xs/DayDV.java       |  120 +
 .../xerces/impl/dv/xs/DayTimeDurationDV.java    |   62 +
 .../jena/ext/xerces/impl/dv/xs/DecimalDV.java   |  375 ++
 .../jena/ext/xerces/impl/dv/xs/DoubleDV.java    |  265 ++
 .../jena/ext/xerces/impl/dv/xs/DurationDV.java  |  392 ++
 .../jena/ext/xerces/impl/dv/xs/EntityDV.java    |   57 +
 .../impl/dv/xs/ExtendedSchemaDVFactoryImpl.java |   84 +
 .../jena/ext/xerces/impl/dv/xs/FloatDV.java     |  246 ++
 .../ext/xerces/impl/dv/xs/FullDVFactory.java    |  169 +
 .../jena/ext/xerces/impl/dv/xs/HexBinaryDV.java |   94 +
 .../apache/jena/ext/xerces/impl/dv/xs/IDDV.java |   56 +
 .../jena/ext/xerces/impl/dv/xs/IDREFDV.java     |   55 +
 .../jena/ext/xerces/impl/dv/xs/IntegerDV.java   |   43 +
 .../jena/ext/xerces/impl/dv/xs/ListDV.java      |  146 +
 .../jena/ext/xerces/impl/dv/xs/MonthDV.java     |  168 +
 .../jena/ext/xerces/impl/dv/xs/MonthDayDV.java  |  132 +
 .../xerces/impl/dv/xs/PrecisionDecimalDV.java   |  369 ++
 .../jena/ext/xerces/impl/dv/xs/QNameDV.java     |  112 +
 .../xerces/impl/dv/xs/SchemaDVFactoryImpl.java  |   76 +
 .../impl/dv/xs/SchemaDateTimeException.java     |   37 +
 .../jena/ext/xerces/impl/dv/xs/StringDV.java    |   46 +
 .../jena/ext/xerces/impl/dv/xs/TimeDV.java      |  114 +
 .../ext/xerces/impl/dv/xs/TypeValidator.java    |  108 +
 .../jena/ext/xerces/impl/dv/xs/UnionDV.java     |   47 +
 .../ext/xerces/impl/dv/xs/XSSimpleTypeDecl.java | 3562 ++++++++++++++++++
 .../xerces/impl/dv/xs/XSSimpleTypeDelegate.java |  249 ++
 .../jena/ext/xerces/impl/dv/xs/YearDV.java      |  129 +
 .../jena/ext/xerces/impl/dv/xs/YearMonthDV.java |  103 +
 .../xerces/impl/dv/xs/YearMonthDurationDV.java  |   64 +
 .../validation/ConfigurableValidationState.java |  126 +
 .../ext/xerces/impl/validation/EntityState.java |   47 +
 .../impl/validation/ValidationManager.java      |   84 +
 .../xerces/impl/validation/ValidationState.java |  215 ++
 .../ext/xerces/impl/xpath/regex/BMPattern.java  |  236 ++
 .../impl/xpath/regex/CaseInsensitiveMap.java    |  162 +
 .../jena/ext/xerces/impl/xpath/regex/Match.java |  185 +
 .../jena/ext/xerces/impl/xpath/regex/Op.java    |  261 ++
 .../xerces/impl/xpath/regex/ParseException.java |   53 +
 .../impl/xpath/regex/ParserForXMLSchema.java    |  534 +++
 .../ext/xerces/impl/xpath/regex/REUtil.java     |  363 ++
 .../ext/xerces/impl/xpath/regex/RangeToken.java |  631 ++++
 .../xerces/impl/xpath/regex/RegexParser.java    | 1230 ++++++
 .../impl/xpath/regex/RegularExpression.java     | 2456 ++++++++++++
 .../jena/ext/xerces/impl/xpath/regex/Token.java | 1562 ++++++++
 .../xerces/impl/xpath/regex/message.properties  |   58 +
 .../impl/xpath/regex/message_fr.properties      |   58 +
 .../impl/xpath/regex/message_ja.properties      |   58 +
 .../jena/ext/xerces/impl/xs/SchemaSymbols.java  |  215 ++
 .../ext/xerces/impl/xs/XSDeclarationPool.java   |  315 ++
 .../ext/xerces/impl/xs/util/ObjectListImpl.java |  123 +
 .../ext/xerces/impl/xs/util/ShortListImpl.java  |  128 +
 .../ext/xerces/impl/xs/util/StringListImpl.java |  171 +
 .../xerces/impl/xs/util/XSObjectListImpl.java   |  293 ++
 .../jaxp/datatype/DatatypeFactoryImpl.java      |  394 ++
 .../ext/xerces/jaxp/datatype/DurationImpl.java  | 1991 ++++++++++
 .../jaxp/datatype/XMLGregorianCalendarImpl.java | 3232 ++++++++++++++++
 .../xerces/util/DatatypeMessageFormatter.java   |   96 +
 .../apache/jena/ext/xerces/util/IntStack.java   |  114 +
 .../apache/jena/ext/xerces/util/SymbolHash.java |  223 ++
 .../jena/ext/xerces/util/SymbolTable.java       |  408 ++
 .../org/apache/jena/ext/xerces/util/URI.java    | 2185 +++++++++++
 .../apache/jena/ext/xerces/util/XML11Char.java  |  413 ++
 .../apache/jena/ext/xerces/util/XMLChar.java    | 1062 ++++++
 .../jena/ext/xerces/xni/NamespaceContext.java   |  177 +
 .../jena/ext/xerces/xs/AttributePSVI.java       |   30 +
 .../apache/jena/ext/xerces/xs/ElementPSVI.java  |   47 +
 .../org/apache/jena/ext/xerces/xs/ItemPSVI.java |  209 +
 .../apache/jena/ext/xerces/xs/LSInputList.java  |   48 +
 .../apache/jena/ext/xerces/xs/PSVIProvider.java |   90 +
 .../apache/jena/ext/xerces/xs/ShortList.java    |   57 +
 .../apache/jena/ext/xerces/xs/StringList.java   |   55 +
 .../apache/jena/ext/xerces/xs/XSAnnotation.java |   60 +
 .../ext/xerces/xs/XSAttributeDeclaration.java   |  121 +
 .../xerces/xs/XSAttributeGroupDefinition.java   |   45 +
 .../jena/ext/xerces/xs/XSAttributeUse.java      |  108 +
 .../ext/xerces/xs/XSComplexTypeDefinition.java  |  113 +
 .../apache/jena/ext/xerces/xs/XSConstants.java  |  326 ++
 .../ext/xerces/xs/XSElementDeclaration.java     |  189 +
 .../apache/jena/ext/xerces/xs/XSException.java  |   53 +
 .../org/apache/jena/ext/xerces/xs/XSFacet.java  |   69 +
 .../jena/ext/xerces/xs/XSIDCDefinition.java     |   69 +
 .../jena/ext/xerces/xs/XSImplementation.java    |   64 +
 .../org/apache/jena/ext/xerces/xs/XSLoader.java |   90 +
 .../org/apache/jena/ext/xerces/xs/XSModel.java  |  173 +
 .../apache/jena/ext/xerces/xs/XSModelGroup.java |   63 +
 .../ext/xerces/xs/XSModelGroupDefinition.java   |   39 +
 .../jena/ext/xerces/xs/XSMultiValueFacet.java   |   47 +
 .../apache/jena/ext/xerces/xs/XSNamedMap.java   |   67 +
 .../jena/ext/xerces/xs/XSNamespaceItem.java     |  117 +
 .../jena/ext/xerces/xs/XSNamespaceItemList.java |   46 +
 .../ext/xerces/xs/XSNotationDeclaration.java    |   46 +
 .../org/apache/jena/ext/xerces/xs/XSObject.java |   55 +
 .../apache/jena/ext/xerces/xs/XSObjectList.java |   46 +
 .../apache/jena/ext/xerces/xs/XSParticle.java   |   52 +
 .../ext/xerces/xs/XSSimpleTypeDefinition.java   |  244 ++
 .../org/apache/jena/ext/xerces/xs/XSTerm.java   |   27 +
 .../jena/ext/xerces/xs/XSTypeDefinition.java    |  102 +
 .../org/apache/jena/ext/xerces/xs/XSValue.java  |   97 +
 .../apache/jena/ext/xerces/xs/XSWildcard.java   |   87 +
 .../jena/ext/xerces/xs/datatypes/ByteList.java  |   66 +
 .../ext/xerces/xs/datatypes/ObjectList.java     |   60 +
 .../ext/xerces/xs/datatypes/XSDateTime.java     |  291 ++
 .../jena/ext/xerces/xs/datatypes/XSDecimal.java |   65 +
 .../jena/ext/xerces/xs/datatypes/XSDouble.java  |   33 +
 .../jena/ext/xerces/xs/datatypes/XSFloat.java   |   33 +
 .../jena/ext/xerces/xs/datatypes/package.html   |  306 ++
 .../org/apache/jena/rdf/model/impl/Util.java    |    2 +-
 .../rdfxml/xmlinput/impl/ParserSupport.java     |    4 +-
 .../jena/rdfxml/xmlinput/impl/RDFXMLParser.java |  141 +-
 .../rdfxml/xmloutput/impl/BaseXMLWriter.java    |    2 +-
 .../jena/rdfxml/xmloutput/impl/Unparser.java    |    2 +-
 .../jena/shared/impl/PrefixMappingImpl.java     |    2 +-
 .../ext/xerces/impl/msg/DOMMessages.properties  |   84 +
 .../xerces/impl/msg/DatatypeMessages.properties |   47 +
 .../impl/msg/JAXPValidationMessages.properties  |   50 +
 .../ext/xerces/impl/msg/SAXMessages.properties  |   46 +
 .../xerces/impl/msg/XIncludeMessages.properties |   56 +
 .../ext/xerces/impl/msg/XMLMessages.properties  |  309 ++
 .../impl/msg/XMLSchemaMessages.properties       |  320 ++
 .../impl/msg/XMLSerializerMessages.properties   |   50 +
 .../xerces/impl/msg/XPointerMessages.properties |   44 +
 .../xerces/impl/xpath/regex/message.properties  |   58 +
 .../impl/xpath/regex/message_fr.properties      |   58 +
 .../impl/xpath/regex/message_ja.properties      |   58 +
 .../jena/graph/test/TestTypedLiterals.java      |  121 +-
 .../apache/jena/rdfxml/xmlinput/MoreTests.java  |  107 +-
 .../jena/rdfxml/xmlinput/SAX2RDFMoreTests.java  |    9 +-
 .../jena/rdfxml/xmlinput/SAX2RDFTest.java       |    5 +-
 .../rdfxml/xmlinput/states/TestARPStates.java   |    2 +-
 .../jena/rdfxml/xmloutput/TestMacEncodings.java |    6 +-
 .../jena/rdfxml/xmloutput/TestPackage.java      |    7 +-
 .../jena/tdb2/store/value/DateTimeNode.java     |   14 +-
 .../jena/tdb2/store/value/TestNodeIdInline.java |    2 +-
 .../org/apache/jena/tdb/store/DateTimeNode.java |   15 +-
 .../java/org/apache/jena/tdb/store/NodeId.java  |    3 -
 .../org/apache/jena/tdb/store/TestNodeId.java   |    2 +-
 pom.xml                                         |    7 -
 172 files changed, 38259 insertions(+), 407 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/jena/blob/c9a7e646/apache-jena-osgi/jena-osgi/pom.xml
----------------------------------------------------------------------
diff --git a/apache-jena-osgi/jena-osgi/pom.xml b/apache-jena-osgi/jena-osgi/pom.xml
index aa434ae..9fd2c35 100644
--- a/apache-jena-osgi/jena-osgi/pom.xml
+++ b/apache-jena-osgi/jena-osgi/pom.xml
@@ -116,19 +116,6 @@
       <version>3.8.0-SNAPSHOT</version>
       <scope>provided</scope>
     </dependency>
-   <!-- xerces is needed - but this is marked as optional as some
-        OSGi frameworks like Karaf will include their own
-        xerces in their boot delegation.
-
-        See also pull request #134
-        https://github.com/apache/jena/pull/134#issuecomment-209474708
-   -->
-    <dependency>
-        <groupId>org.apache.servicemix.bundles</groupId>
-        <artifactId>org.apache.servicemix.bundles.xerces</artifactId>
-        <version>2.11.0_1</version>
-        <optional>true</optional>
-    </dependency>
 
     <dependency>
       <groupId>org.apache.jena</groupId>
@@ -256,14 +243,10 @@
           <instructions>
             <Export-Package>org.apache.jena.*,!org.apache.jena.ext.*</Export-Package>            
             <Embed-Dependency>artifactId=jena*;inline=true</Embed-Dependency>
-            <!--            
-            <Embed-Dependency>artifactId=jena*;inline=true,artifactId=xercesImpl;inline=true,artifactId=xml-apis;inline=true</Embed-Dependency>
-            -->
             <Embed-Transitive>true</Embed-Transitive>
-            <!-- Do not embed but import Xerces classes via OSGi -->
-            <Import-Package>org.osgi.framework.*,org.apache.xml.*,org.apache.xerces.*;version="2.11.0",!sun.io,!org.apache.avalon.framework.logger,!com.ibm.uvm.tools,!com.sun.jdmk.comm,!org.apache.log,!org.apache.jena.ext.*,sun.misc;resolution:=optional,com.google.errorprone.annotations.concurrent;resolution:=optional,*</Import-Package>
+            <Import-Package>org.osgi.framework.*,!sun.io,!org.apache.avalon.framework.logger,!com.ibm.uvm.tools,!com.sun.jdmk.comm,!org.apache.log,!org.apache.jena.ext.*,sun.misc;resolution:=optional,com.google.errorprone.annotations.concurrent;resolution:=optional,*</Import-Package>
             <!--
-            <Import-Package>org.osgi.framework.*,!sun.io,!org.apache.avalon.framework.logger,!com.ibm.uvm.tools,!com.sun.jdmk.comm,!org.apache.log,!org.apache.xml.*,!org.apache.xerces.*,!org.apache.jena.ext.*,sun.misc;resolution:=optional,*</Import-Package>
+            <Import-Package>org.osgi.framework.*,!sun.io,!org.apache.avalon.framework.logger,!com.ibm.uvm.tools,!com.sun.jdmk.comm,!org.apache.log,!org.apache.xml.*,!org.apache.jena.ext.*,sun.misc;resolution:=optional,*</Import-Package>
             -->
             <Private-Package>org.apache.jena.ext.*</Private-Package>
             <Bundle-Activator>org.apache.jena.osgi.Activator</Bundle-Activator>

http://git-wip-us.apache.org/repos/asf/jena/blob/c9a7e646/jena-arq/src/main/java/org/apache/jena/sparql/expr/NodeValue.java
----------------------------------------------------------------------
diff --git a/jena-arq/src/main/java/org/apache/jena/sparql/expr/NodeValue.java b/jena-arq/src/main/java/org/apache/jena/sparql/expr/NodeValue.java
index 1a1b675..23b5c79 100644
--- a/jena-arq/src/main/java/org/apache/jena/sparql/expr/NodeValue.java
+++ b/jena-arq/src/main/java/org/apache/jena/sparql/expr/NodeValue.java
@@ -22,17 +22,10 @@ import static javax.xml.datatype.DatatypeConstants.* ;
 import static org.apache.jena.datatypes.xsd.XSDDatatype.* ;
 import static org.apache.jena.sparql.expr.ValueSpaceClassification.* ;
 
-import java.io.File ;
-import java.io.FileInputStream ;
-import java.io.InputStream ;
 import java.math.BigDecimal ;
 import java.math.BigInteger ;
 import java.util.Calendar ;
-import java.util.Iterator ;
-import java.util.Properties ;
-import java.util.ServiceLoader ;
 
-import javax.xml.datatype.DatatypeConfigurationException ;
 import javax.xml.datatype.DatatypeFactory ;
 import javax.xml.datatype.Duration ;
 import javax.xml.datatype.XMLGregorianCalendar ;
@@ -45,6 +38,7 @@ import org.apache.jena.datatypes.DatatypeFormatException ;
 import org.apache.jena.datatypes.RDFDatatype ;
 import org.apache.jena.datatypes.TypeMapper ;
 import org.apache.jena.datatypes.xsd.XSDDateTime ;
+import org.apache.jena.ext.xerces.DatatypeFactoryInst;
 import org.apache.jena.graph.Node ;
 import org.apache.jena.graph.NodeFactory ;
 import org.apache.jena.graph.impl.LiteralLabel ;
@@ -145,66 +139,8 @@ public abstract class NodeValue extends ExprNode
     
     public static final String xsdNamespace = XSD+"#" ; 
     
-    public static DatatypeFactory xmlDatatypeFactory = null ;
-    static
-    {
-        try { xmlDatatypeFactory = getDatatypeFactory() ; }
-        catch (DatatypeConfigurationException ex)
-        { throw new ARQInternalErrorException("Can't create a javax.xml DatatypeFactory", ex) ; }
-    }
-    
-    /**
-     * Get a datatype factory using the correct classloader
-     * 
-     * See JENA-328. DatatypeFactory.newInstance() clashes with OSGi
-     * This is clearly crazy, but DatatypeFactory is missing a very obvious
-     * method newInstance(Classloader). The method that was added is very
-     * hard to use correctly, as we shall see...
-     */
-    private static DatatypeFactory getDatatypeFactory() 
-            throws DatatypeConfigurationException {
-        // Step 1. Try the system property
-        String dtfClass = System.getProperty(DatatypeFactory.DATATYPEFACTORY_PROPERTY);
-        
-        try {
-            File jaxpPropFile = new File(System.getProperty("java.home") + 
-                                         File.separator + "lib" + File.separator + "jaxp.properties");
-            // Step 2. Otherwise, try property in jaxp.properties
-            if (dtfClass == null && jaxpPropFile.exists() && jaxpPropFile.canRead()) {
-                Properties jaxp = new Properties();
-                try(InputStream in = new FileInputStream(jaxpPropFile)) {
-                    jaxp.load(in);
-                    dtfClass = jaxp.getProperty(DatatypeFactory.DATATYPEFACTORY_PROPERTY);
-                } catch (Exception e) {
-                    log.warn("Issue loading jaxp.properties", e);
-                }
-            }
-        }
-        // File.exists and File.canRead may throw  SecurityException (probably AccessControlException)
-        catch (SecurityException ex) {
-            log.warn("Security exception try to get jaxp.properties: "+ex.getMessage()) ;
-        }
-        
-        // Step 3. Otherwise try the service approach
-        // This is the normal initialization path, getting it from the Apach Xerces dependency
-        // and loading org.apache.xerces.jaxp.datatype.DatatypeFactoryImpl
-        if (dtfClass == null) {
-            ClassLoader cl = NodeValue.class.getClassLoader();
-            Iterator<DatatypeFactory> factoryIterator = 
-                ServiceLoader.load(DatatypeFactory.class, cl).iterator();
-            if (factoryIterator.hasNext()) return factoryIterator.next();
-        }
-        
-        // Step 4. Use the default.
-        // Note: When Apache Xerces is on the classpath for Jena, javax.xml.datatype.DatatypeFactory is from that jar and
-        //  DATATYPEFACTORY_IMPLEMENTATION_CLASS is "org.apache.xerces.jaxp.datatype.DatatypeFactoryImpl"
-        // Without an explicit Xerces, we would get "com.sun.org.apache.xerces.internal.jaxp.datatype.DatatypeFactoryImpl"
-        // from the JDK rt.jar version of javax.xml.datatype.DatatypeFactory.
-        if (dtfClass == null) 
-            dtfClass = DatatypeFactory.DATATYPEFACTORY_IMPLEMENTATION_CLASS;
-        return DatatypeFactory.newInstance(dtfClass, NodeValue.class.getClassLoader()) ;
-    }
-    
+    public static  DatatypeFactory xmlDatatypeFactory = DatatypeFactoryInst.newDatatypeFactory();
+
     private Node node = null ;     // Null used when a value has not be turned into a Node.
     
     // Don't create direct - the static builders manage the value/node relationship 

http://git-wip-us.apache.org/repos/asf/jena/blob/c9a7e646/jena-arq/src/main/java/org/apache/jena/sparql/expr/RegexXerces.java
----------------------------------------------------------------------
diff --git a/jena-arq/src/main/java/org/apache/jena/sparql/expr/RegexXerces.java b/jena-arq/src/main/java/org/apache/jena/sparql/expr/RegexXerces.java
index b2a2a88..42b10c2 100644
--- a/jena-arq/src/main/java/org/apache/jena/sparql/expr/RegexXerces.java
+++ b/jena-arq/src/main/java/org/apache/jena/sparql/expr/RegexXerces.java
@@ -18,9 +18,9 @@
 
 package org.apache.jena.sparql.expr;
 
-import org.apache.xerces.impl.xpath.regex.ParseException ;
-import org.apache.xerces.impl.xpath.regex.REUtil ;
-import org.apache.xerces.impl.xpath.regex.RegularExpression ;
+import org.apache.jena.ext.xerces.impl.xpath.regex.ParseException;
+import org.apache.jena.ext.xerces.impl.xpath.regex.REUtil;
+import org.apache.jena.ext.xerces.impl.xpath.regex.RegularExpression;
 
 public class RegexXerces implements RegexEngine
 {
@@ -29,7 +29,6 @@ public class RegexXerces implements RegexEngine
     public RegexXerces(String pattern, String flags)
     {
         if ( flags.contains("q") )
-            // Nest we can do.
             pattern = REUtil.quoteMeta(pattern);
         regexPattern = makePattern(pattern, flags) ;
     }

http://git-wip-us.apache.org/repos/asf/jena/blob/c9a7e646/jena-cmds/src/main/java/jena/schemagen.java
----------------------------------------------------------------------
diff --git a/jena-cmds/src/main/java/jena/schemagen.java b/jena-cmds/src/main/java/jena/schemagen.java
index 698cc7d..d988a60 100644
--- a/jena-cmds/src/main/java/jena/schemagen.java
+++ b/jena-cmds/src/main/java/jena/schemagen.java
@@ -34,6 +34,7 @@ import java.util.* ;
 import java.util.regex.Pattern ;
 import java.util.regex.PatternSyntaxException ;
 
+import org.apache.jena.ext.xerces.util.XMLChar;
 import org.apache.jena.ontology.Individual ;
 import org.apache.jena.ontology.OntModel ;
 import org.apache.jena.ontology.OntModelSpec ;
@@ -46,7 +47,6 @@ import org.apache.jena.vocabulary.OWL ;
 import org.apache.jena.vocabulary.RDF ;
 import org.apache.jena.vocabulary.RDFS ;
 import org.apache.jena.vocabulary.XSD ;
-import org.apache.xerces.util.XMLChar ;
 
 
 

http://git-wip-us.apache.org/repos/asf/jena/blob/c9a7e646/jena-core/pom.xml
----------------------------------------------------------------------
diff --git a/jena-core/pom.xml b/jena-core/pom.xml
index 48de2b1..3ebda27 100644
--- a/jena-core/pom.xml
+++ b/jena-core/pom.xml
@@ -58,11 +58,6 @@
       <version>3.8.0-SNAPSHOT</version>
     </dependency>
 
-    <dependency>
-      <groupId>xerces</groupId>
-      <artifactId>xercesImpl</artifactId>
-    </dependency>
-
      <dependency>
        <artifactId>commons-cli</artifactId>
        <groupId>commons-cli</groupId>

http://git-wip-us.apache.org/repos/asf/jena/blob/c9a7e646/jena-core/src/main/java/org/apache/jena/datatypes/xsd/XSDDatatype.java
----------------------------------------------------------------------
diff --git a/jena-core/src/main/java/org/apache/jena/datatypes/xsd/XSDDatatype.java b/jena-core/src/main/java/org/apache/jena/datatypes/xsd/XSDDatatype.java
index a7266fd..3319c8e 100644
--- a/jena-core/src/main/java/org/apache/jena/datatypes/xsd/XSDDatatype.java
+++ b/jena-core/src/main/java/org/apache/jena/datatypes/xsd/XSDDatatype.java
@@ -18,33 +18,25 @@
 
 package org.apache.jena.datatypes.xsd;
 
-import java.io.Reader ;
 import java.math.BigDecimal ;
 import java.math.BigInteger ;
 import java.net.URI ;
-import java.util.ArrayList ;
-import java.util.List ;
 
 import org.apache.jena.datatypes.BaseDatatype ;
 import org.apache.jena.datatypes.DatatypeFormatException ;
 import org.apache.jena.datatypes.RDFDatatype ;
 import org.apache.jena.datatypes.TypeMapper ;
 import org.apache.jena.datatypes.xsd.impl.* ;
+import org.apache.jena.ext.xerces.impl.dv.*;
+import org.apache.jena.ext.xerces.impl.dv.util.Base64;
+import org.apache.jena.ext.xerces.impl.dv.util.HexBin;
+import org.apache.jena.ext.xerces.impl.dv.xs.DecimalDV;
+import org.apache.jena.ext.xerces.impl.dv.xs.XSSimpleTypeDecl;
+import org.apache.jena.ext.xerces.impl.validation.ValidationState;
+import org.apache.jena.ext.xerces.util.SymbolHash;
+import org.apache.jena.ext.xerces.xs.XSConstants;
+import org.apache.jena.ext.xerces.xs.XSTypeDefinition;
 import org.apache.jena.graph.impl.LiteralLabel ;
-import org.apache.xerces.impl.dv.* ;
-import org.apache.xerces.impl.dv.util.Base64 ;
-import org.apache.xerces.impl.dv.util.HexBin ;
-import org.apache.xerces.impl.dv.xs.DecimalDV ;
-import org.apache.xerces.impl.dv.xs.XSSimpleTypeDecl ;
-import org.apache.xerces.impl.validation.ValidationState ;
-import org.apache.xerces.parsers.XMLGrammarPreparser ;
-import org.apache.xerces.util.SymbolHash ;
-import org.apache.xerces.xni.grammars.XMLGrammarDescription ;
-import org.apache.xerces.xni.grammars.XSGrammar ;
-import org.apache.xerces.xni.parser.XMLInputSource ;
-import org.apache.xerces.xs.XSConstants ;
-import org.apache.xerces.xs.XSNamedMap ;
-import org.apache.xerces.xs.XSTypeDefinition ;
 
 /**
  * Representation of an XSD datatype based on the Xerces-2
@@ -315,77 +307,82 @@ public class XSDDatatype extends BaseDatatype {
         return typeDeclaration;
     }
 
-    /**
-     * Create and register a set of types specified in a user schema file.
-     * We use the (illegal) DAML+OIL approach that the uriref of the type
-     * is the url of the schema file with fragment ID corresponding the
-     * the name of the type.
-     *
-     * @param uri the absolute uri of the schema file to be loaded
-     * @param reader the Reader stream onto the file (useful if you wish to load a cached copy of the schema file)
-     * @param encoding the encoding of the source file (can be null)
-     * @param tm the type mapper into which to load the definitions
-     * @return a List of strings giving the uri's of the newly defined datatypes
-     * @throws DatatypeFormatException if there is a problem during load (not that we use Xerces
-     * in default mode for load which may provide diagnostic output direct to stderr)
-     */
-    public static List<String> loadUserDefined(String uri, Reader reader, String encoding, TypeMapper tm) throws DatatypeFormatException {
-        return loadUserDefined(new XMLInputSource(null, uri, uri, reader, encoding), tm);
-    }
-
-    /**
-     * Create and register a set of types specified in a user schema file.
-     * We use the (illegal) DAML+OIL approach that the uriref of the type
-     * is the url of the schema file with fragment ID corresponding the
-     * the name of the type.
-     *
-     * @param uri the absolute uri of the schema file to be loaded, this should be a resolvable URL
-     * @param encoding the encoding of the source file (can be null)
-     * @param tm the type mapper into which to load the definitions
-     * @return a List of strings giving the uri's of the newly defined datatypes
-     * @throws DatatypeFormatException if there is a problem during load (not that we use Xerces
-     * in default mode for load which may provide diagnostic output direct to stderr)
-     */
-    public static List<String> loadUserDefined(String uri, String encoding, TypeMapper tm) throws DatatypeFormatException {
-        return loadUserDefined(new XMLInputSource(null, uri, uri), tm);
-    }
-
-    /**
-     * Internal implementation of loadUserDefined
-     *
-     * @param uri the absolute uri of the schema file to be loaded
-     * @param reader the Reader stream onto the file (useful if you wish to load a cached copy of the schema file)
-     * @param encoding the encoding of the source file (can be null)
-     * @param tm the type mapper into which to load the definitions
-     * @return a List of strings giving the uri's of the newly defined datatypes
-     * @throws DatatypeFormatException if there is a problem during load (not that we use Xerces
-     * in default mode for load which may provide diagnostic output direct to stderr)
-     */
-    private static List<String> loadUserDefined(XMLInputSource source, TypeMapper tm) throws DatatypeFormatException {
-        XMLGrammarPreparser parser = new XMLGrammarPreparser();
-        parser.registerPreparser(XMLGrammarDescription.XML_SCHEMA, null);
-        try {
-            XSGrammar xsg = (XSGrammar) parser.preparseGrammar(XMLGrammarDescription.XML_SCHEMA, source);
-            org.apache.xerces.xs.XSModel xsm = xsg.toXSModel();
-            XSNamedMap map = xsm.getComponents(XSTypeDefinition.SIMPLE_TYPE);
-            int numDefs = map.getLength();
-            ArrayList<String> names = new ArrayList<>(numDefs);
-            for (int i = 0; i < numDefs; i++) {
-                XSSimpleType xstype = (XSSimpleType) map.item(i);
-                // Filter built in types - only needed for 2.6.0
-                if ( ! XSD.equals(xstype.getNamespace()) ) {
-                    //xstype.derivedFrom()
-                    XSDDatatype definedType = new XSDGenericType(xstype, source.getSystemId());
-                    tm.registerDatatype(definedType);
-                    names.add(definedType.getURI());
-                }
-            }
-            return names;
-        } catch (Exception e) {
-            e.printStackTrace();    // Temp
-            throw new DatatypeFormatException(e.toString());
-        }
-    }
+    // The following code parses an external XSD file for XSD datatype definitions.
+    // See an example "testing/xsd/daml+oil-ex-dt.xsd" and TestTypeLiterals.testUserDefined.
+    // It calls into Xerces internal XM parsing, which is problematic if switching to the
+    // JDK built-in XML parser in Java9 and later.
+    
+//    /**
+//     * Create and register a set of types specified in a user schema file.
+//     * We use the (illegal) DAML+OIL approach that the uriref of the type
+//     * is the url of the schema file with fragment ID corresponding the
+//     * the name of the type.
+//     *
+//     * @param uri the absolute uri of the schema file to be loaded
+//     * @param reader the Reader stream onto the file (useful if you wish to load a cached copy of the schema file)
+//     * @param encoding the encoding of the source file (can be null)
+//     * @param tm the type mapper into which to load the definitions
+//     * @return a List of strings giving the uri's of the newly defined datatypes
+//     * @throws DatatypeFormatException if there is a problem during load (not that we use Xerces
+//     * in default mode for load which may provide diagnostic output direct to stderr)
+//     */
+//    public static List<String> loadUserDefined(String uri, Reader reader, String encoding, TypeMapper tm) throws DatatypeFormatException {
+//        return loadUserDefined(new XMLInputSource(null, uri, uri, reader, encoding), tm);
+//    }
+//
+//    /**
+//     * Create and register a set of types specified in a user schema file.
+//     * We use the (illegal) DAML+OIL approach that the uriref of the type
+//     * is the url of the schema file with fragment ID corresponding the
+//     * the name of the type.
+//     *
+//     * @param uri the absolute uri of the schema file to be loaded, this should be a resolvable URL
+//     * @param encoding the encoding of the source file (can be null)
+//     * @param tm the type mapper into which to load the definitions
+//     * @return a List of strings giving the uri's of the newly defined datatypes
+//     * @throws DatatypeFormatException if there is a problem during load (not that we use Xerces
+//     * in default mode for load which may provide diagnostic output direct to stderr)
+//     */
+//    public static List<String> loadUserDefined(String uri, String encoding, TypeMapper tm) throws DatatypeFormatException {
+//        return loadUserDefined(new XMLInputSource(null, uri, uri), tm);
+//    }
+//
+//    /**
+//     * Internal implementation of loadUserDefined
+//     *
+//     * @param uri the absolute uri of the schema file to be loaded
+//     * @param reader the Reader stream onto the file (useful if you wish to load a cached copy of the schema file)
+//     * @param encoding the encoding of the source file (can be null)
+//     * @param tm the type mapper into which to load the definitions
+//     * @return a List of strings giving the uri's of the newly defined datatypes
+//     * @throws DatatypeFormatException if there is a problem during load (not that we use Xerces
+//     * in default mode for load which may provide diagnostic output direct to stderr)
+//     */
+//    private static List<String> loadUserDefined(XMLInputSource source, TypeMapper tm) throws DatatypeFormatException {
+//        XMLGrammarPreparser parser = new XMLGrammarPreparser();
+//        parser.registerPreparser(XMLGrammarDescription.XML_SCHEMA, null);
+//        try {
+//            XSGrammar xsg = (XSGrammar) parser.preparseGrammar(XMLGrammarDescription.XML_SCHEMA, source);
+//            org.apache.xerces.xs.XSModel xsm = xsg.toXSModel();
+//            XSNamedMap map = xsm.getComponents(XSTypeDefinition.SIMPLE_TYPE);
+//            int numDefs = map.getLength();
+//            ArrayList<String> names = new ArrayList<>(numDefs);
+//            for (int i = 0; i < numDefs; i++) {
+//                XSSimpleType xstype = (XSSimpleType) map.item(i);
+//                // Filter built in types - only needed for 2.6.0
+//                if ( ! XSD.equals(xstype.getNamespace()) ) {
+//                    //xstype.derivedFrom()
+//                    XSDDatatype definedType = new XSDGenericType(xstype, source.getSystemId());
+//                    tm.registerDatatype(definedType);
+//                    names.add(definedType.getURI());
+//                }
+//            }
+//            return names;
+//        } catch (Exception e) {
+//            e.printStackTrace();    // Temp
+//            throw new DatatypeFormatException(e.toString());
+//        }
+//    }
 
     /**
      * Convert a validated xerces data value into the corresponding java data value.

http://git-wip-us.apache.org/repos/asf/jena/blob/c9a7e646/jena-core/src/main/java/org/apache/jena/ext/xerces/DatatypeFactoryInst.java
----------------------------------------------------------------------
diff --git a/jena-core/src/main/java/org/apache/jena/ext/xerces/DatatypeFactoryInst.java b/jena-core/src/main/java/org/apache/jena/ext/xerces/DatatypeFactoryInst.java
new file mode 100644
index 0000000..c6c8068
--- /dev/null
+++ b/jena-core/src/main/java/org/apache/jena/ext/xerces/DatatypeFactoryInst.java
@@ -0,0 +1,32 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you 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.jena.ext.xerces;
+
+import javax.xml.datatype.DatatypeFactory;
+
+import org.apache.jena.ext.xerces.jaxp.datatype.DatatypeFactoryImpl;
+
+public class DatatypeFactoryInst {
+    
+    /** The extracted Xerces 2.11.0 DatatypeFactory.
+     * Gets T24:00:00 right, the JDK does not
+     * (it looses the distinction of with +1 day T00:00:00)
+     */
+    public static DatatypeFactory newDatatypeFactory() { return new DatatypeFactoryImpl(); }
+}

http://git-wip-us.apache.org/repos/asf/jena/blob/c9a7e646/jena-core/src/main/java/org/apache/jena/ext/xerces/impl/Constants.java
----------------------------------------------------------------------
diff --git a/jena-core/src/main/java/org/apache/jena/ext/xerces/impl/Constants.java b/jena-core/src/main/java/org/apache/jena/ext/xerces/impl/Constants.java
new file mode 100644
index 0000000..74399c9
--- /dev/null
+++ b/jena-core/src/main/java/org/apache/jena/ext/xerces/impl/Constants.java
@@ -0,0 +1,694 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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.jena.ext.xerces.impl;
+
+import java.util.Enumeration;
+import java.util.NoSuchElementException;
+
+/**
+ * Commonly used constants.
+ * 
+ * @xerces.internal
+ *
+ * @author Andy Clark, IBM
+ *
+ * @version $Id: Constants.java 915483 2010-02-23 19:00:14Z mrglavas $
+ */
+@SuppressWarnings("all")
+public final class Constants {
+    
+    //
+    // Constants
+    //
+    // Schema Types:
+    public static final String NS_XMLSCHEMA = "http://www.w3.org/2001/XMLSchema".intern();
+    public static final String NS_DTD = "http://www.w3.org/TR/REC-xml".intern();
+    
+    // sax features
+    
+    /** SAX feature prefix ("http://xml.org/sax/features/"). */
+    public static final String SAX_FEATURE_PREFIX = "http://xml.org/sax/features/";
+    
+    /** Namespaces feature ("namespaces"). */
+    public static final String NAMESPACES_FEATURE = "namespaces";
+    
+    /** Namespace prefixes feature ("namespace-prefixes"). */
+    public static final String NAMESPACE_PREFIXES_FEATURE = "namespace-prefixes";
+    
+    /** String interning feature ("string-interning"). */
+    public static final String STRING_INTERNING_FEATURE = "string-interning";
+    
+    /** Validation feature ("validation"). */
+    public static final String VALIDATION_FEATURE = "validation";
+    
+    /** External general entities feature ("external-general-entities "). */
+    public static final String EXTERNAL_GENERAL_ENTITIES_FEATURE = "external-general-entities";
+    
+    /** External parameter entities feature ("external-parameter-entities "). */
+    public static final String EXTERNAL_PARAMETER_ENTITIES_FEATURE = "external-parameter-entities";
+    
+    /** Lexical handler parameter entities feature ("lexical-handler/parameter-entities"). */
+    public static final String LEXICAL_HANDLER_PARAMETER_ENTITIES_FEATURE = "lexical-handler/parameter-entities";
+    
+    /** Is standalone feature ("is-standalone"). */
+    public static final String IS_STANDALONE_FEATURE = "is-standalone";
+    
+    /** Resolve DTD URIs feature ("resolve-dtd-uris"). */
+    public static final String RESOLVE_DTD_URIS_FEATURE = "resolve-dtd-uris";
+    
+    /** Use Attributes2 feature ("use-attributes2"). */
+    public static final String USE_ATTRIBUTES2_FEATURE = "use-attributes2";
+    
+    /** Use Locator2 feature ("use-locator2"). */
+    public static final String USE_LOCATOR2_FEATURE = "use-locator2";
+    
+    /** Use EntityResolver2 feature ("use-entity-resolver2"). */
+    public static final String USE_ENTITY_RESOLVER2_FEATURE = "use-entity-resolver2";
+    
+    /** Unicode normalization checking feature ("unicode-normalization-checking"). */
+    public static final String UNICODE_NORMALIZATION_CHECKING_FEATURE = "unicode-normalization-checking";
+    
+    /** xmlns URIs feature ("xmlns-uris"). */
+    public static final String XMLNS_URIS_FEATURE = "xmlns-uris";
+    
+    /** XML 1.1 feature ("xml-1.1"). */
+    public static final String XML_11_FEATURE = "xml-1.1";
+    
+    /** Allow unparsed entity and notation declaration events to be sent after the end DTD event ("allow-dtd-events-after-endDTD") */
+    public static final String ALLOW_DTD_EVENTS_AFTER_ENDDTD_FEATURE = "allow-dtd-events-after-endDTD";
+    
+    // sax properties
+    
+    /** SAX property prefix ("http://xml.org/sax/properties/"). */
+    public static final String SAX_PROPERTY_PREFIX = "http://xml.org/sax/properties/";
+    
+    /** Declaration handler property ("declaration-handler"). */
+    public static final String DECLARATION_HANDLER_PROPERTY = "declaration-handler";
+    
+    /** Lexical handler property ("lexical-handler"). */
+    public static final String LEXICAL_HANDLER_PROPERTY = "lexical-handler";
+    
+    /** DOM node property ("dom-node"). */
+    public static final String DOM_NODE_PROPERTY = "dom-node";
+    
+    /** XML string property ("xml-string"). */
+    public static final String XML_STRING_PROPERTY = "xml-string";
+    
+    /** Document XML version property ("document-xml-version"). */
+    public static final String DOCUMENT_XML_VERSION_PROPERTY = "document-xml-version";
+    
+    
+    //
+    // JAXP properties
+    //
+    
+    /** JAXP property prefix ("http://java.sun.com/xml/jaxp/properties/"). */
+    public static final String JAXP_PROPERTY_PREFIX =
+        "http://java.sun.com/xml/jaxp/properties/";
+    
+    /** JAXP schemaSource property: when used internally may include DTD sources (DOM) */
+    public static final String SCHEMA_SOURCE = "schemaSource";
+    
+    /** JAXP schemaSource language: when used internally may include DTD namespace (DOM) */
+    public static final String SCHEMA_LANGUAGE = "schemaLanguage";
+    
+    
+    //
+    // DOM features
+    //
+    
+    /** Comments feature ("include-comments"). */
+    public static final String INCLUDE_COMMENTS_FEATURE = "include-comments";
+    
+    /** Create cdata nodes feature ("create-cdata-nodes"). */
+    public static final String CREATE_CDATA_NODES_FEATURE = "create-cdata-nodes";
+    
+    /** Feature id: load as infoset. */
+    public static final String LOAD_AS_INFOSET = "load-as-infoset";
+    
+    
+    //
+    // Constants: DOM Level 3 feature ids
+    //
+    
+    public static final String DOM_CANONICAL_FORM = "canonical-form";
+    public static final String DOM_CDATA_SECTIONS ="cdata-sections";
+    public static final String DOM_COMMENTS = "comments"; 
+    
+    // REVISIT: this feature seems to have no effect for Xerces
+    public static final String DOM_CHARSET_OVERRIDES_XML_ENCODING = 
+        "charset-overrides-xml-encoding"; 
+    
+    public static final String DOM_DATATYPE_NORMALIZATION = "datatype-normalization"; 
+    public static final String DOM_ENTITIES = "entities";
+    public static final String DOM_INFOSET = "infoset";  
+    public static final String DOM_NAMESPACES = "namespaces";
+    public static final String DOM_NAMESPACE_DECLARATIONS = "namespace-declarations";
+    public static final String DOM_SUPPORTED_MEDIATYPES_ONLY =
+        "supported-media-types-only";
+    
+    public static final String DOM_VALIDATE_IF_SCHEMA = "validate-if-schema";
+    public static final String DOM_VALIDATE = "validate";
+    public static final String DOM_ELEMENT_CONTENT_WHITESPACE =
+        "element-content-whitespace";
+    
+    // DOM Level 3 features defined in Core:
+    public static final String DOM_DISCARD_DEFAULT_CONTENT = "discard-default-content";
+    public static final String DOM_NORMALIZE_CHARACTERS    = "normalize-characters";
+    public static final String DOM_CHECK_CHAR_NORMALIZATION  = "check-character-normalization";
+    public static final String DOM_WELLFORMED  = "well-formed";
+    public static final String DOM_SPLIT_CDATA = "split-cdata-sections";
+    
+    // Load and Save
+    public static final String DOM_FORMAT_PRETTY_PRINT = "format-pretty-print";
+    public static final String DOM_XMLDECL = "xml-declaration";
+    public static final String DOM_UNKNOWNCHARS = "unknown-characters";
+    public static final String DOM_CERTIFIED =  "certified";
+    public static final String DOM_DISALLOW_DOCTYPE =  "disallow-doctype";
+    public static final String DOM_IGNORE_UNKNOWN_CHARACTER_DENORMALIZATIONS =  "ignore-unknown-character-denormalizations";
+    
+    // DOM Properties
+    public static final String DOM_RESOURCE_RESOLVER = "resource-resolver";
+    public static final String DOM_ERROR_HANDLER = "error-handler";
+    public static final String DOM_SCHEMA_TYPE = "schema-type";
+    public static final String DOM_SCHEMA_LOCATION = "schema-location";
+    
+    // XSModel
+    public static final String DOM_PSVI = "psvi";
+    
+    
+    // xerces features
+    
+    /** Xerces features prefix ("http://apache.org/xml/features/"). */
+    public static final String XERCES_FEATURE_PREFIX = "http://apache.org/xml/features/";
+    
+    /** Schema validation feature ("validation/schema"). */
+    public static final String SCHEMA_VALIDATION_FEATURE = "validation/schema";
+    
+    /** Expose schema normalized values */
+    public static final String SCHEMA_NORMALIZED_VALUE = "validation/schema/normalized-value";
+    
+    /** Send schema default value via characters() */
+    public static final String SCHEMA_ELEMENT_DEFAULT = "validation/schema/element-default";
+    
+    /** Schema full constraint checking ("validation/schema-full-checking"). */
+    public static final String SCHEMA_FULL_CHECKING = "validation/schema-full-checking";
+    
+    /** Augment Post-Schema-Validation-Infoset */
+    public static final String SCHEMA_AUGMENT_PSVI = "validation/schema/augment-psvi";
+    
+    /** Dynamic validation feature ("validation/dynamic"). */
+    public static final String DYNAMIC_VALIDATION_FEATURE = "validation/dynamic";
+    
+    /** Warn on duplicate attribute declaration feature ("validation/warn-on-duplicate-attdef"). */
+    public static final String WARN_ON_DUPLICATE_ATTDEF_FEATURE = "validation/warn-on-duplicate-attdef";
+    
+    /** Warn on undeclared element feature ("validation/warn-on-undeclared-elemdef"). */
+    public static final String WARN_ON_UNDECLARED_ELEMDEF_FEATURE = "validation/warn-on-undeclared-elemdef";
+    
+    /** Warn on duplicate entity declaration feature ("warn-on-duplicate-entitydef"). */
+    public static final String WARN_ON_DUPLICATE_ENTITYDEF_FEATURE = "warn-on-duplicate-entitydef";
+    
+    /** Allow Java encoding names feature ("allow-java-encodings"). */
+    public static final String ALLOW_JAVA_ENCODINGS_FEATURE = "allow-java-encodings";
+    
+    /** Disallow DOCTYPE declaration feature ("disallow-doctype-decl"). */
+    public static final String DISALLOW_DOCTYPE_DECL_FEATURE = "disallow-doctype-decl";
+    
+    /** Continue after fatal error feature ("continue-after-fatal-error"). */
+    public static final String CONTINUE_AFTER_FATAL_ERROR_FEATURE = "continue-after-fatal-error";
+    
+    /** Load dtd grammar when nonvalidating feature ("nonvalidating/load-dtd-grammar"). */
+    public static final String LOAD_DTD_GRAMMAR_FEATURE = "nonvalidating/load-dtd-grammar";
+    
+    /** Load external dtd when nonvalidating feature ("nonvalidating/load-external-dtd"). */
+    public static final String LOAD_EXTERNAL_DTD_FEATURE = "nonvalidating/load-external-dtd";
+    
+    /** Defer node expansion feature ("dom/defer-node-expansion"). */
+    public static final String DEFER_NODE_EXPANSION_FEATURE = "dom/defer-node-expansion";
+    
+    /** Create entity reference nodes feature ("dom/create-entity-ref-nodes"). */
+    public static final String CREATE_ENTITY_REF_NODES_FEATURE = "dom/create-entity-ref-nodes";
+    
+    /** Include ignorable whitespace feature ("dom/include-ignorable-whitespace"). */
+    public static final String INCLUDE_IGNORABLE_WHITESPACE = "dom/include-ignorable-whitespace";
+    
+    /** Default attribute values feature ("validation/default-attribute-values"). */
+    public static final String DEFAULT_ATTRIBUTE_VALUES_FEATURE = "validation/default-attribute-values";
+    
+    /** Validate content models feature ("validation/validate-content-models"). */
+    public static final String VALIDATE_CONTENT_MODELS_FEATURE = "validation/validate-content-models";
+    
+    /** Validate datatypes feature ("validation/validate-datatypes"). */
+    public static final String VALIDATE_DATATYPES_FEATURE = "validation/validate-datatypes";
+    
+    /** Balance syntax trees feature ("validation/balance-syntax-trees"). */
+    public static final String BALANCE_SYNTAX_TREES = "validation/balance-syntax-trees";
+    
+    /** Notify character references feature (scanner/notify-char-refs"). */
+    public static final String NOTIFY_CHAR_REFS_FEATURE = "scanner/notify-char-refs";
+    
+    /** Notify built-in (&amp;amp;, etc.) references feature (scanner/notify-builtin-refs"). */
+    public static final String NOTIFY_BUILTIN_REFS_FEATURE = "scanner/notify-builtin-refs";
+    
+    /** Standard URI conformant feature ("standard-uri-conformant"). */
+    public static final String STANDARD_URI_CONFORMANT_FEATURE = "standard-uri-conformant";
+    
+    /** Generate synthetic annotations feature ("generate-synthetic-annotations"). */
+    public static final String GENERATE_SYNTHETIC_ANNOTATIONS_FEATURE = "generate-synthetic-annotations";
+    
+    /** Validate annotations feature ("validate-annotations"). */
+    public static final String VALIDATE_ANNOTATIONS_FEATURE = "validate-annotations";
+    
+    /** Honour all schemaLocations feature ("honour-all-schemaLocations"). */
+    public static final String HONOUR_ALL_SCHEMALOCATIONS_FEATURE = "honour-all-schemaLocations";
+    
+    /** Namespace growth feature ("namespace-growth"). */
+    public static final String NAMESPACE_GROWTH_FEATURE = "namespace-growth";
+
+    /** Tolerate duplicates feature ("internal/tolerate-duplicates"). */
+    public static final String TOLERATE_DUPLICATES_FEATURE = "internal/tolerate-duplicates";
+    
+    /** String interned feature ("internal/strings-interned"). */
+    public static final String STRINGS_INTERNED_FEATURE = "internal/strings-interned";
+    
+    /** XInclude processing feature ("xinclude"). */
+    public static final String XINCLUDE_FEATURE = "xinclude";
+    
+    /** XInclude fixup base URIs feature ("xinclude/fixup-base-uris"). */
+    public static final String XINCLUDE_FIXUP_BASE_URIS_FEATURE = "xinclude/fixup-base-uris";
+    
+    /** XInclude fixup language feature ("xinclude/fixup-language"). */
+    public static final String XINCLUDE_FIXUP_LANGUAGE_FEATURE = "xinclude/fixup-language";    
+    
+    /**
+     * Feature to ignore xsi:type attributes on elements during validation,
+     * until a global element declaration is found. ("validation/schema/ignore-xsi-type-until-elemdecl")
+     * If this feature is on when validating a document, then beginning at the validation root
+     * element, xsi:type attributes are ignored until a global element declaration is
+     * found for an element.  Once a global element declaration has been found, xsi:type
+     * attributes will start being processed for the sub-tree beginning at the element for
+     * which the declaration was found.
+     * 
+     * Suppose an element A has two element children, B and C.
+     * 
+     * If a global element declaration is found for A, xsi:type attributes on A, B and C,
+     * and all of B and C's descendents, will be processed.
+     * 
+     * If no global element declaration is found for A or B, but one is found for C,
+     * then xsi:type attributes will be ignored on A and B (and any descendents of B,
+     * until a global element declaration is found), but xsi:type attributes will be
+     * processed for C and all of C's descendents.
+     * 
+     * Once xsi:type attributes stop being ignored for a subtree, they do not start
+     * being ignored again, even if more elements are encountered for which no global
+     * element declaration can be found.
+     */
+    public static final String IGNORE_XSI_TYPE_FEATURE = "validation/schema/ignore-xsi-type-until-elemdecl";
+    
+    /** Perform checking of ID/IDREFs ("validation/id-idref-checking") */
+    public static final String ID_IDREF_CHECKING_FEATURE = "validation/id-idref-checking";
+    
+    /** Feature to ignore errors caused by identity constraints ("validation/identity-constraint-checking") */
+    public static final String IDC_CHECKING_FEATURE = "validation/identity-constraint-checking";
+    
+    /** Feature to ignore errors caused by unparsed entities ("validation/unparsed-entity-checking") */
+    public static final String UNPARSED_ENTITY_CHECKING_FEATURE = "validation/unparsed-entity-checking";
+    
+    /**
+     * Internal feature. When set to true the schema validator will only use
+     * schema components from the grammar pool provided.
+     */
+    public static final String USE_GRAMMAR_POOL_ONLY_FEATURE = "internal/validation/schema/use-grammar-pool-only";
+    
+    /** Internal performance related feature: 
+     * false - the parser settings (features/properties) have not changed between 2 parses
+     * true - the parser settings have changed between 2 parses  
+     * NOTE: this feature should only be set by the parser configuration.
+     */
+    public static final String PARSER_SETTINGS = "internal/parser-settings";
+    
+    // xerces properties
+    
+    /** Xerces properties prefix ("http://apache.org/xml/properties/"). */
+    public static final String XERCES_PROPERTY_PREFIX = "http://apache.org/xml/properties/";
+    
+    /** Current element node property ("dom/current-element-node"). */
+    public static final String CURRENT_ELEMENT_NODE_PROPERTY = "dom/current-element-node";
+    
+    /** Document class name property ("dom/document-class-name"). */
+    public static final String DOCUMENT_CLASS_NAME_PROPERTY = "dom/document-class-name";
+    
+    /** Symbol table property ("internal/symbol-table"). */
+    public static final String SYMBOL_TABLE_PROPERTY = "internal/symbol-table";
+    
+    /** Error reporter property ("internal/error-reporter"). */
+    public static final String ERROR_REPORTER_PROPERTY = "internal/error-reporter";
+    
+    /** Error handler property ("internal/error-handler"). */
+    public static final String ERROR_HANDLER_PROPERTY = "internal/error-handler";
+    
+    /** XInclude handler property ("internal/xinclude-handler"). */
+    public static final String XINCLUDE_HANDLER_PROPERTY = "internal/xinclude-handler";
+    
+    /** XPointer handler property ("internal/xpointer-handler"). */
+    public static final String XPOINTER_HANDLER_PROPERTY = "internal/xpointer-handler";
+    
+    /** Entity manager property ("internal/entity-manager"). */
+    public static final String ENTITY_MANAGER_PROPERTY = "internal/entity-manager";
+    
+    /** Input buffer size property ("input-buffer-size"). */
+    public static final String BUFFER_SIZE_PROPERTY = "input-buffer-size";
+    
+    /** Security manager property ("security-manager"). */
+    public static final String SECURITY_MANAGER_PROPERTY = "security-manager";
+    
+    /** Locale property ("locale"). */
+    public static final String LOCALE_PROPERTY = "locale";
+    
+    /** Entity resolver property ("internal/entity-resolver"). */
+    public static final String ENTITY_RESOLVER_PROPERTY = "internal/entity-resolver";
+    
+    /** Grammar pool property ("internal/grammar-pool"). */
+    public static final String XMLGRAMMAR_POOL_PROPERTY = "internal/grammar-pool";
+    
+    /** Datatype validator factory ("internal/datatype-validator-factory"). */
+    public static final String DATATYPE_VALIDATOR_FACTORY_PROPERTY = "internal/datatype-validator-factory";
+    
+    /** Document scanner property ("internal/document-scanner"). */
+    public static final String DOCUMENT_SCANNER_PROPERTY = "internal/document-scanner";
+    
+    /** DTD scanner property ("internal/dtd-scanner"). */
+    public static final String DTD_SCANNER_PROPERTY = "internal/dtd-scanner";
+    
+    /** DTD processor property ("internal/dtd-processor"). */
+    public static final String DTD_PROCESSOR_PROPERTY = "internal/dtd-processor";
+    
+    /** Validator property ("internal/validator"). */
+    public static final String VALIDATOR_PROPERTY = "internal/validator";
+    
+    /** Validator property ("internal/validator/dtd"). */
+    public static final String DTD_VALIDATOR_PROPERTY = "internal/validator/dtd";
+    
+    /** Validator property ("internal/validator/schema"). */
+    public static final String SCHEMA_VALIDATOR_PROPERTY = "internal/validator/schema";
+    
+    /** No namespace schema location property ("schema/external-schemaLocation"). */
+    public static final String SCHEMA_LOCATION = "schema/external-schemaLocation";
+    
+    /** Schema location property ("schema/external-noNamespaceSchemaLocation"). */
+    public static final String SCHEMA_NONS_LOCATION = "schema/external-noNamespaceSchemaLocation";
+    
+    /** Namespace binder property ("internal/namespace-binder"). */
+    public static final String NAMESPACE_BINDER_PROPERTY = "internal/namespace-binder";
+    
+    /** Namespace context property ("internal/namespace-context"). */
+    public static final String NAMESPACE_CONTEXT_PROPERTY = "internal/namespace-context";
+    
+    /** Validation manager property ("internal/validation-manager"). */
+    public static final String VALIDATION_MANAGER_PROPERTY = "internal/validation-manager";
+    
+    /** Schema type for the root element in a document ("validation/schema/root-type-definition"). */
+    public static final String ROOT_TYPE_DEFINITION_PROPERTY = "validation/schema/root-type-definition";
+    
+    /** Schema element declaration for the root element in a document ("validation/schema/root-element-declaration"). */
+    public static final String ROOT_ELEMENT_DECLARATION_PROPERTY = "validation/schema/root-element-declaration";
+    
+    /** Schema element declaration for the root element in a document ("internal/validation/schema/dv-factory"). */
+    public static final String SCHEMA_DV_FACTORY_PROPERTY = "internal/validation/schema/dv-factory";
+    
+    // general constants
+    
+    /** Element PSVI is stored in augmentations using string "ELEMENT_PSVI" */
+    public final static String ELEMENT_PSVI = "ELEMENT_PSVI";
+    
+    /** Attribute PSVI is stored in augmentations using string "ATTRIBUTE_PSVI" */
+    public final static String ATTRIBUTE_PSVI = "ATTRIBUTE_PSVI";
+    
+    /** 
+     * Boolean indicating whether an attribute is declared in the DTD is stored 
+     * in augmentations using the string "ATTRIBUTE_DECLARED". The absence of this
+     * augmentation indicates that the attribute was not declared in the DTD.
+     */
+    public final static String ATTRIBUTE_DECLARED = "ATTRIBUTE_DECLARED";
+    
+    /** 
+     * Boolean indicating whether an entity referenced in the document has
+     * not been read is stored in augmentations using the string "ENTITY_SKIPPED". 
+     * The absence of this augmentation indicates that the entity had a 
+     * declaration and was expanded.
+     */
+    public final static String ENTITY_SKIPPED = "ENTITY_SKIPPED";
+    
+    /**
+     * Boolean indicating whether a character is a probable white space
+     * character (ch <= 0x20) that was the replacement text of a character 
+     * reference is stored in augmentations using the string "CHAR_REF_PROBABLE_WS". 
+     * The absence of this augmentation indicates that the character is not 
+     * probable white space and/or was not included from a character reference.
+     */
+    public final static String CHAR_REF_PROBABLE_WS = "CHAR_REF_PROBABLE_WS";
+    
+    // XML version constants 
+    public final static short XML_VERSION_ERROR = -1;
+    public final static short XML_VERSION_1_0 = 1;
+    public final static short XML_VERSION_1_1 = 2;
+    
+    // Constant to enable Schema 1.1 support
+    public final static boolean SCHEMA_1_1_SUPPORT = false;
+    public final static short SCHEMA_VERSION_1_0          = 1;
+    public final static short SCHEMA_VERSION_1_0_EXTENDED = 2;
+    
+    // private
+    
+    /** SAX features. */
+    private static final String[] fgSAXFeatures = {
+            NAMESPACES_FEATURE,
+            NAMESPACE_PREFIXES_FEATURE,
+            STRING_INTERNING_FEATURE,
+            VALIDATION_FEATURE,
+            EXTERNAL_GENERAL_ENTITIES_FEATURE,
+            EXTERNAL_PARAMETER_ENTITIES_FEATURE,
+    };
+    
+    /** SAX properties. */
+    private static final String[] fgSAXProperties = {
+            DECLARATION_HANDLER_PROPERTY,
+            LEXICAL_HANDLER_PROPERTY,
+            DOM_NODE_PROPERTY,
+            XML_STRING_PROPERTY,
+    };
+    
+    /** Xerces features. */
+    private static final String[] fgXercesFeatures = {
+            SCHEMA_VALIDATION_FEATURE,
+            SCHEMA_FULL_CHECKING,
+            DYNAMIC_VALIDATION_FEATURE,
+            WARN_ON_DUPLICATE_ATTDEF_FEATURE,
+            WARN_ON_UNDECLARED_ELEMDEF_FEATURE,
+            ALLOW_JAVA_ENCODINGS_FEATURE,
+            CONTINUE_AFTER_FATAL_ERROR_FEATURE,
+            LOAD_DTD_GRAMMAR_FEATURE,
+            LOAD_EXTERNAL_DTD_FEATURE,
+            //DEFER_NODE_EXPANSION_FEATURE,
+            CREATE_ENTITY_REF_NODES_FEATURE,
+            INCLUDE_IGNORABLE_WHITESPACE,
+            //GRAMMAR_ACCESS_FEATURE,
+            DEFAULT_ATTRIBUTE_VALUES_FEATURE,
+            VALIDATE_CONTENT_MODELS_FEATURE,
+            VALIDATE_DATATYPES_FEATURE,
+            BALANCE_SYNTAX_TREES,
+            NOTIFY_CHAR_REFS_FEATURE,
+            NOTIFY_BUILTIN_REFS_FEATURE,
+            DISALLOW_DOCTYPE_DECL_FEATURE,
+            STANDARD_URI_CONFORMANT_FEATURE,
+            GENERATE_SYNTHETIC_ANNOTATIONS_FEATURE,
+            VALIDATE_ANNOTATIONS_FEATURE,
+            HONOUR_ALL_SCHEMALOCATIONS_FEATURE,
+            XINCLUDE_FEATURE,
+            XINCLUDE_FIXUP_BASE_URIS_FEATURE,
+            XINCLUDE_FIXUP_LANGUAGE_FEATURE,
+            IGNORE_XSI_TYPE_FEATURE,
+            ID_IDREF_CHECKING_FEATURE,
+            IDC_CHECKING_FEATURE,
+            UNPARSED_ENTITY_CHECKING_FEATURE,
+            NAMESPACE_GROWTH_FEATURE,
+            TOLERATE_DUPLICATES_FEATURE,
+            STRINGS_INTERNED_FEATURE,
+    };
+    
+    /** Xerces properties. */
+    private static final String[] fgXercesProperties = {
+            CURRENT_ELEMENT_NODE_PROPERTY,
+            DOCUMENT_CLASS_NAME_PROPERTY,
+            SYMBOL_TABLE_PROPERTY,
+            ERROR_HANDLER_PROPERTY,
+            ERROR_REPORTER_PROPERTY,
+            ENTITY_MANAGER_PROPERTY,
+            ENTITY_RESOLVER_PROPERTY,
+            XMLGRAMMAR_POOL_PROPERTY,
+            DATATYPE_VALIDATOR_FACTORY_PROPERTY,
+            DOCUMENT_SCANNER_PROPERTY,
+            DTD_SCANNER_PROPERTY,
+            VALIDATOR_PROPERTY,
+            SCHEMA_LOCATION,
+            SCHEMA_NONS_LOCATION,
+            VALIDATION_MANAGER_PROPERTY,
+            BUFFER_SIZE_PROPERTY,
+            SECURITY_MANAGER_PROPERTY,
+            LOCALE_PROPERTY,
+            ROOT_TYPE_DEFINITION_PROPERTY,
+            ROOT_ELEMENT_DECLARATION_PROPERTY,
+            SCHEMA_DV_FACTORY_PROPERTY,
+    };
+    
+    /** Empty enumeration. */
+    private static final Enumeration fgEmptyEnumeration = new ArrayEnumeration(new Object[] {});
+    
+    //
+    // Constructors
+    //
+    
+    /** This class cannot be instantiated. */
+    private Constants() {}
+    
+    //
+    // Public methods
+    //
+    
+    // sax
+    
+    /** Returns an enumeration of the SAX features. */
+    public static Enumeration getSAXFeatures() {
+        return fgSAXFeatures.length > 0
+        ? new ArrayEnumeration(fgSAXFeatures) : fgEmptyEnumeration;
+    } // getSAXFeatures():Enumeration
+    
+    /** Returns an enumeration of the SAX properties. */
+    public static Enumeration getSAXProperties() {
+        return fgSAXProperties.length > 0
+        ? new ArrayEnumeration(fgSAXProperties) : fgEmptyEnumeration;
+    } // getSAXProperties():Enumeration
+    
+    // xerces
+    
+    /** Returns an enumeration of the Xerces features. */
+    public static Enumeration getXercesFeatures() {
+        return fgXercesFeatures.length > 0
+        ? new ArrayEnumeration(fgXercesFeatures) : fgEmptyEnumeration;
+    } // getXercesFeatures():Enumeration
+    
+    /** Returns an enumeration of the Xerces properties. */
+    public static Enumeration getXercesProperties() {
+        return fgXercesProperties.length > 0
+        ? new ArrayEnumeration(fgXercesProperties) : fgEmptyEnumeration;
+    } // getXercesProperties():Enumeration
+    
+    //
+    // Classes
+    //
+    
+    /**
+     * An array enumeration.
+     *
+     * @author Andy Clark, IBM
+     */
+    static class ArrayEnumeration
+    implements Enumeration {
+        
+        //
+        // Data
+        //
+        
+        /** Array. */
+        private Object[] array;
+        
+        /** Index. */
+        private int index;
+        
+        //
+        // Constructors
+        //
+        
+        /** Constructs an array enumeration. */
+        public ArrayEnumeration(Object[] array) {
+            this.array = array;
+        } // <init>(Object[])
+        
+        //
+        // Enumeration methods
+        //
+        
+        /**
+         * Tests if this enumeration contains more elements.
+         *
+         * @return  <code>true</code> if this enumeration contains more elements;
+         *          <code>false</code> otherwise.
+         * @since   JDK1.0
+         */
+        public boolean hasMoreElements() {
+            return index < array.length;
+        } // hasMoreElement():boolean
+        
+        /**
+         * Returns the next element of this enumeration.
+         *
+         * @return     the next element of this enumeration.
+         * @exception  NoSuchElementException  if no more elements exist.
+         * @since      JDK1.0
+         */
+        public Object nextElement() {
+            if (index < array.length) {
+                return array[index++];
+            }
+            throw new NoSuchElementException();
+        } // nextElement():Object
+        
+    } // class ArrayEnumeration
+    
+    //
+    // MAIN
+    //
+    
+    /** Prints all of the constants to standard output. */
+    public static void main(String[] argv) {
+        
+        print("SAX features:", SAX_FEATURE_PREFIX, fgSAXFeatures);
+        print("SAX properties:", SAX_PROPERTY_PREFIX, fgSAXProperties);
+        print("Xerces features:", XERCES_FEATURE_PREFIX, fgXercesFeatures);
+        print("Xerces properties:", XERCES_PROPERTY_PREFIX, fgXercesProperties);
+        
+    } // main(String[])
+    
+    /** Prints a list of features/properties. */
+    private static void print(String header, String prefix, Object[] array) {
+        System.out.print(header);
+        if (array.length > 0) {
+            System.out.println();
+            for (int i = 0; i < array.length; i++) {
+                System.out.print("  ");
+                System.out.print(prefix);
+                System.out.println(array[i]);
+            }
+        }
+        else {
+            System.out.println(" none.");
+        }
+    } // print(String,String,Object[])
+    
+} // class Constants

http://git-wip-us.apache.org/repos/asf/jena/blob/c9a7e646/jena-core/src/main/java/org/apache/jena/ext/xerces/impl/Version.java
----------------------------------------------------------------------
diff --git a/jena-core/src/main/java/org/apache/jena/ext/xerces/impl/Version.java b/jena-core/src/main/java/org/apache/jena/ext/xerces/impl/Version.java
new file mode 100644
index 0000000..5e09fa8
--- /dev/null
+++ b/jena-core/src/main/java/org/apache/jena/ext/xerces/impl/Version.java
@@ -0,0 +1,37 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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.jena.ext.xerces.impl;
+
+/**
+ * This class defines the version number of the parser.
+ *
+ * @version $Id: Version.java 446761 2006-09-15 21:59:29Z mrglavas $
+ */
+public class Version {
+
+    /** Version string. */
+    private static String fVersion = "2.11.0-jena";
+
+    /* Print out the version information.
+     * @return the version of the parser.
+     */
+    public static String getVersion() {
+        return fVersion;
+    }
+
+}

http://git-wip-us.apache.org/repos/asf/jena/blob/c9a7e646/jena-core/src/main/java/org/apache/jena/ext/xerces/impl/dv/DTDDVFactory.java
----------------------------------------------------------------------
diff --git a/jena-core/src/main/java/org/apache/jena/ext/xerces/impl/dv/DTDDVFactory.java b/jena-core/src/main/java/org/apache/jena/ext/xerces/impl/dv/DTDDVFactory.java
new file mode 100644
index 0000000..294a3a9
--- /dev/null
+++ b/jena-core/src/main/java/org/apache/jena/ext/xerces/impl/dv/DTDDVFactory.java
@@ -0,0 +1,86 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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.jena.ext.xerces.impl.dv;
+
+import java.util.Hashtable;
+
+/**
+ * The factory to create and return DTD types. The implementation should
+ * store the created datatypes in static data, so that they can be shared by
+ * multiple parser instance, and multiple threads.
+ * 
+ * @xerces.internal 
+ *
+ * @author Sandy Gao, IBM
+ *
+ * @version $Id: DTDDVFactory.java 558581 2007-07-23 01:38:26Z mrglavas $
+ */
+@SuppressWarnings("all")
+public abstract class DTDDVFactory {
+
+    private static final String DEFAULT_FACTORY_CLASS = "org.apache.jena.ext.xerces.impl.dv.dtd.DTDDVFactoryImpl";
+
+    /**
+     * Get an instance of the default DTDDVFactory implementation.
+     *
+     * @return  an instance of DTDDVFactory implementation
+     * @exception DVFactoryException  cannot create an instance of the specified
+     *                                class name or the default class name
+     */
+    public static final DTDDVFactory getInstance() throws DVFactoryException {
+        return getInstance(DEFAULT_FACTORY_CLASS);
+    }
+
+    /**
+     * Get an instance of DTDDVFactory implementation.
+     *
+     * @param factoryClass  name of the implementation to load.
+     * @return  an instance of DTDDVFactory implementation
+     * @exception DVFactoryException  cannot create an instance of the specified
+     *                                class name or the default class name
+     */
+    public static final DTDDVFactory getInstance(String factoryClass) throws DVFactoryException {
+        try {
+            // if the class name is not specified, use the default one
+            return (DTDDVFactory)
+                (ObjectFactory.newInstance(factoryClass, ObjectFactory.findClassLoader(), true));
+        } 
+        catch (ClassCastException e) {
+            throw new DVFactoryException("DTD factory class " + factoryClass + " does not extend from DTDDVFactory.");
+        }
+    }
+
+    // can't create a new object of this class
+    protected DTDDVFactory() {}
+
+    /**
+     * return a dtd type of the given name
+     *
+     * @param name  the name of the datatype
+     * @return      the datatype validator of the given name
+     */
+    public abstract DatatypeValidator getBuiltInDV(String name);
+
+    /**
+     * get all built-in DVs, which are stored in a hashtable keyed by the name
+     *
+     * @return      a hashtable which contains all datatypes
+     */
+    public abstract Hashtable getBuiltInTypes();
+
+}

http://git-wip-us.apache.org/repos/asf/jena/blob/c9a7e646/jena-core/src/main/java/org/apache/jena/ext/xerces/impl/dv/DVFactoryException.java
----------------------------------------------------------------------
diff --git a/jena-core/src/main/java/org/apache/jena/ext/xerces/impl/dv/DVFactoryException.java b/jena-core/src/main/java/org/apache/jena/ext/xerces/impl/dv/DVFactoryException.java
new file mode 100644
index 0000000..dd7ab56
--- /dev/null
+++ b/jena-core/src/main/java/org/apache/jena/ext/xerces/impl/dv/DVFactoryException.java
@@ -0,0 +1,40 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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.jena.ext.xerces.impl.dv;
+
+/**
+ * A runtime exception that's thrown if an error happens when the application
+ * tries to get a DV factory instance.
+ *
+ * @xerces.internal 
+ *
+ * @version $Id: DVFactoryException.java 446751 2006-09-15 21:54:06Z mrglavas $
+ */
+public class DVFactoryException extends RuntimeException {
+    
+    /** Serialization version. */
+    static final long serialVersionUID = -3738854697928682412L;
+    
+    public DVFactoryException() {
+        super();
+    }
+
+    public DVFactoryException(String msg) {
+        super(msg);
+    }
+}

http://git-wip-us.apache.org/repos/asf/jena/blob/c9a7e646/jena-core/src/main/java/org/apache/jena/ext/xerces/impl/dv/DatatypeException.java
----------------------------------------------------------------------
diff --git a/jena-core/src/main/java/org/apache/jena/ext/xerces/impl/dv/DatatypeException.java b/jena-core/src/main/java/org/apache/jena/ext/xerces/impl/dv/DatatypeException.java
new file mode 100644
index 0000000..68ade2e
--- /dev/null
+++ b/jena-core/src/main/java/org/apache/jena/ext/xerces/impl/dv/DatatypeException.java
@@ -0,0 +1,106 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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.jena.ext.xerces.impl.dv;
+
+import java.util.MissingResourceException;
+import java.util.ResourceBundle;
+
+/**
+ * Base class for datatype exceptions. For DTD types, the exception can be
+ * created from an error message. For Schema types, it needs an error code
+ * (as defined in Appendix C of the structure spec), plus an array of arguments,
+ * for error message substitution.
+ * 
+ * @xerces.internal 
+ *
+ * @author Sandy Gao, IBM
+ *
+ * @version $Id: DatatypeException.java 809242 2009-08-30 03:34:31Z mrglavas $
+ */
+@SuppressWarnings("all")
+public class DatatypeException extends Exception {
+
+    /** Serialization version. */
+    static final long serialVersionUID = 1940805832730465578L;
+    
+    // used to store error code and error substitution arguments
+    protected final String key;
+    protected final Object[] args;
+
+    /**
+     * Create a new datatype exception by providing an error code and a list
+     * of error message substitution arguments.
+     *
+     * @param key  error code
+     * @param args error arguments
+     */
+    public DatatypeException(String key, Object[] args) {
+        super(key);
+        this.key = key;
+        this.args = args;
+    }
+
+    /**
+     * Return the error code
+     *
+     * @return  error code
+     */
+    public String getKey() {
+        return key;
+    }
+
+    /**
+     * Return the list of error arguments
+     *
+     * @return  error arguments
+     */
+    public Object[] getArgs() {
+        return args;
+    }
+    
+    /**
+     * Overrides this method to get the formatted&localized error message.
+     * 
+     * REVISIT: the system locale is used to load the property file.
+     *          do we want to allow the appilcation to specify a
+     *          different locale?
+     */
+    public String getMessage() {
+        ResourceBundle resourceBundle = null;
+        resourceBundle = ResourceBundle.getBundle("org.apache.jena.ext.xerces.impl.msg.XMLSchemaMessages");
+        if (resourceBundle == null)
+            throw new MissingResourceException("Property file not found!", "org.apache.jena.ext.xerces.impl.msg.XMLSchemaMessages", key);
+
+        String msg = resourceBundle.getString(key);
+        if (msg == null) {
+            msg = resourceBundle.getString("BadMessageKey");
+            throw new MissingResourceException(msg, "org.apache.jena.ext.xerces.impl.msg.XMLSchemaMessages", key);
+        }
+
+        if (args != null) {
+            try {
+                msg = java.text.MessageFormat.format(msg, args);
+            } catch (Exception e) {
+                msg = resourceBundle.getString("FormatFailed");
+                msg += " " + resourceBundle.getString(key);
+            }
+        } 
+
+        return msg;
+    }
+}

http://git-wip-us.apache.org/repos/asf/jena/blob/c9a7e646/jena-core/src/main/java/org/apache/jena/ext/xerces/impl/dv/DatatypeValidator.java
----------------------------------------------------------------------
diff --git a/jena-core/src/main/java/org/apache/jena/ext/xerces/impl/dv/DatatypeValidator.java b/jena-core/src/main/java/org/apache/jena/ext/xerces/impl/dv/DatatypeValidator.java
new file mode 100644
index 0000000..1585958
--- /dev/null
+++ b/jena-core/src/main/java/org/apache/jena/ext/xerces/impl/dv/DatatypeValidator.java
@@ -0,0 +1,42 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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.jena.ext.xerces.impl.dv;
+
+
+/**
+ * The interface that a DTD datatype must implement. The implementation of this
+ * interface must be thread-safe.
+ * 
+ * @xerces.internal
+ *
+ * @author Sandy Gao, IBM
+ *
+ * @version $Id: DatatypeValidator.java 699892 2008-09-28 21:08:27Z mrglavas $
+ */
+public interface DatatypeValidator {
+
+    /**
+     * validate a given string against this DV
+     *
+     * @param content       the string value that needs to be validated
+     * @param context       the validation context
+     */
+    public void validate(String content, ValidationContext context)
+        throws InvalidDatatypeValueException;
+
+}

http://git-wip-us.apache.org/repos/asf/jena/blob/c9a7e646/jena-core/src/main/java/org/apache/jena/ext/xerces/impl/dv/InvalidDatatypeFacetException.java
----------------------------------------------------------------------
diff --git a/jena-core/src/main/java/org/apache/jena/ext/xerces/impl/dv/InvalidDatatypeFacetException.java b/jena-core/src/main/java/org/apache/jena/ext/xerces/impl/dv/InvalidDatatypeFacetException.java
new file mode 100644
index 0000000..4e8cc13
--- /dev/null
+++ b/jena-core/src/main/java/org/apache/jena/ext/xerces/impl/dv/InvalidDatatypeFacetException.java
@@ -0,0 +1,47 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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.jena.ext.xerces.impl.dv;
+
+/**
+ * Datatype exception for invalid facet. This exception is only used by
+ * schema datatypes.
+ *
+ * @xerces.internal 
+ *
+ * @author Sandy Gao, IBM
+ *
+ * @version $Id: InvalidDatatypeFacetException.java 446751 2006-09-15 21:54:06Z mrglavas $
+ */
+@SuppressWarnings("all")
+public class InvalidDatatypeFacetException extends DatatypeException {
+
+    /** Serialization version. */
+    static final long serialVersionUID = -4104066085909970654L;
+    
+    /**
+     * Create a new datatype exception by providing an error code and a list
+     * of error message substitution arguments.
+     *
+     * @param key  error code
+     * @param args error arguments
+     */
+    public InvalidDatatypeFacetException(String key, Object[] args) {
+        super(key, args);
+    }
+
+}

http://git-wip-us.apache.org/repos/asf/jena/blob/c9a7e646/jena-core/src/main/java/org/apache/jena/ext/xerces/impl/dv/InvalidDatatypeValueException.java
----------------------------------------------------------------------
diff --git a/jena-core/src/main/java/org/apache/jena/ext/xerces/impl/dv/InvalidDatatypeValueException.java b/jena-core/src/main/java/org/apache/jena/ext/xerces/impl/dv/InvalidDatatypeValueException.java
new file mode 100644
index 0000000..cdfc4cc
--- /dev/null
+++ b/jena-core/src/main/java/org/apache/jena/ext/xerces/impl/dv/InvalidDatatypeValueException.java
@@ -0,0 +1,46 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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.jena.ext.xerces.impl.dv;
+
+/**
+ * Datatype exception for invalid values.
+ *
+ * @xerces.internal 
+ *
+ * @author Sandy Gao, IBM
+ *
+ * @version $Id: InvalidDatatypeValueException.java 446751 2006-09-15 21:54:06Z mrglavas $
+ */
+@SuppressWarnings("all")
+public class InvalidDatatypeValueException extends DatatypeException {
+
+    /** Serialization version. */
+    static final long serialVersionUID = -5523739426958236125L;
+    
+    /**
+     * Create a new datatype exception by providing an error code and a list
+     * of error message substitution arguments.
+     *
+     * @param key  error code
+     * @param args error arguments
+     */
+    public InvalidDatatypeValueException(String key, Object[] args) {
+        super(key, args);
+    }
+
+}


[13/24] jena git commit: JENA-1537: Remove dependency on Xerces. Import needed code

Posted by an...@apache.org.
http://git-wip-us.apache.org/repos/asf/jena/blob/c9a7e646/jena-core/src/main/java/org/apache/jena/ext/xerces/impl/xpath/regex/RegularExpression.java
----------------------------------------------------------------------
diff --git a/jena-core/src/main/java/org/apache/jena/ext/xerces/impl/xpath/regex/RegularExpression.java b/jena-core/src/main/java/org/apache/jena/ext/xerces/impl/xpath/regex/RegularExpression.java
new file mode 100644
index 0000000..ea77556
--- /dev/null
+++ b/jena-core/src/main/java/org/apache/jena/ext/xerces/impl/xpath/regex/RegularExpression.java
@@ -0,0 +1,2456 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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.jena.ext.xerces.impl.xpath.regex;
+
+import java.text.CharacterIterator;
+import java.util.Locale;
+import java.util.Stack;
+
+import org.apache.jena.ext.xerces.util.IntStack;
+
+/**
+ * A regular expression matching engine using Non-deterministic Finite Automaton (NFA).
+ * This engine does not conform to the POSIX regular expression.
+ *
+ * <hr width="50%">
+ * <h3>How to use</h3>
+ *
+ * <dl>
+ *   <dt>A. Standard way
+ *   <dd>
+ * <pre>
+ * RegularExpression re = new RegularExpression(<var>regex</var>);
+ * if (re.matches(text)) { ... }
+ * </pre>
+ *
+ *   <dt>B. Capturing groups
+ *   <dd>
+ * <pre>
+ * RegularExpression re = new RegularExpression(<var>regex</var>);
+ * Match match = new Match();
+ * if (re.matches(text, match)) {
+ *     ... // You can refer captured texts with methods of the <code>Match</code> class.
+ * }
+ * </pre>
+ *
+ * </dl>
+ *
+ * <h4>Case-insensitive matching</h4>
+ * <pre>
+ * RegularExpression re = new RegularExpression(<var>regex</var>, "i");
+ * if (re.matches(text) >= 0) { ...}
+ * </pre>
+ *
+ * <h4>Options</h4>
+ * <p>You can specify options to <a href="#RegularExpression(java.lang.String, java.lang.String)"><code>RegularExpression(</code><var>regex</var><code>, </code><var>options</var><code>)</code></a>
+ *    or <a href="#setPattern(java.lang.String, java.lang.String)"><code>setPattern(</code><var>regex</var><code>, </code><var>options</var><code>)</code></a>.
+ *    This <var>options</var> parameter consists of the following characters.
+ * </p>
+ * <dl>
+ *   <dt><a name="I_OPTION"><code>"i"</code></a>
+ *   <dd>This option indicates case-insensitive matching.
+ *   <dt><a name="M_OPTION"><code>"m"</code></a>
+ *   <dd class="REGEX"><kbd>^</kbd> and <kbd>$</kbd> consider the EOL characters within the text.
+ *   <dt><a name="S_OPTION"><code>"s"</code></a>
+ *   <dd class="REGEX"><kbd>.</kbd> matches any one character.
+ *   <dt><a name="U_OPTION"><code>"u"</code></a>
+ *   <dd class="REGEX">Redefines <Kbd>\d \D \w \W \s \S \b \B \&lt; \></kbd> as becoming to Unicode.
+ *   <dt><a name="W_OPTION"><code>"w"</code></a>
+ *   <dd class="REGEX">By this option, <kbd>\b \B \&lt; \></kbd> are processed with the method of
+ *      'Unicode Regular Expression Guidelines' Revision 4.
+ *      When "w" and "u" are specified at the same time,
+ *      <kbd>\b \B \&lt; \></kbd> are processed for the "w" option.
+ *   <dt><a name="COMMA_OPTION"><code>","</code></a>
+ *   <dd>The parser treats a comma in a character class as a range separator.
+ *      <kbd class="REGEX">[a,b]</kbd> matches <kbd>a</kbd> or <kbd>,</kbd> or <kbd>b</kbd> without this option.
+ *      <kbd class="REGEX">[a,b]</kbd> matches <kbd>a</kbd> or <kbd>b</kbd> with this option.
+ *
+ *   <dt><a name="X_OPTION"><code>"X"</code></a>
+ *   <dd class="REGEX">
+ *       By this option, the engine confoms to <a href="http://www.w3.org/TR/2000/WD-xmlschema-2-20000407/#regexs">XML Schema: Regular Expression</a>.
+ *       The <code>match()</code> method does not do subsring matching
+ *       but entire string matching.
+ *
+ * </dl>
+ * 
+ * <hr width="50%">
+ * <h3>Syntax</h3>
+ * <table border="1" bgcolor="#ddeeff">
+ *   <tr>
+ *    <td>
+ *     <h4>Differences from the Perl 5 regular expression</h4>
+ *     <ul>
+ *      <li>There is 6-digit hexadecimal character representation  (<kbd>\u005cv</kbd><var>HHHHHH</var>.)
+ *      <li>Supports subtraction, union, and intersection operations for character classes.
+ *      <li>Not supported: <kbd>\</kbd><var>ooo</var> (Octal character representations),
+ *          <Kbd>\G</kbd>, <kbd>\C</kbd>, <kbd>\l</kbd><var>c</var>,
+ *          <kbd>\u005c u</kbd><var>c</var>, <kbd>\L</kbd>, <kbd>\U</kbd>,
+ *          <kbd>\E</kbd>, <kbd>\Q</kbd>, <kbd>\N{</kbd><var>name</var><kbd>}</kbd>,
+ *          <Kbd>(?{<kbd><var>code</var><kbd>})</kbd>, <Kbd>(??{<kbd><var>code</var><kbd>})</kbd>
+ *     </ul>
+ *    </td>
+ *   </tr>
+ * </table>
+ *
+ * <P>Meta characters are `<KBD>. * + ? { [ ( ) | \ ^ $</KBD>'.</P>
+ * <ul>
+ *   <li>Character
+ *     <dl>
+ *       <dt class="REGEX"><kbd>.</kbd> (A period)
+ *       <dd>Matches any one character except the following characters.
+ *       <dd>LINE FEED (U+000A), CARRIAGE RETURN (U+000D),
+ *           PARAGRAPH SEPARATOR (U+2029), LINE SEPARATOR (U+2028)
+ *       <dd>This expression matches one code point in Unicode. It can match a pair of surrogates.
+ *       <dd>When <a href="#S_OPTION">the "s" option</a> is specified,
+ *           it matches any character including the above four characters.
+ *
+ *       <dt class="REGEX"><Kbd>\e \f \n \r \t</kbd>
+ *       <dd>Matches ESCAPE (U+001B), FORM FEED (U+000C), LINE FEED (U+000A),
+ *           CARRIAGE RETURN (U+000D), HORIZONTAL TABULATION (U+0009)
+ *
+ *       <dt class="REGEX"><kbd>\c</kbd><var>C</var>
+ *       <dd>Matches a control character.
+ *           The <var>C</var> must be one of '<kbd>@</kbd>', '<kbd>A</kbd>'-'<kbd>Z</kbd>',
+ *           '<kbd>[</kbd>', '<kbd>\u005c</kbd>', '<kbd>]</kbd>', '<kbd>^</kbd>', '<kbd>_</kbd>'.
+ *           It matches a control character of which the character code is less than
+ *           the character code of the <var>C</var> by 0x0040.
+ *       <dd class="REGEX">For example, a <kbd>\cJ</kbd> matches a LINE FEED (U+000A),
+ *           and a <kbd>\c[</kbd> matches an ESCAPE (U+001B).
+ *
+ *       <dt class="REGEX">a non-meta character
+ *       <dd>Matches the character.
+ *
+ *       <dt class="REGEX"><KBD>\</KBD> + a meta character
+ *       <dd>Matches the meta character.
+ *
+ *       <dt class="REGEX"><kbd>\u005cx</kbd><var>HH</var> <kbd>\u005cx{</kbd><var>HHHH</var><kbd>}</kbd>
+ *       <dd>Matches a character of which code point is <var>HH</var> (Hexadecimal) in Unicode.
+ *           You can write just 2 digits for <kbd>\u005cx</kbd><var>HH</var>, and
+ *           variable length digits for <kbd>\u005cx{</kbd><var>HHHH</var><kbd>}</kbd>.
+ *
+ *       <!--
+ *       <dt class="REGEX"><kbd>\u005c u</kbd><var>HHHH</var>
+ *       <dd>Matches a character of which code point is <var>HHHH</var> (Hexadecimal) in Unicode.
+ *       -->
+ *
+ *       <dt class="REGEX"><kbd>\u005cv</kbd><var>HHHHHH</var>
+ *       <dd>Matches a character of which code point is <var>HHHHHH</var> (Hexadecimal) in Unicode.
+ *
+ *       <dt class="REGEX"><kbd>\g</kbd>
+ *       <dd>Matches a grapheme.
+ *       <dd class="REGEX">It is equivalent to <kbd>(?[\p{ASSIGNED}]-[\p{M}\p{C}])?(?:\p{M}|[\x{094D}\x{09CD}\x{0A4D}\x{0ACD}\x{0B3D}\x{0BCD}\x{0C4D}\x{0CCD}\x{0D4D}\x{0E3A}\x{0F84}]\p{L}|[\x{1160}-\x{11A7}]|[\x{11A8}-\x{11FF}]|[\x{FF9E}\x{FF9F}])*</kbd>
+ *
+ *       <dt class="REGEX"><kbd>\X</kbd>
+ *       <dd class="REGEX">Matches a combining character sequence.
+ *       It is equivalent to <kbd>(?:\PM\pM*)</kbd>
+ *     </dl>
+ *   </li>
+ *
+ *   <li>Character class
+ *     <dl>
++ *       <dt class="REGEX"><kbd>[</kbd><var>R<sub>1</sub></var><var>R<sub>2</sub></var><var>...</var><var>R<sub>n</sub></var><kbd>]</kbd> (without <a href="#COMMA_OPTION">"," option</a>)
++ *       <dt class="REGEX"><kbd>[</kbd><var>R<sub>1</sub></var><kbd>,</kbd><var>R<sub>2</sub></var><kbd>,</kbd><var>...</var><kbd>,</kbd><var>R<sub>n</sub></var><kbd>]</kbd> (with <a href="#COMMA_OPTION">"," option</a>)
+ *       <dd>Positive character class.  It matches a character in ranges.
+ *       <dd><var>R<sub>n</sub></var>:
+ *       <ul>
+ *         <li class="REGEX">A character (including <Kbd>\e \f \n \r \t</kbd> <kbd>\u005cx</kbd><var>HH</var> <kbd>\u005cx{</kbd><var>HHHH</var><kbd>}</kbd> <!--kbd>\u005c u</kbd><var>HHHH</var--> <kbd>\u005cv</kbd><var>HHHHHH</var>)
+ *             <p>This range matches the character.
+ *         <li class="REGEX"><var>C<sub>1</sub></var><kbd>-</kbd><var>C<sub>2</sub></var>
+ *             <p>This range matches a character which has a code point that is >= <var>C<sub>1</sub></var>'s code point and &lt;= <var>C<sub>2</sub></var>'s code point.
++ *         <li class="REGEX">A POSIX character class: <Kbd>[:alpha:] [:alnum:] [:ascii:] [:cntrl:] [:digit:] [:graph:] [:lower:] [:print:] [:punct:] [:space:] [:upper:] [:xdigit:]</kbd>,
++ *             and negative POSIX character classes in Perl like <kbd>[:^alpha:]</kbd>
+ *             <p>...
+ *         <li class="REGEX"><kbd>\d \D \s \S \w \W \p{</kbd><var>name</var><kbd>} \P{</kbd><var>name</var><kbd>}</kbd>
+ *             <p>These expressions specifies the same ranges as the following expressions.
+ *       </ul>
+ *       <p class="REGEX">Enumerated ranges are merged (union operation).
+ *          <kbd>[a-ec-z]</kbd> is equivalent to <kbd>[a-z]</kbd>
+ *
+ *       <dt class="REGEX"><kbd>[^</kbd><var>R<sub>1</sub></var><var>R<sub>2</sub></var><var>...</var><var>R<sub>n</sub></var><kbd>]</kbd> (without a <a href="#COMMA_OPTION">"," option</a>)
+ *       <dt class="REGEX"><kbd>[^</kbd><var>R<sub>1</sub></var><kbd>,</kbd><var>R<sub>2</sub></var><kbd>,</kbd><var>...</var><kbd>,</kbd><var>R<sub>n</sub></var><kbd>]</kbd> (with a <a href="#COMMA_OPTION">"," option</a>)
+ *       <dd>Negative character class.  It matches a character not in ranges.
+ *
+ *       <dt class="REGEX"><kbd>(?[</kbd><var>ranges</var><kbd>]</kbd><var>op</var><kbd>[</kbd><var>ranges</var><kbd>]</kbd><var>op</var><kbd>[</kbd><var>ranges</var><kbd>]</kbd> ... <Kbd>)</kbd>
+ *       (<var>op</var> is <kbd>-</kbd> or <kbd>+</kbd> or <kbd>&</kbd>.)
+ *       <dd>Subtraction or union or intersection for character classes.
+ *       <dd class="REGEX">For exmaple, <kbd>(?[A-Z]-[CF])</kbd> is equivalent to <kbd>[A-BD-EG-Z]</kbd>, and <kbd>(?[0x00-0x7f]-[K]&[\p{Lu}])</kbd> is equivalent to <kbd>[A-JL-Z]</kbd>.
+ *       <dd>The result of this operations is a <u>positive character class</u>
+ *           even if an expression includes any negative character classes.
+ *           You have to take care on this in case-insensitive matching.
+ *           For instance, <kbd>(?[^b])</kbd> is equivalent to <kbd>[\x00-ac-\x{10ffff}]</kbd>,
+ *           which is equivalent to <kbd>[^b]</kbd> in case-sensitive matching.
+ *           But, in case-insensitive matching, <kbd>(?[^b])</kbd> matches any character because
+ *           it includes '<kbd>B</kbd>' and '<kbd>B</kbd>' matches '<kbd>b</kbd>'
+ *           though <kbd>[^b]</kbd> is processed as <kbd>[^Bb]</kbd>.
+ *
+ *       <dt class="REGEX"><kbd>[</kbd><var>R<sub>1</sub>R<sub>2</sub>...</var><kbd>-[</kbd><var>R<sub>n</sub>R<sub>n+1</sub>...</var><kbd>]]</kbd> (with an <a href="#X_OPTION">"X" option</a>)</dt>
+ *       <dd>Character class subtraction for the XML Schema.
+ *           You can use this syntax when you specify an <a href="#X_OPTION">"X" option</a>.
+ *           
+ *       <dt class="REGEX"><kbd>\d</kbd>
+ *       <dd class="REGEX">Equivalent to <kbd>[0-9]</kbd>.
+ *       <dd>When <a href="#U_OPTION">a "u" option</a> is set, it is equivalent to
+ *           <span class="REGEX"><kbd>\p{Nd}</kbd></span>.
+ *
+ *       <dt class="REGEX"><kbd>\D</kbd>
+ *       <dd class="REGEX">Equivalent to <kbd>[^0-9]</kbd>
+ *       <dd>When <a href="#U_OPTION">a "u" option</a> is set, it is equivalent to
+ *           <span class="REGEX"><kbd>\P{Nd}</kbd></span>.
+ *
+ *       <dt class="REGEX"><kbd>\s</kbd>
+ *       <dd class="REGEX">Equivalent to <kbd>[ \f\n\r\t]</kbd>
+ *       <dd>When <a href="#U_OPTION">a "u" option</a> is set, it is equivalent to
+ *           <span class="REGEX"><kbd>[ \f\n\r\t\p{Z}]</kbd></span>.
+ *
+ *       <dt class="REGEX"><kbd>\S</kbd>
+ *       <dd class="REGEX">Equivalent to <kbd>[^ \f\n\r\t]</kbd>
+ *       <dd>When <a href="#U_OPTION">a "u" option</a> is set, it is equivalent to
+ *           <span class="REGEX"><kbd>[^ \f\n\r\t\p{Z}]</kbd></span>.
+ *
+ *       <dt class="REGEX"><kbd>\w</kbd>
+ *       <dd class="REGEX">Equivalent to <kbd>[a-zA-Z0-9_]</kbd>
+ *       <dd>When <a href="#U_OPTION">a "u" option</a> is set, it is equivalent to
+ *           <span class="REGEX"><kbd>[\p{Lu}\p{Ll}\p{Lo}\p{Nd}_]</kbd></span>.
+ *
+ *       <dt class="REGEX"><kbd>\W</kbd>
+ *       <dd class="REGEX">Equivalent to <kbd>[^a-zA-Z0-9_]</kbd>
+ *       <dd>When <a href="#U_OPTION">a "u" option</a> is set, it is equivalent to
+ *           <span class="REGEX"><kbd>[^\p{Lu}\p{Ll}\p{Lo}\p{Nd}_]</kbd></span>.
+ *
+ *       <dt class="REGEX"><kbd>\p{</kbd><var>name</var><kbd>}</kbd>
+ *       <dd>Matches one character in the specified General Category (the second field in <a href="ftp://ftp.unicode.org/Public/UNIDATA/UnicodeData.txt"><kbd>UnicodeData.txt</kbd></a>) or the specified <a href="ftp://ftp.unicode.org/Public/UNIDATA/Blocks.txt">Block</a>.
+ *       The following names are available:
+ *       <dl>
+ *         <dt>Unicode General Categories:
+ *         <dd><kbd>
+ *       L, M, N, Z, C, P, S, Lu, Ll, Lt, Lm, Lo, Mn, Me, Mc, Nd, Nl, No, Zs, Zl, Zp,
+ *       Cc, Cf, Cn, Co, Cs, Pd, Ps, Pe, Pc, Po, Sm, Sc, Sk, So,
+ *         </kbd>
+ *         <dd>(Currently the Cn category includes U+10000-U+10FFFF characters)
+ *         <dt>Unicode Blocks:
+ *         <dd><kbd>
+ *       Basic Latin, Latin-1 Supplement, Latin Extended-A, Latin Extended-B,
+ *       IPA Extensions, Spacing Modifier Letters, Combining Diacritical Marks, Greek,
+ *       Cyrillic, Armenian, Hebrew, Arabic, Devanagari, Bengali, Gurmukhi, Gujarati,
+ *       Oriya, Tamil, Telugu, Kannada, Malayalam, Thai, Lao, Tibetan, Georgian,
+ *       Hangul Jamo, Latin Extended Additional, Greek Extended, General Punctuation,
+ *       Superscripts and Subscripts, Currency Symbols, Combining Marks for Symbols,
+ *       Letterlike Symbols, Number Forms, Arrows, Mathematical Operators,
+ *       Miscellaneous Technical, Control Pictures, Optical Character Recognition,
+ *       Enclosed Alphanumerics, Box Drawing, Block Elements, Geometric Shapes,
+ *       Miscellaneous Symbols, Dingbats, CJK Symbols and Punctuation, Hiragana,
+ *       Katakana, Bopomofo, Hangul Compatibility Jamo, Kanbun,
+ *       Enclosed CJK Letters and Months, CJK Compatibility, CJK Unified Ideographs,
+ *       Hangul Syllables, High Surrogates, High Private Use Surrogates, Low Surrogates,
+ *       Private Use, CJK Compatibility Ideographs, Alphabetic Presentation Forms,
+ *       Arabic Presentation Forms-A, Combining Half Marks, CJK Compatibility Forms,
+ *       Small Form Variants, Arabic Presentation Forms-B, Specials,
+ *       Halfwidth and Fullwidth Forms
+ *         </kbd>
+ *         <dt>Others:
+ *         <dd><kbd>ALL</kbd> (Equivalent to <kbd>[\u005cu0000-\u005cv10FFFF]</kbd>)
+ *         <dd><kbd>ASSGINED</kbd> (<kbd>\p{ASSIGNED}</kbd> is equivalent to <kbd>\P{Cn}</kbd>)
+ *         <dd><kbd>UNASSGINED</kbd>
+ *             (<kbd>\p{UNASSIGNED}</kbd> is equivalent to <kbd>\p{Cn}</kbd>)
+ *       </dl>
+ *
+ *       <dt class="REGEX"><kbd>\P{</kbd><var>name</var><kbd>}</kbd>
+ *       <dd>Matches one character not in the specified General Category or the specified Block.
+ *     </dl>
+ *   </li>
+ *
+ *   <li>Selection and Quantifier
+ *     <dl>
+ *       <dt class="REGEX"><VAR>X</VAR><kbd>|</kbd><VAR>Y</VAR>
+ *       <dd>...
+ *
+ *       <dt class="REGEX"><VAR>X</VAR><kbd>*</KBD>
+ *       <dd>Matches 0 or more <var>X</var>.
+ *
+ *       <dt class="REGEX"><VAR>X</VAR><kbd>+</KBD>
+ *       <dd>Matches 1 or more <var>X</var>.
+ *
+ *       <dt class="REGEX"><VAR>X</VAR><kbd>?</KBD>
+ *       <dd>Matches 0 or 1 <var>X</var>.
+ *
+ *       <dt class="REGEX"><var>X</var><kbd>{</kbd><var>number</var><kbd>}</kbd>
+ *       <dd>Matches <var>number</var> times.
+ *
+ *       <dt class="REGEX"><var>X</var><kbd>{</kbd><var>min</var><kbd>,}</kbd>
+ *       <dd>...
+ *
+ *       <dt class="REGEX"><var>X</var><kbd>{</kbd><var>min</var><kbd>,</kbd><var>max</var><kbd>}</kbd>
+ *       <dd>...
+ *
+ *       <dt class="REGEX"><VAR>X</VAR><kbd>*?</kbd>
+ *       <dt class="REGEX"><VAR>X</VAR><kbd>+?</kbd>
+ *       <dt class="REGEX"><VAR>X</VAR><kbd>??</kbd>
+ *       <dt class="REGEX"><var>X</var><kbd>{</kbd><var>min</var><kbd>,}?</kbd>
+ *       <dt class="REGEX"><var>X</var><kbd>{</kbd><var>min</var><kbd>,</kbd><var>max</var><kbd>}?</kbd>
+ *       <dd>Non-greedy matching.
+ *     </dl>
+ *   </li>
+ *
+ *   <li>Grouping, Capturing, and Back-reference
+ *     <dl>
+ *       <dt class="REGEX"><KBD>(?:</kbd><VAR>X</VAR><kbd>)</KBD>
+ *       <dd>Grouping. "<KBD>foo+</KBD>" matches "<KBD>foo</KBD>" or "<KBD>foooo</KBD>".
+ *       If you want it matches "<KBD>foofoo</KBD>" or "<KBD>foofoofoo</KBD>",
+ *       you have to write "<KBD>(?:foo)+</KBD>".
+ *
+ *       <dt class="REGEX"><KBD>(</kbd><VAR>X</VAR><kbd>)</KBD>
+ *       <dd>Grouping with capturing.
+ * It make a group and applications can know
+ * where in target text a group matched with methods of a <code>Match</code> instance
+ * after <code><a href="#matches(java.lang.String, org.apache.xerces.utils.regex.Match)">matches(String,Match)</a></code>.
+ * The 0th group means whole of this regular expression.
+ * The <VAR>N</VAR>th gorup is the inside of the <VAR>N</VAR>th left parenthesis.
+ * 
+ *   <p>For instance, a regular expression is
+ *   "<FONT color=blue><KBD> *([^&lt;:]*) +&lt;([^&gt;]*)&gt; *</KBD></FONT>"
+ *   and target text is
+ *   "<FONT color=red><KBD>From: TAMURA Kent &lt;kent@trl.ibm.co.jp&gt;</KBD></FONT>":
+ *   <ul>
+ *     <li><code>Match.getCapturedText(0)</code>:
+ *     "<FONT color=red><KBD> TAMURA Kent &lt;kent@trl.ibm.co.jp&gt;</KBD></FONT>"
+ *     <li><code>Match.getCapturedText(1)</code>: "<FONT color=red><KBD>TAMURA Kent</KBD></FONT>"
+ *     <li><code>Match.getCapturedText(2)</code>: "<FONT color=red><KBD>kent@trl.ibm.co.jp</KBD></FONT>"
+ *   </ul>
+ *
+ *       <dt class="REGEX"><kbd>\1 \2 \3 \4 \5 \6 \7 \8 \9</kbd>
+ *       <dd>
+ *
+ *       <dt class="REGEX"><kbd>(?></kbd><var>X</var><kbd>)</kbd>
+ *       <dd>Independent expression group. ................
+ *
+ *       <dt class="REGEX"><kbd>(?</kbd><var>options</var><kbd>:</kbd><var>X</var><kbd>)</kbd>
+ *       <dt class="REGEX"><kbd>(?</kbd><var>options</var><kbd>-</kbd><var>options2</var><kbd>:</kbd><var>X</var><kbd>)</kbd>
+ *       <dd>............................
+ *       <dd>The <var>options</var> or the <var>options2</var> consists of 'i' 'm' 's' 'w'.
+ *           Note that it can not contain 'u'.
+ *
+ *       <dt class="REGEX"><kbd>(?</kbd><var>options</var><kbd>)</kbd>
+ *       <dt class="REGEX"><kbd>(?</kbd><var>options</var><kbd>-</kbd><var>options2</var><kbd>)</kbd>
+ *       <dd>......
+ *       <dd>These expressions must be at the beginning of a group.
+ *     </dl>
+ *   </li>
+ *
+ *   <li>Anchor
+ *     <dl>
+ *       <dt class="REGEX"><kbd>\A</kbd>
+ *       <dd>Matches the beginnig of the text.
+ *
+ *       <dt class="REGEX"><kbd>\Z</kbd>
+ *       <dd>Matches the end of the text, or before an EOL character at the end of the text,
+ *           or CARRIAGE RETURN + LINE FEED at the end of the text.
+ *
+ *       <dt class="REGEX"><kbd>\z</kbd>
+ *       <dd>Matches the end of the text.
+ *
+ *       <dt class="REGEX"><kbd>^</kbd>
+ *       <dd>Matches the beginning of the text.  It is equivalent to <span class="REGEX"><Kbd>\A</kbd></span>.
+ *       <dd>When <a href="#M_OPTION">a "m" option</a> is set,
+ *           it matches the beginning of the text, or after one of EOL characters (
+ *           LINE FEED (U+000A), CARRIAGE RETURN (U+000D), LINE SEPARATOR (U+2028),
+ *           PARAGRAPH SEPARATOR (U+2029).)
+ *
+ *       <dt class="REGEX"><kbd>$</kbd>
+ *       <dd>Matches the end of the text, or before an EOL character at the end of the text,
+ *           or CARRIAGE RETURN + LINE FEED at the end of the text.
+ *       <dd>When <a href="#M_OPTION">a "m" option</a> is set,
+ *           it matches the end of the text, or before an EOL character.
+ *
+ *       <dt class="REGEX"><kbd>\b</kbd>
+ *       <dd>Matches word boundary.
+ *           (See <a href="#W_OPTION">a "w" option</a>)
+ *
+ *       <dt class="REGEX"><kbd>\B</kbd>
+ *       <dd>Matches non word boundary.
+ *           (See <a href="#W_OPTION">a "w" option</a>)
+ *
+ *       <dt class="REGEX"><kbd>\&lt;</kbd>
+ *       <dd>Matches the beginning of a word.
+ *           (See <a href="#W_OPTION">a "w" option</a>)
+ *
+ *       <dt class="REGEX"><kbd>\&gt;</kbd>
+ *       <dd>Matches the end of a word.
+ *           (See <a href="#W_OPTION">a "w" option</a>)
+ *     </dl>
+ *   </li>
+ *   <li>Lookahead and lookbehind
+ *     <dl>
+ *       <dt class="REGEX"><kbd>(?=</kbd><var>X</var><kbd>)</kbd>
+ *       <dd>Lookahead.
+ *
+ *       <dt class="REGEX"><kbd>(?!</kbd><var>X</var><kbd>)</kbd>
+ *       <dd>Negative lookahead.
+ *
+ *       <dt class="REGEX"><kbd>(?&lt;=</kbd><var>X</var><kbd>)</kbd>
+ *       <dd>Lookbehind.
+ *       <dd>(Note for text capturing......)
+ *
+ *       <dt class="REGEX"><kbd>(?&lt;!</kbd><var>X</var><kbd>)</kbd>
+ *       <dd>Negative lookbehind.
+ *     </dl>
+ *   </li>
+ *
+ *   <li>Misc.
+ *     <dl>
+ *       <dt class="REGEX"><kbd>(?(</Kbd><var>condition</var><Kbd>)</kbd><var>yes-pattern</var><kbd>|</kbd><var>no-pattern</var><kbd>)</kbd>,
+ *       <dt class="REGEX"><kbd>(?(</kbd><var>condition</var><kbd>)</kbd><var>yes-pattern</var><kbd>)</kbd>
+ *       <dd>......
+ *       <dt class="REGEX"><kbd>(?#</kbd><var>comment</var><kbd>)</kbd>
+ *       <dd>Comment.  A comment string consists of characters except '<kbd>)</kbd>'.
+ *           You can not write comments in character classes and before quantifiers.
+ *     </dl>
+ *   </li>
+ * </ul>
+ *
+ *
+ * <hr width="50%">
+ * <h3>BNF for the regular expression</h3>
+ * <pre>
+ * regex ::= ('(?' options ')')? term ('|' term)*
+ * term ::= factor+
+ * factor ::= anchors | atom (('*' | '+' | '?' | minmax ) '?'? )?
+ *            | '(?#' [^)]* ')'
+ * minmax ::= '{' ([0-9]+ | [0-9]+ ',' | ',' [0-9]+ | [0-9]+ ',' [0-9]+) '}'
+ * atom ::= char | '.' | char-class | '(' regex ')' | '(?:' regex ')' | '\' [0-9]
+ *          | '\w' | '\W' | '\d' | '\D' | '\s' | '\S' | category-block | '\X'
+ *          | '(?>' regex ')' | '(?' options ':' regex ')'
+ *          | '(?' ('(' [0-9] ')' | '(' anchors ')' | looks) term ('|' term)? ')'
+ * options ::= [imsw]* ('-' [imsw]+)?
+ * anchors ::= '^' | '$' | '\A' | '\Z' | '\z' | '\b' | '\B' | '\&lt;' | '\>'
+ * looks ::= '(?=' regex ')'  | '(?!' regex ')'
+ *           | '(?&lt;=' regex ')' | '(?&lt;!' regex ')'
+ * char ::= '\\' | '\' [efnrtv] | '\c' [@-_] | code-point | character-1
+ * category-block ::= '\' [pP] category-symbol-1
+ *                    | ('\p{' | '\P{') (category-symbol | block-name
+ *                                       | other-properties) '}'
+ * category-symbol-1 ::= 'L' | 'M' | 'N' | 'Z' | 'C' | 'P' | 'S'
+ * category-symbol ::= category-symbol-1 | 'Lu' | 'Ll' | 'Lt' | 'Lm' | Lo'
+ *                     | 'Mn' | 'Me' | 'Mc' | 'Nd' | 'Nl' | 'No'
+ *                     | 'Zs' | 'Zl' | 'Zp' | 'Cc' | 'Cf' | 'Cn' | 'Co' | 'Cs'
+ *                     | 'Pd' | 'Ps' | 'Pe' | 'Pc' | 'Po'
+ *                     | 'Sm' | 'Sc' | 'Sk' | 'So'
+ * block-name ::= (See above)
+ * other-properties ::= 'ALL' | 'ASSIGNED' | 'UNASSIGNED'
+ * character-1 ::= (any character except meta-characters)
+ *
+ * char-class ::= '[' ranges ']'
+ *                | '(?[' ranges ']' ([-+&] '[' ranges ']')? ')'
+ * ranges ::= '^'? (range <a href="#COMMA_OPTION">','?</a>)+
+ * range ::= '\d' | '\w' | '\s' | '\D' | '\W' | '\S' | category-block
+ *           | range-char | range-char '-' range-char
+ * range-char ::= '\[' | '\]' | '\\' | '\' [,-efnrtv] | code-point | character-2
+ * code-point ::= '\x' hex-char hex-char
+ *                | '\x{' hex-char+ '}'
+ * <!--               | '\u005c u' hex-char hex-char hex-char hex-char
+ * -->               | '\v' hex-char hex-char hex-char hex-char hex-char hex-char
+ * hex-char ::= [0-9a-fA-F]
+ * character-2 ::= (any character except \[]-,)
+ * </pre>
+ *
+ * <hr width="50%">
+ * <h3>TODO</h3>
+ * <ul>
+ *   <li><a href="http://www.unicode.org/unicode/reports/tr18/">Unicode Regular Expression Guidelines</a>
+ *     <ul>
+ *       <li>2.4 Canonical Equivalents
+ *       <li>Level 3
+ *     </ul>
+ *   <li>Parsing performance
+ * </ul>
+ *
+ * <hr width="50%">
+ * 
+ * @xerces.internal
+ *
+ * @author TAMURA Kent &lt;kent@trl.ibm.co.jp&gt;
+ * @version $Id: RegularExpression.java 961928 2010-07-08 20:43:46Z knoaman $
+ */
+@SuppressWarnings("all")
+public class RegularExpression implements java.io.Serializable {
+    
+    private static final long serialVersionUID = 6242499334195006401L;
+
+    static final boolean DEBUG = false;
+
+    /**
+     * Compiles a token tree into an operation flow.
+     */
+    private synchronized void compile(Token tok) {
+        if (this.operations != null)
+            return;
+        this.numberOfClosures = 0;
+        this.operations = this.compile(tok, null, false);
+    }
+
+    /**
+     * Converts a token to an operation.
+     */
+    private Op compile(Token tok, Op next, boolean reverse) {
+        Op ret;
+        switch (tok.type) {
+        case Token.DOT:
+            ret = Op.createDot();
+            ret.next = next;
+            break;
+
+        case Token.CHAR:
+            ret = Op.createChar(tok.getChar());
+            ret.next = next;
+            break;
+
+        case Token.ANCHOR:
+            ret = Op.createAnchor(tok.getChar());
+            ret.next = next;
+            break;
+
+        case Token.RANGE:
+        case Token.NRANGE:
+            ret = Op.createRange(tok);
+            ret.next = next;
+            break;
+
+        case Token.CONCAT:
+            ret = next;
+            if (!reverse) {
+                for (int i = tok.size()-1;  i >= 0;  i --) {
+                    ret = compile(tok.getChild(i), ret, false);
+                }
+            } else {
+                for (int i = 0;  i < tok.size();  i ++) {
+                    ret = compile(tok.getChild(i), ret, true);
+                }
+            }
+            break;
+
+        case Token.UNION:
+            Op.UnionOp uni = Op.createUnion(tok.size());
+            for (int i = 0;  i < tok.size();  i ++) {
+                uni.addElement(compile(tok.getChild(i), next, reverse));
+            }
+            ret = uni;                          // ret.next is null.
+            break;
+
+        case Token.CLOSURE:
+        case Token.NONGREEDYCLOSURE:
+            Token child = tok.getChild(0);
+            int min = tok.getMin();
+            int max = tok.getMax();
+            if (min >= 0 && min == max) { // {n}
+                ret = next;
+                for (int i = 0; i < min;  i ++) {
+                    ret = compile(child, ret, reverse);
+                }
+                break;
+            }
+            if (min > 0 && max > 0)
+                max -= min;
+            if (max > 0) {
+                // X{2,6} -> XX(X(X(XX?)?)?)?
+                ret = next;
+                for (int i = 0;  i < max;  i ++) {
+                    Op.ChildOp q = Op.createQuestion(tok.type == Token.NONGREEDYCLOSURE);
+                    q.next = next;
+                    q.setChild(compile(child, ret, reverse));
+                    ret = q;
+                }
+            } else {
+                Op.ChildOp op;
+                if (tok.type == Token.NONGREEDYCLOSURE) {
+                    op = Op.createNonGreedyClosure();
+                } else {                        // Token.CLOSURE
+                    op = Op.createClosure(this.numberOfClosures++);
+                }
+                op.next = next;
+                op.setChild(compile(child, op, reverse));
+                ret = op;
+            }
+            if (min > 0) {
+                for (int i = 0;  i < min;  i ++) {
+                    ret = compile(child, ret, reverse);
+                }
+            }
+            break;
+
+        case Token.EMPTY:
+            ret = next;
+            break;
+
+        case Token.STRING:
+            ret = Op.createString(tok.getString());
+            ret.next = next;
+            break;
+
+        case Token.BACKREFERENCE:
+            ret = Op.createBackReference(tok.getReferenceNumber());
+            ret.next = next;
+            break;
+
+        case Token.PAREN:
+            if (tok.getParenNumber() == 0) {
+                ret = compile(tok.getChild(0), next, reverse);
+            } else if (reverse) {
+                next = Op.createCapture(tok.getParenNumber(), next);
+                next = compile(tok.getChild(0), next, reverse);
+                ret = Op.createCapture(-tok.getParenNumber(), next);
+            } else {
+                next = Op.createCapture(-tok.getParenNumber(), next);
+                next = compile(tok.getChild(0), next, reverse);
+                ret = Op.createCapture(tok.getParenNumber(), next);
+            }
+            break;
+
+        case Token.LOOKAHEAD:
+            ret = Op.createLook(Op.LOOKAHEAD, next, compile(tok.getChild(0), null, false));
+            break;
+        case Token.NEGATIVELOOKAHEAD:
+            ret = Op.createLook(Op.NEGATIVELOOKAHEAD, next, compile(tok.getChild(0), null, false));
+            break;
+        case Token.LOOKBEHIND:
+            ret = Op.createLook(Op.LOOKBEHIND, next, compile(tok.getChild(0), null, true));
+            break;
+        case Token.NEGATIVELOOKBEHIND:
+            ret = Op.createLook(Op.NEGATIVELOOKBEHIND, next, compile(tok.getChild(0), null, true));
+            break;
+
+        case Token.INDEPENDENT:
+            ret = Op.createIndependent(next, compile(tok.getChild(0), null, reverse));
+            break;
+
+        case Token.MODIFIERGROUP:
+            ret = Op.createModifier(next, compile(tok.getChild(0), null, reverse),
+                                    ((Token.ModifierToken)tok).getOptions(),
+                                    ((Token.ModifierToken)tok).getOptionsMask());
+            break;
+
+        case Token.CONDITION:
+            Token.ConditionToken ctok = (Token.ConditionToken)tok;
+            int ref = ctok.refNumber;
+            Op condition = ctok.condition == null ? null : compile(ctok.condition, null, reverse);
+            Op yes = compile(ctok.yes, next, reverse);
+            Op no = ctok.no == null ? null : compile(ctok.no, next, reverse);
+            ret = Op.createCondition(next, ref, condition, yes, no);
+            break;
+
+        default:
+            throw new RuntimeException("Unknown token type: "+tok.type);
+        } // switch (tok.type)
+        return ret;
+    }
+
+
+//Public
+
+    /**
+     * Checks whether the <var>target</var> text <strong>contains</strong> this pattern or not.
+     *
+     * @return true if the target is matched to this regular expression.
+     */
+    public boolean matches(char[]  target) {
+        return this.matches(target, 0,  target .length , (Match)null);
+    }
+
+    /**
+     * Checks whether the <var>target</var> text <strong>contains</strong> this pattern
+     * in specified range or not.
+     *
+     * @param start Start offset of the range.
+     * @param end  End offset +1 of the range.
+     * @return true if the target is matched to this regular expression.
+     */
+    public boolean matches(char[]  target, int start, int end) {
+        return this.matches(target, start, end, (Match)null);
+    }
+
+    /**
+     * Checks whether the <var>target</var> text <strong>contains</strong> this pattern or not.
+     *
+     * @param match A Match instance for storing matching result.
+     * @return Offset of the start position in <VAR>target</VAR>; or -1 if not match.
+     */
+    public boolean matches(char[]  target, Match match) {
+        return this.matches(target, 0,  target .length , match);
+    }
+
+
+    /**
+     * Checks whether the <var>target</var> text <strong>contains</strong> this pattern
+     * in specified range or not.
+     *
+     * @param start Start offset of the range.
+     * @param end  End offset +1 of the range.
+     * @param match A Match instance for storing matching result.
+     * @return Offset of the start position in <VAR>target</VAR>; or -1 if not match.
+     */
+    public boolean matches(char[] target, int start, int end, Match match) {
+
+        synchronized (this) {
+            if (this.operations == null)
+                this.prepare();
+            if (this.context == null)
+                this.context = new Context();
+        }
+        Context con = null;
+        synchronized (this.context) {
+            con = this.context.inuse ? new Context() : this.context;
+            con.reset(target, start, end, this.numberOfClosures);
+        }
+        if (match != null) {
+            match.setNumberOfGroups(this.nofparen);
+            match.setSource(target);
+        } else if (this.hasBackReferences) {
+            match = new Match();
+            match.setNumberOfGroups(this.nofparen);
+            // Need not to call setSource() because
+            // a caller can not access this match instance.
+        }
+        con.match = match;
+
+        if (RegularExpression.isSet(this.options, XMLSCHEMA_MODE)) {
+            int matchEnd = this. match(con, this.operations, con.start, 1, this.options);
+            //System.err.println("DEBUG: matchEnd="+matchEnd);
+            if (matchEnd == con.limit) {
+                if (con.match != null) {
+                    con.match.setBeginning(0, con.start);
+                    con.match.setEnd(0, matchEnd);
+                }
+                con.setInUse(false);
+                return true;
+            }
+            return false;
+        }
+
+        /*
+         * The pattern has only fixed string.
+         * The engine uses Boyer-Moore.
+         */
+        if (this.fixedStringOnly) {
+            //System.err.println("DEBUG: fixed-only: "+this.fixedString);
+            int o = this.fixedStringTable.matches(target, con.start, con.limit);
+            if (o >= 0) {
+                if (con.match != null) {
+                    con.match.setBeginning(0, o);
+                    con.match.setEnd(0, o+this.fixedString.length());
+                }
+                con.setInUse(false);
+                return true;
+            }
+            con.setInUse(false);
+            return false;
+        }
+
+        /*
+         * The pattern contains a fixed string.
+         * The engine checks with Boyer-Moore whether the text contains the fixed string or not.
+         * If not, it return with false.
+         */
+        if (this.fixedString != null) {
+            int o = this.fixedStringTable.matches(target, con.start, con.limit);
+            if (o < 0) {
+                //System.err.println("Non-match in fixed-string search.");
+                con.setInUse(false);
+                return false;
+            }
+        }
+
+        int limit = con.limit-this.minlength;
+        int matchStart;
+        int matchEnd = -1;
+
+        /*
+         * Checks whether the expression starts with ".*".
+         */
+        if (this.operations != null
+            && this.operations.type == Op.CLOSURE && this.operations.getChild().type == Op.DOT) {
+            if (isSet(this.options, SINGLE_LINE)) {
+                matchStart = con.start;
+                matchEnd = this. match(con, this.operations, con.start, 1, this.options);
+            } else {
+                boolean previousIsEOL = true;
+                for (matchStart = con.start;  matchStart <= limit;  matchStart ++) {
+                    int ch =  target [  matchStart ] ;
+                    if (isEOLChar(ch)) {
+                        previousIsEOL = true;
+                    } else {
+                        if (previousIsEOL) {
+                            if (0 <= (matchEnd = this. match(con, this.operations,
+                                                             matchStart, 1, this.options)))
+                                break;
+                        }
+                        previousIsEOL = false;
+                    }
+                }
+            }
+        }
+
+        /*
+         * Optimization against the first character.
+         */
+        else if (this.firstChar != null) {
+            //System.err.println("DEBUG: with firstchar-matching: "+this.firstChar);
+            RangeToken range = this.firstChar;
+            for (matchStart = con.start;  matchStart <= limit;  matchStart ++) {
+                int ch =  target [matchStart] ;
+                if (REUtil.isHighSurrogate(ch) && matchStart+1 < con.limit) {
+                    ch = REUtil.composeFromSurrogates(ch, target[matchStart+1]);
+                }
+                if (!range.match(ch))  {
+                    continue;
+                }
+                if (0 <= (matchEnd = this. match(con, this.operations,
+                                                 matchStart, 1, this.options))) {
+                        break;
+                }
+            }
+        }
+
+        /*
+         * Straightforward matching.
+         */
+        else {
+            for (matchStart = con.start;  matchStart <= limit;  matchStart ++) {
+                if (0 <= (matchEnd = this. match(con, this.operations, matchStart, 1, this.options)))
+                    break;
+            }
+        }
+
+        if (matchEnd >= 0) {
+            if (con.match != null) {
+                con.match.setBeginning(0, matchStart);
+                con.match.setEnd(0, matchEnd);
+            }
+            con.setInUse(false);
+            return true;
+        } else {
+            con.setInUse(false);
+            return false;
+        }
+    }
+
+    /**
+     * Checks whether the <var>target</var> text <strong>contains</strong> this pattern or not.
+     *
+     * @return true if the target is matched to this regular expression.
+     */
+    public boolean matches(String  target) {
+        return this.matches(target, 0,  target .length() , (Match)null);
+    }
+
+    /**
+     * Checks whether the <var>target</var> text <strong>contains</strong> this pattern
+     * in specified range or not.
+     *
+     * @param start Start offset of the range.
+     * @param end  End offset +1 of the range.
+     * @return true if the target is matched to this regular expression.
+     */
+    public boolean matches(String  target, int start, int end) {
+        return this.matches(target, start, end, (Match)null);
+    }
+
+    /**
+     * Checks whether the <var>target</var> text <strong>contains</strong> this pattern or not.
+     *
+     * @param match A Match instance for storing matching result.
+     * @return Offset of the start position in <VAR>target</VAR>; or -1 if not match.
+     */
+    public boolean matches(String  target, Match match) {
+        return this.matches(target, 0,  target .length() , match);
+    }
+
+    /**
+     * Checks whether the <var>target</var> text <strong>contains</strong> this pattern
+     * in specified range or not.
+     *
+     * @param start Start offset of the range.
+     * @param end  End offset +1 of the range.
+     * @param match A Match instance for storing matching result.
+     * @return Offset of the start position in <VAR>target</VAR>; or -1 if not match.
+     */
+    public boolean matches(String  target, int start, int end, Match match) {
+
+        synchronized (this) {
+            if (this.operations == null)
+                this.prepare();
+            if (this.context == null)
+                this.context = new Context();
+        }
+        Context con = null;
+        synchronized (this.context) {
+            con = this.context.inuse ? new Context() : this.context;
+            con.reset(target, start, end, this.numberOfClosures);
+        }
+        if (match != null) {
+            match.setNumberOfGroups(this.nofparen);
+            match.setSource(target);
+        } else if (this.hasBackReferences) {
+            match = new Match();
+            match.setNumberOfGroups(this.nofparen);
+            // Need not to call setSource() because
+            // a caller can not access this match instance.
+        }
+        con.match = match;
+
+        if (RegularExpression.isSet(this.options, XMLSCHEMA_MODE)) {
+            if (DEBUG) {
+                System.err.println("target string="+target);
+            }
+            int matchEnd = this. match(con, this.operations, con.start, 1, this.options);
+            if (DEBUG) {
+                System.err.println("matchEnd="+matchEnd);
+                System.err.println("con.limit="+con.limit);
+            }
+            if (matchEnd == con.limit) {
+                if (con.match != null) {
+                    con.match.setBeginning(0, con.start);
+                    con.match.setEnd(0, matchEnd);
+                }
+                con.setInUse(false);
+                return true;
+            }
+            return false;
+        }
+
+        /*
+         * The pattern has only fixed string.
+         * The engine uses Boyer-Moore.
+         */
+        if (this.fixedStringOnly) {
+            //System.err.println("DEBUG: fixed-only: "+this.fixedString);
+            int o = this.fixedStringTable.matches(target, con.start, con.limit);
+            if (o >= 0) {
+                if (con.match != null) {
+                    con.match.setBeginning(0, o);
+                    con.match.setEnd(0, o+this.fixedString.length());
+                }
+                con.setInUse(false);
+                return true;
+            }
+            con.setInUse(false);
+            return false;
+        }
+
+        /*
+         * The pattern contains a fixed string.
+         * The engine checks with Boyer-Moore whether the text contains the fixed string or not.
+         * If not, it return with false.
+         */
+        if (this.fixedString != null) {
+            int o = this.fixedStringTable.matches(target, con.start, con.limit);
+            if (o < 0) {
+                //System.err.println("Non-match in fixed-string search.");
+                con.setInUse(false);
+                return false;
+            }
+        }
+
+        int limit = con.limit-this.minlength;
+        int matchStart;
+        int matchEnd = -1;
+
+        /*
+         * Checks whether the expression starts with ".*".
+         */
+        if (this.operations != null
+            && this.operations.type == Op.CLOSURE && this.operations.getChild().type == Op.DOT) {
+            if (isSet(this.options, SINGLE_LINE)) {
+                matchStart = con.start;
+                matchEnd = this.match(con, this.operations, con.start, 1, this.options);
+            } else {
+                boolean previousIsEOL = true;
+                for (matchStart = con.start;  matchStart <= limit;  matchStart ++) {
+                    int ch =  target .charAt(  matchStart ) ;
+                    if (isEOLChar(ch)) {
+                        previousIsEOL = true;
+                    } else {
+                        if (previousIsEOL) {
+                            if (0 <= (matchEnd = this.match(con, this.operations,
+                                                            matchStart, 1, this.options)))
+                                break;
+                        }
+                        previousIsEOL = false;
+                    }
+                }
+            }
+        }
+
+        /*
+         * Optimization against the first character.
+         */
+        else if (this.firstChar != null) {
+            //System.err.println("DEBUG: with firstchar-matching: "+this.firstChar);
+            RangeToken range = this.firstChar;
+            for (matchStart = con.start;  matchStart <= limit;  matchStart ++) {
+                int ch =  target .charAt(  matchStart ) ;
+                if (REUtil.isHighSurrogate(ch) && matchStart+1 < con.limit) {
+                    ch = REUtil.composeFromSurrogates(ch, target.charAt(matchStart+1));
+                }
+                if (!range.match(ch)) {
+                    continue;
+                }
+                if (0 <= (matchEnd = this.match(con, this.operations,
+                                                matchStart, 1, this.options))) {
+                        break;
+                }                
+            }
+        }
+
+        /*
+         * Straightforward matching.
+         */
+        else {
+            for (matchStart = con.start;  matchStart <= limit;  matchStart ++) {
+                if (0 <= (matchEnd = this.match(con, this.operations, matchStart, 1, this.options)))
+                    break;
+            }
+        }
+
+        if (matchEnd >= 0) {
+            if (con.match != null) {
+                con.match.setBeginning(0, matchStart);
+                con.match.setEnd(0, matchEnd);
+            }
+            con.setInUse(false);
+            return true;
+        } else {
+            con.setInUse(false);
+            return false;
+        }
+    }
+
+    /**
+     * @return -1 when not match; offset of the end of matched string when match.
+     */
+    private int match(Context con, Op op, int offset, int dx, int opts) {
+        final ExpressionTarget target = con.target;
+        final Stack opStack = new Stack();
+        final IntStack dataStack = new IntStack();
+        final boolean isSetIgnoreCase = isSet(opts, IGNORE_CASE);
+        int retValue = -1;
+        boolean returned = false;
+
+        for (;;) {
+            if (op == null || offset > con.limit || offset < con.start) {
+                if (op == null) {
+                    retValue = isSet(opts, XMLSCHEMA_MODE) && offset != con.limit ? -1 : offset;
+                }
+                else {
+                   retValue = -1; 
+                }
+                returned = true;
+            }
+            else  {
+                retValue = -1;
+                // dx value is either 1 or -1
+                switch (op.type) {
+                case Op.CHAR:
+                    {
+                        final int o1 = (dx > 0) ? offset : offset -1;
+                        if (o1 >= con.limit || o1 < 0 || !matchChar(op.getData(), target.charAt(o1), isSetIgnoreCase)) {
+                            returned = true;
+                            break;
+                        }
+                        offset += dx;
+                        op = op.next;
+                    }
+                    break;
+
+                case Op.DOT:
+                    {
+                        int o1 = (dx > 0) ? offset : offset - 1;
+                        if (o1 >= con.limit || o1 < 0) {
+                            returned = true;
+                            break;
+                        }
+                        if (isSet(opts, SINGLE_LINE)) {
+                            if (REUtil.isHighSurrogate(target.charAt(o1)) && o1+dx >= 0 && o1+dx < con.limit) {
+                                o1 += dx;
+                            }
+                        }
+                        else {
+                            int ch = target.charAt(o1);
+                            if (REUtil.isHighSurrogate(ch) && o1+dx >= 0 && o1+dx < con.limit) {
+                                o1 += dx;
+                                ch = REUtil.composeFromSurrogates(ch, target.charAt(o1));
+                            }
+                            if (isEOLChar(ch)) {
+                                returned = true;
+                                break;
+                            }
+                        }
+                        offset = (dx > 0) ? o1 + 1 : o1;
+                        op = op.next;
+                    }
+                    break;
+
+                case Op.RANGE:
+                case Op.NRANGE:
+                    {
+                        int o1 = (dx > 0) ? offset : offset -1;
+                        if (o1 >= con.limit || o1 < 0) {
+                            returned = true;
+                            break;
+                        }
+                        int ch = target.charAt(offset);
+                        if (REUtil.isHighSurrogate(ch) && o1+dx < con.limit && o1+dx >=0) {
+                            o1 += dx;
+                            ch = REUtil.composeFromSurrogates(ch, target.charAt(o1));
+                        }
+                        final RangeToken tok = op.getToken();
+                        if (!tok.match(ch)) {
+                            returned = true;
+                            break;
+                        }
+                        offset = (dx > 0) ? o1+1 : o1;
+                        op = op.next;
+                    }
+                    break;
+
+                case Op.ANCHOR:
+                    {
+                        if (!matchAnchor(target, op, con, offset, opts)) {
+                            returned = true;
+                            break;
+                        }
+                        op = op.next;
+                    }
+                    break;
+
+                case Op.BACKREFERENCE:
+                    {
+                        int refno = op.getData();
+                        if (refno <= 0 || refno >= this.nofparen) {
+                            throw new RuntimeException("Internal Error: Reference number must be more than zero: "+refno);
+                        }
+                        if (con.match.getBeginning(refno) < 0 || con.match.getEnd(refno) < 0) {
+                            returned = true;
+                            break;
+                        }
+                        int o2 = con.match.getBeginning(refno);
+                        int literallen = con.match.getEnd(refno)-o2;
+                        if (dx > 0) {
+                            if (!target.regionMatches(isSetIgnoreCase, offset, con.limit, o2, literallen)) {
+                                returned = true;
+                                break;
+                            }
+                            offset += literallen;
+                        }
+                        else {
+                            if (!target.regionMatches(isSetIgnoreCase, offset-literallen, con.limit, o2, literallen)) {
+                                returned = true;
+                                break;
+                            }
+                            offset -= literallen;
+                        }
+                        op = op.next;
+                    }
+                    break;
+
+                case Op.STRING:
+                    {
+                        String literal = op.getString();
+                        int literallen = literal.length();
+                        if (dx > 0) {
+                            if (!target.regionMatches(isSetIgnoreCase, offset, con.limit, literal, literallen)) {
+                                returned = true;
+                                break;
+                            }
+                            offset += literallen;
+                        }
+                        else {
+                            if (!target.regionMatches(isSetIgnoreCase, offset-literallen, con.limit, literal, literallen)) {
+                                returned = true;
+                                break;
+                            }
+                            offset -= literallen;
+                        }
+                        op = op.next;
+                    }
+                    break;
+
+                case Op.CLOSURE:
+                    {
+                        // Saves current position to avoid zero-width repeats.
+                        final int id = op.getData();
+                        if (con.closureContexts[id].contains(offset)) {
+                            returned = true;
+                            break;
+                        }
+                        
+                        con.closureContexts[id].addOffset(offset);
+                    }
+                    // fall through
+
+                case Op.QUESTION:
+                    {
+                        opStack.push(op);
+                        dataStack.push(offset);
+                        op = op.getChild();
+                    }
+                    break;
+
+                case Op.NONGREEDYCLOSURE:
+                case Op.NONGREEDYQUESTION:
+                    {
+                        opStack.push(op);
+                        dataStack.push(offset);
+                        op = op.next;
+                    }
+                    break;
+
+                case Op.UNION:
+                    if (op.size() == 0) {
+                        returned = true;
+                    }
+                    else {
+                        opStack.push(op);
+                        dataStack.push(0);
+                        dataStack.push(offset);
+                        op = op.elementAt(0);
+                    }
+                    break;
+
+                case Op.CAPTURE:
+                    {
+                        final int refno = op.getData();
+                        if (con.match != null) {
+                            if (refno > 0) {
+                                dataStack.push(con.match.getBeginning(refno));
+                                con.match.setBeginning(refno, offset);
+                            }
+                            else {
+                                final int index = -refno;
+                                dataStack.push(con.match.getEnd(index));
+                                con.match.setEnd(index, offset);
+                            }
+                            opStack.push(op);
+                            dataStack.push(offset);
+                        }
+                        op = op.next;
+                    }
+                    break;
+
+                case Op.LOOKAHEAD:
+                case Op.NEGATIVELOOKAHEAD:
+                case Op.LOOKBEHIND:
+                case Op.NEGATIVELOOKBEHIND:
+                    {
+                        opStack.push(op);
+                        dataStack.push(dx);
+                        dataStack.push(offset);
+                        dx = (op.type == Op.LOOKAHEAD || op.type == Op.NEGATIVELOOKAHEAD) ? 1 : -1;
+                        op = op.getChild();
+                    }
+                    break;
+
+                case Op.INDEPENDENT:
+                    {
+                        opStack.push(op);
+                        dataStack.push(offset);
+                        op = op.getChild();
+                    }
+                    break;
+
+                case Op.MODIFIER:
+                    {
+                        int localopts = opts;
+                        localopts |= op.getData();
+                        localopts &= ~op.getData2();
+                        opStack.push(op);
+                        dataStack.push(opts);
+                        dataStack.push(offset);
+                        opts = localopts;
+                        op = op.getChild();
+                    }
+                    break;
+
+                case Op.CONDITION:
+                    {
+                        Op.ConditionOp cop = (Op.ConditionOp)op;
+                        if (cop.refNumber > 0) {
+                            if (cop.refNumber >= this.nofparen) {
+                                throw new RuntimeException("Internal Error: Reference number must be more than zero: "+cop.refNumber);
+                            }
+                            if (con.match.getBeginning(cop.refNumber) >= 0
+                                    && con.match.getEnd(cop.refNumber) >= 0) {
+                                op = cop.yes;
+                            }
+                            else if (cop.no != null) {
+                                op = cop.no;
+                            }
+                            else {
+                                op = cop.next;
+                            }
+                        }
+                        else {
+                            opStack.push(op);
+                            dataStack.push(offset);
+                            op = cop.condition;
+                        }
+                    }
+                    break;
+
+                default:
+                    throw new RuntimeException("Unknown operation type: " + op.type);
+                }
+            }
+
+            // handle recursive operations
+            while (returned) {
+                // exhausted all the operations
+                if (opStack.isEmpty()) {
+                    return retValue;
+                }
+
+                op = (Op) opStack.pop();
+                offset = dataStack.pop();
+
+                switch (op.type) {
+                case Op.CLOSURE:
+                case Op.QUESTION:
+                    if (retValue < 0) {
+                        op = op.next;
+                        returned = false;
+                    }
+                    break;
+
+                case Op.NONGREEDYCLOSURE:
+                case Op.NONGREEDYQUESTION:
+                    if (retValue < 0) {
+                        op = op.getChild();
+                        returned = false;
+                    }
+                    break;
+
+                case Op.UNION:
+                    {
+                        int unionIndex = dataStack.pop();
+                        if (DEBUG) {
+                            System.err.println("UNION: "+unionIndex+", ret="+retValue);
+                        }
+
+                        if (retValue < 0) {
+                            if (++unionIndex < op.size()) {
+                                opStack.push(op);
+                                dataStack.push(unionIndex);
+                                dataStack.push(offset);
+                                op = op.elementAt(unionIndex);
+                                returned = false;
+                            }
+                            else {
+                                retValue = -1;
+                            }
+                        }
+                    }
+                    break;
+
+                case Op.CAPTURE:
+                    final int refno = op.getData();
+                    final int saved = dataStack.pop();
+                    if (retValue < 0) {
+                        if (refno > 0) {
+                            con.match.setBeginning(refno, saved);
+                        }
+                        else {
+                            con.match.setEnd(-refno, saved);
+                        }
+                    }
+                    break;
+                    
+                case Op.LOOKAHEAD:
+                case Op.LOOKBEHIND:
+                    {
+                        dx = dataStack.pop();
+                        if (0 <= retValue) {
+                            op = op.next;
+                            returned = false;
+                        }
+                        retValue = -1;
+                    }
+                    break;
+
+                case Op.NEGATIVELOOKAHEAD:
+                case Op.NEGATIVELOOKBEHIND:
+                    {
+                        dx = dataStack.pop();
+                        if (0 > retValue)  {
+                            op = op.next;
+                            returned = false;
+                        }
+                        retValue = -1;
+                    }
+                    break;
+
+                case Op.MODIFIER:
+                    opts = dataStack.pop();
+                    // fall through
+
+                case Op.INDEPENDENT:
+                    if (retValue >= 0)  {
+                        offset = retValue;
+                        op = op.next;
+                        returned = false;
+                    }
+                    break;
+
+                case Op.CONDITION:
+                    {
+                        final Op.ConditionOp cop = (Op.ConditionOp)op;
+                        if (0 <= retValue) {
+                            op = cop.yes;
+                        }
+                        else if (cop.no != null) {
+                            op = cop.no;
+                        }
+                        else {
+                            op = cop.next;
+                        }
+                    }
+                    returned = false;
+                    break;
+
+                default:
+                    break;
+                }
+            }
+        }
+    }
+
+    private boolean matchChar(int ch, int other, boolean ignoreCase) {
+        return (ignoreCase) ? matchIgnoreCase(ch, other) : ch == other;
+    }
+
+    boolean matchAnchor(ExpressionTarget target, Op op, Context con, int offset, int opts) {
+        boolean go = false;
+        switch (op.getData()) {
+        case '^':
+            if (isSet(opts, MULTIPLE_LINES)) {
+                if (!(offset == con.start
+                      || offset > con.start && offset < con.limit && isEOLChar(target.charAt(offset-1))))
+                    return false;
+            } else {
+                if (offset != con.start)
+                    return false;
+            }
+            break;
+
+        case '@':                         // Internal use only.
+            // The @ always matches line beginnings.
+            if (!(offset == con.start
+                  || offset > con.start && isEOLChar(target.charAt(offset-1))))
+                return false;
+            break;
+
+        case '$':
+            if (isSet(opts, MULTIPLE_LINES)) {
+                if (!(offset == con.limit
+                      || offset < con.limit && isEOLChar(target.charAt(offset))))
+                    return false;
+            } else {
+                if (!(offset == con.limit
+                      || offset+1 == con.limit && isEOLChar(target.charAt(offset))
+                      || offset+2 == con.limit &&  target.charAt(offset) == CARRIAGE_RETURN
+                      &&  target.charAt(offset+1) == LINE_FEED))
+                    return false;
+            }
+            break;
+
+        case 'A':
+            if (offset != con.start)  return false;
+            break;
+
+        case 'Z':
+            if (!(offset == con.limit
+                  || offset+1 == con.limit && isEOLChar(target.charAt(offset))
+                  || offset+2 == con.limit &&  target.charAt(offset) == CARRIAGE_RETURN
+                  &&  target.charAt(offset+1) == LINE_FEED))
+                return false;
+            break;
+
+        case 'z':
+            if (offset != con.limit)  return false;
+            break;
+
+        case 'b':
+            if (con.length == 0) 
+                return false;
+            {
+                int after = getWordType(target, con.start, con.limit, offset, opts);
+                if (after == WT_IGNORE)  return false;
+                int before = getPreviousWordType(target, con.start, con.limit, offset, opts);
+                if (after == before)  return false;
+            }
+            break;
+
+        case 'B':
+            if (con.length == 0)
+                go = true;
+            else {
+                int after = getWordType(target, con.start, con.limit, offset, opts);
+                go = after == WT_IGNORE
+                     || after == getPreviousWordType(target, con.start, con.limit, offset, opts);
+            }
+            if (!go)  return false;
+            break;
+
+        case '<':
+            if (con.length == 0 || offset == con.limit)  return false;
+            if (getWordType(target, con.start, con.limit, offset, opts) != WT_LETTER
+                || getPreviousWordType(target, con.start, con.limit, offset, opts) != WT_OTHER)
+                return false;
+            break;
+
+        case '>':
+            if (con.length == 0 || offset == con.start)  return false;
+            if (getWordType(target, con.start, con.limit, offset, opts) != WT_OTHER
+                || getPreviousWordType(target, con.start, con.limit, offset, opts) != WT_LETTER)
+                return false;
+            break;
+        } // switch anchor type
+        
+        return true;
+    }
+
+    private static final int getPreviousWordType(ExpressionTarget target, int begin, int end,
+                                                 int offset, int opts) {
+        int ret = getWordType(target, begin, end, --offset, opts);
+        while (ret == WT_IGNORE)
+            ret = getWordType(target, begin, end, --offset, opts);
+        return ret;
+    }
+
+    private static final int getWordType(ExpressionTarget target, int begin, int end,
+                                         int offset, int opts) {
+        if (offset < begin || offset >= end)  return WT_OTHER;
+        return getWordType0(target.charAt(offset) , opts);
+    }
+
+
+    /**
+     * Checks whether the <var>target</var> text <strong>contains</strong> this pattern or not.
+     *
+     * @return true if the target is matched to this regular expression.
+     */
+    public boolean matches(CharacterIterator target) {
+        return this.matches(target, (Match)null);
+    }
+
+
+    /**
+     * Checks whether the <var>target</var> text <strong>contains</strong> this pattern or not.
+     *
+     * @param match A Match instance for storing matching result.
+     * @return Offset of the start position in <VAR>target</VAR>; or -1 if not match.
+     */
+    public boolean matches(CharacterIterator  target, Match match) {
+        int start = target.getBeginIndex();
+        int end = target.getEndIndex();
+
+
+
+        synchronized (this) {
+            if (this.operations == null)
+                this.prepare();
+            if (this.context == null)
+                this.context = new Context();
+        }
+        Context con = null;
+        synchronized (this.context) {
+            con = this.context.inuse ? new Context() : this.context;
+            con.reset(target, start, end, this.numberOfClosures);
+        }
+        if (match != null) {
+            match.setNumberOfGroups(this.nofparen);
+            match.setSource(target);
+        } else if (this.hasBackReferences) {
+            match = new Match();
+            match.setNumberOfGroups(this.nofparen);
+            // Need not to call setSource() because
+            // a caller can not access this match instance.
+        }
+        con.match = match;
+
+        if (RegularExpression.isSet(this.options, XMLSCHEMA_MODE)) {
+            int matchEnd = this.match(con, this.operations, con.start, 1, this.options);
+            //System.err.println("DEBUG: matchEnd="+matchEnd);
+            if (matchEnd == con.limit) {
+                if (con.match != null) {
+                    con.match.setBeginning(0, con.start);
+                    con.match.setEnd(0, matchEnd);
+                }
+                con.setInUse(false);
+                return true;
+            }
+            return false;
+        }
+
+        /*
+         * The pattern has only fixed string.
+         * The engine uses Boyer-Moore.
+         */
+        if (this.fixedStringOnly) {
+            //System.err.println("DEBUG: fixed-only: "+this.fixedString);
+            int o = this.fixedStringTable.matches(target, con.start, con.limit);
+            if (o >= 0) {
+                if (con.match != null) {
+                    con.match.setBeginning(0, o);
+                    con.match.setEnd(0, o+this.fixedString.length());
+                }
+                con.setInUse(false);
+                return true;
+            }
+            con.setInUse(false);
+            return false;
+        }
+
+        /*
+         * The pattern contains a fixed string.
+         * The engine checks with Boyer-Moore whether the text contains the fixed string or not.
+         * If not, it return with false.
+         */
+        if (this.fixedString != null) {
+            int o = this.fixedStringTable.matches(target, con.start, con.limit);
+            if (o < 0) {
+                //System.err.println("Non-match in fixed-string search.");
+                con.setInUse(false);
+                return false;
+            }
+        }
+
+        int limit = con.limit-this.minlength;
+        int matchStart;
+        int matchEnd = -1;
+
+        /*
+         * Checks whether the expression starts with ".*".
+         */
+        if (this.operations != null
+            && this.operations.type == Op.CLOSURE && this.operations.getChild().type == Op.DOT) {
+            if (isSet(this.options, SINGLE_LINE)) {
+                matchStart = con.start;
+                matchEnd = this.match(con, this.operations, con.start, 1, this.options);
+            } else {
+                boolean previousIsEOL = true;
+                for (matchStart = con.start;  matchStart <= limit;  matchStart ++) {
+                    int ch =  target .setIndex(  matchStart ) ;
+                    if (isEOLChar(ch)) {
+                        previousIsEOL = true;
+                    } else {
+                        if (previousIsEOL) {
+                            if (0 <= (matchEnd = this.match(con, this.operations,
+                                                            matchStart, 1, this.options)))
+                                break;
+                        }
+                        previousIsEOL = false;
+                    }
+                }
+            }
+        }
+
+        /*
+         * Optimization against the first character.
+         */
+        else if (this.firstChar != null) {
+            //System.err.println("DEBUG: with firstchar-matching: "+this.firstChar);
+            RangeToken range = this.firstChar;
+            for (matchStart = con.start;  matchStart <= limit;  matchStart ++) {
+                int ch =  target .setIndex(  matchStart ) ;
+                if (REUtil.isHighSurrogate(ch) && matchStart+1 < con.limit) {
+                    ch = REUtil.composeFromSurrogates(ch, target.setIndex(matchStart+1));
+                }
+                if (!range.match(ch)) {
+                    continue;
+                }
+                if (0 <= (matchEnd = this.match(con, this.operations,
+                                                matchStart, 1, this.options))) {
+                    break;
+                }
+            }
+        }
+
+        /*
+         * Straightforward matching.
+         */
+        else {
+            for (matchStart = con.start;  matchStart <= limit;  matchStart ++) {
+                if (0 <= (matchEnd = this. match(con, this.operations, matchStart, 1, this.options)))
+                    break;
+            }
+        }
+
+        if (matchEnd >= 0) {
+            if (con.match != null) {
+                con.match.setBeginning(0, matchStart);
+                con.match.setEnd(0, matchEnd);
+            }
+            con.setInUse(false);
+            return true;
+        } else {
+            con.setInUse(false);
+            return false;
+        }
+    }
+
+    // ================================================================
+
+    /**
+     * A regular expression.
+     * @serial
+     */
+    String regex;
+    /**
+     * @serial
+     */
+    int options;
+
+    /**
+     * The number of parenthesis in the regular expression.
+     * @serial
+     */
+    int nofparen;
+    /**
+     * Internal representation of the regular expression.
+     * @serial
+     */
+    Token tokentree;
+
+    boolean hasBackReferences = false;
+
+    transient int minlength;
+    transient Op operations = null;
+    transient int numberOfClosures;
+    transient Context context = null;
+    transient RangeToken firstChar = null;
+
+    transient String fixedString = null;
+    transient int fixedStringOptions;
+    transient BMPattern fixedStringTable = null;
+    transient boolean fixedStringOnly = false;
+
+    static abstract class ExpressionTarget {
+        abstract char charAt(int index);
+        abstract boolean regionMatches(boolean ignoreCase, int offset, int limit, String part, int partlen);
+        abstract boolean regionMatches(boolean ignoreCase, int offset, int limit, int offset2, int partlen);
+    }
+    
+    static final class StringTarget extends ExpressionTarget {
+        
+        private String target;
+        
+        StringTarget(String target) {
+            this.target = target;
+        }
+        
+        final void resetTarget(String target) {
+            this.target = target;
+        }
+        
+        @Override
+        final char charAt(int index) {
+            return target.charAt(index);
+        }
+        
+        @Override
+        final boolean regionMatches(boolean ignoreCase, int offset, int limit,
+                              String part, int partlen) {
+            if (limit-offset < partlen) {
+                return false;
+            }
+            return (ignoreCase) ? target.regionMatches(true, offset, part, 0, partlen) : target.regionMatches(offset, part, 0, partlen);
+        }
+
+        @Override
+        final boolean regionMatches(boolean ignoreCase, int offset, int limit,
+                                    int offset2, int partlen) {
+            if (limit-offset < partlen) {
+                return false;
+            }
+            return (ignoreCase) ? target.regionMatches(true, offset, target, offset2, partlen)
+                                : target.regionMatches(offset, target, offset2, partlen);
+        }
+    }
+    
+    static final class CharArrayTarget extends ExpressionTarget {
+        
+        char[] target;
+        
+        CharArrayTarget(char[] target) {
+            this.target = target; 
+        }
+
+        final void resetTarget(char[] target) {
+            this.target = target;
+        }
+
+        @Override
+        char charAt(int index) {
+            return target[index];
+        }
+        
+        @Override
+        final boolean regionMatches(boolean ignoreCase, int offset, int limit,
+                String part, int partlen) {
+            if (offset < 0 || limit-offset < partlen)  {
+                return false;
+            }
+            return (ignoreCase) ? regionMatchesIgnoreCase(offset, limit, part, partlen)
+                                : regionMatches(offset, limit, part, partlen);
+        }
+
+        private final boolean regionMatches(int offset, int limit, String part, int partlen) {
+            int i = 0;
+            while (partlen-- > 0) {
+                if (target[offset++] != part.charAt(i++)) {
+                    return false;
+                }
+            }
+            return true;
+        }
+
+        private final boolean regionMatchesIgnoreCase(int offset, int limit, String part, int partlen) {
+            int i = 0;
+            while (partlen-- > 0) {
+                final char ch1 = target[offset++] ;
+                final char ch2 = part.charAt(i++);
+                if (ch1 == ch2) {
+                    continue;
+                }
+                final char uch1 = Character.toUpperCase(ch1);
+                final char uch2 = Character.toUpperCase(ch2);
+                if (uch1 == uch2) {
+                    continue;
+                }
+                if (Character.toLowerCase(uch1) != Character.toLowerCase(uch2)) {
+                    return false;
+                }
+            }
+            return true;
+        }
+
+        @Override
+        final boolean regionMatches(boolean ignoreCase, int offset, int limit, int offset2, int partlen) {
+            if (offset < 0 || limit-offset < partlen) {
+                return false;
+            }
+            return (ignoreCase) ? regionMatchesIgnoreCase(offset, limit, offset2, partlen)
+                                : regionMatches(offset, limit, offset2, partlen);
+        }
+
+        private final boolean regionMatches(int offset, int limit, int offset2, int partlen) {
+            int i = offset2;
+            while (partlen-- > 0) {
+                if ( target [  offset++ ]  !=  target [  i++ ] )
+                    return false;
+            }
+            return true;
+        }
+
+        private final boolean regionMatchesIgnoreCase(int offset, int limit, int offset2, int partlen) {
+            int i = offset2;
+            while (partlen-- > 0) {
+                final char ch1 =  target[offset++] ;
+                final char ch2 =  target[i++] ;
+                if (ch1 == ch2) {
+                    continue;
+                }
+                final char uch1 = Character.toUpperCase(ch1);
+                final char uch2 = Character.toUpperCase(ch2);
+                if (uch1 == uch2) {
+                    continue;
+                }
+                if (Character.toLowerCase(uch1) != Character.toLowerCase(uch2)) {
+                    return false;
+                }
+            }
+            return true;
+        }
+    }
+
+    static final class CharacterIteratorTarget extends ExpressionTarget {
+        CharacterIterator target;
+        
+        CharacterIteratorTarget(CharacterIterator target) {
+            this.target = target; 
+        }
+
+        final void resetTarget(CharacterIterator target) {
+            this.target = target;
+        }
+
+        @Override
+        final char charAt(int index) {
+            return target.setIndex(index);
+        }
+
+        @Override
+        final boolean regionMatches(boolean ignoreCase, int offset, int limit,
+                String part, int partlen) {
+            if (offset < 0 || limit-offset < partlen)  {
+                return false;
+            }
+            return (ignoreCase) ? regionMatchesIgnoreCase(offset, limit, part, partlen)
+                                : regionMatches(offset, limit, part, partlen);
+        }
+        
+        private final boolean regionMatches(int offset, int limit, String part, int partlen) {
+            int i = 0;
+            while (partlen-- > 0) {
+                if (target.setIndex(offset++) != part.charAt(i++)) {
+                    return false;
+                }
+            }
+            return true;
+        }
+        
+        private final boolean regionMatchesIgnoreCase(int offset, int limit, String part, int partlen) {
+            int i = 0;
+            while (partlen-- > 0) {
+                final char ch1 = target.setIndex(offset++) ;
+                final char ch2 = part.charAt(i++);
+                if (ch1 == ch2) {
+                    continue;
+                }
+                final char uch1 = Character.toUpperCase(ch1);
+                final char uch2 = Character.toUpperCase(ch2);
+                if (uch1 == uch2) {
+                    continue;
+                }
+                if (Character.toLowerCase(uch1) != Character.toLowerCase(uch2)) {
+                    return false;
+                }
+            }
+            return true;
+        }
+
+        @Override
+        final boolean regionMatches(boolean ignoreCase, int offset, int limit, int offset2, int partlen) {
+            if (offset < 0 || limit-offset < partlen) {
+                return false;
+            }
+            return (ignoreCase) ? regionMatchesIgnoreCase(offset, limit, offset2, partlen)
+                                : regionMatches(offset, limit, offset2, partlen);
+        }
+
+        private final boolean regionMatches(int offset, int limit, int offset2, int partlen) {
+            int i = offset2;
+            while (partlen-- > 0) {
+                if (target.setIndex(offset++) != target.setIndex(i++)) {
+                    return false;
+                }
+            }
+            return true;
+        }
+
+        private final boolean regionMatchesIgnoreCase(int offset, int limit, int offset2, int partlen) {
+            int i = offset2;
+            while (partlen-- > 0) {
+                final char ch1 = target.setIndex(offset++) ;
+                final char ch2 = target.setIndex(i++) ;
+                if (ch1 == ch2) {
+                    continue;
+                }
+                final char uch1 = Character.toUpperCase(ch1);
+                final char uch2 = Character.toUpperCase(ch2);
+                if (uch1 == uch2) {
+                    continue;
+                }
+                if (Character.toLowerCase(uch1) != Character.toLowerCase(uch2)) {
+                    return false;
+                }
+            }
+            return true;
+        }
+    }
+
+    static final class ClosureContext {
+        
+        int[] offsets = new int[4];
+        int currentIndex = 0;
+        
+        boolean contains(int offset) {
+            for (int i=0; i<currentIndex;++i) {
+                if (offsets[i] == offset) {
+                    return true;
+                }
+            }
+            return false;
+        }
+        
+        void reset() {
+            currentIndex = 0;
+        }
+
+        void addOffset(int offset) {
+            // We do not check for duplicates, caller is responsible for that
+            if (currentIndex == offsets.length) {
+                offsets = expandOffsets();
+            }
+            offsets[currentIndex++] = offset;
+        }
+        
+        private int[] expandOffsets() {
+            final int len = offsets.length;
+            final int newLen = len << 1;
+            int[] newOffsets = new int[newLen];
+            
+            System.arraycopy(offsets, 0, newOffsets, 0, currentIndex);
+            return newOffsets;
+        }
+    }
+    
+    static final class Context {
+        int start;
+        int limit;
+        int length;
+        Match match;
+        boolean inuse = false;
+        ClosureContext[] closureContexts;
+        
+        private StringTarget stringTarget; 
+        private CharArrayTarget charArrayTarget;
+        private CharacterIteratorTarget characterIteratorTarget;
+
+        ExpressionTarget target;
+
+        Context() {
+        }
+
+        private void resetCommon(int nofclosures) {
+            this.length = this.limit-this.start;
+            setInUse(true);
+            this.match = null;
+            if (this.closureContexts == null || this.closureContexts.length != nofclosures) {
+                this.closureContexts = new ClosureContext[nofclosures];
+            }
+            for (int i = 0;  i < nofclosures;  i ++)  {
+                if (this.closureContexts[i] == null) {
+                    this.closureContexts[i] = new ClosureContext();
+                }
+                else {
+                    this.closureContexts[i].reset();
+                }
+            }
+        }
+
+        void reset(CharacterIterator target, int start, int limit, int nofclosures) {
+            if (characterIteratorTarget == null) {
+                characterIteratorTarget = new CharacterIteratorTarget(target);
+            }
+            else {
+                characterIteratorTarget.resetTarget(target);
+            }
+            this.target = characterIteratorTarget;
+            this.start = start;
+            this.limit = limit;
+            this.resetCommon(nofclosures);
+        }
+
+        void reset(String target, int start, int limit, int nofclosures) {
+            if (stringTarget == null) {
+                stringTarget = new StringTarget(target);
+            }
+            else {
+                stringTarget.resetTarget(target);
+            }
+            this.target = stringTarget;
+            this.start = start;
+            this.limit = limit;
+            this.resetCommon(nofclosures);
+        }
+
+        void reset(char[] target, int start, int limit, int nofclosures) {
+            if (charArrayTarget == null) {
+                charArrayTarget = new CharArrayTarget(target);
+            }
+            else {
+                charArrayTarget.resetTarget(target);
+            }
+            this.target = charArrayTarget;
+            this.start = start;
+            this.limit = limit;
+            this.resetCommon(nofclosures);
+        }
+        synchronized void setInUse(boolean inUse) {
+            this.inuse = inUse;
+        }
+    }
+
+    /**
+     * Prepares for matching.  This method is called just before starting matching.
+     */
+    void prepare() {
+        if (Op.COUNT)  Op.nofinstances = 0;
+        this.compile(this.tokentree);
+        /*
+        if  (this.operations.type == Op.CLOSURE && this.operations.getChild().type == Op.DOT) { // .*
+            Op anchor = Op.createAnchor(isSet(this.options, SINGLE_LINE) ? 'A' : '@');
+            anchor.next = this.operations;
+            this.operations = anchor;
+        }
+        */
+        if (Op.COUNT)  System.err.println("DEBUG: The number of operations: "+Op.nofinstances);
+
+        this.minlength = this.tokentree.getMinLength();
+
+        this.firstChar = null;
+        if (!isSet(this.options, PROHIBIT_HEAD_CHARACTER_OPTIMIZATION)
+            && !isSet(this.options, XMLSCHEMA_MODE)) {
+            RangeToken firstChar = Token.createRange();
+            int fresult = this.tokentree.analyzeFirstCharacter(firstChar, this.options);
+            if (fresult == Token.FC_TERMINAL) {
+                firstChar.compactRanges();
+                this.firstChar = firstChar;
+                if (DEBUG)
+                    System.err.println("DEBUG: Use the first character optimization: "+firstChar);
+            }
+        }
+
+        if (this.operations != null
+            && (this.operations.type == Op.STRING || this.operations.type == Op.CHAR)
+            && this.operations.next == null) {
+            if (DEBUG)
+                System.err.print(" *** Only fixed string! *** ");
+            this.fixedStringOnly = true;
+            if (this.operations.type == Op.STRING)
+                this.fixedString = this.operations.getString();
+            else if (this.operations.getData() >= 0x10000) { // Op.CHAR
+                this.fixedString = REUtil.decomposeToSurrogates(this.operations.getData());
+            } else {
+                char[] ac = new char[1];
+                ac[0] = (char)this.operations.getData();
+                this.fixedString = new String(ac);
+            }
+            this.fixedStringOptions = this.options;
+            this.fixedStringTable = new BMPattern(this.fixedString, 256,
+                                                  isSet(this.fixedStringOptions, IGNORE_CASE));
+        } else if (!isSet(this.options, PROHIBIT_FIXED_STRING_OPTIMIZATION)
+                   && !isSet(this.options, XMLSCHEMA_MODE)) {
+            Token.FixedStringContainer container = new Token.FixedStringContainer();
+            this.tokentree.findFixedString(container, this.options);
+            this.fixedString = container.token == null ? null : container.token.getString();
+            this.fixedStringOptions = container.options;
+            if (this.fixedString != null && this.fixedString.length() < 2)
+                this.fixedString = null;
+            // This pattern has a fixed string of which length is more than one.
+            if (this.fixedString != null) {
+                this.fixedStringTable = new BMPattern(this.fixedString, 256,
+                                                      isSet(this.fixedStringOptions, IGNORE_CASE));
+                if (DEBUG) {
+                    System.err.println("DEBUG: The longest fixed string: "+this.fixedString.length()
+                                       +"/" //+this.fixedString
+                                       +"/"+REUtil.createOptionString(this.fixedStringOptions));
+                    System.err.print("String: ");
+                    REUtil.dumpString(this.fixedString);
+                }
+            }
+        }
+    }
+
+    /**
+     * An option.
+     * If you specify this option, <span class="REGEX"><kbd>(</kbd><var>X</var><kbd>)</kbd></span>
+     * captures matched text, and <span class="REGEX"><kbd>(:?</kbd><var>X</var><kbd>)</kbd></span>
+     * does not capture.
+     *
+     * @see #RegularExpression(java.

<TRUNCATED>

[15/24] jena git commit: JENA-1537: Remove dependency on Xerces. Import needed code

Posted by an...@apache.org.
http://git-wip-us.apache.org/repos/asf/jena/blob/c9a7e646/jena-core/src/main/java/org/apache/jena/ext/xerces/impl/xpath/regex/ParserForXMLSchema.java
----------------------------------------------------------------------
diff --git a/jena-core/src/main/java/org/apache/jena/ext/xerces/impl/xpath/regex/ParserForXMLSchema.java b/jena-core/src/main/java/org/apache/jena/ext/xerces/impl/xpath/regex/ParserForXMLSchema.java
new file mode 100644
index 0000000..4161472
--- /dev/null
+++ b/jena-core/src/main/java/org/apache/jena/ext/xerces/impl/xpath/regex/ParserForXMLSchema.java
@@ -0,0 +1,534 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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.jena.ext.xerces.impl.xpath.regex;
+
+import java.util.Hashtable;
+import java.util.Locale;
+
+/**
+ * A regular expression parser for the XML Schema.
+ * 
+ * @xerces.internal
+ *
+ * @author TAMURA Kent &lt;kent@trl.ibm.co.jp&gt;
+ * @version $Id: ParserForXMLSchema.java 831926 2009-11-02 15:38:53Z knoaman $
+ */
+@SuppressWarnings("all")
+class ParserForXMLSchema extends RegexParser {
+
+    public ParserForXMLSchema() {
+        //this.setLocale(Locale.getDefault());
+    }
+    public ParserForXMLSchema(Locale locale) {
+        super(locale);
+    }
+
+    @Override
+    Token processCaret() throws ParseException {
+        this.next();
+        return Token.createChar('^');
+    }
+    @Override
+    Token processDollar() throws ParseException {
+        this.next();
+        return Token.createChar('$');
+     }
+    @Override
+    Token processLookahead() throws ParseException {
+        throw ex("parser.process.1", this.offset);
+    }
+    @Override
+    Token processNegativelookahead() throws ParseException {
+        throw ex("parser.process.1", this.offset);
+    }
+    @Override
+    Token processLookbehind() throws ParseException {
+        throw ex("parser.process.1", this.offset);
+    }
+    @Override
+    Token processNegativelookbehind() throws ParseException {
+        throw ex("parser.process.1", this.offset);
+    }
+    @Override
+    Token processBacksolidus_A() throws ParseException {
+        throw ex("parser.process.1", this.offset);
+    }
+    @Override
+    Token processBacksolidus_Z() throws ParseException {
+        throw ex("parser.process.1", this.offset);
+    }
+    @Override
+    Token processBacksolidus_z() throws ParseException {
+        throw ex("parser.process.1", this.offset);
+    }
+    @Override
+    Token processBacksolidus_b() throws ParseException {
+        throw ex("parser.process.1", this.offset);
+    }
+    @Override
+    Token processBacksolidus_B() throws ParseException {
+        throw ex("parser.process.1", this.offset);
+    }
+    @Override
+    Token processBacksolidus_lt() throws ParseException {
+        throw ex("parser.process.1", this.offset);
+    }
+    @Override
+    Token processBacksolidus_gt() throws ParseException {
+        throw ex("parser.process.1", this.offset);
+    }
+    @Override
+    Token processStar(Token tok) throws ParseException {
+        this.next();
+        return Token.createClosure(tok);
+    }
+    @Override
+    Token processPlus(Token tok) throws ParseException {
+        // X+ -> XX*
+        this.next();
+        return Token.createConcat(tok, Token.createClosure(tok));
+    }
+    @Override
+    Token processQuestion(Token tok) throws ParseException {
+        // X? -> X|
+        this.next();
+        Token par = Token.createUnion();
+        par.addChild(tok);
+        par.addChild(Token.createEmpty());
+        return par;
+    }
+    @Override
+    boolean checkQuestion(int off) {
+        return false;
+    }
+    @Override
+    Token processParen() throws ParseException {
+        this.next();
+        Token tok = Token.createParen(this.parseRegex(), 0);
+        if (this.read() != T_RPAREN)  throw ex("parser.factor.1", this.offset-1);
+        this.next();                            // Skips ')'
+        return tok;
+    }
+    @Override
+    Token processParen2() throws ParseException {
+        throw ex("parser.process.1", this.offset);
+    }
+    @Override
+    Token processCondition() throws ParseException {
+        throw ex("parser.process.1", this.offset);
+    }
+    @Override
+    Token processModifiers() throws ParseException {
+        throw ex("parser.process.1", this.offset);
+    }
+    @Override
+    Token processIndependent() throws ParseException {
+        throw ex("parser.process.1", this.offset);
+    }
+    @Override
+    Token processBacksolidus_c() throws ParseException {
+        this.next();
+        return this.getTokenForShorthand('c');
+    }
+    @Override
+    Token processBacksolidus_C() throws ParseException {
+        this.next();
+        return this.getTokenForShorthand('C');
+    }
+    @Override
+    Token processBacksolidus_i() throws ParseException {
+        this.next();
+        return this.getTokenForShorthand('i');
+    }
+    @Override
+    Token processBacksolidus_I() throws ParseException {
+        this.next();
+        return this.getTokenForShorthand('I');
+    }
+    @Override
+    Token processBacksolidus_g() throws ParseException {
+        throw this.ex("parser.process.1", this.offset-2);
+    }
+    @Override
+    Token processBacksolidus_X() throws ParseException {
+        throw ex("parser.process.1", this.offset-2);
+    }
+    @Override
+    Token processBackreference() throws ParseException {
+        throw ex("parser.process.1", this.offset-4);
+    }
+
+    @Override
+    int processCIinCharacterClass(RangeToken tok, int c) {
+        tok.mergeRanges(this.getTokenForShorthand(c));
+        return -1;
+    }
+
+
+    /**
+     * Parses a character-class-expression, not a character-class-escape.
+     *
+     * c-c-expression   ::= '[' c-group ']'
+     * c-group          ::= positive-c-group | negative-c-group | c-c-subtraction
+     * positive-c-group ::= (c-range | c-c-escape)+
+     * negative-c-group ::= '^' positive-c-group
+     * c-c-subtraction  ::= (positive-c-group | negative-c-group) subtraction
+     * subtraction      ::= '-' c-c-expression
+     * c-range          ::= single-range | from-to-range
+     * single-range     ::= multi-c-escape | category-c-escape | block-c-escape | &lt;any XML char&gt;
+     * cc-normal-c      ::= &lt;any character except [, ], \&gt;
+     * from-to-range    ::= cc-normal-c '-' cc-normal-c
+     *
+     * @param useNrage Ignored.
+     * @return This returns no NrageToken.
+     */
+    @Override
+    protected RangeToken parseCharacterClass(boolean useNrange) throws ParseException {
+        this.setContext(S_INBRACKETS);
+        this.next();                            // '['
+        boolean nrange = false;
+        boolean wasDecoded = false;     		// used to detect if the last - was escaped.
+        RangeToken base = null;
+        RangeToken tok;
+        if (this.read() == T_CHAR && this.chardata == '^') {
+            nrange = true;
+            this.next();                        // '^'
+            base = Token.createRange();
+            base.addRange(0, Token.UTF16_MAX);
+            tok = Token.createRange();
+        } else {
+            tok = Token.createRange();
+        }
+        int type;
+        boolean firstloop = true;
+        while ((type = this.read()) != T_EOF) { // Don't use 'cotinue' for this loop.
+        	
+        	wasDecoded = false;
+            // single-range | from-to-range | subtraction
+            if (type == T_CHAR && this.chardata == ']' && !firstloop) {
+                if (nrange) {
+                    base.subtractRanges(tok);
+                    tok = base;
+                }
+                break;
+            }
+            int c = this.chardata;
+            boolean end = false;
+            if (type == T_BACKSOLIDUS) {
+                switch (c) {
+                  case 'd':  case 'D':
+                  case 'w':  case 'W':
+                  case 's':  case 'S':
+                    tok.mergeRanges(this.getTokenForShorthand(c));
+                    end = true;
+                    break;
+
+                  case 'i':  case 'I':
+                  case 'c':  case 'C':
+                    c = this.processCIinCharacterClass(tok, c);
+                    if (c < 0)  end = true;
+                    break;
+                    
+                  case 'p':
+                  case 'P':
+                    int pstart = this.offset;
+                    RangeToken tok2 = this.processBacksolidus_pP(c);
+                    if (tok2 == null)  throw this.ex("parser.atom.5", pstart);
+                    tok.mergeRanges(tok2);
+                    end = true;
+                    break;
+                   
+                 case '-':
+                 	c = this.decodeEscaped();
+                 	wasDecoded = true;
+                 	break;
+
+                  default:
+                    c = this.decodeEscaped();
+                } // \ + c
+            } // backsolidus
+            else if (type == T_XMLSCHEMA_CC_SUBTRACTION && !firstloop) {
+                                                // Subraction
+                if (nrange) {
+                    base.subtractRanges(tok);
+                    tok = base;
+                }
+                RangeToken range2 = this.parseCharacterClass(false);
+                tok.subtractRanges(range2);
+                if (this.read() != T_CHAR || this.chardata != ']')
+                    throw this.ex("parser.cc.5", this.offset);
+                break;                          // Exit this loop
+            }
+            this.next();
+            if (!end) {                         // if not shorthands...
+                if (type == T_CHAR) {
+                    if (c == '[')  throw this.ex("parser.cc.6", this.offset-2);
+                    if (c == ']')  throw this.ex("parser.cc.7", this.offset-2);
+                    if (c == '-' && this.chardata != ']' && !firstloop)  throw this.ex("parser.cc.8", this.offset-2);	// if regex = '[-]' then invalid
+                }
+                if (this.read() != T_CHAR || this.chardata != '-' || c == '-' && firstloop) { // Here is no '-'.
+                    if (!this.isSet(RegularExpression.IGNORE_CASE) || c > 0xffff) {
+                        tok.addRange(c, c);
+                    }
+                    else {
+                        addCaseInsensitiveChar(tok, c);
+                    }
+                } else {                        // Found '-'
+                                                // Is this '-' is a from-to token??
+                    this.next(); // Skips '-'
+                    if ((type = this.read()) == T_EOF)  throw this.ex("parser.cc.2", this.offset);
+                                                // c '-' ']' -> '-' is a single-range.
+                    if(type == T_CHAR && this.chardata == ']') {				// if - is at the last position of the group
+                        if (!this.isSet(RegularExpression.IGNORE_CASE) || c > 0xffff) {
+                    	    tok.addRange(c, c);
+                        }
+                        else {
+                            addCaseInsensitiveChar(tok, c);
+                        }
+                    	tok.addRange('-', '-');
+                    }
+                    else if (type == T_XMLSCHEMA_CC_SUBTRACTION) {
+                        throw this.ex("parser.cc.8", this.offset-1);
+                    } else {
+                    	
+                        int rangeend = this.chardata;
+                        if (type == T_CHAR) {
+                            if (rangeend == '[')  throw this.ex("parser.cc.6", this.offset-1);
+                            if (rangeend == ']')  throw this.ex("parser.cc.7", this.offset-1);
+                            if (rangeend == '-')  throw this.ex("parser.cc.8", this.offset-2);
+                        }
+                        else if (type == T_BACKSOLIDUS)
+                            rangeend = this.decodeEscaped();
+                        this.next();
+
+                        if (c > rangeend)  throw this.ex("parser.ope.3", this.offset-1);
+                        if (!this.isSet(RegularExpression.IGNORE_CASE) ||
+                                (c > 0xffff && rangeend > 0xffff)) {
+                            tok.addRange(c, rangeend);
+                        }
+                        else {
+                            addCaseInsensitiveCharRange(tok, c, rangeend);
+                        }
+                    }
+                }
+            }
+            firstloop = false;
+        }
+        if (this.read() == T_EOF)
+            throw this.ex("parser.cc.2", this.offset);
+        tok.sortRanges();
+        tok.compactRanges();
+        //tok.dumpRanges();
+        this.setContext(S_NORMAL);
+        this.next();                    // Skips ']'
+
+        return tok;
+    }
+
+    @Override
+    protected RangeToken parseSetOperations() throws ParseException {
+        throw this.ex("parser.process.1", this.offset);
+    }
+ 
+    @Override
+    Token getTokenForShorthand(int ch) {
+        switch (ch) {
+          case 'd':
+            return ParserForXMLSchema.getRange("xml:isDigit", true);
+          case 'D':
+            return ParserForXMLSchema.getRange("xml:isDigit", false);
+          case 'w':
+            return ParserForXMLSchema.getRange("xml:isWord", true);
+          case 'W':
+            return ParserForXMLSchema.getRange("xml:isWord", false);
+          case 's':
+            return ParserForXMLSchema.getRange("xml:isSpace", true);
+          case 'S':
+            return ParserForXMLSchema.getRange("xml:isSpace", false);
+          case 'c':
+            return ParserForXMLSchema.getRange("xml:isNameChar", true);
+          case 'C':
+            return ParserForXMLSchema.getRange("xml:isNameChar", false);
+          case 'i':
+            return ParserForXMLSchema.getRange("xml:isInitialNameChar", true);
+          case 'I':
+            return ParserForXMLSchema.getRange("xml:isInitialNameChar", false);
+          default:
+            throw new RuntimeException("Internal Error: shorthands: \\u"+Integer.toString(ch, 16));
+        }
+    }
+    @Override
+    int decodeEscaped() throws ParseException {
+        if (this.read() != T_BACKSOLIDUS)  throw ex("parser.next.1", this.offset-1);
+        int c = this.chardata;
+        switch (c) {
+          case 'n':  c = '\n';  break; // LINE FEED U+000A
+          case 'r':  c = '\r';  break; // CRRIAGE RETURN U+000D
+          case 't':  c = '\t';  break; // HORIZONTAL TABULATION U+0009
+          case '\\':
+          case '|':
+          case '.':
+          case '^':
+          case '-':
+          case '?':
+          case '*':
+          case '+':
+          case '{':
+          case '}':
+          case '(':
+          case ')':
+          case '[':
+          case ']':
+            break; // return actucal char
+          default:
+            throw ex("parser.process.1", this.offset-2);
+        }
+        return c;
+    }
+
+    static private Hashtable ranges = null;
+    static private Hashtable ranges2 = null;
+    static synchronized protected RangeToken getRange(String name, boolean positive) {
+        if (ranges == null) {
+            ranges = new Hashtable();
+            ranges2 = new Hashtable();
+
+            Token tok = Token.createRange();
+            setupRange(tok, SPACES);
+            ranges.put("xml:isSpace", tok);
+            ranges2.put("xml:isSpace", Token.complementRanges(tok));
+
+            tok = Token.createRange();
+            setupRange(tok, DIGITS);
+            ranges.put("xml:isDigit", tok);
+            ranges2.put("xml:isDigit", Token.complementRanges(tok));
+
+            tok = Token.createRange();
+            setupRange(tok, DIGITS);
+            ranges.put("xml:isDigit", tok);
+            ranges2.put("xml:isDigit", Token.complementRanges(tok));
+
+            tok = Token.createRange();
+            setupRange(tok, LETTERS);
+            tok.mergeRanges((Token)ranges.get("xml:isDigit"));
+            ranges.put("xml:isWord", tok);
+            ranges2.put("xml:isWord", Token.complementRanges(tok));
+
+            tok = Token.createRange();
+            setupRange(tok, NAMECHARS);
+            ranges.put("xml:isNameChar", tok);
+            ranges2.put("xml:isNameChar", Token.complementRanges(tok));
+
+            tok = Token.createRange();
+            setupRange(tok, LETTERS);
+            tok.addRange('_', '_');
+            tok.addRange(':', ':');
+            ranges.put("xml:isInitialNameChar", tok);
+            ranges2.put("xml:isInitialNameChar", Token.complementRanges(tok));
+        }
+        RangeToken tok = positive ? (RangeToken)ranges.get(name)
+            : (RangeToken)ranges2.get(name);
+        return tok;
+    }
+
+    static void setupRange(Token range, String src) {
+        int len = src.length();
+        for (int i = 0;  i < len;  i += 2)
+            range.addRange(src.charAt(i), src.charAt(i+1));
+    }
+
+    private static final String SPACES = "\t\n\r\r  ";
+    private static final String NAMECHARS =
+        "\u002d\u002e\u0030\u003a\u0041\u005a\u005f\u005f\u0061\u007a\u00b7\u00b7\u00c0\u00d6"
+        +"\u00d8\u00f6\u00f8\u0131\u0134\u013e\u0141\u0148\u014a\u017e\u0180\u01c3\u01cd\u01f0"
+        +"\u01f4\u01f5\u01fa\u0217\u0250\u02a8\u02bb\u02c1\u02d0\u02d1\u0300\u0345\u0360\u0361"
+        +"\u0386\u038a\u038c\u038c\u038e\u03a1\u03a3\u03ce\u03d0\u03d6\u03da\u03da\u03dc\u03dc"
+        +"\u03de\u03de\u03e0\u03e0\u03e2\u03f3\u0401\u040c\u040e\u044f\u0451\u045c\u045e\u0481"
+        +"\u0483\u0486\u0490\u04c4\u04c7\u04c8\u04cb\u04cc\u04d0\u04eb\u04ee\u04f5\u04f8\u04f9"
+        +"\u0531\u0556\u0559\u0559\u0561\u0586\u0591\u05a1\u05a3\u05b9\u05bb\u05bd\u05bf\u05bf"
+        +"\u05c1\u05c2\u05c4\u05c4\u05d0\u05ea\u05f0\u05f2\u0621\u063a\u0640\u0652\u0660\u0669"
+        +"\u0670\u06b7\u06ba\u06be\u06c0\u06ce\u06d0\u06d3\u06d5\u06e8\u06ea\u06ed\u06f0\u06f9"
+        +"\u0901\u0903\u0905\u0939\u093c\u094d\u0951\u0954\u0958\u0963\u0966\u096f\u0981\u0983"
+        +"\u0985\u098c\u098f\u0990\u0993\u09a8\u09aa\u09b0\u09b2\u09b2\u09b6\u09b9\u09bc\u09bc"
+        +"\u09be\u09c4\u09c7\u09c8\u09cb\u09cd\u09d7\u09d7\u09dc\u09dd\u09df\u09e3\u09e6\u09f1"
+        +"\u0a02\u0a02\u0a05\u0a0a\u0a0f\u0a10\u0a13\u0a28\u0a2a\u0a30\u0a32\u0a33\u0a35\u0a36"
+        +"\u0a38\u0a39\u0a3c\u0a3c\u0a3e\u0a42\u0a47\u0a48\u0a4b\u0a4d\u0a59\u0a5c\u0a5e\u0a5e"
+        +"\u0a66\u0a74\u0a81\u0a83\u0a85\u0a8b\u0a8d\u0a8d\u0a8f\u0a91\u0a93\u0aa8\u0aaa\u0ab0"
+        +"\u0ab2\u0ab3\u0ab5\u0ab9\u0abc\u0ac5\u0ac7\u0ac9\u0acb\u0acd\u0ae0\u0ae0\u0ae6\u0aef"
+        +"\u0b01\u0b03\u0b05\u0b0c\u0b0f\u0b10\u0b13\u0b28\u0b2a\u0b30\u0b32\u0b33\u0b36\u0b39"
+        +"\u0b3c\u0b43\u0b47\u0b48\u0b4b\u0b4d\u0b56\u0b57\u0b5c\u0b5d\u0b5f\u0b61\u0b66\u0b6f"
+        +"\u0b82\u0b83\u0b85\u0b8a\u0b8e\u0b90\u0b92\u0b95\u0b99\u0b9a\u0b9c\u0b9c\u0b9e\u0b9f"
+        +"\u0ba3\u0ba4\u0ba8\u0baa\u0bae\u0bb5\u0bb7\u0bb9\u0bbe\u0bc2\u0bc6\u0bc8\u0bca\u0bcd"
+        +"\u0bd7\u0bd7\u0be7\u0bef\u0c01\u0c03\u0c05\u0c0c\u0c0e\u0c10\u0c12\u0c28\u0c2a\u0c33"
+        +"\u0c35\u0c39\u0c3e\u0c44\u0c46\u0c48\u0c4a\u0c4d\u0c55\u0c56\u0c60\u0c61\u0c66\u0c6f"
+        +"\u0c82\u0c83\u0c85\u0c8c\u0c8e\u0c90\u0c92\u0ca8\u0caa\u0cb3\u0cb5\u0cb9\u0cbe\u0cc4"
+        +"\u0cc6\u0cc8\u0cca\u0ccd\u0cd5\u0cd6\u0cde\u0cde\u0ce0\u0ce1\u0ce6\u0cef\u0d02\u0d03"
+        +"\u0d05\u0d0c\u0d0e\u0d10\u0d12\u0d28\u0d2a\u0d39\u0d3e\u0d43\u0d46\u0d48\u0d4a\u0d4d"
+        +"\u0d57\u0d57\u0d60\u0d61\u0d66\u0d6f\u0e01\u0e2e\u0e30\u0e3a\u0e40\u0e4e\u0e50\u0e59"
+        +"\u0e81\u0e82\u0e84\u0e84\u0e87\u0e88\u0e8a\u0e8a\u0e8d\u0e8d\u0e94\u0e97\u0e99\u0e9f"
+        +"\u0ea1\u0ea3\u0ea5\u0ea5\u0ea7\u0ea7\u0eaa\u0eab\u0ead\u0eae\u0eb0\u0eb9\u0ebb\u0ebd"
+        +"\u0ec0\u0ec4\u0ec6\u0ec6\u0ec8\u0ecd\u0ed0\u0ed9\u0f18\u0f19\u0f20\u0f29\u0f35\u0f35"
+        +"\u0f37\u0f37\u0f39\u0f39\u0f3e\u0f47\u0f49\u0f69\u0f71\u0f84\u0f86\u0f8b\u0f90\u0f95"
+        +"\u0f97\u0f97\u0f99\u0fad\u0fb1\u0fb7\u0fb9\u0fb9\u10a0\u10c5\u10d0\u10f6\u1100\u1100"
+        +"\u1102\u1103\u1105\u1107\u1109\u1109\u110b\u110c\u110e\u1112\u113c\u113c\u113e\u113e"
+        +"\u1140\u1140\u114c\u114c\u114e\u114e\u1150\u1150\u1154\u1155\u1159\u1159\u115f\u1161"
+        +"\u1163\u1163\u1165\u1165\u1167\u1167\u1169\u1169\u116d\u116e\u1172\u1173\u1175\u1175"
+        +"\u119e\u119e\u11a8\u11a8\u11ab\u11ab\u11ae\u11af\u11b7\u11b8\u11ba\u11ba\u11bc\u11c2"
+        +"\u11eb\u11eb\u11f0\u11f0\u11f9\u11f9\u1e00\u1e9b\u1ea0\u1ef9\u1f00\u1f15\u1f18\u1f1d"
+        +"\u1f20\u1f45\u1f48\u1f4d\u1f50\u1f57\u1f59\u1f59\u1f5b\u1f5b\u1f5d\u1f5d\u1f5f\u1f7d"
+        +"\u1f80\u1fb4\u1fb6\u1fbc\u1fbe\u1fbe\u1fc2\u1fc4\u1fc6\u1fcc\u1fd0\u1fd3\u1fd6\u1fdb"
+        +"\u1fe0\u1fec\u1ff2\u1ff4\u1ff6\u1ffc\u20d0\u20dc\u20e1\u20e1\u2126\u2126\u212a\u212b"
+        +"\u212e\u212e\u2180\u2182\u3005\u3005\u3007\u3007\u3021\u302f\u3031\u3035\u3041\u3094"
+        +"\u3099\u309a\u309d\u309e\u30a1\u30fa\u30fc\u30fe\u3105\u312c\u4e00\u9fa5\uac00\ud7a3"
+        +"";
+    private static final String LETTERS =
+        "\u0041\u005a\u0061\u007a\u00c0\u00d6\u00d8\u00f6\u00f8\u0131\u0134\u013e\u0141\u0148"
+        +"\u014a\u017e\u0180\u01c3\u01cd\u01f0\u01f4\u01f5\u01fa\u0217\u0250\u02a8\u02bb\u02c1"
+        +"\u0386\u0386\u0388\u038a\u038c\u038c\u038e\u03a1\u03a3\u03ce\u03d0\u03d6\u03da\u03da"
+        +"\u03dc\u03dc\u03de\u03de\u03e0\u03e0\u03e2\u03f3\u0401\u040c\u040e\u044f\u0451\u045c"
+        +"\u045e\u0481\u0490\u04c4\u04c7\u04c8\u04cb\u04cc\u04d0\u04eb\u04ee\u04f5\u04f8\u04f9"
+        +"\u0531\u0556\u0559\u0559\u0561\u0586\u05d0\u05ea\u05f0\u05f2\u0621\u063a\u0641\u064a"
+        +"\u0671\u06b7\u06ba\u06be\u06c0\u06ce\u06d0\u06d3\u06d5\u06d5\u06e5\u06e6\u0905\u0939"
+        +"\u093d\u093d\u0958\u0961\u0985\u098c\u098f\u0990\u0993\u09a8\u09aa\u09b0\u09b2\u09b2"
+        +"\u09b6\u09b9\u09dc\u09dd\u09df\u09e1\u09f0\u09f1\u0a05\u0a0a\u0a0f\u0a10\u0a13\u0a28"
+        +"\u0a2a\u0a30\u0a32\u0a33\u0a35\u0a36\u0a38\u0a39\u0a59\u0a5c\u0a5e\u0a5e\u0a72\u0a74"
+        +"\u0a85\u0a8b\u0a8d\u0a8d\u0a8f\u0a91\u0a93\u0aa8\u0aaa\u0ab0\u0ab2\u0ab3\u0ab5\u0ab9"
+        +"\u0abd\u0abd\u0ae0\u0ae0\u0b05\u0b0c\u0b0f\u0b10\u0b13\u0b28\u0b2a\u0b30\u0b32\u0b33"
+        +"\u0b36\u0b39\u0b3d\u0b3d\u0b5c\u0b5d\u0b5f\u0b61\u0b85\u0b8a\u0b8e\u0b90\u0b92\u0b95"
+        +"\u0b99\u0b9a\u0b9c\u0b9c\u0b9e\u0b9f\u0ba3\u0ba4\u0ba8\u0baa\u0bae\u0bb5\u0bb7\u0bb9"
+        +"\u0c05\u0c0c\u0c0e\u0c10\u0c12\u0c28\u0c2a\u0c33\u0c35\u0c39\u0c60\u0c61\u0c85\u0c8c"
+        +"\u0c8e\u0c90\u0c92\u0ca8\u0caa\u0cb3\u0cb5\u0cb9\u0cde\u0cde\u0ce0\u0ce1\u0d05\u0d0c"
+        +"\u0d0e\u0d10\u0d12\u0d28\u0d2a\u0d39\u0d60\u0d61\u0e01\u0e2e\u0e30\u0e30\u0e32\u0e33"
+        +"\u0e40\u0e45\u0e81\u0e82\u0e84\u0e84\u0e87\u0e88\u0e8a\u0e8a\u0e8d\u0e8d\u0e94\u0e97"
+        +"\u0e99\u0e9f\u0ea1\u0ea3\u0ea5\u0ea5\u0ea7\u0ea7\u0eaa\u0eab\u0ead\u0eae\u0eb0\u0eb0"
+        +"\u0eb2\u0eb3\u0ebd\u0ebd\u0ec0\u0ec4\u0f40\u0f47\u0f49\u0f69\u10a0\u10c5\u10d0\u10f6"
+        +"\u1100\u1100\u1102\u1103\u1105\u1107\u1109\u1109\u110b\u110c\u110e\u1112\u113c\u113c"
+        +"\u113e\u113e\u1140\u1140\u114c\u114c\u114e\u114e\u1150\u1150\u1154\u1155\u1159\u1159"
+        +"\u115f\u1161\u1163\u1163\u1165\u1165\u1167\u1167\u1169\u1169\u116d\u116e\u1172\u1173"
+        +"\u1175\u1175\u119e\u119e\u11a8\u11a8\u11ab\u11ab\u11ae\u11af\u11b7\u11b8\u11ba\u11ba"
+        +"\u11bc\u11c2\u11eb\u11eb\u11f0\u11f0\u11f9\u11f9\u1e00\u1e9b\u1ea0\u1ef9\u1f00\u1f15"
+        +"\u1f18\u1f1d\u1f20\u1f45\u1f48\u1f4d\u1f50\u1f57\u1f59\u1f59\u1f5b\u1f5b\u1f5d\u1f5d"
+        +"\u1f5f\u1f7d\u1f80\u1fb4\u1fb6\u1fbc\u1fbe\u1fbe\u1fc2\u1fc4\u1fc6\u1fcc\u1fd0\u1fd3"
+        +"\u1fd6\u1fdb\u1fe0\u1fec\u1ff2\u1ff4\u1ff6\u1ffc\u2126\u2126\u212a\u212b\u212e\u212e"
+        +"\u2180\u2182\u3007\u3007\u3021\u3029\u3041\u3094\u30a1\u30fa\u3105\u312c\u4e00\u9fa5"
+        +"\uac00\ud7a3";
+    private static final String DIGITS =
+        "\u0030\u0039\u0660\u0669\u06F0\u06F9\u0966\u096F\u09E6\u09EF\u0A66\u0A6F\u0AE6\u0AEF"
+        +"\u0B66\u0B6F\u0BE7\u0BEF\u0C66\u0C6F\u0CE6\u0CEF\u0D66\u0D6F\u0E50\u0E59\u0ED0\u0ED9"
+        +"\u0F20\u0F29";
+}

http://git-wip-us.apache.org/repos/asf/jena/blob/c9a7e646/jena-core/src/main/java/org/apache/jena/ext/xerces/impl/xpath/regex/REUtil.java
----------------------------------------------------------------------
diff --git a/jena-core/src/main/java/org/apache/jena/ext/xerces/impl/xpath/regex/REUtil.java b/jena-core/src/main/java/org/apache/jena/ext/xerces/impl/xpath/regex/REUtil.java
new file mode 100644
index 0000000..88dcf11
--- /dev/null
+++ b/jena-core/src/main/java/org/apache/jena/ext/xerces/impl/xpath/regex/REUtil.java
@@ -0,0 +1,363 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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.jena.ext.xerces.impl.xpath.regex;
+
+import java.text.CharacterIterator;
+
+/**
+ * @xerces.internal
+ * 
+ * @version $Id: REUtil.java 828015 2009-10-21 13:56:13Z knoaman $
+ */
+public final class REUtil {
+    private REUtil() {
+    }
+
+    static final int composeFromSurrogates(int high, int low) {
+        return 0x10000 + ((high-0xd800)<<10) + low-0xdc00;
+    }
+
+    static final boolean isLowSurrogate(int ch) {
+        return (ch & 0xfc00) == 0xdc00;
+    }
+
+    static final boolean isHighSurrogate(int ch) {
+        return (ch & 0xfc00) == 0xd800;
+    }
+
+    static final String decomposeToSurrogates(int ch) {
+        char[] chs = new char[2];
+        ch -= 0x10000;
+        chs[0] = (char)((ch>>10)+0xd800);
+        chs[1] = (char)((ch&0x3ff)+0xdc00);
+        return new String(chs);
+    }
+
+    static final String substring(CharacterIterator iterator, int begin, int end) {
+        char[] src = new char[end-begin];
+        for (int i = 0;  i < src.length;  i ++)
+            src[i] = iterator.setIndex(i+begin);
+        return new String(src);
+    }
+
+    // ================================================================
+
+    static final int getOptionValue(int ch) {
+        int ret = 0;
+        switch (ch) {
+          case 'i':
+            ret = RegularExpression.IGNORE_CASE;
+            break;
+          case 'm':
+            ret = RegularExpression.MULTIPLE_LINES;
+            break;
+          case 's':
+            ret = RegularExpression.SINGLE_LINE;
+            break;
+          case 'x':
+            ret = RegularExpression.EXTENDED_COMMENT;
+            break;
+          case 'u':
+            ret = RegularExpression.USE_UNICODE_CATEGORY;
+            break;
+          case 'w':
+            ret = RegularExpression.UNICODE_WORD_BOUNDARY;
+            break;
+          case 'F':
+            ret = RegularExpression.PROHIBIT_FIXED_STRING_OPTIMIZATION;
+            break;
+          case 'H':
+            ret = RegularExpression.PROHIBIT_HEAD_CHARACTER_OPTIMIZATION;
+            break;
+          case 'X':
+            ret = RegularExpression.XMLSCHEMA_MODE;
+            break;
+          case ',':
+            ret = RegularExpression.SPECIAL_COMMA;
+            break;
+          default:
+        }
+        return ret;
+    }
+
+    static final int parseOptions(String opts) throws ParseException {
+        if (opts == null)  return 0;
+        int options = 0;
+        for (int i = 0;  i < opts.length();  i ++) {
+            int v = getOptionValue(opts.charAt(i));
+            if (v == 0)
+                throw new ParseException("Unknown Option: "+opts.substring(i), -1);
+            options |= v;
+        }
+        return options;
+    }
+
+    static final String createOptionString(int options) {
+        StringBuffer sb = new StringBuffer(9);
+        if ((options & RegularExpression.PROHIBIT_FIXED_STRING_OPTIMIZATION) != 0)
+            sb.append('F');
+        if ((options & RegularExpression.PROHIBIT_HEAD_CHARACTER_OPTIMIZATION) != 0)
+            sb.append('H');
+        if ((options & RegularExpression.XMLSCHEMA_MODE) != 0)
+            sb.append('X');
+        if ((options & RegularExpression.IGNORE_CASE) != 0)
+            sb.append('i');
+        if ((options & RegularExpression.MULTIPLE_LINES) != 0)
+            sb.append('m');
+        if ((options & RegularExpression.SINGLE_LINE) != 0)
+            sb.append('s');
+        if ((options & RegularExpression.USE_UNICODE_CATEGORY) != 0)
+            sb.append('u');
+        if ((options & RegularExpression.UNICODE_WORD_BOUNDARY) != 0)
+            sb.append('w');
+        if ((options & RegularExpression.EXTENDED_COMMENT) != 0)
+            sb.append('x');
+        if ((options & RegularExpression.SPECIAL_COMMA) != 0)
+            sb.append(',');
+        return sb.toString().intern();
+    }
+
+    // ================================================================
+
+    static String stripExtendedComment(String regex) {
+        int len = regex.length();
+        StringBuffer buffer = new StringBuffer(len);
+        int offset = 0;
+        int charClass = 0;
+        while (offset < len) {
+            int ch = regex.charAt(offset++);
+                                                // Skips a white space.
+            if (ch == '\t' || ch == '\n' || ch == '\f' || ch == '\r' || ch == ' ') {
+                // if we are inside a character class, we keep the white space
+                if (charClass > 0) {
+                    buffer.append((char)ch);
+                }
+                continue;
+            }
+
+            if (ch == '#') {                    // Skips chracters between '#' and a line end.
+                while (offset < len) {
+                    ch = regex.charAt(offset++);
+                    if (ch == '\r' || ch == '\n')
+                        break;
+                }
+                continue;
+            }
+
+            int next;                           // Strips an escaped white space.
+            if (ch == '\\' && offset < len) {
+                if ((next = regex.charAt(offset)) == '#'
+                    || next == '\t' || next == '\n' || next == '\f'
+                    || next == '\r' || next == ' ') {
+                    buffer.append((char)next);
+                    offset ++;
+                } else {                        // Other escaped character.
+                    buffer.append('\\');
+                    buffer.append((char)next);
+                    offset ++;
+                }
+            }
+            else if (ch == '[') {
+                charClass++;
+                buffer.append((char)ch);
+                if (offset < len) {
+                    next = regex.charAt(offset);
+                    if (next == '[' || next ==']') {
+                        buffer.append((char)next);
+                        offset ++;
+                    }
+                    else if (next == '^' && offset + 1 < len) {
+                        next = regex.charAt(offset + 1);
+                        if (next == '[' || next ==']') {
+                            buffer.append('^');
+                            buffer.append((char)next);
+                            offset += 2;
+                        }
+                    }
+                }
+            }
+            else {
+                if (charClass > 0 && ch == ']') {
+                    --charClass;
+                }
+                buffer.append((char)ch);
+            }
+        }
+        return buffer.toString();
+    }
+
+    // ================================================================
+
+    /**
+     * Sample entry.
+     * <div>Usage: <KBD>org.apache.jena.ext.xerces.utils.regex.REUtil &lt;regex&gt; &lt;string&gt;</KBD></div>
+     */
+    public static void main(String[] argv) {
+        String pattern = null;
+        try {
+            String options = "";
+            String target = null;
+            if( argv.length == 0 ) {
+                System.out.println( "Error:Usage: java REUtil -i|-m|-s|-u|-w|-X regularExpression String" );
+                System.exit( 0 );
+            }
+            for (int i = 0;  i < argv.length;  i ++) {
+                if (argv[i].length() == 0 || argv[i].charAt(0) != '-') {
+                    if (pattern == null)
+                        pattern = argv[i];
+                    else if (target == null)
+                        target = argv[i];
+                    else
+                        System.err.println("Unnecessary: "+argv[i]);
+                } else if (argv[i].equals("-i")) {
+                    options += "i";
+                } else if (argv[i].equals("-m")) {
+                    options += "m";
+                } else if (argv[i].equals("-s")) {
+                    options += "s";
+                } else if (argv[i].equals("-u")) {
+                    options += "u";
+                } else if (argv[i].equals("-w")) {
+                    options += "w";
+                } else if (argv[i].equals("-X")) {
+                    options += "X";
+                } else {
+                    System.err.println("Unknown option: "+argv[i]);
+                }
+            }
+            RegularExpression reg = new RegularExpression(pattern, options);
+            System.out.println("RegularExpression: "+reg);
+            Match match = new Match();
+            reg.matches(target, match);
+            for (int i = 0;  i < match.getNumberOfGroups();  i ++) {
+                if (i == 0 )  System.out.print("Matched range for the whole pattern: ");
+                else System.out.print("["+i+"]: ");
+                if (match.getBeginning(i) < 0)
+                    System.out.println("-1");
+                else {
+                    System.out.print(match.getBeginning(i)+", "+match.getEnd(i)+", ");
+                    System.out.println("\""+match.getCapturedText(i)+"\"");
+                }
+            }
+        } catch (ParseException pe) {
+            if (pattern == null) {
+                pe.printStackTrace();
+            } else {
+                System.err.println("org.apache.jena.ext.xerces.utils.regex.ParseException: "+pe.getMessage());
+                String indent = "        ";
+                System.err.println(indent+pattern);
+                int loc = pe.getLocation();
+                if (loc >= 0) {
+                    System.err.print(indent);
+                    for (int i = 0;  i < loc;  i ++)  System.err.print("-");
+                    System.err.println("^");
+                }
+            }
+        } catch (Exception e) {
+            e.printStackTrace();
+        }
+    }
+
+    static final int CACHESIZE = 20;
+    static final RegularExpression[] regexCache = new RegularExpression[CACHESIZE];
+    /**
+     * Creates a RegularExpression instance.
+     * This method caches created instances.
+     *
+     * @see RegularExpression#RegularExpression(java.lang.String, java.lang.String)
+     */
+    public static RegularExpression createRegex(String pattern, String options)
+        throws ParseException {
+        RegularExpression re = null;
+        int intOptions = REUtil.parseOptions(options);
+        synchronized (REUtil.regexCache) {
+            int i;
+            for (i = 0;  i < REUtil.CACHESIZE;  i ++) {
+                RegularExpression cached = REUtil.regexCache[i];
+                if (cached == null) {
+                    i = -1;
+                    break;
+                }
+                if (cached.equals(pattern, intOptions)) {
+                    re = cached;
+                    break;
+                }
+            }
+            if (re != null) {
+                if (i != 0) {
+                    System.arraycopy(REUtil.regexCache, 0, REUtil.regexCache, 1, i);
+                    REUtil.regexCache[0] = re;
+                }
+            } else {
+                re = new RegularExpression(pattern, options);
+                System.arraycopy(REUtil.regexCache, 0, REUtil.regexCache, 1, REUtil.CACHESIZE-1);
+                REUtil.regexCache[0] = re;
+            }
+        }
+        return re;
+    }
+
+    /**
+     *
+     * @see RegularExpression#matches(java.lang.String)
+     */
+    public static boolean matches(String regex, String target) throws ParseException {
+        return REUtil.createRegex(regex, null).matches(target);
+    }
+
+    /**
+     *
+     * @see RegularExpression#matches(java.lang.String)
+     */
+    public static boolean matches(String regex, String options, String target) throws ParseException {
+        return REUtil.createRegex(regex, options).matches(target);
+    }
+
+    // ================================================================
+
+    /**
+     *
+     */
+    public static String quoteMeta(String literal) {
+        int len = literal.length();
+        StringBuffer buffer = null;
+        for (int i = 0;  i < len;  i ++) {
+            int ch = literal.charAt(i);
+            if (".*+?{[()|\\^$".indexOf(ch) >= 0) {
+                if (buffer == null) {
+                    buffer = new StringBuffer(i+(len-i)*2);
+                    if (i > 0)  buffer.append(literal.substring(0, i));
+                }
+                buffer.append('\\');
+                buffer.append((char)ch);
+            } else if (buffer != null)
+                buffer.append((char)ch);
+        }
+        return buffer != null ? buffer.toString() : literal;
+    }
+
+    // ================================================================
+
+    static void dumpString(String v) {
+        for (int i = 0;  i < v.length();  i ++) {
+            System.out.print(Integer.toHexString(v.charAt(i)));
+            System.out.print(" ");
+        }
+        System.out.println();
+    }
+}

http://git-wip-us.apache.org/repos/asf/jena/blob/c9a7e646/jena-core/src/main/java/org/apache/jena/ext/xerces/impl/xpath/regex/RangeToken.java
----------------------------------------------------------------------
diff --git a/jena-core/src/main/java/org/apache/jena/ext/xerces/impl/xpath/regex/RangeToken.java b/jena-core/src/main/java/org/apache/jena/ext/xerces/impl/xpath/regex/RangeToken.java
new file mode 100644
index 0000000..7d3e0da
--- /dev/null
+++ b/jena-core/src/main/java/org/apache/jena/ext/xerces/impl/xpath/regex/RangeToken.java
@@ -0,0 +1,631 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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.jena.ext.xerces.impl.xpath.regex;
+
+/**
+ * This class represents a character class such as [a-z] or a period.
+ * 
+ * @xerces.internal
+ *
+ * @version $Id: RangeToken.java 965250 2010-07-18 16:04:58Z mrglavas $
+ */
+final class RangeToken extends Token implements java.io.Serializable {
+
+    private static final long serialVersionUID = -553983121197679934L;
+    
+    int[] ranges;
+    boolean sorted;
+    boolean compacted;
+    RangeToken icaseCache = null;
+    int[] map = null;
+    int nonMapIndex;
+
+    RangeToken(int type) {
+        super(type);
+        this.setSorted(false);
+    }
+
+                                                // for RANGE or NRANGE
+    @Override
+    protected void addRange(int start, int end) {
+        this.icaseCache = null;
+        //System.err.println("Token#addRange(): "+start+" "+end);
+        int r1, r2;
+        if (start <= end) {
+            r1 = start;
+            r2 = end;
+        } else {
+            r1 = end;
+            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;
+                return;
+            }
+            int[] temp = new int[pos+2];
+            System.arraycopy(this.ranges, 0, temp, 0, pos);
+            this.ranges = temp;
+            if (this.ranges[pos-1] >= r1)
+                this.setSorted(false);
+            this.ranges[pos++] = r1;
+            this.ranges[pos] = r2;
+            if (!this.sorted)
+                this.sortRanges();
+        }
+    }
+
+    private final boolean isSorted() {
+        return this.sorted;
+    }
+    private final void setSorted(boolean sort) {
+        this.sorted = sort;
+        if (!sort)  this.compacted = false;
+    }
+    private final boolean isCompacted() {
+        return this.compacted;
+    }
+    private final void setCompacted() {
+        this.compacted = true;
+    }
+
+    @Override
+    protected void sortRanges() {
+        if (this.isSorted())
+            return;
+        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]) {
+                    int tmp;
+                    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;
+                }
+            }
+        }
+        this.setSorted(true);
+    }
+
+    /**
+     * this.ranges is sorted.
+     */
+    @Override
+    protected void compactRanges() {
+        boolean DEBUG = false;
+        if (this.ranges == null || this.ranges.length <= 2)
+            return;
+        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
+                target += 2;
+            int baseend = this.ranges[base+1];
+            while (target < this.ranges.length) {
+                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];
+                    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]
+                                           +"]");
+                    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];
+                    target += 2;
+                } else {
+                    throw new RuntimeException("Token#compactRanges(): Internel Error: ["
+                                               +this.ranges[base]
+                                               +","+this.ranges[base+1]
+                                               +"] ["+this.ranges[target]
+                                               +","+this.ranges[target+1]+"]");
+                }
+            } // while
+            base += 2;
+        }
+
+        if (base != this.ranges.length) {
+            int[] result = new int[base];
+            System.arraycopy(this.ranges, 0, result, 0, base);
+            this.ranges = result;
+        }
+        this.setCompacted();
+    }
+
+    @Override
+    protected void mergeRanges(Token token) {
+        RangeToken tok = (RangeToken)token;
+        this.sortRanges();
+        tok.sortRanges();
+        if (tok.ranges == null)
+            return;
+        this.icaseCache = null;
+        this.setSorted(true);
+        if (this.ranges == null) {
+            this.ranges = new int[tok.ranges.length];
+            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;) {
+            if (i >= this.ranges.length) {
+                result[k++] = tok.ranges[j++];
+                result[k++] = tok.ranges[j++];
+            } else if (j >= tok.ranges.length) {
+                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]) {
+                result[k++] = tok.ranges[j++];
+                result[k++] = tok.ranges[j++];
+            } else {
+                result[k++] = this.ranges[i++];
+                result[k++] = this.ranges[i++];
+            }
+        }
+        this.ranges = result;
+    }
+
+    @Override
+    protected void subtractRanges(Token token) {
+        if (token.type == NRANGE) {
+            this.intersectRanges(token);
+            return;
+        }
+        RangeToken tok = (RangeToken)token;
+        if (tok.ranges == null || this.ranges == null)
+            return;
+        this.icaseCache = null;
+        this.sortRanges();
+        this.compactRanges();
+        tok.sortRanges();
+        tok.compactRanges();
+
+        //System.err.println("Token#substractRanges(): Entry: "+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 subbegin = tok.ranges[sub];
+            int subend = tok.ranges[sub+1];
+            if (srcend < subbegin) {            // Not overlapped
+                                                // 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
+                if (subbegin <= srcbegin && srcend <= subend) {
+                                                // 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;
+                    sub += 2;
+                } else if (srcend <= subend) {
+                                                // src:    o--------o
+                                                // sub:          o----o
+                                                // res:    o-----o
+                                                // Reuse sub
+                    result[wp++] = srcbegin;
+                    result[wp++] = subbegin-1;
+                    src += 2;
+                } else {
+                                                // 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;
+                    sub += 2;
+                }
+            } else if (subend < srcbegin) {
+                                                // 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]
+                                           +"]");
+            }
+        }
+        while (src < this.ranges.length) {
+            result[wp++] = this.ranges[src++];
+            result[wp++] = this.ranges[src++];
+        }
+        this.ranges = new int[wp];
+        System.arraycopy(result, 0, this.ranges, 0, wp);
+                                                // this.ranges is sorted and compacted.
+    }
+
+    /**
+     * @param tok Ignore whether it is NRANGE or not.
+     */
+    @Override
+    protected void intersectRanges(Token token) {
+        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 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 src2begin = tok.ranges[src2];
+            int src2end = tok.ranges[src2+1];
+            if (src1end < src2begin) {          // Not overlapped
+                                                // 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 <= 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
+                    result[wp++] = src1begin;
+                    result[wp++] = src2end;
+                    this.ranges[src1] = src2end+1;
+                    src2 += 2;
+                } else if (src1end <= src2end) {
+                                                // 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
+                    result[wp++] = src2begin;
+                    result[wp++] = src2end;
+                    this.ranges[src1] = src2end+1;
+                }
+            } else if (src2end < src1begin) {
+                                                // 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]
+                                           +"]");
+            }
+        }
+        while (src1 < this.ranges.length) {
+            result[wp++] = this.ranges[src1++];
+            result[wp++] = this.ranges[src1++];
+        }
+        this.ranges = new int[wp];
+        System.arraycopy(result, 0, this.ranges, 0, wp);
+                                                // this.ranges is sorted and compacted.
+    }
+
+    /**
+     * for RANGE: Creates complement.
+     * 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;
+        tok.sortRanges();
+        tok.compactRanges();
+        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)
+            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;
+        }
+        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] = UTF16_MAX;
+        }
+        ret.setCompacted();
+        return ret;
+    }
+
+    synchronized RangeToken getCaseInsensitiveToken() {
+        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)
+                    uppers.addRange(ch, 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)
+                    lowers.addRange(ch, ch);
+                else {
+                    char uch = Character.toLowerCase((char)ch);
+                    lowers.addRange(uch, uch);
+                }
+            }
+        }
+        lowers.mergeRanges(uppers);
+        lowers.mergeRanges(this);
+        lowers.compactRanges();
+
+        this.icaseCache = lowers;
+        return lowers;
+    }
+
+    void dumpRanges() {
+        System.err.print("RANGE: ");
+        if (this.ranges == null) {
+            System.err.println(" NULL");
+            return;
+        }
+        for (int i = 0;  i < this.ranges.length;  i += 2) {
+            System.err.print("["+this.ranges[i]+","+this.ranges[i+1]+"] ");
+        }
+        System.err.println("");
+    }
+
+    @Override
+    boolean match(int ch) {
+        if (this.map == null)  this.createMap();
+        boolean ret;
+        if (this.type == RANGE) {
+            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])
+                    return true;
+            }
+        } else {
+            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])
+                    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 [] map = new int[asize];
+        int nonMapIndex = this.ranges.length;
+        for (int i = 0; i < asize; ++i) {
+            map[i] = 0;
+        }
+        for (int i = 0; i < this.ranges.length;  i += 2) {
+            int s = this.ranges[i];
+            int e = this.ranges[i+1];
+            if (s < MAPSIZE) {
+                for (int j = s; j <= e && j < MAPSIZE; j++) {
+                    map[j/32] |= 1<<(j&0x1f); // s&0x1f : 0-31
+                }
+            } 
+            else {
+                nonMapIndex = i;
+                break;
+            }
+            if (e >= MAPSIZE) {
+                nonMapIndex = i;
+                break;
+            }
+        }
+        this.map = map;
+        this.nonMapIndex = nonMapIndex;
+        //for (int i = 0;  i < asize;  i ++)  System.err.println("Map: "+Integer.toString(this.map[i], 16));
+    }
+
+    @Override
+    public String toString(int options) {
+        String ret;
+        if (this.type == RANGE) {
+            if (this == Token.token_dot)
+                ret = ".";
+            else if (this == Token.token_0to9)
+                ret = "\\d";
+            else if (this == Token.token_wordchars)
+                ret = "\\w";
+            else if (this == Token.token_spaces)
+                ret = "\\s";
+            else {
+                StringBuffer sb = new StringBuffer();
+                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]) {
+                        sb.append(escapeCharInCharClass(this.ranges[i]));
+                    } else {
+                        sb.append(escapeCharInCharClass(this.ranges[i]));
+                        sb.append('-');
+                        sb.append(escapeCharInCharClass(this.ranges[i+1]));
+                    }
+                }
+                sb.append(']');
+                ret = sb.toString();
+            }
+        } else {
+            if (this == Token.token_not_0to9)
+                ret = "\\D";
+            else if (this == Token.token_not_wordchars)
+                ret = "\\W";
+            else if (this == Token.token_not_spaces)
+                ret = "\\S";
+            else {
+                StringBuffer sb = new StringBuffer();
+                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]) {
+                        sb.append(escapeCharInCharClass(this.ranges[i]));
+                    } else {
+                        sb.append(escapeCharInCharClass(this.ranges[i]));
+                        sb.append('-');
+                        sb.append(escapeCharInCharClass(this.ranges[i+1]));
+                    }
+                }
+                sb.append(']');
+                ret = sb.toString();
+            }
+        }
+        return ret;
+    }
+
+    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;
+        }
+        return ret;
+    }
+
+}


[23/24] jena git commit: JENA-1537: Update NOTICE to include NOTICE items from Apache Xerces source

Posted by an...@apache.org.
JENA-1537: Update NOTICE to include NOTICE items from Apache Xerces source


Project: http://git-wip-us.apache.org/repos/asf/jena/repo
Commit: http://git-wip-us.apache.org/repos/asf/jena/commit/44f751b5
Tree: http://git-wip-us.apache.org/repos/asf/jena/tree/44f751b5
Diff: http://git-wip-us.apache.org/repos/asf/jena/diff/44f751b5

Branch: refs/heads/master
Commit: 44f751b5d65d528a65756608fbea5b3ef43a2ea0
Parents: c9a7e64
Author: Andy Seaborne <an...@apache.org>
Authored: Wed May 2 10:55:42 2018 +0100
Committer: Andy Seaborne <an...@apache.org>
Committed: Wed May 2 11:06:48 2018 +0100

----------------------------------------------------------------------
 NOTICE           | 4 ++++
 jena-core/NOTICE | 4 ++++
 2 files changed, 8 insertions(+)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/jena/blob/44f751b5/NOTICE
----------------------------------------------------------------------
diff --git a/NOTICE b/NOTICE
index 1dcf842..a7d3075 100644
--- a/NOTICE
+++ b/NOTICE
@@ -15,3 +15,7 @@ PluggedIn Software under a BSD license.
 
 This product includes software developed by Mort Bay Consulting Pty. Ltd.
    Copyright (c) 2004-2009 Mort Bay Consulting Pty. Ltd.
+
+Portions of this software are from Apache Xerces and were originally based on the following:
+  - software copyright (c) 1999, IBM Corporation., http://www.ibm.com.
+  - software copyright (c) 1999, Sun Microsystems., http://www.sun.com.

http://git-wip-us.apache.org/repos/asf/jena/blob/44f751b5/jena-core/NOTICE
----------------------------------------------------------------------
diff --git a/jena-core/NOTICE b/jena-core/NOTICE
index 1eada3f..02bec7f 100644
--- a/jena-core/NOTICE
+++ b/jena-core/NOTICE
@@ -12,3 +12,7 @@ These have been licensed to the Apache Software Foundation under a software gran
 
 This product includes software developed by
 PluggedIn Software under a BSD license.
+
+Portions of this software are from Apache Xerces and were originally based on the following:
+  - software copyright (c) 1999, IBM Corporation., http://www.ibm.com.
+  - software copyright (c) 1999, Sun Microsystems., http://www.sun.com.


[24/24] jena git commit: JENA-1537: Merge commit 'refs/pull/413/head' of https://github.com/apache/jena

Posted by an...@apache.org.
JENA-1537: Merge commit 'refs/pull/413/head' of https://github.com/apache/jena

This closes #413.


Project: http://git-wip-us.apache.org/repos/asf/jena/repo
Commit: http://git-wip-us.apache.org/repos/asf/jena/commit/2e917bd0
Tree: http://git-wip-us.apache.org/repos/asf/jena/tree/2e917bd0
Diff: http://git-wip-us.apache.org/repos/asf/jena/diff/2e917bd0

Branch: refs/heads/master
Commit: 2e917bd07fb8963f09f39921553e8e2909cc8fb1
Parents: 88cd917 44f751b
Author: Andy Seaborne <an...@apache.org>
Authored: Fri May 4 09:51:41 2018 +0100
Committer: Andy Seaborne <an...@apache.org>
Committed: Fri May 4 09:51:41 2018 +0100

----------------------------------------------------------------------
 NOTICE                                          |    4 +
 apache-jena-osgi/jena-osgi/pom.xml              |   21 +-
 .../org/apache/jena/sparql/expr/NodeValue.java  |   70 +-
 .../apache/jena/sparql/expr/RegexXerces.java    |    7 +-
 jena-cmds/src/main/java/jena/schemagen.java     |    2 +-
 jena-core/NOTICE                                |    4 +
 jena-core/pom.xml                               |    5 -
 .../apache/jena/datatypes/xsd/XSDDatatype.java  |  173 +-
 .../jena/ext/xerces/DatatypeFactoryInst.java    |   32 +
 .../apache/jena/ext/xerces/impl/Constants.java  |  694 ++++
 .../apache/jena/ext/xerces/impl/Version.java    |   37 +
 .../jena/ext/xerces/impl/dv/DTDDVFactory.java   |   86 +
 .../ext/xerces/impl/dv/DVFactoryException.java  |   40 +
 .../ext/xerces/impl/dv/DatatypeException.java   |  106 +
 .../ext/xerces/impl/dv/DatatypeValidator.java   |   42 +
 .../impl/dv/InvalidDatatypeFacetException.java  |   47 +
 .../impl/dv/InvalidDatatypeValueException.java  |   46 +
 .../jena/ext/xerces/impl/dv/ObjectFactory.java  |  546 +++
 .../ext/xerces/impl/dv/SchemaDVFactory.java     |  145 +
 .../ext/xerces/impl/dv/SecuritySupport.java     |  150 +
 .../jena/ext/xerces/impl/dv/ValidatedInfo.java  |  239 ++
 .../ext/xerces/impl/dv/ValidationContext.java   |   63 +
 .../jena/ext/xerces/impl/dv/XSFacets.java       |  135 +
 .../jena/ext/xerces/impl/dv/XSSimpleType.java   |  201 +
 .../jena/ext/xerces/impl/dv/util/Base64.java    |  305 ++
 .../ext/xerces/impl/dv/util/ByteListImpl.java   |  112 +
 .../jena/ext/xerces/impl/dv/util/HexBin.java    |  113 +
 .../xerces/impl/dv/xs/AbstractDateTimeDV.java   | 1107 ++++++
 .../jena/ext/xerces/impl/dv/xs/AnyAtomicDV.java |   43 +
 .../jena/ext/xerces/impl/dv/xs/AnySimpleDV.java |   45 +
 .../jena/ext/xerces/impl/dv/xs/AnyURIDV.java    |  170 +
 .../ext/xerces/impl/dv/xs/Base64BinaryDV.java   |   92 +
 .../ext/xerces/impl/dv/xs/BaseDVFactory.java    |  248 ++
 .../xerces/impl/dv/xs/BaseSchemaDVFactory.java  |  326 ++
 .../jena/ext/xerces/impl/dv/xs/BooleanDV.java   |   50 +
 .../jena/ext/xerces/impl/dv/xs/DateDV.java      |   96 +
 .../jena/ext/xerces/impl/dv/xs/DateTimeDV.java  |   95 +
 .../jena/ext/xerces/impl/dv/xs/DayDV.java       |  120 +
 .../xerces/impl/dv/xs/DayTimeDurationDV.java    |   62 +
 .../jena/ext/xerces/impl/dv/xs/DecimalDV.java   |  375 ++
 .../jena/ext/xerces/impl/dv/xs/DoubleDV.java    |  265 ++
 .../jena/ext/xerces/impl/dv/xs/DurationDV.java  |  392 ++
 .../jena/ext/xerces/impl/dv/xs/EntityDV.java    |   57 +
 .../impl/dv/xs/ExtendedSchemaDVFactoryImpl.java |   84 +
 .../jena/ext/xerces/impl/dv/xs/FloatDV.java     |  246 ++
 .../ext/xerces/impl/dv/xs/FullDVFactory.java    |  169 +
 .../jena/ext/xerces/impl/dv/xs/HexBinaryDV.java |   94 +
 .../apache/jena/ext/xerces/impl/dv/xs/IDDV.java |   56 +
 .../jena/ext/xerces/impl/dv/xs/IDREFDV.java     |   55 +
 .../jena/ext/xerces/impl/dv/xs/IntegerDV.java   |   43 +
 .../jena/ext/xerces/impl/dv/xs/ListDV.java      |  146 +
 .../jena/ext/xerces/impl/dv/xs/MonthDV.java     |  168 +
 .../jena/ext/xerces/impl/dv/xs/MonthDayDV.java  |  132 +
 .../xerces/impl/dv/xs/PrecisionDecimalDV.java   |  369 ++
 .../jena/ext/xerces/impl/dv/xs/QNameDV.java     |  112 +
 .../xerces/impl/dv/xs/SchemaDVFactoryImpl.java  |   76 +
 .../impl/dv/xs/SchemaDateTimeException.java     |   37 +
 .../jena/ext/xerces/impl/dv/xs/StringDV.java    |   46 +
 .../jena/ext/xerces/impl/dv/xs/TimeDV.java      |  114 +
 .../ext/xerces/impl/dv/xs/TypeValidator.java    |  108 +
 .../jena/ext/xerces/impl/dv/xs/UnionDV.java     |   47 +
 .../ext/xerces/impl/dv/xs/XSSimpleTypeDecl.java | 3562 ++++++++++++++++++
 .../xerces/impl/dv/xs/XSSimpleTypeDelegate.java |  249 ++
 .../jena/ext/xerces/impl/dv/xs/YearDV.java      |  129 +
 .../jena/ext/xerces/impl/dv/xs/YearMonthDV.java |  103 +
 .../xerces/impl/dv/xs/YearMonthDurationDV.java  |   64 +
 .../validation/ConfigurableValidationState.java |  126 +
 .../ext/xerces/impl/validation/EntityState.java |   47 +
 .../impl/validation/ValidationManager.java      |   84 +
 .../xerces/impl/validation/ValidationState.java |  215 ++
 .../ext/xerces/impl/xpath/regex/BMPattern.java  |  236 ++
 .../impl/xpath/regex/CaseInsensitiveMap.java    |  162 +
 .../jena/ext/xerces/impl/xpath/regex/Match.java |  185 +
 .../jena/ext/xerces/impl/xpath/regex/Op.java    |  261 ++
 .../xerces/impl/xpath/regex/ParseException.java |   53 +
 .../impl/xpath/regex/ParserForXMLSchema.java    |  534 +++
 .../ext/xerces/impl/xpath/regex/REUtil.java     |  363 ++
 .../ext/xerces/impl/xpath/regex/RangeToken.java |  631 ++++
 .../xerces/impl/xpath/regex/RegexParser.java    | 1230 ++++++
 .../impl/xpath/regex/RegularExpression.java     | 2456 ++++++++++++
 .../jena/ext/xerces/impl/xpath/regex/Token.java | 1562 ++++++++
 .../xerces/impl/xpath/regex/message.properties  |   58 +
 .../impl/xpath/regex/message_fr.properties      |   58 +
 .../impl/xpath/regex/message_ja.properties      |   58 +
 .../jena/ext/xerces/impl/xs/SchemaSymbols.java  |  215 ++
 .../ext/xerces/impl/xs/XSDeclarationPool.java   |  315 ++
 .../ext/xerces/impl/xs/util/ObjectListImpl.java |  123 +
 .../ext/xerces/impl/xs/util/ShortListImpl.java  |  128 +
 .../ext/xerces/impl/xs/util/StringListImpl.java |  171 +
 .../xerces/impl/xs/util/XSObjectListImpl.java   |  293 ++
 .../jaxp/datatype/DatatypeFactoryImpl.java      |  394 ++
 .../ext/xerces/jaxp/datatype/DurationImpl.java  | 1991 ++++++++++
 .../jaxp/datatype/XMLGregorianCalendarImpl.java | 3232 ++++++++++++++++
 .../xerces/util/DatatypeMessageFormatter.java   |   96 +
 .../apache/jena/ext/xerces/util/IntStack.java   |  114 +
 .../apache/jena/ext/xerces/util/SymbolHash.java |  223 ++
 .../jena/ext/xerces/util/SymbolTable.java       |  408 ++
 .../org/apache/jena/ext/xerces/util/URI.java    | 2185 +++++++++++
 .../apache/jena/ext/xerces/util/XML11Char.java  |  413 ++
 .../apache/jena/ext/xerces/util/XMLChar.java    | 1062 ++++++
 .../jena/ext/xerces/xni/NamespaceContext.java   |  177 +
 .../jena/ext/xerces/xs/AttributePSVI.java       |   30 +
 .../apache/jena/ext/xerces/xs/ElementPSVI.java  |   47 +
 .../org/apache/jena/ext/xerces/xs/ItemPSVI.java |  209 +
 .../apache/jena/ext/xerces/xs/LSInputList.java  |   48 +
 .../apache/jena/ext/xerces/xs/PSVIProvider.java |   90 +
 .../apache/jena/ext/xerces/xs/ShortList.java    |   57 +
 .../apache/jena/ext/xerces/xs/StringList.java   |   55 +
 .../apache/jena/ext/xerces/xs/XSAnnotation.java |   60 +
 .../ext/xerces/xs/XSAttributeDeclaration.java   |  121 +
 .../xerces/xs/XSAttributeGroupDefinition.java   |   45 +
 .../jena/ext/xerces/xs/XSAttributeUse.java      |  108 +
 .../ext/xerces/xs/XSComplexTypeDefinition.java  |  113 +
 .../apache/jena/ext/xerces/xs/XSConstants.java  |  326 ++
 .../ext/xerces/xs/XSElementDeclaration.java     |  189 +
 .../apache/jena/ext/xerces/xs/XSException.java  |   53 +
 .../org/apache/jena/ext/xerces/xs/XSFacet.java  |   69 +
 .../jena/ext/xerces/xs/XSIDCDefinition.java     |   69 +
 .../jena/ext/xerces/xs/XSImplementation.java    |   64 +
 .../org/apache/jena/ext/xerces/xs/XSLoader.java |   90 +
 .../org/apache/jena/ext/xerces/xs/XSModel.java  |  173 +
 .../apache/jena/ext/xerces/xs/XSModelGroup.java |   63 +
 .../ext/xerces/xs/XSModelGroupDefinition.java   |   39 +
 .../jena/ext/xerces/xs/XSMultiValueFacet.java   |   47 +
 .../apache/jena/ext/xerces/xs/XSNamedMap.java   |   67 +
 .../jena/ext/xerces/xs/XSNamespaceItem.java     |  117 +
 .../jena/ext/xerces/xs/XSNamespaceItemList.java |   46 +
 .../ext/xerces/xs/XSNotationDeclaration.java    |   46 +
 .../org/apache/jena/ext/xerces/xs/XSObject.java |   55 +
 .../apache/jena/ext/xerces/xs/XSObjectList.java |   46 +
 .../apache/jena/ext/xerces/xs/XSParticle.java   |   52 +
 .../ext/xerces/xs/XSSimpleTypeDefinition.java   |  244 ++
 .../org/apache/jena/ext/xerces/xs/XSTerm.java   |   27 +
 .../jena/ext/xerces/xs/XSTypeDefinition.java    |  102 +
 .../org/apache/jena/ext/xerces/xs/XSValue.java  |   97 +
 .../apache/jena/ext/xerces/xs/XSWildcard.java   |   87 +
 .../jena/ext/xerces/xs/datatypes/ByteList.java  |   66 +
 .../ext/xerces/xs/datatypes/ObjectList.java     |   60 +
 .../ext/xerces/xs/datatypes/XSDateTime.java     |  291 ++
 .../jena/ext/xerces/xs/datatypes/XSDecimal.java |   65 +
 .../jena/ext/xerces/xs/datatypes/XSDouble.java  |   33 +
 .../jena/ext/xerces/xs/datatypes/XSFloat.java   |   33 +
 .../jena/ext/xerces/xs/datatypes/package.html   |  306 ++
 .../org/apache/jena/rdf/model/impl/Util.java    |    2 +-
 .../rdfxml/xmlinput/impl/ParserSupport.java     |    4 +-
 .../jena/rdfxml/xmlinput/impl/RDFXMLParser.java |  141 +-
 .../rdfxml/xmloutput/impl/BaseXMLWriter.java    |    2 +-
 .../jena/rdfxml/xmloutput/impl/Unparser.java    |    2 +-
 .../jena/shared/impl/PrefixMappingImpl.java     |    2 +-
 .../ext/xerces/impl/msg/DOMMessages.properties  |   84 +
 .../xerces/impl/msg/DatatypeMessages.properties |   47 +
 .../impl/msg/JAXPValidationMessages.properties  |   50 +
 .../ext/xerces/impl/msg/SAXMessages.properties  |   46 +
 .../xerces/impl/msg/XIncludeMessages.properties |   56 +
 .../ext/xerces/impl/msg/XMLMessages.properties  |  309 ++
 .../impl/msg/XMLSchemaMessages.properties       |  320 ++
 .../impl/msg/XMLSerializerMessages.properties   |   50 +
 .../xerces/impl/msg/XPointerMessages.properties |   44 +
 .../xerces/impl/xpath/regex/message.properties  |   58 +
 .../impl/xpath/regex/message_fr.properties      |   58 +
 .../impl/xpath/regex/message_ja.properties      |   58 +
 .../jena/graph/test/TestTypedLiterals.java      |  121 +-
 .../apache/jena/rdfxml/xmlinput/MoreTests.java  |  107 +-
 .../jena/rdfxml/xmlinput/SAX2RDFMoreTests.java  |    9 +-
 .../jena/rdfxml/xmlinput/SAX2RDFTest.java       |    5 +-
 .../rdfxml/xmlinput/states/TestARPStates.java   |    2 +-
 .../jena/rdfxml/xmloutput/TestMacEncodings.java |    6 +-
 .../jena/rdfxml/xmloutput/TestPackage.java      |    7 +-
 .../jena/tdb2/store/value/DateTimeNode.java     |   14 +-
 .../jena/tdb2/store/value/TestNodeIdInline.java |    2 +-
 .../org/apache/jena/tdb/store/DateTimeNode.java |   15 +-
 .../java/org/apache/jena/tdb/store/NodeId.java  |    3 -
 .../org/apache/jena/tdb/store/TestNodeId.java   |    2 +-
 pom.xml                                         |    7 -
 174 files changed, 38267 insertions(+), 407 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/jena/blob/2e917bd0/apache-jena-osgi/jena-osgi/pom.xml
----------------------------------------------------------------------


[10/24] jena git commit: JENA-1537: Remove dependency on Xerces. Import needed code

Posted by an...@apache.org.
http://git-wip-us.apache.org/repos/asf/jena/blob/c9a7e646/jena-core/src/main/java/org/apache/jena/ext/xerces/jaxp/datatype/DurationImpl.java
----------------------------------------------------------------------
diff --git a/jena-core/src/main/java/org/apache/jena/ext/xerces/jaxp/datatype/DurationImpl.java b/jena-core/src/main/java/org/apache/jena/ext/xerces/jaxp/datatype/DurationImpl.java
new file mode 100644
index 0000000..e1d85ff
--- /dev/null
+++ b/jena-core/src/main/java/org/apache/jena/ext/xerces/jaxp/datatype/DurationImpl.java
@@ -0,0 +1,1991 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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.jena.ext.xerces.jaxp.datatype;
+
+import java.io.IOException;
+import java.io.Serializable;
+import java.math.BigDecimal;
+import java.math.BigInteger;
+import java.util.Calendar;
+import java.util.Date;
+import java.util.GregorianCalendar;
+
+import javax.xml.datatype.DatatypeConstants;
+import javax.xml.datatype.Duration;
+import javax.xml.datatype.XMLGregorianCalendar;
+
+import org.apache.jena.ext.xerces.util.DatatypeMessageFormatter;
+
+/**
+ * <p>Immutable representation of a time span as defined in
+ * the W3C XML Schema 1.0 specification.</p>
+ * 
+ * <p>A Duration object represents a period of Gregorian time,
+ * which consists of six fields (years, months, days, hours,
+ * minutes, and seconds) plus a sign (+/-) field.</p>
+ * 
+ * <p>The first five fields have non-negative (>=0) integers or null
+ * (which represents that the field is not set),
+ * and the seconds field has a non-negative decimal or null.
+ * A negative sign indicates a negative duration.</p> 
+ * 
+ * <p>This class provides a number of methods that make it easy
+ * to use for the duration datatype of XML Schema 1.0 with
+ * the errata.</p>
+ * 
+ * <h2>Order relationship</h2>
+ * <p>Duration objects only have partial order, where two values A and B
+ * maybe either:</p>
+ * <ol>
+ *  <li>A&lt;B (A is shorter than B)
+ *  <li>A&gt;B (A is longer than B)
+ *  <li>A==B   (A and B are of the same duration)
+ *  <li>A&lt;>B (Comparison between A and B is indeterminate)
+ * </ol>
+ * <p>For example, 30 days cannot be meaningfully compared to one month.
+ * The {@link #compare(Duration)} method implements this
+ * relationship.</p>
+ * 
+ * <p>See the {@link #isLongerThan(Duration)} method for details about
+ * the order relationship among {@link Duration} objects.</p>
+ * 
+ * 
+ * 
+ * <h2>Operations over Duration</h2>
+ * <p>This class provides a set of basic arithmetic operations, such
+ * as addition, subtraction and multiplication.
+ * Because durations don't have total order, an operation could
+ * fail for some combinations of operations. For example, you cannot
+ * subtract 15 days from 1 month. See the javadoc of those methods
+ * for detailed conditions where this could happen.</p>
+ * 
+ * <p>Also, division of a duration by a number is not provided because
+ * the {@link Duration} class can only deal with finite precision
+ * decimal numbers. For example, one cannot represent 1 sec divided by 3.</p> 
+ * 
+ * <p>However, you could substitute a division by 3 with multiplying
+ * by numbers such as 0.3 or 0.333.</p>
+ *
+ *
+ * 
+ * <h2>Range of allowed values</h2>
+ * <p>
+ * Because some operations of {@link Duration} rely on {@link Calendar}
+ * even though {@link Duration} can hold very large or very small values,
+ * some of the methods may not work correctly on such {@link Duration}s.
+ * The impacted methods document their dependency on {@link Calendar}.
+ * 
+ *  
+ * @author <a href="mailto:Kohsuke.Kawaguchi@Sun.com">Kohsuke Kawaguchi</a>
+ * @author <a href="mailto:Joseph.Fialli@Sun.com">Joseph Fialli</a>
+ * @version $Id: DurationImpl.java 944783 2010-05-16 09:45:19Z mukulg $
+ * @see XMLGregorianCalendar#add(Duration)
+ */
+@SuppressWarnings("all")
+class DurationImpl
+	extends Duration
+	implements Serializable {
+    
+    /**
+     * <p>Stream Unique Identifier.</p>
+     */
+    private static final long serialVersionUID = -2650025807136350131L;
+
+    /**
+     * <p>Internal array of value Fields.</p>
+     */
+    private static final DatatypeConstants.Field[] FIELDS = new DatatypeConstants.Field[]{
+        DatatypeConstants.YEARS,
+        DatatypeConstants.MONTHS,
+        DatatypeConstants.DAYS,
+        DatatypeConstants.HOURS,
+        DatatypeConstants.MINUTES,
+        DatatypeConstants.SECONDS
+    };
+
+    /**
+     * <p>BigDecimal value of 0.</p>
+     */    
+    private static final BigDecimal ZERO = BigDecimal.valueOf(0);
+
+    /**
+     * <p>Indicates the sign. -1, 0 or 1 if the duration is negative,
+     * zero, or positive.</p>
+     */
+    private final int signum;
+
+    /**
+     * <p>Years of this <code>Duration</code>.</p>
+     */
+    private final BigInteger years;
+
+    /**
+     * <p>Months of this <code>Duration</code>.</p>
+     */
+    private final BigInteger months;
+
+    /**
+     * <p>Days of this <code>Duration</code>.</p>
+     */
+    private final BigInteger days;
+
+    /**
+     * <p>Hours of this <code>Duration</code>.</p>
+     */
+    private final BigInteger hours;
+
+    /**
+     * <p>Minutes of this <code>Duration</code>.</p>
+     */
+    private final BigInteger minutes;
+
+    /**
+     * <p>Seconds of this <code>Duration</code>.</p>
+     */
+    private final BigDecimal seconds;
+
+    /**
+     * Returns the sign of this duration in -1,0, or 1.
+     * 
+     * @return
+     *      -1 if this duration is negative, 0 if the duration is zero,
+     *      and 1 if the duration is postive.
+     */
+    @Override
+    public int getSign() {
+
+        return signum;
+    }
+
+	/**
+	 * TODO: Javadoc
+	 * @param isPositive Sign.
+	 * 
+	 * @return 1 if positive, else -1.
+	 */	        
+    private int calcSignum(boolean isPositive) {
+        if ((years == null || years.signum() == 0)
+             && (months == null || months.signum() == 0)
+             && (days == null || days.signum() == 0)
+             && (hours == null || hours.signum() == 0)
+             && (minutes == null || minutes.signum() == 0)
+             && (seconds == null || seconds.signum() == 0)) {
+            return 0;
+        }
+
+        if (isPositive) {
+            return 1;
+        } 
+        else {
+            return -1;
+        }
+    }
+    
+    /**
+     * <p>Constructs a new Duration object by specifying each field individually.</p>
+     * 
+     * <p>All the parameters are optional as long as at least one field is present.
+     * If specified, parameters have to be zero or positive.</p>
+     * 
+     * @param isPositive Set to <code>false</code> to create a negative duration. When the length
+     *   of the duration is zero, this parameter will be ignored.
+     * @param years of this <code>Duration</code>
+     * @param months of this <code>Duration</code>
+     * @param days of this <code>Duration</code>
+     * @param hours of this <code>Duration</code>
+     * @param minutes of this <code>Duration</code>
+     * @param seconds of this <code>Duration</code>
+     * 
+     * @throws IllegalArgumentException
+     *    If years, months, days, hours, minutes and
+     *    seconds parameters are all <code>null</code>. Or if any
+     *    of those parameters are negative.
+     */
+    protected DurationImpl(
+        boolean isPositive,
+        BigInteger years,
+        BigInteger months,
+        BigInteger days,
+        BigInteger hours,
+        BigInteger minutes,
+        BigDecimal seconds) {
+            
+        this.years = years;
+        this.months = months;
+        this.days = days;
+        this.hours = hours;
+        this.minutes = minutes;
+        this.seconds = seconds;
+
+        this.signum = calcSignum(isPositive);
+
+        // sanity check
+        if (years == null
+            && months == null
+            && days == null
+            && hours == null
+            && minutes == null
+            && seconds == null) {
+            throw new IllegalArgumentException(
+            //"all the fields are null"
+            DatatypeMessageFormatter.formatMessage(null, "AllFieldsNull", null)
+            );
+        }
+        testNonNegative(years, DatatypeConstants.YEARS);
+        testNonNegative(months, DatatypeConstants.MONTHS);
+        testNonNegative(days, DatatypeConstants.DAYS);
+        testNonNegative(hours, DatatypeConstants.HOURS);
+        testNonNegative(minutes, DatatypeConstants.MINUTES);
+        testNonNegative(seconds, DatatypeConstants.SECONDS);
+    }
+    
+    /**
+     * <p>Makes sure that the given number is non-negative. If it is not,
+     * throw {@link IllegalArgumentException}.</p>
+     * 
+     * @param n Number to test.
+     * @param f Field to test.
+     */
+    private static void testNonNegative(BigInteger n, DatatypeConstants.Field f) {
+        if (n != null && n.signum() < 0) {
+            throw new IllegalArgumentException(             
+                DatatypeMessageFormatter.formatMessage(null, "NegativeField", new Object[]{f.toString()})
+            );
+        }
+    }
+    
+    /**
+     * <p>Makes sure that the given number is non-negative. If it is not,
+     * throw {@link IllegalArgumentException}.</p>
+     * 
+     * @param n Number to test.
+     * @param f Field to test.
+     */
+    private static void testNonNegative(BigDecimal n, DatatypeConstants.Field f) {
+        if (n != null && n.signum() < 0) {
+            
+            throw new IllegalArgumentException(
+                DatatypeMessageFormatter.formatMessage(null, "NegativeField", new Object[]{f.toString()})            
+            );
+        }
+    }
+    
+    /**
+     * <p>Constructs a new Duration object by specifying each field
+     * individually.</p>
+     * 
+     * <p>This method is functionally equivalent to
+     * invoking another constructor by wrapping
+     * all non-zero parameters into {@link BigInteger} and {@link BigDecimal}.
+     * Zero value of int parameter is equivalent of null value of
+     * the corresponding field.</p> 
+     * 
+     * @see #DurationImpl(boolean, BigInteger, BigInteger, BigInteger, BigInteger,
+     *   BigInteger, BigDecimal)
+     */
+    protected DurationImpl(
+        final boolean isPositive,
+        final int years,
+        final int months,
+        final int days,
+        final int hours,
+        final int minutes,
+        final int seconds) {
+        this(
+            isPositive,
+            wrap(years),
+            wrap(months),
+            wrap(days),
+            wrap(hours),
+            wrap(minutes),
+            seconds != 0 ? BigDecimal.valueOf(seconds) : null);
+    }
+
+	/**
+	 * TODO: Javadoc
+	 * 
+	 * @param i int to convert to BigInteger.
+	 * 
+	 * @return BigInteger representation of int.
+	 */
+    private static BigInteger wrap(final int i) {
+    	// field may not be set
+    	if (i == DatatypeConstants.FIELD_UNDEFINED) {
+    		return null;
+    	}
+    	
+    	// int -> BigInteger
+        return BigInteger.valueOf(i);
+    }
+    
+    /**
+     * <p>Constructs a new Duration object by specifying the duration
+     * in milliseconds.</p>
+     * 
+     * <p>The DAYS, HOURS, MINUTES and SECONDS fields are used to
+     * represent the specifed duration in a reasonable way.
+     * That is, the constructed object <code>x</code> satisfies
+     * the following conditions:</p>
+     * <ul>
+     *  <li>x.getHours()&lt;24
+     *  <li>x.getMinutes()&lt;60
+     *  <li>x.getSeconds()&lt;60 
+     * </ul>
+     * 
+     * @param durationInMilliSeconds
+     *      The length of the duration in milliseconds.
+     */
+    protected DurationImpl(final long durationInMilliSeconds) {
+
+        boolean is0x8000000000000000L = false;
+        long l = durationInMilliSeconds;
+
+        if (l > 0) {
+            signum = 1;
+        } 
+        else if (l < 0) {
+            signum = -1;
+            if (l == 0x8000000000000000L) {
+                // negating 0x8000000000000000L causes an overflow
+                l++;
+                is0x8000000000000000L = true;
+            }
+            l *= -1;
+        } 
+        else {
+            signum = 0;
+        }
+
+        this.years = null;
+        this.months = null;
+
+        this.seconds =
+            BigDecimal.valueOf((l % 60000L) + (is0x8000000000000000L ? 1 : 0), 3);
+
+        l /= 60000L;
+        this.minutes = (l == 0) ? null : BigInteger.valueOf(l % 60L);
+
+        l /= 60L;
+        this.hours = (l == 0) ? null : BigInteger.valueOf(l % 24L);
+
+        l /= 24L;
+        this.days = (l == 0) ? null : BigInteger.valueOf(l);
+    }
+    
+    
+    /**
+     * Constructs a new Duration object by
+     * parsing its string representation
+     * "PnYnMnDTnHnMnS" as defined in XML Schema 1.0 section 3.2.6.1.
+     * 
+     * <p>
+     * The string representation may not have any leading
+     * and trailing whitespaces.
+     * 
+     * <p>
+     * For example, this method parses strings like
+     * "P1D" (1 day), "-PT100S" (-100 sec.), "P1DT12H" (1 days and 12 hours).
+     *  
+     * <p>
+     * The parsing is done field by field so that   
+     * the following holds for any lexically correct string x:
+     * <pre>
+     * new Duration(x).toString().equals(x)
+     * </pre>
+     * 
+     * Returns a non-null valid duration object that holds the value
+     * indicated by the lexicalRepresentation parameter.
+     *
+     * @param lexicalRepresentation
+     *      Lexical representation of a duration.
+     * @throws IllegalArgumentException
+     *      If the given string does not conform to the aforementioned
+     *      specification.
+     * @throws NullPointerException
+     *      If the given string is null.
+     */
+    protected DurationImpl(String lexicalRepresentation)
+        throws IllegalArgumentException {
+        // only if I could use the JDK1.4 regular expression ....
+
+        if (lexicalRepresentation == null) {
+           throw new NullPointerException();
+        }
+        
+        final String s = lexicalRepresentation;
+        boolean positive;
+        int[] idx = new int[1];
+        int length = s.length();
+        boolean timeRequired = false;
+
+        idx[0] = 0;
+        if (length != idx[0] && s.charAt(idx[0]) == '-') {
+            idx[0]++;
+            positive = false;
+        } 
+        else {
+            positive = true;
+        }
+
+        if (length != idx[0] && s.charAt(idx[0]++) != 'P') {
+            throw new IllegalArgumentException(s); //,idx[0]-1);
+        }
+
+
+        // phase 1: chop the string into chunks
+        // (where a chunk is '<number><a symbol>'
+        //--------------------------------------
+        int dateLen = 0;
+        String[] dateParts = new String[3];
+        int[] datePartsIndex = new int[3];
+        while (length != idx[0]
+               && isDigit(s.charAt(idx[0]))
+               && dateLen < 3) {
+            datePartsIndex[dateLen] = idx[0];
+            dateParts[dateLen++] = parsePiece(s, idx);
+        }
+
+        if (length != idx[0]) {
+            if (s.charAt(idx[0]++) == 'T') {
+                timeRequired = true;
+            } 
+            else {
+                throw new IllegalArgumentException(s); // ,idx[0]-1);
+            }
+        }
+
+        int timeLen = 0;
+        String[] timeParts = new String[3];
+        int[] timePartsIndex = new int[3];
+        while (length != idx[0]
+                             && isDigitOrPeriod(s.charAt(idx[0]))
+                             && timeLen < 3) {
+            timePartsIndex[timeLen] = idx[0];
+            timeParts[timeLen++] = parsePiece(s, idx);
+        }
+
+        if (timeRequired && timeLen == 0) {
+            throw new IllegalArgumentException(s); // ,idx[0]);
+        }
+
+        if (length != idx[0]) {
+            throw new IllegalArgumentException(s); // ,idx[0]);
+        }
+        if (dateLen == 0 && timeLen == 0) {
+            throw new IllegalArgumentException(s); // ,idx[0]);
+        }
+
+        // phase 2: check the ordering of chunks
+        //--------------------------------------
+        organizeParts(s, dateParts, datePartsIndex, dateLen, "YMD");
+        organizeParts(s, timeParts, timePartsIndex, timeLen, "HMS");
+
+        // parse into numbers
+        years = parseBigInteger(s, dateParts[0], datePartsIndex[0]);
+        months = parseBigInteger(s, dateParts[1], datePartsIndex[1]);
+        days = parseBigInteger(s, dateParts[2], datePartsIndex[2]);
+        hours = parseBigInteger(s, timeParts[0], timePartsIndex[0]);
+        minutes = parseBigInteger(s, timeParts[1], timePartsIndex[1]);
+        seconds = parseBigDecimal(s, timeParts[2], timePartsIndex[2]);
+        signum = calcSignum(positive);
+    }
+        
+     
+    /**
+     * TODO: Javadoc
+     * 
+     * @param ch char to test.
+     * 
+     * @return true if ch is a digit, else false.
+     */
+    private static boolean isDigit(char ch) {
+        return '0' <= ch && ch <= '9';
+    }
+    
+    /**
+     * TODO: Javadoc
+     * 
+     * @param ch to test.
+     * 
+     * @return true if ch is a digit or a period, else false.
+     */
+    private static boolean isDigitOrPeriod(char ch) {
+        return isDigit(ch) || ch == '.';
+    }
+    
+    /**
+     * TODO: Javadoc
+     * 
+     * @param whole String to parse.
+     * @param idx TODO: ???
+     * 
+     * @return Result of parsing.
+     * 
+     * @throws IllegalArgumentException If whole cannot be parsed.
+     */
+    private static String parsePiece(String whole, int[] idx)
+        throws IllegalArgumentException {
+        int start = idx[0];
+        while (idx[0] < whole.length()
+            && isDigitOrPeriod(whole.charAt(idx[0]))) {
+            idx[0]++;
+            }
+        if (idx[0] == whole.length()) {
+            throw new IllegalArgumentException(whole); // ,idx[0]);
+        }
+
+        idx[0]++;
+
+        return whole.substring(start, idx[0]);
+    }
+    
+    /**
+     * TODO: Javadoc.
+     * 
+     * @param whole TODO: ???
+     * @param parts TODO: ???
+     * @param partsIndex TODO: ???
+     * @param len TODO: ???
+     * @param tokens TODO: ???
+     * 
+     * @throws IllegalArgumentException TODO: ???
+     */
+    private static void organizeParts(
+        String whole,
+        String[] parts,
+        int[] partsIndex,
+        int len,
+        String tokens)
+        throws IllegalArgumentException {
+
+        int idx = tokens.length();
+        for (int i = len - 1; i >= 0; i--) {
+            if (parts[i] == null) {
+                throw new IllegalArgumentException(whole);
+            }
+            int nidx =
+                tokens.lastIndexOf(
+                    parts[i].charAt(parts[i].length() - 1),
+                    idx - 1);
+            if (nidx == -1) {
+                throw new IllegalArgumentException(whole);
+                // ,partsIndex[i]+parts[i].length()-1);
+            }
+
+            for (int j = nidx + 1; j < idx; j++) {
+                parts[j] = null;
+            }
+            idx = nidx;
+            parts[idx] = parts[i];
+            partsIndex[idx] = partsIndex[i];
+        }
+        for (idx--; idx >= 0; idx--) {
+            parts[idx] = null;
+        }
+    }
+    
+    /**
+     * TODO: Javadoc
+     * 
+     * @param whole TODO: ???.
+     * @param part TODO: ???.
+     * @param index TODO: ???.
+     * 
+     * @return TODO: ???.
+     * 
+     * @throws IllegalArgumentException TODO: ???.
+     */
+    private static BigInteger parseBigInteger(
+        String whole,
+        String part,
+        int index)
+        throws IllegalArgumentException {
+        if (part == null) {
+            return null;
+        }
+        part = part.substring(0, part.length() - 1);
+        //        try {
+        return new BigInteger(part);
+        //        } catch( NumberFormatException e ) {
+        //            throw new ParseException( whole, index );
+        //        }
+    }
+    
+    /**
+     * TODO: Javadoc.
+     * 
+     * @param whole TODO: ???.
+     * @param part TODO: ???.
+     * @param index TODO: ???.
+     * 
+     * @return TODO: ???.
+     * 
+     * @throws IllegalArgumentException TODO: ???.
+     */
+    private static BigDecimal parseBigDecimal(
+        String whole,
+        String part,
+        int index)
+        throws IllegalArgumentException {
+        if (part == null) {
+            return null;
+        }
+        part = part.substring(0, part.length() - 1);
+        // NumberFormatException is IllegalArgumentException
+        //        try {
+        return new BigDecimal(part);
+        //        } catch( NumberFormatException e ) {
+        //            throw new ParseException( whole, index );
+        //        }
+    }
+    
+    /**
+     * <p>Four constants defined for the comparison of durations.</p>
+     */
+    private static final XMLGregorianCalendar[] TEST_POINTS = new XMLGregorianCalendar[] {
+        XMLGregorianCalendarImpl.parse("1696-09-01T00:00:00Z"),
+        XMLGregorianCalendarImpl.parse("1697-02-01T00:00:00Z"),
+        XMLGregorianCalendarImpl.parse("1903-03-01T00:00:00Z"),
+        XMLGregorianCalendarImpl.parse("1903-07-01T00:00:00Z")
+    };
+    
+	/**
+	 * <p>Partial order relation comparison with this <code>Duration</code> instance.</p>
+	 * 
+	 * <p>Comparison result must be in accordance with
+	 * <a href="http://www.w3.org/TR/xmlschema-2/#duration-order">W3C XML Schema 1.0 Part 2, Section 3.2.7.6.2,
+	 * <i>Order relation on duration</i></a>.</p>
+	 * 
+	 * <p>Return:</p>
+	 * <ul>
+	 *   <li>{@link DatatypeConstants#LESSER} if this <code>Duration</code> is shorter than <code>duration</code> parameter</li>
+	 *   <li>{@link DatatypeConstants#EQUAL} if this <code>Duration</code> is equal to <code>duration</code> parameter</li>
+	 *   <li>{@link DatatypeConstants#GREATER} if this <code>Duration</code> is longer than <code>duration</code> parameter</li>
+	 *   <li>{@link DatatypeConstants#INDETERMINATE} if a conclusive partial order relation cannot be determined</li>
+	 * </ul>
+	 *
+	 * @param duration to compare
+	 * 
+	 * @return the relationship between <code>this</code> <code>Duration</code>and <code>duration</code> parameter as
+	 *   {@link DatatypeConstants#LESSER}, {@link DatatypeConstants#EQUAL}, {@link DatatypeConstants#GREATER}
+	 *   or {@link DatatypeConstants#INDETERMINATE}.
+	 * 
+	 * @throws UnsupportedOperationException If the underlying implementation
+	 *   cannot reasonably process the request, e.g. W3C XML Schema allows for
+	 *   arbitrarily large/small/precise values, the request may be beyond the
+	 *   implementations capability.
+	 * @throws NullPointerException if <code>duration</code> is <code>null</code>. 
+	 *
+	 * @see #isShorterThan(Duration)
+	 * @see #isLongerThan(Duration)
+	 */
+    @Override
+    public int compare(Duration rhs) {
+    	
+    	BigInteger maxintAsBigInteger = BigInteger.valueOf(Integer.MAX_VALUE);
+
+    	// check for fields that are too large in this Duration
+    	if (years != null && years.compareTo(maxintAsBigInteger) == 1) {    		
+            throw new UnsupportedOperationException(
+                        DatatypeMessageFormatter.formatMessage(null, "TooLarge", 
+                            new Object[]{this.getClass().getName() + "#compare(Duration duration)" + DatatypeConstants.YEARS.toString(), years.toString()})
+    					//this.getClass().getName() + "#compare(Duration duration)"
+						//+ " years too large to be supported by this implementation "
+						//+ years.toString()
+					);
+    	}
+    	if (months != null && months.compareTo(maxintAsBigInteger) == 1) {
+    		throw new UnsupportedOperationException(
+                        DatatypeMessageFormatter.formatMessage(null, "TooLarge", 
+                            new Object[]{this.getClass().getName() + "#compare(Duration duration)" + DatatypeConstants.MONTHS.toString(), months.toString()})
+            
+    					//this.getClass().getName() + "#compare(Duration duration)"
+						//+ " months too large to be supported by this implementation "
+						//+ months.toString()
+					);
+    	}
+    	if (days != null && days.compareTo(maxintAsBigInteger) == 1) {
+    		throw new UnsupportedOperationException(
+                        DatatypeMessageFormatter.formatMessage(null, "TooLarge", 
+                            new Object[]{this.getClass().getName() + "#compare(Duration duration)" + DatatypeConstants.DAYS.toString(), days.toString()})
+            
+    					//this.getClass().getName() + "#compare(Duration duration)"
+						//+ " days too large to be supported by this implementation "
+						//+ days.toString()
+					);
+    	}
+    	if (hours != null && hours.compareTo(maxintAsBigInteger) == 1) {
+    		throw new UnsupportedOperationException(
+                        DatatypeMessageFormatter.formatMessage(null, "TooLarge", 
+                            new Object[]{this.getClass().getName() + "#compare(Duration duration)" + DatatypeConstants.HOURS.toString(), hours.toString()})
+            
+    					//this.getClass().getName() + "#compare(Duration duration)"
+						//+ " hours too large to be supported by this implementation "
+						//+ hours.toString()
+					);
+    	}
+    	if (minutes != null && minutes.compareTo(maxintAsBigInteger) == 1) {
+    		throw new UnsupportedOperationException(
+                        DatatypeMessageFormatter.formatMessage(null, "TooLarge", 
+                            new Object[]{this.getClass().getName() + "#compare(Duration duration)" + DatatypeConstants.MINUTES.toString(), minutes.toString()})
+            
+    					//this.getClass().getName() + "#compare(Duration duration)"
+						//+ " minutes too large to be supported by this implementation "
+						//+ minutes.toString()
+					);
+    	}
+    	if (seconds != null && seconds.toBigInteger().compareTo(maxintAsBigInteger) == 1) {
+    		throw new UnsupportedOperationException(
+                        DatatypeMessageFormatter.formatMessage(null, "TooLarge", 
+                            new Object[]{this.getClass().getName() + "#compare(Duration duration)" + DatatypeConstants.SECONDS.toString(), toString(seconds)})
+            
+    					//this.getClass().getName() + "#compare(Duration duration)"
+						//+ " seconds too large to be supported by this implementation "
+						//+ seconds.toString()
+					);
+    	}
+    	
+    	// check for fields that are too large in rhs Duration
+    	BigInteger rhsYears = (BigInteger) rhs.getField(DatatypeConstants.YEARS);
+    	if (rhsYears != null && rhsYears.compareTo(maxintAsBigInteger) == 1) {
+    		throw new UnsupportedOperationException(
+                        DatatypeMessageFormatter.formatMessage(null, "TooLarge", 
+                            new Object[]{this.getClass().getName() + "#compare(Duration duration)" + DatatypeConstants.YEARS.toString(), rhsYears.toString()})
+            
+    					//this.getClass().getName() + "#compare(Duration duration)"
+						//+ " years too large to be supported by this implementation "
+						//+ rhsYears.toString()
+					);
+    	}
+    	BigInteger rhsMonths = (BigInteger) rhs.getField(DatatypeConstants.MONTHS);
+    	if (rhsMonths != null && rhsMonths.compareTo(maxintAsBigInteger) == 1) {
+    		throw new UnsupportedOperationException(
+                        DatatypeMessageFormatter.formatMessage(null, "TooLarge", 
+                            new Object[]{this.getClass().getName() + "#compare(Duration duration)" + DatatypeConstants.MONTHS.toString(), rhsMonths.toString()})
+            
+    					//this.getClass().getName() + "#compare(Duration duration)"
+						//+ " months too large to be supported by this implementation "
+						//+ rhsMonths.toString()
+					);
+    	}
+    	BigInteger rhsDays = (BigInteger) rhs.getField(DatatypeConstants.DAYS);
+    	if (rhsDays != null && rhsDays.compareTo(maxintAsBigInteger) == 1) {
+    		throw new UnsupportedOperationException(
+                        DatatypeMessageFormatter.formatMessage(null, "TooLarge", 
+                            new Object[]{this.getClass().getName() + "#compare(Duration duration)" + DatatypeConstants.DAYS.toString(), rhsDays.toString()})
+            
+    					//this.getClass().getName() + "#compare(Duration duration)"
+						//+ " days too large to be supported by this implementation "
+						//+ rhsDays.toString()
+					);
+    	}
+    	BigInteger rhsHours = (BigInteger) rhs.getField(DatatypeConstants.HOURS);
+    	if (rhsHours != null && rhsHours.compareTo(maxintAsBigInteger) == 1) {
+    		throw new UnsupportedOperationException(
+                        DatatypeMessageFormatter.formatMessage(null, "TooLarge", 
+                            new Object[]{this.getClass().getName() + "#compare(Duration duration)" + DatatypeConstants.HOURS.toString(), rhsHours.toString()})
+            
+    					//this.getClass().getName() + "#compare(Duration duration)"
+						//+ " hours too large to be supported by this implementation "
+						//+ rhsHours.toString()
+					);
+    	}
+    	BigInteger rhsMinutes = (BigInteger) rhs.getField(DatatypeConstants.MINUTES);
+    	if (rhsMinutes != null && rhsMinutes.compareTo(maxintAsBigInteger) == 1) {
+    		throw new UnsupportedOperationException(
+                        DatatypeMessageFormatter.formatMessage(null, "TooLarge", 
+                            new Object[]{this.getClass().getName() + "#compare(Duration duration)" + DatatypeConstants.MINUTES.toString(), rhsMinutes.toString()})
+            
+    					//this.getClass().getName() + "#compare(Duration duration)"
+						//+ " minutes too large to be supported by this implementation "
+						//+ rhsMinutes.toString()
+					);
+    	}
+    	BigDecimal rhsSecondsAsBigDecimal = (BigDecimal) rhs.getField(DatatypeConstants.SECONDS);
+    	BigInteger rhsSeconds = null;
+        if ( rhsSecondsAsBigDecimal != null ) {
+                rhsSeconds =  rhsSecondsAsBigDecimal.toBigInteger();
+        }
+    	if (rhsSeconds != null && rhsSeconds.compareTo(maxintAsBigInteger) == 1) {
+    		throw new UnsupportedOperationException(
+                        DatatypeMessageFormatter.formatMessage(null, "TooLarge", 
+                            new Object[]{this.getClass().getName() + "#compare(Duration duration)" + DatatypeConstants.SECONDS.toString(), rhsSeconds.toString()})
+            
+    					//this.getClass().getName() + "#compare(Duration duration)"
+						//+ " seconds too large to be supported by this implementation "
+						//+ rhsSeconds.toString()
+					);
+    	}
+
+    	// turn this Duration into a GregorianCalendar
+    	GregorianCalendar lhsCalendar = new GregorianCalendar(
+    			1970,
+				1,
+				1,
+				0,
+				0,
+				0);
+   		lhsCalendar.add(GregorianCalendar.YEAR, getYears() * getSign());
+   		lhsCalendar.add(GregorianCalendar.MONTH, getMonths() * getSign());
+   		lhsCalendar.add(GregorianCalendar.DAY_OF_YEAR, getDays() * getSign());
+   		lhsCalendar.add(GregorianCalendar.HOUR_OF_DAY, getHours() * getSign());
+   		lhsCalendar.add(GregorianCalendar.MINUTE, getMinutes() * getSign());
+   		lhsCalendar.add(GregorianCalendar.SECOND, getSeconds() * getSign());
+   		
+   		// turn compare Duration into a GregorianCalendar
+    	GregorianCalendar rhsCalendar = new GregorianCalendar(
+				1970,
+				1,
+				1,
+				0,
+				0,
+				0);
+   		rhsCalendar.add(GregorianCalendar.YEAR, rhs.getYears() * rhs.getSign());
+   		rhsCalendar.add(GregorianCalendar.MONTH, rhs.getMonths() * rhs.getSign());
+   		rhsCalendar.add(GregorianCalendar.DAY_OF_YEAR, rhs.getDays() * rhs.getSign());
+   		rhsCalendar.add(GregorianCalendar.HOUR_OF_DAY, rhs.getHours() * rhs.getSign());
+   		rhsCalendar.add(GregorianCalendar.MINUTE, rhs.getMinutes() * rhs.getSign());
+   		rhsCalendar.add(GregorianCalendar.SECOND, rhs.getSeconds() * rhs.getSign());
+   	
+   		
+   		if (lhsCalendar.equals(rhsCalendar)) {
+   			return DatatypeConstants.EQUAL;
+   		}
+
+   		return compareDates(this, rhs);
+    }
+    
+    /**
+     * Compares 2 given durations. (refer to W3C Schema Datatypes "3.2.6 duration")
+     *
+     * @param duration1  Unnormalized duration
+     * @param duration2  Unnormalized duration
+     * @return INDETERMINATE if the order relationship between date1 and date2 is indeterminate.
+     * EQUAL if the order relation between date1 and date2 is EQUAL.
+     * If the strict parameter is true, return LESS_THAN if date1 is less than date2 and
+     * return GREATER_THAN if date1 is greater than date2.
+     * If the strict parameter is false, return LESS_THAN if date1 is less than OR equal to date2 and
+     * return GREATER_THAN if date1 is greater than OR equal to date2
+     */
+    private int compareDates(Duration duration1, Duration duration2) {
+        
+        int resultA = DatatypeConstants.INDETERMINATE; 
+        int resultB = DatatypeConstants.INDETERMINATE;
+        
+        XMLGregorianCalendar tempA = (XMLGregorianCalendar)TEST_POINTS[0].clone();
+        XMLGregorianCalendar tempB = (XMLGregorianCalendar)TEST_POINTS[0].clone();
+        
+        //long comparison algorithm is required
+        tempA.add(duration1);
+        tempB.add(duration2);
+        resultA =  tempA.compare(tempB);
+        if ( resultA == DatatypeConstants.INDETERMINATE ) {
+            return DatatypeConstants.INDETERMINATE;
+        }
+
+        tempA = (XMLGregorianCalendar)TEST_POINTS[1].clone();
+        tempB = (XMLGregorianCalendar)TEST_POINTS[1].clone();
+        
+        tempA.add(duration1);
+        tempB.add(duration2);
+        resultB = tempA.compare(tempB);
+        resultA = compareResults(resultA, resultB);
+        if (resultA == DatatypeConstants.INDETERMINATE) {
+            return DatatypeConstants.INDETERMINATE;
+        }
+
+        tempA = (XMLGregorianCalendar)TEST_POINTS[2].clone();
+        tempB = (XMLGregorianCalendar)TEST_POINTS[2].clone();
+        
+        tempA.add(duration1);
+        tempB.add(duration2);
+        resultB = tempA.compare(tempB);
+        resultA = compareResults(resultA, resultB);
+        if (resultA == DatatypeConstants.INDETERMINATE) {
+            return DatatypeConstants.INDETERMINATE;
+        }
+
+        tempA = (XMLGregorianCalendar)TEST_POINTS[3].clone();
+        tempB = (XMLGregorianCalendar)TEST_POINTS[3].clone();
+        
+        tempA.add(duration1);
+        tempB.add(duration2);
+        resultB = tempA.compare(tempB);
+        resultA = compareResults(resultA, resultB);
+
+        return resultA;
+    }
+
+    private int compareResults(int resultA, int resultB) {
+
+        if ( resultB == DatatypeConstants.INDETERMINATE ) {
+            return DatatypeConstants.INDETERMINATE;
+        }
+        else if ( resultA!=resultB) {
+            return DatatypeConstants.INDETERMINATE;
+        }
+        return resultA;
+    }
+    
+    /**
+     * Returns a hash code consistent with the definition of the equals method.
+     * 
+     * @see Object#hashCode() 
+     */
+    @Override
+    public int hashCode() {
+        // component wise hash is not correct because 1day = 24hours
+        Calendar cal = TEST_POINTS[0].toGregorianCalendar();
+        this.addTo(cal);
+        return (int) getCalendarTimeInMillis(cal);
+    }
+    
+    /**
+     * Returns a string representation of this duration object.
+     * 
+     * <p>
+     * The result is formatter according to the XML Schema 1.0
+     * spec and can be always parsed back later into the
+     * equivalent duration object by
+     * the {@link #DurationImpl(String)} constructor.
+     * 
+     * <p>
+     * Formally, the following holds for any {@link Duration}
+     * object x. 
+     * <pre>
+     * new Duration(x.toString()).equals(x)
+     * </pre>
+     * 
+     * @return
+     *      Always return a non-null valid String object.
+     */
+    @Override
+    public String toString() {
+        StringBuffer buf = new StringBuffer();
+        if (signum < 0) {
+            buf.append('-');
+        }
+        buf.append('P');
+        
+        if (years != null) {
+            buf.append(years).append('Y');
+        }
+        if (months != null) {
+            buf.append(months).append('M');
+        }
+        if (days != null) {
+            buf.append(days).append('D');
+        }
+
+        if (hours != null || minutes != null || seconds != null) {
+            buf.append('T');
+            if (hours != null) {
+                buf.append(hours).append('H');
+            }
+            if (minutes != null) {
+                buf.append(minutes).append('M');
+            }
+            if (seconds != null) {
+                buf.append(toString(seconds)).append('S');
+            }
+        }
+        
+        return buf.toString();
+    }
+
+    /**
+     * <p>Turns {@link BigDecimal} to a string representation.</p>
+     * 
+     * <p>Due to a behavior change in the {@link BigDecimal#toString()}
+     * method in JDK1.5, this had to be implemented here.</p>
+     * 
+     * @param bd <code>BigDecimal</code> to format as a <code>String</code>
+     * 
+     * @return  <code>String</code> representation of <code>BigDecimal</code> 
+     */
+    private String toString(BigDecimal bd) {
+        String intString = bd.unscaledValue().toString();
+        int scale = bd.scale();
+
+        if (scale == 0) {
+            return intString;
+        }
+
+        /* Insert decimal point */
+        StringBuffer buf;
+        int insertionPoint = intString.length() - scale;
+        if (insertionPoint == 0) { /* Point goes right before intVal */
+            return "0." + intString;
+        } 
+        else if (insertionPoint > 0) { /* Point goes inside intVal */
+            buf = new StringBuffer(intString);
+            buf.insert(insertionPoint, '.');
+        } 
+        else { /* We must insert zeros between point and intVal */
+            buf = new StringBuffer(3 - insertionPoint + intString.length());
+            buf.append("0.");
+            for (int i = 0; i < -insertionPoint; i++) {
+                buf.append('0');
+            }
+            buf.append(intString);
+        }
+        return buf.toString();
+    }
+
+    /**
+     * Checks if a field is set.
+     * 
+     * A field of a duration object may or may not be present.
+     * This method can be used to test if a field is present.
+     * 
+     * @param field
+     *      one of the six Field constants (YEARS,MONTHS,DAYS,HOURS,
+     *      MINUTES, or SECONDS.)
+     * @return
+     *      true if the field is present. false if not.
+     * 
+     * @throws NullPointerException
+     *      If the field parameter is null.
+     */
+    @Override
+    public boolean isSet(DatatypeConstants.Field field) {
+    	
+    	if (field == null) {
+            String methodName = "javax.xml.datatype.Duration" + "#isSet(DatatypeConstants.Field field)" ;
+    		throw new NullPointerException(                
+                //"cannot be called with field == null"
+                DatatypeMessageFormatter.formatMessage(null, "FieldCannotBeNull", new Object[]{methodName})                
+    		);
+    	}
+    	
+    	if (field == DatatypeConstants.YEARS) {
+			return years != null;
+    	}
+
+		if (field == DatatypeConstants.MONTHS) {
+			return months != null;
+		}
+
+		if (field == DatatypeConstants.DAYS) {
+			return days != null;
+		}
+
+		if (field == DatatypeConstants.HOURS) {
+			return hours != null;
+		}
+
+		if (field == DatatypeConstants.MINUTES) {
+			return minutes != null;
+		}
+		
+		if (field == DatatypeConstants.SECONDS) {
+			return seconds != null;
+		}
+        String methodName = "javax.xml.datatype.Duration" + "#isSet(DatatypeConstants.Field field)";
+        
+        throw new IllegalArgumentException(
+            DatatypeMessageFormatter.formatMessage(null,"UnknownField", new Object[]{methodName, field.toString()})			
+		);
+		
+    }
+    
+    /**
+     * Gets the value of a field. 
+     * 
+     * Fields of a duration object may contain arbitrary large value.
+     * Therefore this method is designed to return a {@link Number} object.
+     * 
+     * In case of YEARS, MONTHS, DAYS, HOURS, and MINUTES, the returned
+     * number will be a non-negative integer. In case of seconds,
+     * the returned number may be a non-negative decimal value.
+     * 
+     * @param field
+     *      one of the six Field constants (YEARS,MONTHS,DAYS,HOURS,
+     *      MINUTES, or SECONDS.)
+     * @return
+     *      If the specified field is present, this method returns
+     *      a non-null non-negative {@link Number} object that
+     *      represents its value. If it is not present, return null.
+     *      For YEARS, MONTHS, DAYS, HOURS, and MINUTES, this method
+     *      returns a {@link BigInteger} object. For SECONDS, this
+     *      method returns a {@link BigDecimal}. 
+     * 
+     * @throws NullPointerException
+     *      If the field parameter is null.
+     */
+    @Override
+    public Number getField(DatatypeConstants.Field field) {
+
+		if (field == null) {
+            String methodName = "javax.xml.datatype.Duration" + "#isSet(DatatypeConstants.Field field) " ;
+            
+			throw new NullPointerException(				
+                DatatypeMessageFormatter.formatMessage(null,"FieldCannotBeNull", new Object[]{methodName})
+                );
+		}
+    	
+		if (field == DatatypeConstants.YEARS) {
+			return years;
+		}
+
+		if (field == DatatypeConstants.MONTHS) {
+			return months;
+		}
+
+		if (field == DatatypeConstants.DAYS) {
+			return days;
+		}
+
+		if (field == DatatypeConstants.HOURS) {
+			return hours;
+		}
+
+		if (field == DatatypeConstants.MINUTES) {
+			return minutes;
+		}
+		
+		if (field == DatatypeConstants.SECONDS) {
+			return seconds;
+		}
+		/**
+		throw new IllegalArgumentException(
+			"javax.xml.datatype.Duration"
+			+ "#(getSet(DatatypeConstants.Field field) called with an unknown field: "
+			+ field.toString()
+		);
+        */
+        String methodName = "javax.xml.datatype.Duration" + "#(getSet(DatatypeConstants.Field field)";
+        
+        throw new IllegalArgumentException(
+            DatatypeMessageFormatter.formatMessage(null,"UnknownField", new Object[]{methodName, field.toString()})			
+		);
+        
+    }
+    
+    /**
+     * Obtains the value of the YEARS field as an integer value,
+     * or 0 if not present.
+     * 
+     * <p>
+     * This method is a convenience method around the 
+     * {@link #getField(DatatypeConstants.Field)} method.
+     * 
+     * <p>
+     * Note that since this method returns <tt>int</tt>, this
+     * method will return an incorrect value for {@link Duration}s
+     * with the year field that goes beyond the range of <tt>int</tt>.
+     * Use <code>getField(YEARS)</code> to avoid possible loss of precision.</p>
+     * 
+     * @return
+     *      If the YEARS field is present, return
+     *      its value as an integer by using the {@link Number#intValue()}
+     *      method. If the YEARS field is not present, return 0.
+     */
+    @Override
+    public int getYears() {
+        return getInt(DatatypeConstants.YEARS);
+    }
+    
+    /**
+     * Obtains the value of the MONTHS field as an integer value,
+     * or 0 if not present.
+     * 
+     * This method works just like {@link #getYears()} except
+     * that this method works on the MONTHS field.
+     * 
+     * @return Months of this <code>Duration</code>.
+     */
+    @Override
+    public int getMonths() {
+        return getInt(DatatypeConstants.MONTHS);
+    }
+    
+    /**
+     * Obtains the value of the DAYS field as an integer value,
+     * or 0 if not present.
+     * 
+     * This method works just like {@link #getYears()} except
+     * that this method works on the DAYS field.
+     * 
+     * @return Days of this <code>Duration</code>.
+     */
+    @Override
+    public int getDays() {
+        return getInt(DatatypeConstants.DAYS);
+    }
+    
+    /**
+     * Obtains the value of the HOURS field as an integer value,
+     * or 0 if not present.
+     * 
+     * This method works just like {@link #getYears()} except
+     * that this method works on the HOURS field.
+     * 
+     * @return Hours of this <code>Duration</code>.
+     * 
+     */
+    @Override
+    public int getHours() {
+        return getInt(DatatypeConstants.HOURS);
+    }
+    
+    /**
+     * Obtains the value of the MINUTES field as an integer value,
+     * or 0 if not present.
+     * 
+     * This method works just like {@link #getYears()} except
+     * that this method works on the MINUTES field.
+     * 
+     * @return Minutes of this <code>Duration</code>.
+     * 
+     */
+    @Override
+    public int getMinutes() {
+        return getInt(DatatypeConstants.MINUTES);
+    }
+    
+    /**
+     * Obtains the value of the SECONDS field as an integer value,
+     * or 0 if not present.
+     * 
+     * This method works just like {@link #getYears()} except
+     * that this method works on the SECONDS field.
+     * 
+     * @return seconds in the integer value. The fraction of seconds
+     *   will be discarded (for example, if the actual value is 2.5,
+     *   this method returns 2)
+     */
+    @Override
+    public int getSeconds() {
+        return getInt(DatatypeConstants.SECONDS);
+    }
+    
+    /**
+     * <p>Return the requested field value as an int.</p>
+     * 
+     * <p>If field is not set, i.e. == null, 0 is returned.</p>
+     * 
+     * @param field To get value for.
+     * 
+     * @return int value of field or 0 if field is not set.
+     */
+    private int getInt(DatatypeConstants.Field field) {
+        Number n = getField(field);
+        if (n == null) {
+            return 0;
+        } 
+        else {
+            return n.intValue();
+        }
+    }
+        
+    /**
+     * <p>Returns the length of the duration in milli-seconds.</p>
+     * 
+     * <p>If the seconds field carries more digits than milli-second order,
+     * those will be simply discarded (or in other words, rounded to zero.)  
+     * For example, for any Calendar value <code>x<code>,</p>
+     * <pre>
+     * <code>new Duration("PT10.00099S").getTimeInMills(x) == 10000</code>.
+     * <code>new Duration("-PT10.00099S").getTimeInMills(x) == -10000</code>.
+     * </pre>
+     * 
+     * <p>
+     * Note that this method uses the {@link #addTo(Calendar)} method,
+     * which may work incorectly with {@link Duration} objects with
+     * very large values in its fields. See the {@link #addTo(Calendar)}
+     * method for details.
+     * 
+     * @param startInstant
+     *      The length of a month/year varies. The <code>startInstant</code> is
+     *      used to disambiguate this variance. Specifically, this method
+     *      returns the difference between <code>startInstant</code> and
+     *      <code>startInstant+duration</code>
+     * 
+     * @return milliseconds between <code>startInstant</code> and
+     *   <code>startInstant</code> plus this <code>Duration</code>
+     *
+     * @throws NullPointerException if <code>startInstant</code> parameter 
+     * is null.
+     * 
+     */
+    @Override
+    public long getTimeInMillis(final Calendar startInstant) {
+        Calendar cal = (Calendar) startInstant.clone();
+        addTo(cal);
+        return getCalendarTimeInMillis(cal) - getCalendarTimeInMillis(startInstant);
+    }
+    
+    /**
+     * <p>Returns the length of the duration in milli-seconds.</p>
+     * 
+     * <p>If the seconds field carries more digits than milli-second order,
+     * those will be simply discarded (or in other words, rounded to zero.)
+     * For example, for any <code>Date</code> value <code>x<code>,</p>   
+     * <pre>
+     * <code>new Duration("PT10.00099S").getTimeInMills(x) == 10000</code>.
+     * <code>new Duration("-PT10.00099S").getTimeInMills(x) == -10000</code>.
+     * </pre>
+     * 
+     * <p>
+     * Note that this method uses the {@link #addTo(Date)} method,
+     * which may work incorectly with {@link Duration} objects with
+     * very large values in its fields. See the {@link #addTo(Date)}
+     * method for details.
+     * 
+     * @param startInstant
+     *      The length of a month/year varies. The <code>startInstant</code> is
+     *      used to disambiguate this variance. Specifically, this method
+     *      returns the difference between <code>startInstant</code> and
+     *      <code>startInstant+duration</code>.
+     * 
+     * @throws NullPointerException
+     *      If the startInstant parameter is null.
+     * 
+     * @return milliseconds between <code>startInstant</code> and
+     *   <code>startInstant</code> plus this <code>Duration</code>
+     *
+     * @see #getTimeInMillis(Calendar)
+     */
+    @Override
+    public long getTimeInMillis(final Date startInstant) {
+        Calendar cal = new GregorianCalendar();
+        cal.setTime(startInstant);
+        this.addTo(cal);
+        return getCalendarTimeInMillis(cal) - startInstant.getTime();
+    }
+    
+//    /**
+//     * Returns an equivalent but "normalized" duration value.
+//     * 
+//     * Intuitively, the normalization moves YEARS into
+//     * MONTHS (by x12) and moves DAYS, HOURS, and MINUTES fields
+//     * into SECONDS (by x86400, x3600, and x60 respectively.)
+//     * 
+//     * 
+//     * Formally, this method satisfies the following conditions:
+//     * <ul>
+//     *  <li>x.normalize().equals(x)
+//     *  <li>!x.normalize().isSet(Duration.YEARS)
+//     *  <li>!x.normalize().isSet(Duration.DAYS)
+//     *  <li>!x.normalize().isSet(Duration.HOURS)
+//     *  <li>!x.normalize().isSet(Duration.MINUTES)
+//     * </ul>
+//     * 
+//     * @return
+//     *      always return a non-null valid value. 
+//     */
+//    public Duration normalize() {
+//        return null;
+//    }
+    
+    /**
+     * <p>Converts the years and months fields into the days field
+     * by using a specific time instant as the reference point.</p>
+     * 
+     * <p>For example, duration of one month normalizes to 31 days
+     * given the start time instance "July 8th 2003, 17:40:32".</p>
+     * 
+     * <p>Formally, the computation is done as follows:</p>
+     * <ol>
+     *  <li>The given Calendar object is cloned.
+     *  <li>The years, months and days fields will be added to
+     *      the {@link Calendar} object
+     *      by using the {@link Calendar#add(int,int)} method. 
+     *  <li>The difference between two Calendars are computed in terms of days.
+     *  <li>The computed days, along with the hours, minutes and seconds
+     *      fields of this duration object is used to construct a new
+     *      Duration object.
+     * </ol>
+     * 
+     * <p>Note that since the Calendar class uses <code>int</code> to
+     * hold the value of year and month, this method may produce
+     * an unexpected result if this duration object holds
+     * a very large value in the years or months fields.</p>
+     *
+     * @param startTimeInstant <code>Calendar</code> reference point.
+     *  
+     * @return <code>Duration</code> of years and months of this <code>Duration</code> as days.
+     * 
+     * @throws NullPointerException If the startTimeInstant parameter is null.
+     */
+    @Override
+    public Duration normalizeWith(Calendar startTimeInstant) {
+
+        Calendar c = (Calendar) startTimeInstant.clone();
+
+        // using int may cause overflow, but 
+        // Calendar internally treats value as int anyways.
+        c.add(Calendar.YEAR, getYears() * signum);
+        c.add(Calendar.MONTH, getMonths() * signum);
+        c.add(Calendar.DAY_OF_MONTH, getDays() * signum);
+
+        // obtain the difference in terms of days
+        long diff = getCalendarTimeInMillis(c) - getCalendarTimeInMillis(startTimeInstant);
+        int days = (int) (diff / (1000L * 60L * 60L * 24L));
+
+        return new DurationImpl(
+                days >= 0,
+                null,
+                null,
+                wrap(Math.abs(days)),
+                (BigInteger) getField(DatatypeConstants.HOURS),
+                (BigInteger) getField(DatatypeConstants.MINUTES),
+                (BigDecimal) getField(DatatypeConstants.SECONDS));
+    }
+    
+    /**
+     * <p>Computes a new duration whose value is <code>factor</code> times
+     * longer than the value of this duration.</p>
+     * 
+     * <p>This method is provided for the convenience.
+     * It is functionally equivalent to the following code:</p>
+     * <pre>
+     * multiply(new BigDecimal(String.valueOf(factor)))
+     * </pre>
+     * 
+     * @param factor Factor times longer of new <code>Duration</code> to create.
+     * 
+     * @return New <code>Duration</code> that is <code>factor</code>times longer than this <code>Duration</code>.
+     * 
+     * @see #multiply(BigDecimal)
+     */
+    @Override
+    public Duration multiply(int factor) {
+        return multiply(BigDecimal.valueOf(factor));
+    }
+    
+    /**
+     * Computes a new duration whose value is <code>factor</code> times
+     * longer than the value of this duration.
+     * 
+     * <p>
+     * For example,
+     * <pre>
+     * "P1M" (1 month) * "12" = "P12M" (12 months)
+     * "PT1M" (1 min) * "0.3" = "PT18S" (18 seconds)
+     * "P1M" (1 month) * "1.5" = IllegalStateException
+     * </pre>
+     *  
+     * <p>
+     * Since the {@link Duration} class is immutable, this method
+     * doesn't change the value of this object. It simply computes
+     * a new Duration object and returns it.
+     * 
+     * <p>
+     * The operation will be performed field by field with the precision
+     * of {@link BigDecimal}. Since all the fields except seconds are
+     * restricted to hold integers,
+     * any fraction produced by the computation will be
+     * carried down toward the next lower unit. For example,
+     * if you multiply "P1D" (1 day) with "0.5", then it will be 0.5 day,
+     * which will be carried down to "PT12H" (12 hours).
+     * When fractions of month cannot be meaningfully carried down
+     * to days, or year to months, this will cause an
+     * {@link IllegalStateException} to be thrown. 
+     * For example if you multiple one month by 0.5.</p>
+     * 
+     * <p>
+     * To avoid {@link IllegalStateException}, use
+     * the {@link #normalizeWith(Calendar)} method to remove the years
+     * and months fields.
+     * 
+     * @param factor to multiply by
+     * 
+     * @return
+     *      returns a non-null valid {@link Duration} object
+     *
+     * @throws IllegalStateException if operation produces fraction in 
+     * the months field.
+     *
+     * @throws NullPointerException if the <code>factor</code> parameter is 
+     * <code>null</code>.
+     *
+     */
+    @Override
+    public Duration multiply(BigDecimal factor) {
+        BigDecimal carry = ZERO;
+        int factorSign = factor.signum();
+        factor = factor.abs();
+        
+        BigDecimal[] buf = new BigDecimal[6];
+        
+        for (int i = 0; i < 5; i++) {
+            BigDecimal bd = getFieldAsBigDecimal(FIELDS[i]);
+            bd = bd.multiply(factor).add(carry);
+            
+            buf[i] = bd.setScale(0, BigDecimal.ROUND_DOWN);
+            
+            bd = bd.subtract(buf[i]);
+            if (i == 1) {
+                if (bd.signum() != 0) {
+                    throw new IllegalStateException(); // illegal carry-down
+                } else {
+                    carry = ZERO;
+                }
+            } 
+            else {
+                carry = bd.multiply(FACTORS[i]);
+            }
+        }
+        
+        if (seconds != null) {
+            buf[5] = seconds.multiply(factor).add(carry);
+        } 
+        else {
+            buf[5] = carry;
+        }
+                
+        return new DurationImpl(
+            this.signum * factorSign >= 0,
+            toBigInteger(buf[0], null == years),
+            toBigInteger(buf[1], null == months),
+            toBigInteger(buf[2], null == days),
+            toBigInteger(buf[3], null == hours),
+            toBigInteger(buf[4], null == minutes),
+            (buf[5].signum() == 0 && seconds == null) ? null : buf[5]);
+    }
+    
+    /**
+     * <p>Gets the value of the field as a {@link BigDecimal}.</p>
+     * 
+     * <p>If the field is unset, return 0.</p>
+     * 
+     * @param f Field to get value for.
+     * 
+     * @return  non-null valid {@link BigDecimal}.
+     */
+    private BigDecimal getFieldAsBigDecimal(DatatypeConstants.Field f) {
+        if (f == DatatypeConstants.SECONDS) {
+            if (seconds != null) {
+                return seconds;
+            } 
+            else {
+                return ZERO;
+            }
+        } 
+        else {
+            BigInteger bi = (BigInteger) getField(f);
+            if (bi == null) {
+                return ZERO;
+            } 
+            else {
+                return new BigDecimal(bi);
+            }
+        }
+    }
+    
+    /**
+     * <p>BigInteger value of BigDecimal value.</p>
+     * 
+     * @param value Value to convert.
+     * @param canBeNull Can returned value be null?
+     * 
+     * @return BigInteger value of BigDecimal, possibly null.
+     */
+    private static BigInteger toBigInteger(
+        BigDecimal value,
+        boolean canBeNull) {
+        if (canBeNull && value.signum() == 0) {
+            return null;
+        } 
+        else {
+            return value.unscaledValue();
+        }
+    }
+    
+    /**
+     * 1 unit of FIELDS[i] is equivalent to <code>FACTORS[i]</code> unit of
+     * FIELDS[i+1].
+     */
+    private static final BigDecimal[] FACTORS = new BigDecimal[] {
+        BigDecimal.valueOf(12),
+        null/*undefined*/,
+        BigDecimal.valueOf(24),
+        BigDecimal.valueOf(60),
+        BigDecimal.valueOf(60)
+    };    
+    
+    /**
+     * <p>Computes a new duration whose value is <code>this+rhs</code>.</p>
+     * 
+     * <p>For example,</p>
+     * <pre>
+     * "1 day" + "-3 days" = "-2 days"
+     * "1 year" + "1 day" = "1 year and 1 day"
+     * "-(1 hour,50 minutes)" + "-20 minutes" = "-(1 hours,70 minutes)"
+     * "15 hours" + "-3 days" = "-(2 days,9 hours)"
+     * "1 year" + "-1 day" = IllegalStateException
+     * </pre>
+     * 
+     * <p>Since there's no way to meaningfully subtract 1 day from 1 month,
+     * there are cases where the operation fails in
+     * {@link IllegalStateException}.</p> 
+     * 
+     * <p>
+     * Formally, the computation is defined as follows.</p>
+     * <p>
+     * Firstly, we can assume that two {@link Duration}s to be added
+     * are both positive without losing generality (i.e.,
+     * <code>(-X)+Y=Y-X</code>, <code>X+(-Y)=X-Y</code>,
+     * <code>(-X)+(-Y)=-(X+Y)</code>)
+     * 
+     * <p>
+     * Addition of two positive {@link Duration}s are simply defined as  
+     * field by field addition where missing fields are treated as 0.
+     * <p>
+     * A field of the resulting {@link Duration} will be unset if and
+     * only if respective fields of two input {@link Duration}s are unset. 
+     * <p>
+     * Note that <code>lhs.add(rhs)</code> will be always successful if
+     * <code>lhs.signum()*rhs.signum()!=-1</code> or both of them are
+     * normalized.</p>
+     * 
+     * @param rhs <code>Duration</code> to add to this <code>Duration</code>
+     * 
+     * @return
+     *      non-null valid Duration object.
+     * 
+     * @throws NullPointerException
+     *      If the rhs parameter is null.
+     * @throws IllegalStateException
+     *      If two durations cannot be meaningfully added. For
+     *      example, adding negative one day to one month causes
+     *      this exception.
+     * 
+     * 
+     * @see #subtract(Duration)
+     */
+    @Override
+    public Duration add(final Duration rhs) {
+        Duration lhs = this;
+        BigDecimal[] buf = new BigDecimal[6];
+        
+        buf[0] = sanitize((BigInteger) lhs.getField(DatatypeConstants.YEARS),
+        	lhs.getSign()).add(sanitize((BigInteger) rhs.getField(DatatypeConstants.YEARS),  rhs.getSign()));
+        buf[1] = sanitize((BigInteger) lhs.getField(DatatypeConstants.MONTHS),
+        	lhs.getSign()).add(sanitize((BigInteger) rhs.getField(DatatypeConstants.MONTHS), rhs.getSign()));
+        buf[2] = sanitize((BigInteger) lhs.getField(DatatypeConstants.DAYS),
+        	lhs.getSign()).add(sanitize((BigInteger) rhs.getField(DatatypeConstants.DAYS),   rhs.getSign()));
+        buf[3] = sanitize((BigInteger) lhs.getField(DatatypeConstants.HOURS),
+        	lhs.getSign()).add(sanitize((BigInteger) rhs.getField(DatatypeConstants.HOURS),  rhs.getSign()));
+        buf[4] = sanitize((BigInteger) lhs.getField(DatatypeConstants.MINUTES),
+        	lhs.getSign()).add(sanitize((BigInteger) rhs.getField(DatatypeConstants.MINUTES), rhs.getSign()));
+        buf[5] = sanitize((BigDecimal) lhs.getField(DatatypeConstants.SECONDS),
+        	lhs.getSign()).add(sanitize((BigDecimal) rhs.getField(DatatypeConstants.SECONDS), rhs.getSign()));
+        
+        // align sign
+        alignSigns(buf, 0, 2); // Y,M
+        alignSigns(buf, 2, 6); // D,h,m,s
+        
+        // make sure that the sign bit is consistent across all 6 fields.
+        int s = 0;
+        for (int i = 0; i < 6; i++) {
+            if (s * buf[i].signum() < 0) {
+                throw new IllegalStateException();
+            }
+            if (s == 0) {
+                s = buf[i].signum();
+            }
+        }
+        
+        return new DurationImpl(
+            s >= 0,
+            toBigInteger(sanitize(buf[0], s),
+            	lhs.getField(DatatypeConstants.YEARS) == null && rhs.getField(DatatypeConstants.YEARS) == null),
+            toBigInteger(sanitize(buf[1], s),
+            	lhs.getField(DatatypeConstants.MONTHS) == null && rhs.getField(DatatypeConstants.MONTHS) == null),
+            toBigInteger(sanitize(buf[2], s),
+            	lhs.getField(DatatypeConstants.DAYS) == null && rhs.getField(DatatypeConstants.DAYS) == null),
+            toBigInteger(sanitize(buf[3], s),
+            	lhs.getField(DatatypeConstants.HOURS) == null && rhs.getField(DatatypeConstants.HOURS) == null),
+            toBigInteger(sanitize(buf[4], s),
+            	lhs.getField(DatatypeConstants.MINUTES) == null && rhs.getField(DatatypeConstants.MINUTES) == null),
+             (buf[5].signum() == 0
+             && lhs.getField(DatatypeConstants.SECONDS) == null
+             && rhs.getField(DatatypeConstants.SECONDS) == null) ? null : sanitize(buf[5], s));
+    }
+    
+    private static void alignSigns(BigDecimal[] buf, int start, int end) {
+        // align sign
+        boolean touched;
+        
+        do { // repeat until all the sign bits become consistent
+            touched = false;
+            int s = 0; // sign of the left fields
+
+            for (int i = start; i < end; i++) {
+                if (s * buf[i].signum() < 0) {
+                    // this field has different sign than its left field.
+                    touched = true;
+
+                    // compute the number of unit that needs to be borrowed.
+                    BigDecimal borrow =
+                        buf[i].abs().divide(
+                            FACTORS[i - 1],
+                            BigDecimal.ROUND_UP);
+                    if (buf[i].signum() > 0) {
+                        borrow = borrow.negate();
+                    }
+
+                    // update values
+                    buf[i - 1] = buf[i - 1].subtract(borrow);
+                    buf[i] = buf[i].add(borrow.multiply(FACTORS[i - 1]));
+                }
+                if (buf[i].signum() != 0) {
+                    s = buf[i].signum();
+                }
+            }
+        } while (touched);
+    }
+    
+    /**
+     * Compute <code>value*signum</code> where value==null is treated as
+     * value==0.
+     * @param value Value to sanitize.
+     * @param signum 0 to sanitize to 0, > 0 to sanitize to <code>value</code>, < 0 to sanitize to negative <code>value</code>.
+     *
+     * @return non-null {@link BigDecimal}.
+     */
+    private static BigDecimal sanitize(BigInteger value, int signum) {
+        if (signum == 0 || value == null) {
+            return ZERO;
+        }
+        if (signum > 0) {
+            return new BigDecimal(value);
+        }
+        return new BigDecimal(value.negate());
+    }
+        
+    /**
+     * <p>Compute <code>value*signum</code> where <code>value==null</code> is treated as <code>value==0</code></p>.
+     * 
+     * @param value Value to sanitize.
+     * @param signum 0 to sanitize to 0, > 0 to sanitize to <code>value</code>, < 0 to sanitize to negative <code>value</code>.
+     * 
+     * @return non-null {@link BigDecimal}.
+     */
+    static BigDecimal sanitize(BigDecimal value, int signum) {
+        if (signum == 0 || value == null) {
+            return ZERO;
+        }
+        if (signum > 0) {
+            return value;
+        }
+        return value.negate();
+    }
+    
+    /**
+     * <p>Computes a new duration whose value is <code>this-rhs</code>.</p>
+     * 
+     * <p>For example:</p>
+     * <pre>
+     * "1 day" - "-3 days" = "4 days"
+     * "1 year" - "1 day" = IllegalStateException
+     * "-(1 hour,50 minutes)" - "-20 minutes" = "-(1hours,30 minutes)"
+     * "15 hours" - "-3 days" = "3 days and 15 hours"
+     * "1 year" - "-1 day" = "1 year and 1 day"
+     * </pre>
+     * 
+     * <p>Since there's no way to meaningfully subtract 1 day from 1 month,
+     * there are cases where the operation fails in {@link IllegalStateException}.</p> 
+     * 
+     * <p>Formally the computation is defined as follows.
+     * First, we can assume that two {@link Duration}s are both positive
+     * without losing generality.  (i.e.,
+     * <code>(-X)-Y=-(X+Y)</code>, <code>X-(-Y)=X+Y</code>,
+     * <code>(-X)-(-Y)=-(X-Y)</code>)</p>
+     *  
+     * <p>Then two durations are subtracted field by field.
+     * If the sign of any non-zero field <tt>F</tt> is different from
+     * the sign of the most significant field,
+     * 1 (if <tt>F</tt> is negative) or -1 (otherwise)
+     * will be borrowed from the next bigger unit of <tt>F</tt>.</p>
+     * 
+     * <p>This process is repeated until all the non-zero fields have
+     * the same sign.</p> 
+     * 
+     * <p>If a borrow occurs in the days field (in other words, if
+     * the computation needs to borrow 1 or -1 month to compensate
+     * days), then the computation fails by throwing an
+     * {@link IllegalStateException}.</p>
+     * 
+     * @param rhs <code>Duration</code> to substract from this <code>Duration</code>.
+     *  
+     * @return New <code>Duration</code> created from subtracting <code>rhs</code> from this <code>Duration</code>.
+     * 
+     * @throws IllegalStateException
+     *      If two durations cannot be meaningfully subtracted. For
+     *      example, subtracting one day from one month causes
+     *      this exception.
+     * 
+     * @throws NullPointerException
+     *      If the rhs parameter is null.
+     * 
+     * @see #add(Duration)
+     */
+    @Override
+    public Duration subtract(final Duration rhs) {
+        return add(rhs.negate());
+    }
+    
+    /**
+     * Returns a new {@link Duration} object whose
+     * value is <code>-this</code>.
+     * 
+     * <p>
+     * Since the {@link Duration} class is immutable, this method
+     * doesn't change the value of this object. It simply computes
+     * a new Duration object and returns it.
+     * 
+     * @return
+     *      always return a non-null valid {@link Duration} object.
+     */
+    @Override
+    public Duration negate() {
+        return new DurationImpl(
+            signum <= 0,
+            years,
+            months,
+            days,
+            hours,
+            minutes,
+            seconds);
+    }
+    
+    /**
+     * Returns the sign of this duration in -1,0, or 1.
+     * 
+     * @return
+     *      -1 if this duration is negative, 0 if the duration is zero,
+     *      and 1 if the duration is postive.
+     */
+    public int signum() {
+        return signum;
+    }
+    
+    
+    /**
+     * Adds this duration to a {@link Calendar} object.
+     * 
+     * <p>
+     * Calls {@link java.util.Calendar#add(int,int)} in the
+     * order of YEARS, MONTHS, DAYS, HOURS, MINUTES, SECONDS, and MILLISECONDS
+     * if those fields are present. Because the {@link Calendar} class
+     * uses int to hold values, there are cases where this method
+     * won't work correctly (for example if values of fields
+     * exceed the range of int.) 
+     * </p>
+     * 
+     * <p>
+     * Also, since this duration class is a Gregorian duration, this
+     * method will not work correctly if the given {@link Calendar}
+     * object is based on some other calendar systems. 
+     * </p>
+     * 
+     * <p>
+     * Any fractional parts of this {@link Duration} object
+     * beyond milliseconds will be simply ignored. For example, if
+     * this duration is "P1.23456S", then 1 is added to SECONDS,
+     * 234 is added to MILLISECONDS, and the rest will be unused. 
+     * </p>
+     * 
+     * <p>
+     * Note that because {@link Calendar#add(int, int)} is using
+     * <tt>int</tt>, {@link Duration} with values beyond the
+     * range of <tt>int</tt> in its fields
+     * will cause overflow/underflow to the given {@link Calendar}.
+     * {@link XMLGregorianCalendar#add(Duration)} provides the same
+     * basic operation as this method while avoiding
+     * the overflow/underflow issues.
+     * 
+     * @param calendar
+     *      A calendar object whose value will be modified.
+     * @throws NullPointerException
+     *      if the calendar parameter is null.
+     */
+    @Override
+    public void addTo(Calendar calendar) {
+        calendar.add(Calendar.YEAR, getYears() * signum);
+        calendar.add(Calendar.MONTH, getMonths() * signum);
+        calendar.add(Calendar.DAY_OF_MONTH, getDays() * signum);
+        calendar.add(Calendar.HOUR, getHours() * signum);
+        calendar.add(Calendar.MINUTE, getMinutes() * signum);
+        calendar.add(Calendar.SECOND, getSeconds() * signum);
+
+        if (seconds != null) {
+            BigDecimal fraction =
+                seconds.subtract(seconds.setScale(0, BigDecimal.ROUND_DOWN));
+            int millisec = fraction.movePointRight(3).intValue();
+            calendar.add(Calendar.MILLISECOND, millisec * signum);
+        }
+    }
+    
+    /**
+     * Adds this duration to a {@link Date} object.
+     * 
+     * <p>
+     * The given date is first converted into
+     * a {@link java.util.GregorianCalendar}, then the duration
+     * is added exactly like the {@link #addTo(Calendar)} method.
+     * 
+     * <p>
+     * The updated time instant is then converted back into a
+     * {@link Date} object and used to update the given {@link Date} object.
+     * 
+     * <p>
+     * This somewhat redundant computation is necessary to unambiguously
+     * determine the duration of months and years.
+     * 
+     * @param date
+     *      A date object whose value will be modified.
+     * @throws NullPointerException
+     *      if the date parameter is null.
+     */
+    @Override
+    public void addTo(Date date) {
+        Calendar cal = new GregorianCalendar();
+        cal.setTime(date); // this will throw NPE if date==null
+        this.addTo(cal);
+        date.setTime(getCalendarTimeInMillis(cal));
+    }
+    
+    /**
+     * Calls the {@link Calendar#getTimeInMillis} method.
+     * Prior to JDK1.4, this method was protected and therefore
+     * cannot be invoked directly.
+     * 
+     * In future, this should be replaced by
+     * <code>cal.getTimeInMillis()</code>
+     */
+    private static long getCalendarTimeInMillis(Calendar cal) {
+        return cal.getTime().getTime();
+    }
+    
+//    /**
+//     * Writes {@link Duration} as a lexical representation
+//     * for maximum future compatibility.
+//     * 
+//     * @return
+//     *      An object that encapsulates the string
+//     *      returned by <code>this.toString()</code>.
+//     */
+//    private Object writeReplace() throws IOException {
+//        return new SerializedDuration(toString());
+//    }
+}


[03/24] jena git commit: JENA-1537: Remove dependency on Xerces. Import needed code

Posted by an...@apache.org.
http://git-wip-us.apache.org/repos/asf/jena/blob/c9a7e646/jena-core/src/main/java/org/apache/jena/shared/impl/PrefixMappingImpl.java
----------------------------------------------------------------------
diff --git a/jena-core/src/main/java/org/apache/jena/shared/impl/PrefixMappingImpl.java b/jena-core/src/main/java/org/apache/jena/shared/impl/PrefixMappingImpl.java
index d601bba..e55b574 100644
--- a/jena-core/src/main/java/org/apache/jena/shared/impl/PrefixMappingImpl.java
+++ b/jena-core/src/main/java/org/apache/jena/shared/impl/PrefixMappingImpl.java
@@ -23,10 +23,10 @@ import java.util.List ;
 import java.util.Map ;
 import java.util.Map.Entry;
 
+import org.apache.jena.ext.xerces.util.XMLChar;
 import org.apache.jena.rdf.model.impl.Util ;
 import org.apache.jena.shared.PrefixMapping ;
 import org.apache.jena.util.CollectionFactory ;
-import org.apache.xerces.util.XMLChar;
 
 /**
     An implementation of PrefixMapping. The mappings are stored in a pair

http://git-wip-us.apache.org/repos/asf/jena/blob/c9a7e646/jena-core/src/main/resources/org/apache/jena/ext/xerces/impl/msg/DOMMessages.properties
----------------------------------------------------------------------
diff --git a/jena-core/src/main/resources/org/apache/jena/ext/xerces/impl/msg/DOMMessages.properties b/jena-core/src/main/resources/org/apache/jena/ext/xerces/impl/msg/DOMMessages.properties
new file mode 100644
index 0000000..dd27455
--- /dev/null
+++ b/jena-core/src/main/resources/org/apache/jena/ext/xerces/impl/msg/DOMMessages.properties
@@ -0,0 +1,84 @@
+#
+# Licensed to the Apache Software Foundation (ASF) under one or more
+# contributor license agreements.  See the NOTICE file distributed with
+# this work for additional information regarding copyright ownership.
+# The ASF licenses this file to You 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.
+#
+
+# This file stores localized messages for the Xerces
+# DOM implementation.
+#
+# The messages are arranged in key and value tuples in a ListResourceBundle.
+#
+# @version $Id: DOMMessages.properties 595211 2007-11-15 05:28:12Z mrglavas $
+
+        BadMessageKey = The error message corresponding to the message key can not be found.
+        FormatFailed = An internal error occurred while formatting the following message:\n  
+
+# DOM Core
+
+# exception codes
+DOMSTRING_SIZE_ERR = The specified range of text does not fit into a DOMString. 
+HIERARCHY_REQUEST_ERR  = An attempt was made to insert a node where it is not permitted. 
+INDEX_SIZE_ERR = The index or size is negative, or greater than the allowed value.
+INUSE_ATTRIBUTE_ERR = An attempt is made to add an attribute that is already in use elsewhere.
+INVALID_ACCESS_ERR  = A parameter or an operation is not supported by the underlying object. 
+INVALID_CHARACTER_ERR = An invalid or illegal XML character is specified. 
+INVALID_MODIFICATION_ERR =  An attempt is made to modify the type of the underlying object. 
+INVALID_STATE_ERR = An attempt is made to use an object that is not, or is no longer, usable. 
+NAMESPACE_ERR = An attempt is made to create or change an object in a way which is incorrect with regard to namespaces.
+NOT_FOUND_ERR = An attempt is made to reference a node in a context where it does not exist.
+NOT_SUPPORTED_ERR = The implementation does not support the requested type of object or operation. 
+NO_DATA_ALLOWED_ERR = Data is specified for a node which does not support data.
+NO_MODIFICATION_ALLOWED_ERR = An attempt is made to modify an object where modifications are not allowed.
+SYNTAX_ERR = An invalid or illegal string is specified. 
+VALIDATION_ERR = A call to a method such as insertBefore or removeChild would make the Node invalid with respect to document grammar.
+WRONG_DOCUMENT_ERR = A node is used in a different document than the one that created it.
+TYPE_MISMATCH_ERR = The value type for this parameter name is incompatible with the expected value type. 
+ 
+#error messages or exceptions
+FEATURE_NOT_SUPPORTED = The parameter {0} is recognized but the requested value cannot be set.
+FEATURE_NOT_FOUND = The parameter {0} is not recognized.
+STRING_TOO_LONG   = The resulting string is too long to fit in a DOMString: ''{0}''.
+
+#DOM Level 3 DOMError codes
+wf-invalid-character =  The text {0} of the {1} node contains invalid XML characters.
+wf-invalid-character-in-node-name = The {0} node named {1} contains invalid XML characters.
+cdata-sections-splitted =  CDATA sections containing the CDATA section termination marker \"]]>\"
+doctype-not-allowed = DOCTYPE declaration is not allowed.
+unsupported-encoding = The encoding {0} is not supported.
+
+#Error codes used in DOM Normalizer
+InvalidXMLCharInDOM = An invalid XML character (Unicode: 0x{0}) was found in the DOM during normalization.
+UndeclaredEntRefInAttrValue = The attribute \"{0}\" value \"{1}\" referenced an entity that was not declared.
+NullLocalElementName = A null local name was encountered during namespace normalization of element {0}.
+NullLocalAttrName = A null local name was encountered during namespace normalization of attribute {0}.
+
+#Error codes used in DOMParser
+InvalidDocumentClassName = The class name of the document factory \"{0}\" used to construct the DOM tree is not of type org.w3c.dom.Document.
+MissingDocumentClassName = The class name of the document factory \"{0}\" used to construct the DOM tree could not be found.
+CannotCreateDocumentClass = The class named \"{0}\" could not be constructed as a org.w3c.dom.Document.
+CannotQueryDeferredNode = Current element node cannot be queried when node expansion is deferred.
+
+# Error codes used by JAXP DocumentBuilder
+jaxp-order-not-supported = Property ''{0}'' must be set before setting property ''{1}''.
+jaxp-null-input-source = The source specified cannot be null.
+
+#Ranges
+BAD_BOUNDARYPOINTS_ERR = The boundary-points of a Range do not meet specific requirements.
+INVALID_NODE_TYPE_ERR = The container of a boundary-point of a Range is being set to either a node of an invalid type or a node with an ancestor of an invalid type.
+
+
+#Events
+UNSPECIFIED_EVENT_TYPE_ERR = The Event's type was not specified by initializing the event before the method was called. 
+

http://git-wip-us.apache.org/repos/asf/jena/blob/c9a7e646/jena-core/src/main/resources/org/apache/jena/ext/xerces/impl/msg/DatatypeMessages.properties
----------------------------------------------------------------------
diff --git a/jena-core/src/main/resources/org/apache/jena/ext/xerces/impl/msg/DatatypeMessages.properties b/jena-core/src/main/resources/org/apache/jena/ext/xerces/impl/msg/DatatypeMessages.properties
new file mode 100644
index 0000000..f1739e7
--- /dev/null
+++ b/jena-core/src/main/resources/org/apache/jena/ext/xerces/impl/msg/DatatypeMessages.properties
@@ -0,0 +1,47 @@
+#
+# Licensed to the Apache Software Foundation (ASF) under one or more
+# contributor license agreements.  See the NOTICE file distributed with
+# this work for additional information regarding copyright ownership.
+# The ASF licenses this file to You 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.
+#
+
+# This file stores localized messages for the Xerces JAXP Datatype API implementation.
+#
+# The messages are arranged in key and value tuples in a ListResourceBundle.
+#
+# @version $Id: DatatypeMessages.properties 595211 2007-11-15 05:28:12Z mrglavas $
+
+BadMessageKey = The error message corresponding to the message key can not be found.
+FormatFailed = An internal error occurred while formatting the following message:\n
+
+FieldCannotBeNull={0} cannot be called with 'null' parameter.
+UnknownField={0} called with an unknown field\:{1}
+#There are two similar keys 'InvalidXMLGreogorianCalendarValue' . Suffix (year, month) has been added and are used as per the context.
+InvalidXGCValue-milli=Year \= {0}, Month \= {1}, Day \= {2}, Hour \= {3}, Minute \= {4}, Second \= {5}, fractionalSecond \= {6}, Timezone \= {7} , is not a valid representation of an XML Gregorian Calendar value.
+#There are two similar keys 'InvalidXMLGreogorianCalendarValue' . Suffix (year, month) has been added and are used as per the context.
+InvalidXGCValue-fractional=Year \= {0}, Month \= {1}, Day \= {2}, Hour \= {3}, Minute \= {4}, Second \= {5}, fractionalSecond \= {6}, Timezone \= {7} , is not a valid representation of an XML Gregorian Calendar value.
+
+InvalidXGCFields=Invalid set of fields set for XMLGregorianCalendar
+
+InvalidFractional=Invalid value {0} for fractional second.
+
+#XGC stands for XML Gregorian Calendar
+InvalidXGCRepresentation="{0}" is not a valid representation of an XML Gregorian Calendar value.
+
+InvalidFieldValue=Invalid value {0} for {1} field.
+
+NegativeField= {0} field is negative
+
+AllFieldsNull=All the fields (javax.xml.datatype.DatatypeConstants.Field) are null.
+
+TooLarge={0} value "{1}" too large to be supported by this implementation

http://git-wip-us.apache.org/repos/asf/jena/blob/c9a7e646/jena-core/src/main/resources/org/apache/jena/ext/xerces/impl/msg/JAXPValidationMessages.properties
----------------------------------------------------------------------
diff --git a/jena-core/src/main/resources/org/apache/jena/ext/xerces/impl/msg/JAXPValidationMessages.properties b/jena-core/src/main/resources/org/apache/jena/ext/xerces/impl/msg/JAXPValidationMessages.properties
new file mode 100644
index 0000000..6a31cad
--- /dev/null
+++ b/jena-core/src/main/resources/org/apache/jena/ext/xerces/impl/msg/JAXPValidationMessages.properties
@@ -0,0 +1,50 @@
+#
+# Licensed to the Apache Software Foundation (ASF) under one or more
+# contributor license agreements.  See the NOTICE file distributed with
+# this work for additional information regarding copyright ownership.
+# The ASF licenses this file to You 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.
+#
+
+# This file stores localized messages for the Xerces JAXP Validation API implementation.
+#
+# The messages are arranged in key and value tuples in a ListResourceBundle.
+#
+# @version $Id: JAXPValidationMessages.properties 683837 2008-08-08 04:12:37Z mrglavas $
+
+# Messages for message reporting
+BadMessageKey = The error message corresponding to the message key can not be found.
+FormatFailed = An internal error occurred while formatting the following message:\n
+
+# SchemaFactory error messages
+SchemaLanguageNull = The schema language specified cannot be null.
+SchemaLanguageLengthZero = The schema language specified cannot have a length of zero characters.
+SchemaSourceArrayNull = The Source array parameter cannot be null.
+SchemaSourceArrayMemberNull = The Source array parameter cannot contain any items that are null.
+SchemaFactorySourceUnrecognized = Source parameter of type ''{0}'' is not recognized by this SchemaFactory.
+SAXSourceNullInputSource = The SAXSource specified contains no InputSource.
+
+# Validator error messages
+SourceParameterNull = Source parameter cannot be null.
+SourceNotAccepted = Source parameter of type ''{0}'' is not accepted by this validator.
+SourceResultMismatch = Source parameter of type ''{0}'' is not compatible with result parameter of type ''{1}''.
+StAXIllegalInitialState = Expecting the initial state to be start document or start element.
+StreamResultNotInitialized = The StreamResult contains no OutputStream, Writer, or system ID.
+
+# TypeInfoProvider error messages
+TypeInfoProviderIllegalStateElement = Element type information cannot be queried from a TypeInfoProvider outside of a startElement or endElement callback.
+TypeInfoProviderIllegalStateAttribute = Attribute type information cannot be queried from a TypeInfoProvider outside of a startElement callback.
+
+# General error messages
+FeatureNameNull = The feature name cannot be null.
+ProperyNameNull = The property name cannot be null.
+

http://git-wip-us.apache.org/repos/asf/jena/blob/c9a7e646/jena-core/src/main/resources/org/apache/jena/ext/xerces/impl/msg/SAXMessages.properties
----------------------------------------------------------------------
diff --git a/jena-core/src/main/resources/org/apache/jena/ext/xerces/impl/msg/SAXMessages.properties b/jena-core/src/main/resources/org/apache/jena/ext/xerces/impl/msg/SAXMessages.properties
new file mode 100644
index 0000000..ae65a96
--- /dev/null
+++ b/jena-core/src/main/resources/org/apache/jena/ext/xerces/impl/msg/SAXMessages.properties
@@ -0,0 +1,46 @@
+#
+# Licensed to the Apache Software Foundation (ASF) under one or more
+# contributor license agreements.  See the NOTICE file distributed with
+# this work for additional information regarding copyright ownership.
+# The ASF licenses this file to You 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.
+#
+
+# This file stores localized messages for the Xerces
+# SAX implementation.
+#
+# The messages are arranged in key and value tuples in a ListResourceBundle.
+#
+# @version $Id: SAXMessages.properties 595211 2007-11-15 05:28:12Z mrglavas $
+
+BadMessageKey = The error message corresponding to the message key can not be found.
+FormatFailed = An internal error occurred while formatting the following message:\n
+
+# JAXP messages
+schema-not-supported = The specified schema language is not supported.
+jaxp-order-not-supported = Property ''{0}'' must be set before setting property ''{1}''. 
+schema-already-specified = Property ''{0}'' cannot be set when a non-null Schema object has already been specified.
+
+# feature messages
+feature-not-supported = Feature ''{0}'' is not supported.
+feature-not-recognized = Feature ''{0}'' is not recognized.
+true-not-supported = True state for feature ''{0}'' is not supported.
+false-not-supported = False state for feature ''{0}'' is not supported.
+feature-read-only = Feature ''{0}'' is read only.
+
+# property messages
+property-not-supported = Property ''{0}'' is not supported.
+property-not-recognized = Property ''{0}'' is not recognized.
+property-read-only = Property ''{0}'' is read only.
+property-not-parsing-supported = Property ''{0}'' is not supported while parsing.
+dom-node-read-not-supported = Cannot read DOM node property. No DOM tree exists.
+incompatible-class = The value specified for property ''{0}'' cannot be casted to {1}.

http://git-wip-us.apache.org/repos/asf/jena/blob/c9a7e646/jena-core/src/main/resources/org/apache/jena/ext/xerces/impl/msg/XIncludeMessages.properties
----------------------------------------------------------------------
diff --git a/jena-core/src/main/resources/org/apache/jena/ext/xerces/impl/msg/XIncludeMessages.properties b/jena-core/src/main/resources/org/apache/jena/ext/xerces/impl/msg/XIncludeMessages.properties
new file mode 100644
index 0000000..01e82ea
--- /dev/null
+++ b/jena-core/src/main/resources/org/apache/jena/ext/xerces/impl/msg/XIncludeMessages.properties
@@ -0,0 +1,56 @@
+#
+# Licensed to the Apache Software Foundation (ASF) under one or more
+# contributor license agreements.  See the NOTICE file distributed with
+# this work for additional information regarding copyright ownership.
+# The ASF licenses this file to You 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.
+#
+
+# This file stores localized messages for the Xerces XInclude implementation.
+#
+# The messages are arranged in key and value tuples in a ListResourceBundle.
+#
+# @version $Id: XIncludeMessages.properties 595211 2007-11-15 05:28:12Z mrglavas $
+
+# Messages for message reporting
+BadMessageKey = The error message corresponding to the message key can not be found.
+FormatFailed = An internal error occurred while formatting the following message:\n  
+
+# Messages for erroneous input
+NoFallback = An 'include' failed, and no 'fallback' element was found.
+MultipleFallbacks = The [children] of an 'include' element cannot contain more than one 'fallback' element.
+FallbackParent = A 'fallback' element was found that did not have 'include' as the parent.
+IncludeChild = Elements from namespace ''http://www.w3.org/2001/XInclude'', other than ''fallback'', are not allowed to be children of ''include'' elements.  However, ''{0}'' was found.
+FallbackChild = Elements from namespace ''http://www.w3.org/2001/XInclude'', other than ''include'', are not allowed to be children of ''fallback'' elements.  However, ''{0}'' was found.
+HrefMissing = The 'href' attribute of an 'include' element is missing.
+RecursiveInclude = Recursive include detected.  Document ''{0}'' was already processed.
+InvalidParseValue = Invalid value for ''parse'' attribute on ''include'' element: ''{0}''.
+XMLParseError = Error attempting to parse XML file (href=''{0}'').
+XMLResourceError = Include operation failed, reverting to fallback. Resource error reading file as XML (href=''{0}''). Reason: {1}
+TextResourceError = Include operation failed, reverting to fallback. Resource error reading file as text (href=''{0}''). Reason: {1}
+NonDuplicateNotation = Multiple notations were used which had the name ''{0}'', but which were not determined to be duplicates.
+NonDuplicateUnparsedEntity = Multiple unparsed entities were used which had the name ''{0}'', but which were not determined to be duplicates.
+XpointerMissing = xpointer attribute must be present when href attribute is absent.
+AcceptMalformed = Characters outside the range #x20 through #x7E are not allowed in the value of the 'accept' attribute of an 'include' element.
+AcceptLanguageMalformed = Characters outside the range #x20 through #x7E are not allowed in the value of the 'accept-language' attribute of an 'include' element.
+RootElementRequired = A well-formed document requires a root element.
+MultipleRootElements = A well-formed document must not contain multiple root elements.
+ContentIllegalAtTopLevel = The replacement of an 'include' element appearing as the document element in the top-level source infoset cannot contain characters.
+UnexpandedEntityReferenceIllegal = The replacement of an 'include' element appearing as the document element in the top-level source infoset cannot contain unexpanded entity references.
+HrefFragmentIdentifierIllegal = Fragment identifiers must not be used. The ''href'' attribute value ''{0}'' is not permitted.
+HrefSyntacticallyInvalid = ''href'' attribute value ''{0}'' is syntactically invalid. After applying escaping rules the value is neither a syntactically correct URI or IRI.
+XPointerStreamability = An xpointer was specified that points to a location in the source infoset. This location cannot be accessed due to the streaming nature of the processor.
+XPointerResolutionUnsuccessful = XPointer resolution unsuccessful.
+
+# Messages from erroneous set-up
+IncompatibleNamespaceContext = The type of the NamespaceContext is incompatible with using XInclude; it must be an instance of XIncludeNamespaceSupport
+ExpandedSystemId = Could not expand system id of included resource

http://git-wip-us.apache.org/repos/asf/jena/blob/c9a7e646/jena-core/src/main/resources/org/apache/jena/ext/xerces/impl/msg/XMLMessages.properties
----------------------------------------------------------------------
diff --git a/jena-core/src/main/resources/org/apache/jena/ext/xerces/impl/msg/XMLMessages.properties b/jena-core/src/main/resources/org/apache/jena/ext/xerces/impl/msg/XMLMessages.properties
new file mode 100644
index 0000000..47e4214
--- /dev/null
+++ b/jena-core/src/main/resources/org/apache/jena/ext/xerces/impl/msg/XMLMessages.properties
@@ -0,0 +1,309 @@
+#
+# Licensed to the Apache Software Foundation (ASF) under one or more
+# contributor license agreements.  See the NOTICE file distributed with
+# this work for additional information regarding copyright ownership.
+# The ASF licenses this file to You 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.
+#
+
+# This file contains error and warning messages related to XML
+# The messages are arranged in key and value tuples in a ListResourceBundle.
+#
+# @version $Id: XMLMessages.properties 595214 2007-11-15 05:32:38Z mrglavas $
+
+        BadMessageKey = The error message corresponding to the message key can not be found.
+        FormatFailed = An internal error occurred while formatting the following message:\n  
+        
+# Document messages
+        PrematureEOF=Premature end of file.
+# 2.1 Well-Formed XML Documents
+        RootElementRequired = The root element is required in a well-formed document.
+# 2.2 Characters
+        InvalidCharInCDSect = An invalid XML character (Unicode: 0x{0}) was found in the CDATA section.
+        InvalidCharInContent = An invalid XML character (Unicode: 0x{0}) was found in the element content of the document.
+        TwoColonsInQName = An invalid second ':' was found in the element type or attribute name.
+        ColonNotLegalWithNS = A colon is not allowed in the name ''{0}'' when namespaces are enabled.
+        InvalidCharInMisc = An invalid XML character (Unicode: 0x{0}) was found in markup after the end of the element content.
+        InvalidCharInProlog = An invalid XML character (Unicode: 0x{0}) was found in the prolog of the document.
+        InvalidCharInXMLDecl = An invalid XML character (Unicode: 0x{0}) was found in the XML declaration.
+# 2.4 Character Data and Markup
+        CDEndInContent = The character sequence \"]]>\" must not appear in content unless used to mark the end of a CDATA section.
+# 2.7 CDATA Sections
+        CDSectUnterminated = The CDATA section must end with \"]]>\".
+# 2.8 Prolog and Document Type Declaration
+        XMLDeclMustBeFirst = The XML declaration may only appear at the very beginning of the document.
+        EqRequiredInXMLDecl = The '' = '' character must follow \"{0}\" in the XML declaration.
+        QuoteRequiredInXMLDecl = The value following \"{0}\" in the XML declaration must be a quoted string.
+        XMLDeclUnterminated = The XML declaration must end with \"?>\".
+        VersionInfoRequired = The version is required in the XML declaration.
+        SpaceRequiredBeforeVersionInXMLDecl = White space is required before the version pseudo attribute in the XML declaration.
+        SpaceRequiredBeforeEncodingInXMLDecl = White space is required before the encoding pseudo attribute in the XML declaration.
+        SpaceRequiredBeforeStandalone = White space is required before the encoding pseudo attribute in the XML declaration.
+        MarkupNotRecognizedInProlog = The markup in the document preceding the root element must be well-formed.
+        MarkupNotRecognizedInMisc = The markup in the document following the root element must be well-formed.
+        AlreadySeenDoctype = Already seen doctype.
+        DoctypeNotAllowed = DOCTYPE is disallowed when the feature "http://apache.org/xml/features/disallow-doctype-decl" set to true.
+        ContentIllegalInProlog = Content is not allowed in prolog.
+        ReferenceIllegalInProlog = Reference is not allowed in prolog.
+# Trailing Misc
+        ContentIllegalInTrailingMisc=Content is not allowed in trailing section.
+        ReferenceIllegalInTrailingMisc=Reference is not allowed in trailing section.
+        
+# 2.9 Standalone Document Declaration
+        SDDeclInvalid = The standalone document declaration value must be \"yes\" or \"no\", not \"{0}\".
+# 2.12 Language Identification
+        XMLLangInvalid = The xml:lang attribute value \"{0}\" is an invalid language identifier.
+# 3. Logical Structures
+        ETagRequired = The element type \"{0}\" must be terminated by the matching end-tag \"</{0}>\".
+# 3.1 Start-Tags, End-Tags, and Empty-Element Tags
+        ElementUnterminated = Element type \"{0}\" must be followed by either attribute specifications, \">\" or \"/>\".
+        EqRequiredInAttribute = Attribute name \"{1}\" associated with an element type \"{0}\" must be followed by the '' = '' character.
+        OpenQuoteExpected = Open quote is expected for attribute \"{1}\" associated with an  element type  \"{0}\".
+        CloseQuoteExpected = Close quote is expected for attribute \"{1}\" associated with an element type \"{0}\".
+        AttributeNotUnique = Attribute \"{1}\" was already specified for element \"{0}\".
+        AttributeNSNotUnique = Attribute \"{1}\" bound to namespace \"{2}\" was already specified for element \"{0}\".
+        ETagUnterminated = The end-tag for element type \"{0}\" must end with a ''>'' delimiter.
+        MarkupNotRecognizedInContent = The content of elements must consist of well-formed character data or markup.
+        DoctypeIllegalInContent = A DOCTYPE is not allowed in content.
+# 4.1 Character and Entity References
+        ReferenceUnterminated = The reference must be terminated by a ';' delimiter.
+# 4.3.2 Well-Formed Parsed Entities
+        ReferenceNotInOneEntity = The reference must be entirely contained within the same parsed entity.
+        ElementEntityMismatch = The element \"{0}\" must start and end within the same entity.
+        MarkupEntityMismatch=XML document structures must start and end within the same entity.
+        
+# Messages common to Document and DTD
+# 2.2 Characters
+        InvalidCharInAttValue = An invalid XML character (Unicode: 0x{2}) was found in the value of attribute \"{1}\" and element is \"{0}\".
+        InvalidCharInComment = An invalid XML character (Unicode: 0x{0}) was found in the comment.
+        InvalidCharInPI = An invalid XML character (Unicode: 0x{0}) was found in the processing instruction.
+        InvalidCharInInternalSubset = An invalid XML character (Unicode: 0x{0}) was found in the internal subset of the DTD.
+        InvalidCharInTextDecl = An invalid XML character (Unicode: 0x{0}) was found in the text declaration.
+# 2.3 Common Syntactic Constructs
+        QuoteRequiredInAttValue = The value of attribute \"{1}\" must begin with either a single or double quote character.
+        LessthanInAttValue = The value of attribute \"{1}\" associated with an element type \"{0}\" must not contain the ''<'' character.
+        AttributeValueUnterminated = The value for attribute \"{1}\" must end with the matching quote character.
+# 2.5 Comments
+        InvalidCommentStart = Comment must start with \"<!--\".
+        DashDashInComment = The string \"--\" is not permitted within comments.
+        CommentUnterminated = The comment must end with \"-->\".
+        COMMENT_NOT_IN_ONE_ENTITY = The comment is not enclosed in the same entity.
+# 2.6 Processing Instructions
+        PITargetRequired = The processing instruction must begin with the name of the target.
+        SpaceRequiredInPI = White space is required between the processing instruction target and data.
+        PIUnterminated = The processing instruction must end with \"?>\".
+        ReservedPITarget = The processing instruction target matching \"[xX][mM][lL]\" is not allowed.
+        PI_NOT_IN_ONE_ENTITY = The processing instruction is not enclosed in the same entity.
+# 2.8 Prolog and Document Type Declaration
+        VersionInfoInvalid = Invalid version \"{0}\".
+        VersionNotSupported = XML version \"{0}\" is not supported, only XML 1.0 is supported.
+        VersionNotSupported11 = XML version \"{0}\" is not supported, only XML 1.0 and XML 1.1 are supported.
+# 4.1 Character and Entity References
+        DigitRequiredInCharRef = A decimal representation must immediately follow the \"&#\" in a character reference.
+        HexdigitRequiredInCharRef = A hexadecimal representation must immediately follow the \"&#x\" in a character reference.
+        SemicolonRequiredInCharRef = The character reference must end with the ';' delimiter.
+        InvalidCharRef = Character reference \"&#{0}\" is an invalid XML character.
+        NameRequiredInReference = The entity name must immediately follow the '&' in the entity reference.
+        SemicolonRequiredInReference = The reference to entity \"{0}\" must end with the '';'' delimiter.
+# 4.3.1 The Text Declaration
+        TextDeclMustBeFirst = The text declaration may only appear at the very beginning of the external parsed entity.
+        EqRequiredInTextDecl = The '' = '' character must follow \"{0}\" in the text declaration.
+        QuoteRequiredInTextDecl = The value following \"{0}\" in the text declaration must be a quoted string.
+        CloseQuoteMissingInTextDecl = closing quote in the value following \"{0}\" in the text declaration is missing.
+        SpaceRequiredBeforeVersionInTextDecl = White space is required before the version pseudo attribute in the text declaration.
+        SpaceRequiredBeforeEncodingInTextDecl = White space is required before the encoding pseudo attribute in the text declaration.
+        TextDeclUnterminated = The text declaration must end with \"?>\".
+        EncodingDeclRequired = The encoding declaration is required in the text declaration.
+        NoMorePseudoAttributes = No more pseudo attributes are allowed.
+        MorePseudoAttributes = More pseudo attributes are expected.
+        PseudoAttrNameExpected = A pseudo attribute name is expected. 
+# 4.3.2 Well-Formed Parsed Entities
+        CommentNotInOneEntity = The comment must be entirely contained within the same parsed entity.
+        PINotInOneEntity = The processing instruction must be entirely contained within the same parsed entity.
+# 4.3.3 Character Encoding in Entities
+        EncodingDeclInvalid = Invalid encoding name \"{0}\".
+        EncodingByteOrderUnsupported = Given byte order for encoding \"{0}\" is not supported.
+        InvalidByte = Invalid byte {0} of {1}-byte UTF-8 sequence.
+        ExpectedByte = Expected byte {0} of {1}-byte UTF-8 sequence.  
+        InvalidHighSurrogate = High surrogate bits in UTF-8 sequence must not exceed 0x10 but found 0x{0}.
+        OperationNotSupported = Operation \"{0}\" not supported by {1} reader.
+        InvalidASCII = Byte \"{0}\" is not a member of the (7-bit) ASCII character set.
+        CharConversionFailure = An entity determined to be in a certain encoding must not contain sequences illegal in that encoding.
+        
+# DTD Messages
+# 2.2 Characters
+        InvalidCharInEntityValue = An invalid XML character (Unicode: 0x{0}) was found in the literal entity value.
+        InvalidCharInExternalSubset = An invalid XML character (Unicode: 0x{0}) was found in the external subset of the DTD.
+        InvalidCharInIgnoreSect = An invalid XML character (Unicode: 0x{0}) was found in the excluded conditional section.
+        InvalidCharInPublicID = An invalid XML character (Unicode: 0x{0}) was found in the public identifier.
+        InvalidCharInSystemID = An invalid XML character (Unicode: 0x{0}) was found in the system identifier.
+# 2.3 Common Syntactic Constructs
+        SpaceRequiredAfterSYSTEM = White space is required after keyword SYSTEM in DOCTYPE decl.
+        QuoteRequiredInSystemID = The system identifier must begin with either a single or double quote character.
+        SystemIDUnterminated = The system identifier must end with the matching quote character.
+        SpaceRequiredAfterPUBLIC = White spaces are required after keyword PUBLIC in DOCTYPE decl.
+        QuoteRequiredInPublicID = The public identifier must begin with either a single or double quote character.
+        PublicIDUnterminated = The public identifier must end with the matching quote character.
+        PubidCharIllegal = The character (Unicode: 0x{0}) is not permitted in the public identifier.
+        SpaceRequiredBetweenPublicAndSystem = White spaces are required between publicId and systemId.
+# 2.8 Prolog and Document Type Declaration
+        MSG_SPACE_REQUIRED_BEFORE_ROOT_ELEMENT_TYPE_IN_DOCTYPEDECL = White space is required after \"<!DOCTYPE\" in the document type declaration.
+        MSG_ROOT_ELEMENT_TYPE_REQUIRED = The root element type must appear after \"<!DOCTYPE\" in the document type declaration.
+        DoctypedeclUnterminated = The document type declaration for root element type \"{0}\" must end with ''>''.
+        PEReferenceWithinMarkup = The parameter entity reference \"%{0};\" cannot occur within markup in the internal subset of the DTD.
+        MSG_MARKUP_NOT_RECOGNIZED_IN_DTD = The markup declarations contained or pointed to by the document type declaration must be well-formed.
+# 2.10 White Space Handling
+        MSG_XML_SPACE_DECLARATION_ILLEGAL = The attribute declaration for \"xml:space\" must be given as an enumerated type whose only possible values are \"default\" and \"preserve\".
+# 3.2 Element Type Declarations
+        MSG_SPACE_REQUIRED_BEFORE_ELEMENT_TYPE_IN_ELEMENTDECL = White space is required after \"<!ELEMENT\" in the element type declaration.
+        MSG_ELEMENT_TYPE_REQUIRED_IN_ELEMENTDECL = The element type is required in the element type declaration.
+        MSG_SPACE_REQUIRED_BEFORE_CONTENTSPEC_IN_ELEMENTDECL = White space is required after the element type \"{0}\" in the element type declaration.
+        MSG_CONTENTSPEC_REQUIRED_IN_ELEMENTDECL = The constraint is required after the element type \"{0}\" in the element type declaration.
+        ElementDeclUnterminated = The declaration for element type \"{0}\" must end with ''>''.
+# 3.2.1 Element Content
+        MSG_OPEN_PAREN_OR_ELEMENT_TYPE_REQUIRED_IN_CHILDREN = A ''('' character or an element type is required in the declaration of element type \"{0}\".
+        MSG_CLOSE_PAREN_REQUIRED_IN_CHILDREN = A '')'' is required in the declaration of element type \"{0}\".
+# 3.2.2 Mixed Content
+        MSG_ELEMENT_TYPE_REQUIRED_IN_MIXED_CONTENT = An element type is required in the declaration of element type \"{0}\".
+        MSG_CLOSE_PAREN_REQUIRED_IN_MIXED = A '')'' is required in the declaration of element type \"{0}\".
+        MixedContentUnterminated = The mixed content model \"{0}\" must end with \")*\" when the types of child elements are constrained.
+# 3.3 Attribute-List Declarations
+        MSG_SPACE_REQUIRED_BEFORE_ELEMENT_TYPE_IN_ATTLISTDECL = White space is required after \"<!ATTLIST\" in the attribute-list declaration.
+        MSG_ELEMENT_TYPE_REQUIRED_IN_ATTLISTDECL = The element type is required in the attribute-list declaration.
+        MSG_SPACE_REQUIRED_BEFORE_ATTRIBUTE_NAME_IN_ATTDEF = White space is required before the attribute name in the attribute-list declaration for element \"{0}\".
+        AttNameRequiredInAttDef = The attribute name must be specified in the attribute-list declaration for element \"{0}\".
+        MSG_SPACE_REQUIRED_BEFORE_ATTTYPE_IN_ATTDEF = White space is required before the attribute type in the declaration of attribute \"{1}\" for element \"{0}\".
+        AttTypeRequiredInAttDef = The attribute type is required in the declaration of attribute \"{1}\" for element \"{0}\".
+        MSG_SPACE_REQUIRED_BEFORE_DEFAULTDECL_IN_ATTDEF = White space is required before the attribute default in the declaration of attribute \"{1}\" for element \"{0}\".
+        MSG_DUPLICATE_ATTRIBUTE_DEFINITION = More than one attribute definition is provided for the same attribute \"{1}\" of a given element \"{0}\".
+# 3.3.1 Attribute Types
+        MSG_SPACE_REQUIRED_AFTER_NOTATION_IN_NOTATIONTYPE = White space must appear after \"NOTATION\" in the \"{1}\" attribute declaration.
+        MSG_OPEN_PAREN_REQUIRED_IN_NOTATIONTYPE = The ''('' character must follow \"NOTATION\" in the \"{1}\" attribute declaration.
+        MSG_NAME_REQUIRED_IN_NOTATIONTYPE = The notation name is required in the notation type list for the \"{1}\" attribute declaration.
+        NotationTypeUnterminated = The notation type list must end with '')'' in the \"{1}\" attribute declaration.
+        MSG_NMTOKEN_REQUIRED_IN_ENUMERATION = The name token is required in the enumerated type list for the \"{1}\" attribute declaration.
+        EnumerationUnterminated = The enumerated type list must end with '')'' in the \"{1}\" attribute declaration.
+        MSG_DISTINCT_TOKENS_IN_ENUMERATION = The enumeration value \"{1}\" was specified more than once in the declaration of attribute \"{2}\" for element \"{0}\". The NMTOKENS in a single Enumeration attribute declaration must all be distinct.
+        MSG_DISTINCT_NOTATION_IN_ENUMERATION = The enumeration value \"{1}\" was specified more than once in the declaration of attribute \"{2}\" for element \"{0}\". The NOTATION names in a single NotationType attribute declaration must all be distinct.
+# 3.3.2 Attribute Defaults
+        MSG_SPACE_REQUIRED_AFTER_FIXED_IN_DEFAULTDECL = White space must appear after \"FIXED\" in the \"{1}\" attribute declaration.
+# 3.4 Conditional Sections
+        IncludeSectUnterminated = The included conditional section must end with \"]]>\".
+        IgnoreSectUnterminated = The excluded conditional section must end with \"]]>\".
+# 4.1 Character and Entity References
+        NameRequiredInPEReference = The entity name must immediately follow the '%' in the parameter entity reference.
+        SemicolonRequiredInPEReference = The parameter entity reference \"%{0};\" must end with the '';'' delimiter.
+# 4.2 Entity Declarations
+        MSG_SPACE_REQUIRED_BEFORE_ENTITY_NAME_IN_ENTITYDECL = White space is required after \"<!ENTITY\" in the entity declaration.
+        MSG_SPACE_REQUIRED_BEFORE_PERCENT_IN_PEDECL = White space is required between \"<!ENTITY\" and the '%' character in the parameter entity declaration.
+        MSG_SPACE_REQUIRED_BEFORE_ENTITY_NAME_IN_PEDECL = White space is required between the '%' and the entity name in the parameter entity declaration.
+        MSG_ENTITY_NAME_REQUIRED_IN_ENTITYDECL = The name of the entity is required in the entity declaration.
+        MSG_SPACE_REQUIRED_AFTER_ENTITY_NAME_IN_ENTITYDECL = White space is required between the entity name \"{0}\" and the definition in the entity declaration.
+        MSG_SPACE_REQUIRED_BEFORE_NOTATION_NAME_IN_UNPARSED_ENTITYDECL = White space is required between \"NDATA\" and the notation name in the declaration for the entity \"{0}\".
+        MSG_SPACE_REQUIRED_BEFORE_NDATA_IN_UNPARSED_ENTITYDECL = White space is required before \"NDATA\" in the declaration for the entity \"{0}\".
+        MSG_NOTATION_NAME_REQUIRED_FOR_UNPARSED_ENTITYDECL = The notation name is required after \"NDATA\" in the declaration for the entity \"{0}\".
+        EntityDeclUnterminated = The declaration for the entity \"{0}\" must end with ''>''.
+        MSG_DUPLICATE_ENTITY_DEFINITION = Entity \"{0}\" is declared more than once.        
+# 4.2.2 External Entities
+        ExternalIDRequired = The external entity declaration must begin with either \"SYSTEM\" or \"PUBLIC\".
+        MSG_SPACE_REQUIRED_BEFORE_PUBIDLITERAL_IN_EXTERNALID = White space is required between \"PUBLIC\" and the public identifier.
+        MSG_SPACE_REQUIRED_AFTER_PUBIDLITERAL_IN_EXTERNALID = White space is required between the public identifier and the system identifier.
+        MSG_SPACE_REQUIRED_BEFORE_SYSTEMLITERAL_IN_EXTERNALID = White space is required between \"SYSTEM\" and the system identifier.
+        MSG_URI_FRAGMENT_IN_SYSTEMID = The fragment identifier should not be specified as part of the system identifier \"{0}\".
+# 4.7 Notation Declarations
+        MSG_SPACE_REQUIRED_BEFORE_NOTATION_NAME_IN_NOTATIONDECL = White space is required after \"<!NOTATION\" in the notation declaration.
+        MSG_NOTATION_NAME_REQUIRED_IN_NOTATIONDECL = The name of the notation is required in the notation declaration.
+        MSG_SPACE_REQUIRED_AFTER_NOTATION_NAME_IN_NOTATIONDECL = White space is required after the notation name \"{0}\" in the notation declaration.
+        ExternalIDorPublicIDRequired = The declaration for the notation \"{0}\" must include a system or public identifier.
+        NotationDeclUnterminated = The declaration for the notation \"{0}\" must end with ''>''.
+        
+# Validation messages
+        DuplicateTypeInMixedContent = The element type \"{1}\" was already specified in the content model of the element decl \"{0}\".
+        ENTITIESInvalid = Attribute value \"{1}\" of type ENTITIES must be the names of one or more unparsed entities.
+        ENTITYInvalid = Attribute value \"{1}\" of type ENTITY must be the name of an unparsed entity.
+        IDDefaultTypeInvalid = The ID attribute \"{0}\" must have a declared default of \"#IMPLIED\" or \"#REQUIRED\".
+        IDInvalid = Attribute value \"{0}\" of type ID must be a name.
+        IDInvalidWithNamespaces = Attribute value \"{0}\" of type ID must be an NCName when namespaces are enabled.
+        IDNotUnique = Attribute value \"{0}\" of type ID must be unique within the document.
+        IDREFInvalid = Attribute value \"{0}\" of type IDREF must be a name.
+        IDREFInvalidWithNamespaces = Attribute value \"{0}\" of type IDREF must be an NCName when namespaces are enabled.
+        IDREFSInvalid = Attribute value \"{0}\" of type IDREFS must be one or more names.
+        ILL_FORMED_PARAMETER_ENTITY_WHEN_USED_IN_DECL = The replacement text of parameter entity \"{0}\" must include properly nested declarations when the entity reference is used as a complete declaration.
+        ImproperDeclarationNesting = The replacement text of parameter entity \"{0}\" must include properly nested declarations.
+        ImproperGroupNesting = The replacement text of parameter entity \"{0}\" must include properly nested pairs of parentheses.
+        INVALID_PE_IN_CONDITIONAL = The replacement text of parameter entity \"{0}\" must include the entire conditional section or just INCLUDE or IGNORE.
+        MSG_ATTRIBUTE_NOT_DECLARED = Attribute \"{1}\" must be declared for element type \"{0}\".
+        MSG_ATTRIBUTE_VALUE_NOT_IN_LIST = Attribute \"{0}\" with value \"{1}\" must have a value from the list \"{2}\".
+        MSG_ATTVALUE_CHANGED_DURING_NORMALIZATION_WHEN_STANDALONE = The value \"{1}\" of attribute \"{0}\" must not be changed by normalization (to \"{2}\") in a standalone document.
+        MSG_CONTENT_INCOMPLETE = The content of element type \"{0}\" is incomplete, it must match \"{1}\".
+        MSG_CONTENT_INVALID = The content of element type \"{0}\" must match \"{1}\".
+        MSG_CONTENT_INVALID_SPECIFIED = The content of element type \"{0}\" must match \"{1}\".  Children of type \"{2}\" are not allowed.
+        MSG_DEFAULTED_ATTRIBUTE_NOT_SPECIFIED = Attribute \"{1}\" for element type \"{0}\" has a default value and must be specified in a standalone document.
+        MSG_DUPLICATE_ATTDEF = Attribute \"{1}\" is already declared for element type \"{0}\".
+        MSG_ELEMENT_ALREADY_DECLARED = Element type \"{0}\" must not be declared more than once.
+        MSG_ELEMENT_NOT_DECLARED = Element type \"{0}\" must be declared.
+        MSG_GRAMMAR_NOT_FOUND = Document is invalid: no grammar found.
+        MSG_ELEMENT_WITH_ID_REQUIRED = An element with the identifier \"{0}\" must appear in the document.
+        MSG_EXTERNAL_ENTITY_NOT_PERMITTED = The reference to external entity \"{0}\" is not permitted in a standalone document.
+        MSG_FIXED_ATTVALUE_INVALID = Attribute \"{1}\" with value \"{2}\" must have a value of \"{3}\".
+        MSG_MORE_THAN_ONE_ID_ATTRIBUTE = Element type \"{0}\" already has attribute \"{1}\" of type ID, a second attribute \"{2}\" of type ID is not permitted.
+        MSG_MORE_THAN_ONE_NOTATION_ATTRIBUTE = Element type \"{0}\" already has attribute \"{1}\" of type NOTATION, a second attribute \"{2}\" of type NOTATION is not permitted.
+        MSG_NOTATION_NOT_DECLARED_FOR_NOTATIONTYPE_ATTRIBUTE = The notation \"{1}\" must be declared when referenced in the notation type list for attribute \"{0}\".
+        MSG_NOTATION_NOT_DECLARED_FOR_UNPARSED_ENTITYDECL = The notation \"{1}\" must be declared when referenced in the unparsed entity declaration for \"{0}\".
+        MSG_REFERENCE_TO_EXTERNALLY_DECLARED_ENTITY_WHEN_STANDALONE = The reference to entity \"{0}\" declared in the external subset of the DTD or in a parameter entity is not permitted in a standalone document.
+        MSG_REQUIRED_ATTRIBUTE_NOT_SPECIFIED = Attribute \"{1}\" is required and must be specified for element type \"{0}\".
+        MSG_WHITE_SPACE_IN_ELEMENT_CONTENT_WHEN_STANDALONE = In a standalone document white space must not occur between elements with element content which are declared in the external subset of the DTD or in a parameter entity.
+        NMTOKENInvalid = Attribute value \"{0}\" of type NMTOKEN must be a name token.
+        NMTOKENSInvalid = Attribute value \"{0}\" of type NMTOKENS must be one or more name tokens.
+        NoNotationOnEmptyElement = Element type \"{0}\" which was declared EMPTY cannot declare attribute \"{1}\" of type NOTATION.
+        RootElementTypeMustMatchDoctypedecl = Document root element \"{1}\", must match DOCTYPE root \"{0}\".
+        UndeclaredElementInContentSpec = The content model of element \"{0}\" refers to the undeclared element \"{1}\".
+        UniqueNotationName = The declaration for the notation \"{0}\" is not unique. A given Name must not be declared in more than one notation declaration.
+        ENTITYFailedInitializeGrammar =  ENTITYDatatype Validator: Failed Need to call initialize method with a valid Grammar reference. 	
+        ENTITYNotUnparsed = ENTITY \"{0}\" is not unparsed.
+        ENTITYNotValid = ENTITY \"{0}\" is not valid.
+        EmptyList = Value of type ENTITIES, IDREFS, and NMTOKENS cannot be empty list.
+
+# Entity related messages
+# 3.1 Start-Tags, End-Tags, and Empty-Element Tags
+        ReferenceToExternalEntity = The external entity reference \"&{0};\" is not permitted in an attribute value.
+# 4.1 Character and Entity References
+        EntityNotDeclared = The entity \"{0}\" was referenced, but not declared.
+        ReferenceToUnparsedEntity = The unparsed entity reference \"&{0};\" is not permitted.
+        RecursiveReference = Recursive entity reference \"{0}\". (Reference path: {1}),
+        RecursiveGeneralReference = Recursive general entity reference \"&{0};\". (Reference path: {1}),
+        RecursivePEReference = Recursive parameter entity reference \"%{0};\". (Reference path: {1}),
+# 4.3.3 Character Encoding in Entities
+        EncodingNotSupported = The encoding \"{0}\" is not supported.
+        EncodingRequired = A parsed entity not encoded in either UTF-8 or UTF-16 must contain an encoding declaration.
+        
+# Namespaces support
+# 4. Using Qualified Names
+        IllegalQName = Element or attribute do not match QName production: QName::=(NCName':')?NCName. 
+        ElementXMLNSPrefix = Element \"{0}\" cannot have \"xmlns\" as its prefix.
+        ElementPrefixUnbound = The prefix \"{0}\" for element \"{1}\" is not bound.
+        AttributePrefixUnbound = The prefix \"{2}\" for attribute \"{1}\" associated with an element type \"{0}\" is not bound.
+        EmptyPrefixedAttName = The value of the attribute \"{0}\" is invalid. Prefixed namespace bindings may not be empty.
+        PrefixDeclared = The namespace prefix \"{0}\" was not declared.
+        CantBindXMLNS = The prefix "xmlns" cannot be bound to any namespace explicitly; neither can the namespace for "xmlns" be bound to any prefix explicitly.
+        CantBindXML = The prefix "xml" cannot be bound to any namespace other than its usual namespace; neither can the namespace for "xml" be bound to any prefix other than "xml".
+        MSG_ATT_DEFAULT_INVALID = The defaultValue \"{1}\" of attribute \"{0}\" is not legal as for the lexical constraints of this attribute type.
+
+# REVISIT: These need messages
+        MSG_SPACE_REQUIRED_AFTER_SYSTEMLITERAL_IN_EXTERNALID=MSG_SPACE_REQUIRED_AFTER_SYSTEMLITERAL_IN_EXTERNALID
+        OpenQuoteMissingInDecl=OpenQuoteMissingInDecl
+        InvalidCharInLiteral=InvalidCharInLiteral
+
+
+#Application can set the limit of number of entities that should be expanded by the parser.
+EntityExpansionLimitExceeded=The parser has encountered more than \"{0}\" entity expansions in this document; this is the limit imposed by the application.
+


[12/24] jena git commit: JENA-1537: Remove dependency on Xerces. Import needed code

Posted by an...@apache.org.
http://git-wip-us.apache.org/repos/asf/jena/blob/c9a7e646/jena-core/src/main/java/org/apache/jena/ext/xerces/impl/xpath/regex/Token.java
----------------------------------------------------------------------
diff --git a/jena-core/src/main/java/org/apache/jena/ext/xerces/impl/xpath/regex/Token.java b/jena-core/src/main/java/org/apache/jena/ext/xerces/impl/xpath/regex/Token.java
new file mode 100644
index 0000000..1d3a296
--- /dev/null
+++ b/jena-core/src/main/java/org/apache/jena/ext/xerces/impl/xpath/regex/Token.java
@@ -0,0 +1,1562 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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.jena.ext.xerces.impl.xpath.regex;
+
+import java.util.Hashtable;
+import java.util.Vector;
+
+/**
+ * This class represents a node in parse tree.
+ * 
+ * @xerces.internal
+ *
+ * @version $Id: Token.java 831926 2009-11-02 15:38:53Z knoaman $
+ */
+@SuppressWarnings("all")
+class Token implements java.io.Serializable {
+
+    private static final long serialVersionUID = 8484976002585487481L;
+
+    static final boolean COUNTTOKENS = true;
+    static int tokens = 0;
+
+    static final int CHAR = 0;                  // Literal char
+    static final int DOT = 11;                  // .
+    static final int CONCAT = 1;                // XY
+    static final int UNION = 2;                 // X|Y|Z
+    static final int CLOSURE = 3;               // X*
+    static final int RANGE = 4;                 // [a-zA-Z] etc.
+    static final int NRANGE = 5;                // [^a-zA-Z] etc.
+    static final int PAREN = 6;                 // (X) or (?:X)
+    static final int EMPTY = 7;                 //
+    static final int ANCHOR = 8;                // ^ $ \b \B \< \> \A \Z \z
+    static final int NONGREEDYCLOSURE = 9;      // *? +?
+    static final int STRING = 10;               // strings
+    static final int BACKREFERENCE = 12;        // back references
+    static final int LOOKAHEAD = 20;            // (?=...)
+    static final int NEGATIVELOOKAHEAD = 21;    // (?!...)
+    static final int LOOKBEHIND = 22;           // (?<=...)
+    static final int NEGATIVELOOKBEHIND = 23;   // (?<!...)
+    static final int INDEPENDENT = 24;          // (?>...)
+    static final int MODIFIERGROUP = 25;        // (?ims-ims:...)
+    static final int CONDITION = 26;            // (?(...)yes|no)
+
+    static final int UTF16_MAX = 0x10ffff;
+
+    final int type;
+
+    static Token token_dot;
+    static Token token_0to9;
+    static Token token_wordchars;
+    static Token token_not_0to9;
+    static Token token_not_wordchars;
+    static Token token_spaces;
+    static Token token_not_spaces;
+    static Token token_empty;
+    static Token token_linebeginning;
+    static Token token_linebeginning2;
+    static Token token_lineend;
+    static Token token_stringbeginning;
+    static Token token_stringend;
+    static Token token_stringend2;
+    static Token token_wordedge;
+    static Token token_not_wordedge;
+    static Token token_wordbeginning;
+    static Token token_wordend;
+    static {
+        Token.token_empty = new Token(Token.EMPTY);
+
+        Token.token_linebeginning = Token.createAnchor('^');
+        Token.token_linebeginning2 = Token.createAnchor('@');
+        Token.token_lineend = Token.createAnchor('$');
+        Token.token_stringbeginning = Token.createAnchor('A');
+        Token.token_stringend = Token.createAnchor('z');
+        Token.token_stringend2 = Token.createAnchor('Z');
+        Token.token_wordedge = Token.createAnchor('b');
+        Token.token_not_wordedge = Token.createAnchor('B');
+        Token.token_wordbeginning = Token.createAnchor('<');
+        Token.token_wordend = Token.createAnchor('>');
+
+        Token.token_dot = new Token(Token.DOT);
+
+        Token.token_0to9 = Token.createRange();
+        Token.token_0to9.addRange('0', '9');
+        Token.token_wordchars = Token.createRange();
+        Token.token_wordchars.addRange('0', '9');
+        Token.token_wordchars.addRange('A', 'Z');
+        Token.token_wordchars.addRange('_', '_');
+        Token.token_wordchars.addRange('a', 'z');
+        Token.token_spaces = Token.createRange();
+        Token.token_spaces.addRange('\t', '\t');
+        Token.token_spaces.addRange('\n', '\n');
+        Token.token_spaces.addRange('\f', '\f');
+        Token.token_spaces.addRange('\r', '\r');
+        Token.token_spaces.addRange(' ', ' ');
+
+        Token.token_not_0to9 = Token.complementRanges(Token.token_0to9);
+        Token.token_not_wordchars = Token.complementRanges(Token.token_wordchars);
+        Token.token_not_spaces = Token.complementRanges(Token.token_spaces);
+    }
+
+    static Token.ParenToken createLook(int type, Token child) {
+        if (COUNTTOKENS)  Token.tokens ++;
+        return new Token.ParenToken(type, child, 0);
+    }
+    static Token.ParenToken createParen(Token child, int pnumber) {
+        if (COUNTTOKENS)  Token.tokens ++;
+        return new Token.ParenToken(Token.PAREN, child, pnumber);
+    }
+    static Token.ClosureToken createClosure(Token tok) {
+        if (COUNTTOKENS)  Token.tokens ++;
+        return new Token.ClosureToken(Token.CLOSURE, tok);
+    }
+    static Token.ClosureToken createNGClosure(Token tok) {
+        if (COUNTTOKENS)  Token.tokens ++;
+        return new Token.ClosureToken(Token.NONGREEDYCLOSURE, tok);
+    }
+    static Token.ConcatToken createConcat(Token tok1, Token tok2) {
+        if (COUNTTOKENS)  Token.tokens ++;
+        return new Token.ConcatToken(tok1, tok2);
+    }
+    static Token.UnionToken createConcat() {
+        if (COUNTTOKENS)  Token.tokens ++;
+        return new Token.UnionToken(Token.CONCAT); // *** It is not a bug.
+    }
+    static Token.UnionToken createUnion() {
+        if (COUNTTOKENS)  Token.tokens ++;
+        return new Token.UnionToken(Token.UNION);
+    }
+    static Token createEmpty() {
+        return Token.token_empty;
+    }
+    static RangeToken createRange() {
+        if (COUNTTOKENS)  Token.tokens ++;
+        return new RangeToken(Token.RANGE);
+    }
+    static RangeToken createNRange() {
+        if (COUNTTOKENS)  Token.tokens ++;
+        return new RangeToken(Token.NRANGE);
+    }
+    static Token.CharToken createChar(int ch) {
+        if (COUNTTOKENS)  Token.tokens ++;
+        return new Token.CharToken(Token.CHAR, ch);
+    }
+    static private Token.CharToken createAnchor(int ch) {
+        if (COUNTTOKENS)  Token.tokens ++;
+        return new Token.CharToken(Token.ANCHOR, ch);
+    }
+    static Token.StringToken createBackReference(int refno) {
+        if (COUNTTOKENS)  Token.tokens ++;
+        return new Token.StringToken(Token.BACKREFERENCE, null, refno);
+    }
+    static Token.StringToken createString(String str) {
+        if (COUNTTOKENS)  Token.tokens ++;
+        return new Token.StringToken(Token.STRING, str, 0);
+    }
+    static Token.ModifierToken createModifierGroup(Token child, int add, int mask) {
+        if (COUNTTOKENS)  Token.tokens ++;
+        return new Token.ModifierToken(child, add, mask);
+    }
+    static Token.ConditionToken createCondition(int refno, Token condition,
+                                                Token yespat, Token nopat) {
+        if (COUNTTOKENS)  Token.tokens ++;
+        return new Token.ConditionToken(refno, condition, yespat, nopat);
+    }
+
+    protected Token(int type) {
+        this.type = type;
+    }
+
+    /**
+     * A number of children.
+     */
+    int size() {
+        return 0;
+    }
+    Token getChild(int index) {
+        return null;
+    }
+    void addChild(Token tok) {
+        throw new RuntimeException("Not supported.");
+    }
+
+                                                // for RANGE or NRANGE
+    protected void addRange(int start, int end) {
+        throw new RuntimeException("Not supported.");
+    }
+    protected void sortRanges() {
+        throw new RuntimeException("Not supported.");
+    }
+    protected void compactRanges() {
+        throw new RuntimeException("Not supported.");
+    }
+    protected void mergeRanges(Token tok) {
+        throw new RuntimeException("Not supported.");
+    }
+    protected void subtractRanges(Token tok) {
+        throw new RuntimeException("Not supported.");
+    }
+    protected void intersectRanges(Token tok) {
+        throw new RuntimeException("Not supported.");
+    }
+    static Token complementRanges(Token tok) {
+        return RangeToken.complementRanges(tok);
+    }
+
+
+    void setMin(int min) {                      // for CLOSURE
+    }
+    void setMax(int max) {                      // for CLOSURE
+    }
+    int getMin() {                              // for CLOSURE
+        return -1;
+    }
+    int getMax() {                              // for CLOSURE
+        return -1;
+    }
+    int getReferenceNumber() {                  // for STRING
+        return 0;
+    }
+    String getString() {                        // for STRING
+        return null;
+    }
+
+    int getParenNumber() {
+        return 0;
+    }
+    int getChar() {
+        return -1;
+    }
+
+    @Override
+    public String toString() {
+        return this.toString(0);
+    }
+    public String toString(int options) {
+        return this.type == Token.DOT ? "." : "";
+    }
+
+    /**
+     * How many characters are needed?
+     */
+    final int getMinLength() {
+        switch (this.type) {
+          case CONCAT:
+            int sum = 0;
+            for (int i = 0;  i < this.size();  i ++)
+                sum += this.getChild(i).getMinLength();
+            return sum;
+
+          case CONDITION:
+          case UNION:
+            if (this.size() == 0)
+                return 0;
+            int ret = this.getChild(0).getMinLength();
+            for (int i = 1;  i < this.size();  i ++) {
+                int min = this.getChild(i).getMinLength();
+                if (min < ret)  ret = min;
+            }
+            return ret;
+
+          case CLOSURE:
+          case NONGREEDYCLOSURE:
+            if (this.getMin() >= 0)
+                return this.getMin() * this.getChild(0).getMinLength();
+            return 0;
+
+          case EMPTY:
+          case ANCHOR:
+            return 0;
+
+          case DOT:
+          case CHAR:
+          case RANGE:
+          case NRANGE:
+            return 1;
+
+          case INDEPENDENT:
+          case PAREN:
+          case MODIFIERGROUP:
+            return this.getChild(0).getMinLength();
+
+          case BACKREFERENCE:
+            return 0;                           // *******
+
+          case STRING:
+            return this.getString().length();
+
+          case LOOKAHEAD:
+          case NEGATIVELOOKAHEAD:
+          case LOOKBEHIND:
+          case NEGATIVELOOKBEHIND:
+            return 0;                           // ***** Really?
+
+          default:
+            throw new RuntimeException("Token#getMinLength(): Invalid Type: "+this.type);
+        }
+    }
+
+    final int getMaxLength() {
+        switch (this.type) {
+          case CONCAT:
+            int sum = 0;
+            for (int i = 0;  i < this.size();  i ++) {
+                int d = this.getChild(i).getMaxLength();
+                if (d < 0)  return -1;
+                sum += d;
+            }
+            return sum;
+
+          case CONDITION:
+          case UNION:
+            if (this.size() == 0)
+                return 0;
+            int ret = this.getChild(0).getMaxLength();
+            for (int i = 1;  ret >= 0 && i < this.size();  i ++) {
+                int max = this.getChild(i).getMaxLength();
+                if (max < 0) {                  // infinity
+                    ret = -1;
+                    break;
+                }
+                if (max > ret)  ret = max;
+            }
+            return ret;
+
+          case CLOSURE:
+          case NONGREEDYCLOSURE:
+            if (this.getMax() >= 0)
+                                                // When this.child.getMaxLength() < 0,
+                                                // this returns minus value
+                return this.getMax() * this.getChild(0).getMaxLength();
+            return -1;
+
+          case EMPTY:
+          case ANCHOR:
+            return 0;
+
+          case CHAR:
+            return 1;
+          case DOT:
+          case RANGE:
+          case NRANGE:
+            return 2;
+
+          case INDEPENDENT:
+          case PAREN:
+          case MODIFIERGROUP:
+            return this.getChild(0).getMaxLength();
+
+          case BACKREFERENCE:
+            return -1;                          // ******
+
+          case STRING:
+            return this.getString().length();
+
+          case LOOKAHEAD:
+          case NEGATIVELOOKAHEAD:
+          case LOOKBEHIND:
+          case NEGATIVELOOKBEHIND:
+            return 0;                           // ***** Really?
+
+          default:
+            throw new RuntimeException("Token#getMaxLength(): Invalid Type: "+this.type);
+        }
+    }
+
+    static final int FC_CONTINUE = 0;
+    static final int FC_TERMINAL = 1;
+    static final int FC_ANY = 2;
+    private static final boolean isSet(int options, int flag) {
+        return (options & flag) == flag;
+    }
+    final int analyzeFirstCharacter(RangeToken result, int options) {
+        switch (this.type) {
+          case CONCAT:
+            int ret = FC_CONTINUE;
+            for (int i = 0;  i < this.size();  i ++)
+                if ((ret = this.getChild(i).analyzeFirstCharacter(result, options)) != FC_CONTINUE)
+                    break;
+            return ret;
+
+          case UNION:
+            if (this.size() == 0)
+                return FC_CONTINUE;
+            /*
+             *  a|b|c -> FC_TERMINAL
+             *  a|.|c -> FC_ANY
+             *  a|b|  -> FC_CONTINUE
+             */
+            int ret2 = FC_CONTINUE;
+            boolean hasEmpty = false;
+            for (int i = 0;  i < this.size();  i ++) {
+                ret2 = this.getChild(i).analyzeFirstCharacter(result, options);
+                if (ret2 == FC_ANY)
+                    break;
+                else if (ret2 == FC_CONTINUE)
+                    hasEmpty = true;
+            }
+            return hasEmpty ? FC_CONTINUE : ret2;
+
+          case CONDITION:
+            int ret3 = this.getChild(0).analyzeFirstCharacter(result, options);
+            if (this.size() == 1)  return FC_CONTINUE;
+            if (ret3 == FC_ANY)  return ret3;
+            int ret4 = this.getChild(1).analyzeFirstCharacter(result, options);
+            if (ret4 == FC_ANY)  return ret4;
+            return ret3 == FC_CONTINUE || ret4 == FC_CONTINUE ? FC_CONTINUE : FC_TERMINAL;
+
+          case CLOSURE:
+          case NONGREEDYCLOSURE:
+            this.getChild(0).analyzeFirstCharacter(result, options);
+            return FC_CONTINUE;
+
+          case EMPTY:
+          case ANCHOR:
+            return FC_CONTINUE;
+
+          case CHAR:
+            int ch = this.getChar();
+            result.addRange(ch, ch);
+            if (ch < 0x10000 && isSet(options, RegularExpression.IGNORE_CASE)) {
+                ch = Character.toUpperCase((char)ch);
+                result.addRange(ch, ch);
+                ch = Character.toLowerCase((char)ch);
+                result.addRange(ch, ch);
+            }
+            return FC_TERMINAL;
+
+          case DOT:
+              return FC_ANY;
+
+          case RANGE:
+            result.mergeRanges(this);
+            return FC_TERMINAL;
+
+          case NRANGE:                          // ****
+            result.mergeRanges(Token.complementRanges(this));
+            return FC_TERMINAL;
+
+          case INDEPENDENT:
+          case PAREN:
+            return this.getChild(0).analyzeFirstCharacter(result, options);
+
+          case MODIFIERGROUP:
+            options |= ((ModifierToken)this).getOptions();
+            options &= ~((ModifierToken)this).getOptionsMask();
+            return this.getChild(0).analyzeFirstCharacter(result, options);
+
+          case BACKREFERENCE:
+            result.addRange(0, UTF16_MAX);  // **** We can not optimize.
+            return FC_ANY;
+
+          case STRING:
+            int cha = this.getString().charAt(0);
+            int ch2;
+            if (REUtil.isHighSurrogate(cha)
+                && this.getString().length() >= 2
+                && REUtil.isLowSurrogate((ch2 = this.getString().charAt(1))))
+                cha = REUtil.composeFromSurrogates(cha, ch2);
+            result.addRange(cha, cha);
+            if (cha < 0x10000 && isSet(options, RegularExpression.IGNORE_CASE)) {
+                cha = Character.toUpperCase((char)cha);
+                result.addRange(cha, cha);
+                cha = Character.toLowerCase((char)cha);
+                result.addRange(cha, cha);
+            }
+            return FC_TERMINAL;
+
+          case LOOKAHEAD:
+          case NEGATIVELOOKAHEAD:
+          case LOOKBEHIND:
+          case NEGATIVELOOKBEHIND:
+            return FC_CONTINUE;
+
+          default:
+            throw new RuntimeException("Token#analyzeHeadCharacter(): Invalid Type: "+this.type);
+        }
+    }
+
+    private final boolean isShorterThan(Token tok) {
+        if (tok == null)  return false;
+        /*
+        int mylength;
+        if (this.type == STRING)  mylength = this.getString().length();
+        else if (this.type == CHAR)  mylength = this.getChar() >= 0x10000 ? 2 : 1;
+        else throw new RuntimeException("Internal Error: Illegal type: "+this.type);
+        int otherlength;
+        if (tok.type == STRING)  otherlength = tok.getString().length();
+        else if (tok.type == CHAR)  otherlength = tok.getChar() >= 0x10000 ? 2 : 1;
+        else throw new RuntimeException("Internal Error: Illegal type: "+tok.type);
+        */
+        int mylength;
+        if (this.type == STRING)  mylength = this.getString().length();
+        else throw new RuntimeException("Internal Error: Illegal type: "+this.type);
+        int otherlength;
+        if (tok.type == STRING)  otherlength = tok.getString().length();
+        else throw new RuntimeException("Internal Error: Illegal type: "+tok.type);
+        return mylength < otherlength;
+    }
+
+    static class FixedStringContainer {
+        Token token = null;
+        int options = 0;
+        FixedStringContainer() {
+        }
+    }
+
+    final void findFixedString(FixedStringContainer container, int options) {
+        switch (this.type) {
+          case CONCAT:
+            Token prevToken = null;
+            int prevOptions = 0;
+            for (int i = 0;  i < this.size();  i ++) {
+                this.getChild(i).findFixedString(container, options);
+                if (prevToken == null || prevToken.isShorterThan(container.token)) {
+                    prevToken = container.token;
+                    prevOptions = container.options;
+                }
+            }
+            container.token = prevToken;
+            container.options = prevOptions;
+            return;
+
+          case UNION:
+          case CLOSURE:
+          case NONGREEDYCLOSURE:
+          case EMPTY:
+          case ANCHOR:
+          case RANGE:
+          case DOT:
+          case NRANGE:
+          case BACKREFERENCE:
+          case LOOKAHEAD:
+          case NEGATIVELOOKAHEAD:
+          case LOOKBEHIND:
+          case NEGATIVELOOKBEHIND:
+          case CONDITION:
+            container.token = null;
+            return;
+
+          case CHAR:                            // Ignore CHAR tokens.
+            container.token = null;             // **
+            return;                             // **
+
+          case STRING:
+            container.token = this;
+            container.options = options;
+            return;
+
+          case INDEPENDENT:
+          case PAREN:
+            this.getChild(0).findFixedString(container, options);
+            return;
+
+          case MODIFIERGROUP:
+            options |= ((ModifierToken)this).getOptions();
+            options &= ~((ModifierToken)this).getOptionsMask();
+            this.getChild(0).findFixedString(container, options);
+            return;
+
+          default:
+            throw new RuntimeException("Token#findFixedString(): Invalid Type: "+this.type);
+        }
+    }
+
+    boolean match(int ch) {
+        throw new RuntimeException("NFAArrow#match(): Internal error: "+this.type);
+    }
+
+    // ------------------------------------------------------
+    private final static Hashtable categories = new Hashtable();
+    private final static Hashtable categories2 = new Hashtable();
+    private static final String[] categoryNames = {
+        "Cn", "Lu", "Ll", "Lt", "Lm", "Lo", "Mn", "Me", "Mc", "Nd",
+        "Nl", "No", "Zs", "Zl", "Zp", "Cc", "Cf", null, "Co", "Cs",
+        "Pd", "Ps", "Pe", "Pc", "Po", "Sm", "Sc", "Sk", "So", // 28
+        "Pi", "Pf",  // 29, 30
+        "L", "M", "N", "Z", "C", "P", "S",      // 31-37
+    };
+
+    // Schema Rec. {Datatypes} - Punctuation 
+    static final int CHAR_INIT_QUOTE  = 29;     // Pi - initial quote
+    static final int CHAR_FINAL_QUOTE = 30;     // Pf - final quote
+    static final int CHAR_LETTER = 31;
+    static final int CHAR_MARK = 32;
+    static final int CHAR_NUMBER = 33;
+    static final int CHAR_SEPARATOR = 34;
+    static final int CHAR_OTHER = 35;
+    static final int CHAR_PUNCTUATION = 36;
+    static final int CHAR_SYMBOL = 37;
+    
+    //blockNames in UNICODE 3.1 that supported by XML Schema REC             
+    private static final String[] blockNames = {
+        /*0000..007F;*/ "Basic Latin",
+        /*0080..00FF;*/ "Latin-1 Supplement",
+        /*0100..017F;*/ "Latin Extended-A",
+        /*0180..024F;*/ "Latin Extended-B",
+        /*0250..02AF;*/ "IPA Extensions",
+        /*02B0..02FF;*/ "Spacing Modifier Letters",
+        /*0300..036F;*/ "Combining Diacritical Marks",
+        /*0370..03FF;*/ "Greek",
+        /*0400..04FF;*/ "Cyrillic",
+        /*0530..058F;*/ "Armenian",
+        /*0590..05FF;*/ "Hebrew",
+        /*0600..06FF;*/ "Arabic",
+        /*0700..074F;*/ "Syriac",  
+        /*0780..07BF;*/ "Thaana",
+        /*0900..097F;*/ "Devanagari",
+        /*0980..09FF;*/ "Bengali",
+        /*0A00..0A7F;*/ "Gurmukhi",
+        /*0A80..0AFF;*/ "Gujarati",
+        /*0B00..0B7F;*/ "Oriya",
+        /*0B80..0BFF;*/ "Tamil",
+        /*0C00..0C7F;*/ "Telugu",
+        /*0C80..0CFF;*/ "Kannada",
+        /*0D00..0D7F;*/ "Malayalam",
+        /*0D80..0DFF;*/ "Sinhala",
+        /*0E00..0E7F;*/ "Thai",
+        /*0E80..0EFF;*/ "Lao",
+        /*0F00..0FFF;*/ "Tibetan",
+        /*1000..109F;*/ "Myanmar", 
+        /*10A0..10FF;*/ "Georgian",
+        /*1100..11FF;*/ "Hangul Jamo",
+        /*1200..137F;*/ "Ethiopic",
+        /*13A0..13FF;*/ "Cherokee",
+        /*1400..167F;*/ "Unified Canadian Aboriginal Syllabics",
+        /*1680..169F;*/ "Ogham",
+        /*16A0..16FF;*/ "Runic",
+        /*1780..17FF;*/ "Khmer",
+        /*1800..18AF;*/ "Mongolian",
+        /*1E00..1EFF;*/ "Latin Extended Additional",
+        /*1F00..1FFF;*/ "Greek Extended",
+        /*2000..206F;*/ "General Punctuation",
+        /*2070..209F;*/ "Superscripts and Subscripts",
+        /*20A0..20CF;*/ "Currency Symbols",
+        /*20D0..20FF;*/ "Combining Marks for Symbols",
+        /*2100..214F;*/ "Letterlike Symbols",
+        /*2150..218F;*/ "Number Forms",
+        /*2190..21FF;*/ "Arrows",
+        /*2200..22FF;*/ "Mathematical Operators",
+        /*2300..23FF;*/ "Miscellaneous Technical",
+        /*2400..243F;*/ "Control Pictures",
+        /*2440..245F;*/ "Optical Character Recognition",
+        /*2460..24FF;*/ "Enclosed Alphanumerics",
+        /*2500..257F;*/ "Box Drawing",
+        /*2580..259F;*/ "Block Elements",
+        /*25A0..25FF;*/ "Geometric Shapes",
+        /*2600..26FF;*/ "Miscellaneous Symbols",
+        /*2700..27BF;*/ "Dingbats",
+        /*2800..28FF;*/ "Braille Patterns",
+        /*2E80..2EFF;*/ "CJK Radicals Supplement",
+        /*2F00..2FDF;*/ "Kangxi Radicals",
+        /*2FF0..2FFF;*/ "Ideographic Description Characters",
+        /*3000..303F;*/ "CJK Symbols and Punctuation",
+        /*3040..309F;*/ "Hiragana",
+        /*30A0..30FF;*/ "Katakana",
+        /*3100..312F;*/ "Bopomofo",
+        /*3130..318F;*/ "Hangul Compatibility Jamo",
+        /*3190..319F;*/ "Kanbun",
+        /*31A0..31BF;*/ "Bopomofo Extended",
+        /*3200..32FF;*/ "Enclosed CJK Letters and Months",
+        /*3300..33FF;*/ "CJK Compatibility",
+        /*3400..4DB5;*/ "CJK Unified Ideographs Extension A",
+        /*4E00..9FFF;*/ "CJK Unified Ideographs",
+        /*A000..A48F;*/ "Yi Syllables",
+        /*A490..A4CF;*/ "Yi Radicals",
+        /*AC00..D7A3;*/ "Hangul Syllables",
+        /*E000..F8FF;*/ "Private Use",
+        /*F900..FAFF;*/ "CJK Compatibility Ideographs",
+        /*FB00..FB4F;*/ "Alphabetic Presentation Forms",
+        /*FB50..FDFF;*/ "Arabic Presentation Forms-A",
+        /*FE20..FE2F;*/ "Combining Half Marks",
+        /*FE30..FE4F;*/ "CJK Compatibility Forms",
+        /*FE50..FE6F;*/ "Small Form Variants",
+        /*FE70..FEFE;*/ "Arabic Presentation Forms-B",
+        /*FEFF..FEFF;*/ "Specials",
+        /*FF00..FFEF;*/ "Halfwidth and Fullwidth Forms",
+         //missing Specials add manually
+        /*10300..1032F;*/ "Old Italic",		// 84
+        /*10330..1034F;*/ "Gothic",
+        /*10400..1044F;*/ "Deseret",
+        /*1D000..1D0FF;*/ "Byzantine Musical Symbols",
+        /*1D100..1D1FF;*/ "Musical Symbols",
+        /*1D400..1D7FF;*/ "Mathematical Alphanumeric Symbols",
+        /*20000..2A6D6;*/ "CJK Unified Ideographs Extension B",
+        /*2F800..2FA1F;*/ "CJK Compatibility Ideographs Supplement",
+        /*E0000..E007F;*/ "Tags",
+        //missing 2 private use add manually
+
+    };
+    //ADD THOSE MANUALLY
+    //F0000..FFFFD; "Private Use",
+    //100000..10FFFD; "Private Use"
+    //FFF0..FFFD; "Specials", 
+    static final String blockRanges = 
+       "\u0000\u007F\u0080\u00FF\u0100\u017F\u0180\u024F\u0250\u02AF\u02B0\u02FF\u0300\u036F"
+        +"\u0370\u03FF\u0400\u04FF\u0530\u058F\u0590\u05FF\u0600\u06FF\u0700\u074F\u0780\u07BF"
+        +"\u0900\u097F\u0980\u09FF\u0A00\u0A7F\u0A80\u0AFF\u0B00\u0B7F\u0B80\u0BFF\u0C00\u0C7F\u0C80\u0CFF"
+        +"\u0D00\u0D7F\u0D80\u0DFF\u0E00\u0E7F\u0E80\u0EFF\u0F00\u0FFF\u1000\u109F\u10A0\u10FF\u1100\u11FF"
+        +"\u1200\u137F\u13A0\u13FF\u1400\u167F\u1680\u169F\u16A0\u16FF\u1780\u17FF\u1800\u18AF\u1E00\u1EFF"
+        +"\u1F00\u1FFF\u2000\u206F\u2070\u209F\u20A0\u20CF\u20D0\u20FF\u2100\u214F\u2150\u218F\u2190\u21FF\u2200\u22FF"
+        +"\u2300\u23FF\u2400\u243F\u2440\u245F\u2460\u24FF\u2500\u257F\u2580\u259F\u25A0\u25FF\u2600\u26FF\u2700\u27BF"
+        +"\u2800\u28FF\u2E80\u2EFF\u2F00\u2FDF\u2FF0\u2FFF\u3000\u303F\u3040\u309F\u30A0\u30FF\u3100\u312F\u3130\u318F"
+        +"\u3190\u319F\u31A0\u31BF\u3200\u32FF\u3300\u33FF\u3400\u4DB5\u4E00\u9FFF\uA000\uA48F\uA490\uA4CF"
+        +"\uAC00\uD7A3\uE000\uF8FF\uF900\uFAFF\uFB00\uFB4F\uFB50\uFDFF"
+        +"\uFE20\uFE2F\uFE30\uFE4F\uFE50\uFE6F\uFE70\uFEFE\uFEFF\uFEFF\uFF00\uFFEF";
+    static final int[] nonBMPBlockRanges = {
+        0x10300, 0x1032F,       // 84
+        0x10330, 0x1034F,
+        0x10400, 0x1044F,
+        0x1D000, 0x1D0FF,
+        0x1D100, 0x1D1FF,
+        0x1D400, 0x1D7FF,
+        0x20000, 0x2A6D6,
+        0x2F800, 0x2FA1F,
+        0xE0000, 0xE007F
+    };
+    private static final int NONBMP_BLOCK_START = 84;
+
+    static protected RangeToken getRange(String name, boolean positive) {
+        if (Token.categories.size() == 0) {
+            synchronized (Token.categories) {
+                Token[] ranges = new Token[Token.categoryNames.length];
+                for (int i = 0;  i < ranges.length;  i ++) {
+                    ranges[i] = Token.createRange();
+                }
+                int type;
+                for (int i = 0;  i < 0x10000;  i ++) {
+                    type = Character.getType((char)i);
+                    if (type == Character.START_PUNCTUATION || 
+                        type == Character.END_PUNCTUATION) {
+                        //build table of Pi values
+                        if (i == 0x00AB || i == 0x2018 || i == 0x201B || i == 0x201C ||
+                            i == 0x201F || i == 0x2039) {
+                            type = CHAR_INIT_QUOTE;
+                        }
+                        //build table of Pf values
+                        if (i == 0x00BB || i == 0x2019 || i == 0x201D || i == 0x203A ) {
+                            type = CHAR_FINAL_QUOTE;
+                        }
+                    }
+                    ranges[type].addRange(i, i);
+                    switch (type) {
+                      case Character.UPPERCASE_LETTER:
+                      case Character.LOWERCASE_LETTER:
+                      case Character.TITLECASE_LETTER:
+                      case Character.MODIFIER_LETTER:
+                      case Character.OTHER_LETTER:
+                        type = CHAR_LETTER;
+                        break;
+                      case Character.NON_SPACING_MARK:
+                      case Character.COMBINING_SPACING_MARK:
+                      case Character.ENCLOSING_MARK:
+                        type = CHAR_MARK;
+                        break;
+                      case Character.DECIMAL_DIGIT_NUMBER:
+                      case Character.LETTER_NUMBER:
+                      case Character.OTHER_NUMBER:
+                        type = CHAR_NUMBER;
+                        break;
+                      case Character.SPACE_SEPARATOR:
+                      case Character.LINE_SEPARATOR:
+                      case Character.PARAGRAPH_SEPARATOR:
+                        type = CHAR_SEPARATOR;
+                        break;
+                      case Character.CONTROL:
+                      case Character.FORMAT:
+                      case Character.SURROGATE:
+                      case Character.PRIVATE_USE:
+                      case Character.UNASSIGNED:
+                        type = CHAR_OTHER;
+                        break;
+                      case Character.CONNECTOR_PUNCTUATION:
+                      case Character.DASH_PUNCTUATION:
+                      case Character.START_PUNCTUATION:
+                      case Character.END_PUNCTUATION:
+                      case CHAR_INIT_QUOTE:
+                      case CHAR_FINAL_QUOTE:
+                      case Character.OTHER_PUNCTUATION:
+                        type = CHAR_PUNCTUATION;
+                        break;
+                      case Character.MATH_SYMBOL:
+                      case Character.CURRENCY_SYMBOL:
+                      case Character.MODIFIER_SYMBOL:
+                      case Character.OTHER_SYMBOL:
+                        type = CHAR_SYMBOL;
+                        break;
+                      default:
+                        throw new RuntimeException(Token.class.getName()+"#getRange(): Unknown Unicode category: "+type);
+                    }
+                    ranges[type].addRange(i, i);
+                } // for all characters
+                ranges[Character.UNASSIGNED].addRange(0x10000, Token.UTF16_MAX);
+
+                for (int i = 0;  i < ranges.length;  i ++) {
+                    if (Token.categoryNames[i] != null) {
+                        if (i == Character.UNASSIGNED) { // Unassigned
+                            ranges[i].addRange(0x10000, Token.UTF16_MAX);
+                        }
+                        Token.categories.put(Token.categoryNames[i], ranges[i]);
+                        Token.categories2.put(Token.categoryNames[i],
+                                              Token.complementRanges(ranges[i]));
+                    }
+                }
+                //REVISIT: do we really need to support block names as in Unicode 3.1
+                //         or we can just create all the names in IsBLOCKNAME format (XML Schema REC)?
+                //
+                StringBuffer buffer = new StringBuffer(50);
+                for (int i = 0;  i < Token.blockNames.length;  i ++) {
+                    Token r1 = Token.createRange();
+                    int location;
+                    if (i < NONBMP_BLOCK_START) {
+                        location = i*2;
+                        int rstart = Token.blockRanges.charAt(location);
+                        int rend = Token.blockRanges.charAt(location+1);
+                        //DEBUGING
+                        //System.out.println(n+" " +Integer.toHexString(rstart)
+                        //                     +"-"+ Integer.toHexString(rend));
+                        r1.addRange(rstart, rend);
+                    } else {
+                        location = (i - NONBMP_BLOCK_START) * 2;
+                        r1.addRange(Token.nonBMPBlockRanges[location],
+                                    Token.nonBMPBlockRanges[location + 1]);
+                    }
+                    String n = Token.blockNames[i];
+                    if (n.equals("Specials"))
+                        r1.addRange(0xfff0, 0xfffd);
+                    if (n.equals("Private Use")) {
+                        r1.addRange(0xF0000,0xFFFFD);
+                        r1.addRange(0x100000,0x10FFFD);
+                    }
+                    Token.categories.put(n, r1);
+                    Token.categories2.put(n, Token.complementRanges(r1));
+                    buffer.setLength(0);
+                    buffer.append("Is");
+                    if (n.indexOf(' ') >= 0) {
+                        for (int ci = 0;  ci < n.length();  ci ++)
+                            if (n.charAt(ci) != ' ')  buffer.append(n.charAt(ci));
+                    }
+                    else {
+                        buffer.append(n);
+                    }
+                    Token.setAlias(buffer.toString(), n, true);
+                }
+
+                // TR#18 1.2
+                Token.setAlias("ASSIGNED", "Cn", false);
+                Token.setAlias("UNASSIGNED", "Cn", true);
+                Token all = Token.createRange();
+                all.addRange(0, Token.UTF16_MAX);
+                Token.categories.put("ALL", all);
+                Token.categories2.put("ALL", Token.complementRanges(all));
+                Token.registerNonXS("ASSIGNED");
+                Token.registerNonXS("UNASSIGNED");
+                Token.registerNonXS("ALL");
+
+                Token isalpha = Token.createRange();
+                isalpha.mergeRanges(ranges[Character.UPPERCASE_LETTER]); // Lu
+                isalpha.mergeRanges(ranges[Character.LOWERCASE_LETTER]); // Ll
+                isalpha.mergeRanges(ranges[Character.OTHER_LETTER]); // Lo
+                Token.categories.put("IsAlpha", isalpha);
+                Token.categories2.put("IsAlpha", Token.complementRanges(isalpha));
+                Token.registerNonXS("IsAlpha");
+
+                Token isalnum = Token.createRange();
+                isalnum.mergeRanges(isalpha);   // Lu Ll Lo
+                isalnum.mergeRanges(ranges[Character.DECIMAL_DIGIT_NUMBER]); // Nd
+                Token.categories.put("IsAlnum", isalnum);
+                Token.categories2.put("IsAlnum", Token.complementRanges(isalnum));
+                Token.registerNonXS("IsAlnum");
+
+                Token isspace = Token.createRange();
+                isspace.mergeRanges(Token.token_spaces);
+                isspace.mergeRanges(ranges[CHAR_SEPARATOR]); // Z
+                Token.categories.put("IsSpace", isspace);
+                Token.categories2.put("IsSpace", Token.complementRanges(isspace));
+                Token.registerNonXS("IsSpace");
+
+                Token isword = Token.createRange();
+                isword.mergeRanges(isalnum);     // Lu Ll Lo Nd
+                isword.addRange('_', '_');
+                Token.categories.put("IsWord", isword);
+                Token.categories2.put("IsWord", Token.complementRanges(isword));
+                Token.registerNonXS("IsWord");
+
+                Token isascii = Token.createRange();
+                isascii.addRange(0, 127);
+                Token.categories.put("IsASCII", isascii);
+                Token.categories2.put("IsASCII", Token.complementRanges(isascii));
+                Token.registerNonXS("IsASCII");
+
+                Token isnotgraph = Token.createRange();
+                isnotgraph.mergeRanges(ranges[CHAR_OTHER]);
+                isnotgraph.addRange(' ', ' ');
+                Token.categories.put("IsGraph", Token.complementRanges(isnotgraph));
+                Token.categories2.put("IsGraph", isnotgraph);
+                Token.registerNonXS("IsGraph");
+
+                Token isxdigit = Token.createRange();
+                isxdigit.addRange('0', '9');
+                isxdigit.addRange('A', 'F');
+                isxdigit.addRange('a', 'f');
+                Token.categories.put("IsXDigit", Token.complementRanges(isxdigit));
+                Token.categories2.put("IsXDigit", isxdigit);
+                Token.registerNonXS("IsXDigit");
+
+                Token.setAlias("IsDigit", "Nd", true);
+                Token.setAlias("IsUpper", "Lu", true);
+                Token.setAlias("IsLower", "Ll", true);
+                Token.setAlias("IsCntrl", "C", true);
+                Token.setAlias("IsPrint", "C", false);
+                Token.setAlias("IsPunct", "P", true);
+                Token.registerNonXS("IsDigit");
+                Token.registerNonXS("IsUpper");
+                Token.registerNonXS("IsLower");
+                Token.registerNonXS("IsCntrl");
+                Token.registerNonXS("IsPrint");
+                Token.registerNonXS("IsPunct");
+
+                Token.setAlias("alpha", "IsAlpha", true);
+                Token.setAlias("alnum", "IsAlnum", true);
+                Token.setAlias("ascii", "IsASCII", true);
+                Token.setAlias("cntrl", "IsCntrl", true);
+                Token.setAlias("digit", "IsDigit", true);
+                Token.setAlias("graph", "IsGraph", true);
+                Token.setAlias("lower", "IsLower", true);
+                Token.setAlias("print", "IsPrint", true);
+                Token.setAlias("punct", "IsPunct", true);
+                Token.setAlias("space", "IsSpace", true);
+                Token.setAlias("upper", "IsUpper", true);
+                Token.setAlias("word", "IsWord", true); // Perl extension
+                Token.setAlias("xdigit", "IsXDigit", true);
+                Token.registerNonXS("alpha");
+                Token.registerNonXS("alnum");
+                Token.registerNonXS("ascii");
+                Token.registerNonXS("cntrl");
+                Token.registerNonXS("digit");
+                Token.registerNonXS("graph");
+                Token.registerNonXS("lower");
+                Token.registerNonXS("print");
+                Token.registerNonXS("punct");
+                Token.registerNonXS("space");
+                Token.registerNonXS("upper");
+                Token.registerNonXS("word");
+                Token.registerNonXS("xdigit");
+            } // synchronized
+        } // if null
+        RangeToken tok = positive ? (RangeToken)Token.categories.get(name)
+            : (RangeToken)Token.categories2.get(name);
+        //if (tok == null) System.out.println(name);
+        return tok;
+    }
+    static protected RangeToken getRange(String name, boolean positive, boolean xs) {
+        RangeToken range = Token.getRange(name, positive);
+        if (xs && range != null && Token.isRegisterNonXS(name))
+            range = null;
+        return range;
+    }
+
+    static Hashtable nonxs = null;
+    /**
+     * This method is called by only getRange().
+     * So this method need not MT-safe.
+     */
+    static protected void registerNonXS(String name) {
+        if (Token.nonxs == null)
+            Token.nonxs = new Hashtable();
+        Token.nonxs.put(name, name);
+    }
+    static protected boolean isRegisterNonXS(String name) {
+        if (Token.nonxs == null)
+            return false;
+        //DEBUG
+        //System.err.println("isRegisterNonXS: "+name);
+        return Token.nonxs.containsKey(name);
+    }
+
+    private static void setAlias(String newName, String name, boolean positive) {
+        Token t1 = (Token)Token.categories.get(name);
+        Token t2 = (Token)Token.categories2.get(name);
+        if (positive) {
+            Token.categories.put(newName, t1);
+            Token.categories2.put(newName, t2);
+        } else {
+            Token.categories2.put(newName, t1);
+            Token.categories.put(newName, t2);
+        }
+    }
+
+    // ------------------------------------------------------
+
+    static final String viramaString =
+    "\u094D"// ;DEVANAGARI SIGN VIRAMA;Mn;9;ON;;;;;N;;;;;
+    +"\u09CD"//;BENGALI SIGN VIRAMA;Mn;9;ON;;;;;N;;;;;
+    +"\u0A4D"//;GURMUKHI SIGN VIRAMA;Mn;9;ON;;;;;N;;;;;
+    +"\u0ACD"//;GUJARATI SIGN VIRAMA;Mn;9;ON;;;;;N;;;;;
+    +"\u0B4D"//;ORIYA SIGN VIRAMA;Mn;9;ON;;;;;N;;;;;
+    +"\u0BCD"//;TAMIL SIGN VIRAMA;Mn;9;ON;;;;;N;;;;;
+    +"\u0C4D"//;TELUGU SIGN VIRAMA;Mn;9;ON;;;;;N;;;;;
+    +"\u0CCD"//;KANNADA SIGN VIRAMA;Mn;9;ON;;;;;N;;;;;
+    +"\u0D4D"//;MALAYALAM SIGN VIRAMA;Mn;9;ON;;;;;N;;;;;
+    +"\u0E3A"//;THAI CHARACTER PHINTHU;Mn;9;ON;;;;;N;THAI VOWEL SIGN PHINTHU;;;;
+    +"\u0F84";//;TIBETAN MARK HALANTA;Mn;9;ON;;;;;N;TIBETAN VIRAMA;;;;
+
+    static private Token token_grapheme = null;
+    static synchronized Token getGraphemePattern() {
+        if (Token.token_grapheme != null)
+            return Token.token_grapheme;
+
+        Token base_char = Token.createRange();  // [{ASSIGNED}]-[{M},{C}]
+        base_char.mergeRanges(Token.getRange("ASSIGNED", true));
+        base_char.subtractRanges(Token.getRange("M", true));
+        base_char.subtractRanges(Token.getRange("C", true));
+
+        Token virama = Token.createRange();
+        for (int i = 0;  i < Token.viramaString.length(); i++) {
+            virama.addRange(i, i);
+        }
+
+        Token combiner_wo_virama = Token.createRange();
+        combiner_wo_virama.mergeRanges(Token.getRange("M", true));
+        combiner_wo_virama.addRange(0x1160, 0x11ff); // hangul_medial and hangul_final
+        combiner_wo_virama.addRange(0xff9e, 0xff9f); // extras
+
+        Token left = Token.createUnion();       // base_char?
+        left.addChild(base_char);
+        left.addChild(Token.token_empty);
+
+        Token foo = Token.createUnion();
+        foo.addChild(Token.createConcat(virama, Token.getRange("L", true)));
+        foo.addChild(combiner_wo_virama);
+
+        foo = Token.createClosure(foo);
+
+        foo = Token.createConcat(left, foo);
+
+        Token.token_grapheme = foo;
+        return Token.token_grapheme;
+    }
+
+    /**
+     * Combing Character Sequence in Perl 5.6.
+     */
+    static private Token token_ccs = null;
+    static synchronized Token getCombiningCharacterSequence() {
+        if (Token.token_ccs != null)
+            return Token.token_ccs;
+
+        Token foo = Token.createClosure(Token.getRange("M", true)); // \pM*
+        foo = Token.createConcat(Token.getRange("M", false), foo); // \PM + \pM*
+        Token.token_ccs = foo;
+        return Token.token_ccs;
+    }
+
+    // ------------------------------------------------------
+
+    // ------------------------------------------------------
+    /**
+     * This class represents a node in parse tree.
+     */
+    static class StringToken extends Token implements java.io.Serializable {
+
+        private static final long serialVersionUID = -4614366944218504172L;
+        
+        String string;
+        final int refNumber;
+
+        StringToken(int type, String str, int n) {
+            super(type);
+            this.string = str;
+            this.refNumber = n;
+        }
+
+        @Override
+        int getReferenceNumber() {              // for STRING
+            return this.refNumber;
+        }
+        @Override
+        String getString() {                    // for STRING
+            return this.string;
+        }
+        
+        @Override
+        public String toString(int options) {
+            if (this.type == BACKREFERENCE)
+                return "\\"+this.refNumber;
+            else
+                return REUtil.quoteMeta(this.string);
+        }
+    }
+
+    /**
+     * This class represents a node in parse tree.
+     */
+    static class ConcatToken extends Token implements java.io.Serializable {
+
+        private static final long serialVersionUID = 8717321425541346381L;
+        
+        final Token child;
+        final Token child2;
+        
+        ConcatToken(Token t1, Token t2) {
+            super(Token.CONCAT);
+            this.child = t1;
+            this.child2 = t2;
+        }
+
+        @Override
+        int size() {
+            return 2;
+        }
+        @Override
+        Token getChild(int index) {
+            return index == 0 ? this.child : this.child2;
+        }
+
+        @Override
+        public String toString(int options) {
+            String ret;
+            if (this.child2.type == CLOSURE && this.child2.getChild(0) == this.child) {
+                ret = this.child.toString(options)+"+";
+            } else if (this.child2.type == NONGREEDYCLOSURE && this.child2.getChild(0) == this.child) {
+                ret = this.child.toString(options)+"+?";
+            } else
+                ret = this.child.toString(options)+this.child2.toString(options);
+            return ret;
+        }
+    }
+
+    /**
+     * This class represents a node in parse tree.
+     */
+    static class CharToken extends Token implements java.io.Serializable {
+
+        private static final long serialVersionUID = -4394272816279496989L;
+        
+        final int chardata;
+
+        CharToken(int type, int ch) {
+            super(type);
+            this.chardata = ch;
+        }
+
+        @Override
+        int getChar() {
+            return this.chardata;
+        }
+
+        @Override
+        public String toString(int options) {
+            String ret;
+            switch (this.type) {
+              case CHAR:
+                switch (this.chardata) {
+                  case '|':  case '*':  case '+':  case '?':
+                  case '(':  case ')':  case '.':  case '[':
+                  case '{':  case '\\':
+                    ret = "\\"+(char)this.chardata;
+                    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 (this.chardata >= 0x10000) {
+                        String pre = "0"+Integer.toHexString(this.chardata);
+                        ret = "\\v"+pre.substring(pre.length()-6, pre.length());
+                    } else
+                        ret = ""+(char)this.chardata;
+                }
+                break;
+
+              case ANCHOR:
+                if (this == Token.token_linebeginning || this == Token.token_lineend)
+                    ret = ""+(char)this.chardata;
+                else 
+                    ret = "\\"+(char)this.chardata;
+                break;
+
+              default:
+                ret = null;
+            }
+            return ret;
+        }
+
+        @Override
+        boolean match(int ch) {
+            if (this.type == CHAR) {
+                return ch == this.chardata;
+            } else
+                throw new RuntimeException("NFAArrow#match(): Internal error: "+this.type);
+        }
+    }
+
+    /**
+     * This class represents a node in parse tree.
+     */
+    static class ClosureToken extends Token implements java.io.Serializable {
+
+        private static final long serialVersionUID = 1308971930673997452L;
+        
+        int min;
+        int max;
+        final Token child;
+
+        ClosureToken(int type, Token tok) {
+            super(type);
+            this.child = tok;
+            this.setMin(-1);
+            this.setMax(-1);
+        }
+
+        @Override
+        int size() {
+            return 1;
+        }
+        @Override
+        Token getChild(int index) {
+            return this.child;
+        }
+
+        @Override
+        final void setMin(int min) {
+            this.min = min;
+        }
+        @Override
+        final void setMax(int max) {
+            this.max = max;
+        }
+        @Override
+        final int getMin() {
+            return this.min;
+        }
+        @Override
+        final int getMax() {
+            return this.max;
+        }
+
+        @Override
+        public String toString(int options) {
+            String ret;
+            if (this.type == CLOSURE) {
+                if (this.getMin() < 0 && this.getMax() < 0) {
+                    ret = this.child.toString(options)+"*";
+                } else if (this.getMin() == this.getMax()) {
+                    ret = this.child.toString(options)+"{"+this.getMin()+"}";
+                } else if (this.getMin() >= 0 && this.getMax() >= 0) {
+                    ret = this.child.toString(options)+"{"+this.getMin()+","+this.getMax()+"}";
+                } else if (this.getMin() >= 0 && this.getMax() < 0) {
+                    ret = this.child.toString(options)+"{"+this.getMin()+",}";
+                } else
+                    throw new RuntimeException("Token#toString(): CLOSURE "
+                                               +this.getMin()+", "+this.getMax());
+            } else {
+                if (this.getMin() < 0 && this.getMax() < 0) {
+                    ret = this.child.toString(options)+"*?";
+                } else if (this.getMin() == this.getMax()) {
+                    ret = this.child.toString(options)+"{"+this.getMin()+"}?";
+                } else if (this.getMin() >= 0 && this.getMax() >= 0) {
+                    ret = this.child.toString(options)+"{"+this.getMin()+","+this.getMax()+"}?";
+                } else if (this.getMin() >= 0 && this.getMax() < 0) {
+                    ret = this.child.toString(options)+"{"+this.getMin()+",}?";
+                } else
+                    throw new RuntimeException("Token#toString(): NONGREEDYCLOSURE "
+                                               +this.getMin()+", "+this.getMax());
+            }
+            return ret;
+        }
+    }
+
+    /**
+     * This class represents a node in parse tree.
+     */
+    static class ParenToken extends Token implements java.io.Serializable {
+
+        private static final long serialVersionUID = -5938014719827987704L;
+        
+        final Token child;
+        final int parennumber;
+
+        ParenToken(int type, Token tok, int paren) {
+            super(type);
+            this.child = tok;
+            this.parennumber = paren;
+        }
+
+        @Override
+        int size() {
+            return 1;
+        }
+        @Override
+        Token getChild(int index) {
+            return this.child;
+        }
+
+        @Override
+        int getParenNumber() {
+            return this.parennumber;
+        }
+
+        @Override
+        public String toString(int options) {
+            String ret = null;
+            switch (this.type) {
+              case PAREN:
+                if (this.parennumber == 0) {
+                    ret = "(?:"+this.child.toString(options)+")";
+                } else {
+                    ret = "("+this.child.toString(options)+")";
+                }
+                break;
+
+              case LOOKAHEAD:
+                ret = "(?="+this.child.toString(options)+")";
+                break;
+              case NEGATIVELOOKAHEAD:
+                ret = "(?!"+this.child.toString(options)+")";
+                break;
+              case LOOKBEHIND:
+                ret = "(?<="+this.child.toString(options)+")";
+                break;
+              case NEGATIVELOOKBEHIND:
+                ret = "(?<!"+this.child.toString(options)+")";
+                break;
+              case INDEPENDENT:
+                ret = "(?>"+this.child.toString(options)+")";
+                break;
+            }
+            return ret;
+        }
+    }
+
+    /**
+     * (?(condition)yes-pattern|no-pattern)
+     */
+    static class ConditionToken extends Token implements java.io.Serializable {
+
+        private static final long serialVersionUID = 4353765277910594411L;
+        
+        final int refNumber;
+        final Token condition;
+        final Token yes;
+        final Token no;
+        ConditionToken(int refno, Token cond, Token yespat, Token nopat) {
+            super(Token.CONDITION);
+            this.refNumber = refno;
+            this.condition = cond;
+            this.yes = yespat;
+            this.no = nopat;
+        }
+        @Override
+        int size() {
+            return this.no == null ? 1 : 2;
+        }
+        @Override
+        Token getChild(int index) {
+            if (index == 0)  return this.yes;
+            if (index == 1)  return this.no;
+            throw new RuntimeException("Internal Error: "+index);
+        }
+
+        @Override
+        public String toString(int options) {
+            String ret;
+            if (refNumber > 0) {
+                ret = "(?("+refNumber+")";
+            } else if (this.condition.type == Token.ANCHOR) {
+                ret = "(?("+this.condition+")";
+            } else {
+                ret = "(?"+this.condition;
+            }
+
+            if (this.no == null) {
+                ret += this.yes+")";
+            } else {
+                ret += this.yes+"|"+this.no+")";
+            }
+            return ret;
+        }
+    }
+
+    /**
+     * (ims-ims: .... )
+     */
+    static class ModifierToken extends Token implements java.io.Serializable {
+
+        private static final long serialVersionUID = -9114536559696480356L;
+        
+        final Token child;
+        final int add;
+        final int mask;
+
+        ModifierToken(Token tok, int add, int mask) {
+            super(Token.MODIFIERGROUP);
+            this.child = tok;
+            this.add = add;
+            this.mask = mask;
+        }
+
+        @Override
+        int size() {
+            return 1;
+        }
+        @Override
+        Token getChild(int index) {
+            return this.child;
+        }
+
+        int getOptions() {
+            return this.add;
+        }
+        int getOptionsMask() {
+            return this.mask;
+        }
+
+        @Override
+        public String toString(int options) {
+            return "(?"
+                +(this.add == 0 ? "" : REUtil.createOptionString(this.add))
+                +(this.mask == 0 ? "" : REUtil.createOptionString(this.mask))
+                +":"
+                +this.child.toString(options)
+                +")";
+        }
+    }
+
+    /**
+     * This class represents a node in parse tree.
+     * for UNION or CONCAT.
+     */
+    static class UnionToken extends Token implements java.io.Serializable {
+
+        private static final long serialVersionUID = -2568843945989489861L;
+        
+        Vector children;
+
+        UnionToken(int type) {
+            super(type);
+        }
+
+        @Override
+        void addChild(Token tok) {
+            if (tok == null)  return;
+            if (this.children == null)  this.children = new Vector();
+            if (this.type == UNION) {
+                this.children.addElement(tok);
+                return;
+            }
+                                                // This is CONCAT, and new child is CONCAT.
+            if (tok.type == CONCAT) {
+                for (int i = 0;  i < tok.size();  i ++)
+                    this.addChild(tok.getChild(i)); // Recursion
+                return;
+            }
+            int size = this.children.size();
+            if (size == 0) {
+                this.children.addElement(tok);
+                return;
+            }
+            Token previous = (Token)this.children.elementAt(size-1);
+            if (!((previous.type == CHAR || previous.type == STRING)
+                  && (tok.type == CHAR || tok.type == STRING))) {
+                this.children.addElement(tok);
+                return;
+            }
+            
+            //System.err.println("Merge '"+previous+"' and '"+tok+"'.");
+
+            StringBuffer buffer;
+            int nextMaxLength = (tok.type == CHAR ? 2 : tok.getString().length());
+            if (previous.type == CHAR) {        // Replace previous token by STRING
+                buffer = new StringBuffer(2 + nextMaxLength);
+                int ch = previous.getChar();
+                if (ch >= 0x10000)
+                    buffer.append(REUtil.decomposeToSurrogates(ch));
+                else
+                    buffer.append((char)ch);
+                previous = Token.createString(null);
+                this.children.setElementAt(previous, size-1);
+            } else {                            // STRING
+                buffer = new StringBuffer(previous.getString().length() + nextMaxLength);
+                buffer.append(previous.getString());
+            }
+
+            if (tok.type == CHAR) {
+                int ch = tok.getChar();
+                if (ch >= 0x10000)
+                    buffer.append(REUtil.decomposeToSurrogates(ch));
+                else
+                    buffer.append((char)ch);
+            } else {
+                buffer.append(tok.getString());
+            }
+
+            ((StringToken)previous).string = new String(buffer);
+        }
+
+        @Override
+        int size() {
+            return this.children == null ? 0 : this.children.size();
+        }
+        @Override
+        Token getChild(int index) {
+            return (Token)this.children.elementAt(index);
+        }
+
+        @Override
+        public String toString(int options) {
+            String ret;
+            if (this.type == CONCAT) {
+                if (this.children.size() == 2) {
+                    Token ch = this.getChild(0);
+                    Token ch2 = this.getChild(1);
+                    if (ch2.type == CLOSURE && ch2.getChild(0) == ch) {
+                        ret = ch.toString(options)+"+";
+                    } else if (ch2.type == NONGREEDYCLOSURE && ch2.getChild(0) == ch) {
+                        ret = ch.toString(options)+"+?";
+                    } else
+                        ret = ch.toString(options)+ch2.toString(options);
+                } else {
+                    StringBuffer sb = new StringBuffer();
+                    for (int i = 0;  i < this.children.size();  i ++) {
+                        sb.append(((Token)this.children.elementAt(i)).toString(options));
+                    }
+                    ret = new String(sb);
+                }
+                return ret;
+            }
+            if (this.children.size() == 2 && this.getChild(1).type == EMPTY) {
+                ret = this.getChild(0).toString(options)+"?";
+            } else if (this.children.size() == 2
+                       && this.getChild(0).type == EMPTY) {
+                ret = this.getChild(1).toString(options)+"??";
+            } else {
+                StringBuffer sb = new StringBuffer();
+                sb.append(((Token)this.children.elementAt(0)).toString(options));
+                for (int i = 1;  i < this.children.size();  i ++) {
+                    sb.append('|');
+                    sb.append(((Token)this.children.elementAt(i)).toString(options));
+                }
+                ret = new String(sb);
+            }
+            return ret;
+        }
+    }
+}

http://git-wip-us.apache.org/repos/asf/jena/blob/c9a7e646/jena-core/src/main/java/org/apache/jena/ext/xerces/impl/xpath/regex/message.properties
----------------------------------------------------------------------
diff --git a/jena-core/src/main/java/org/apache/jena/ext/xerces/impl/xpath/regex/message.properties b/jena-core/src/main/java/org/apache/jena/ext/xerces/impl/xpath/regex/message.properties
new file mode 100644
index 0000000..ee5d50d
--- /dev/null
+++ b/jena-core/src/main/java/org/apache/jena/ext/xerces/impl/xpath/regex/message.properties
@@ -0,0 +1,58 @@
+#
+# Licensed to the Apache Software Foundation (ASF) under one or more
+# contributor license agreements.  See the NOTICE file distributed with
+# this work for additional information regarding copyright ownership.
+# The ASF licenses this file to You 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.
+#
+
+# @version $Id: message.properties 595212 2007-11-15 05:28:57Z mrglavas $
+
+parser.parse.1=Wrong character.
+parser.parse.2=Invalid reference number.
+parser.next.1=A character is required after \\.
+parser.next.2='?' is not expected.  '(?:' or '(?=' or '(?!' or '(?<' or '(?#' or '(?>'?
+parser.next.3='(?<=' or '(?<!' is expected.
+parser.next.4=A comment is not terminated.
+parser.factor.1=')' is expected.
+parser.factor.2=Unexpected end of the pattern in a modifier group.
+parser.factor.3=':' is expected.
+parser.factor.4=Unexpected end of the pattern in a conditional group.
+parser.factor.5=A back reference or an anchor or a lookahead or a lookbehind is expected in a conditional pattern.
+parser.factor.6=There are more than three choices in a conditional group.
+parser.atom.1=A character in U+0040-U+005f must follow \\c.
+parser.atom.2=A '{' is required before a character category.
+parser.atom.3=A property name is not closed by '}'.
+parser.atom.4=Unexpected meta character.
+parser.atom.5=Unknown property.
+parser.cc.1=A POSIX character class must be closed by ':]'.
+parser.cc.2=Unexpected end of the pattern in a character class.
+parser.cc.3=Unknown name for a POSIX character class.
+parser.cc.4='-' is invalid here.
+parser.cc.5=']' is expected.
+parser.cc.6='[' is invalid in a character class.  Write '\\['.
+parser.cc.7=']' is invalid in a character class.  Write '\\]'.
+parser.cc.8='-' is an invalid character range. Write '\\-'.
+parser.ope.1='[' is expected.
+parser.ope.2=')' or '-[' or '+[' or '&[' is expected.
+parser.ope.3=The range end code point is less than the start code point.
+parser.descape.1=Invalid Unicode hex notation.
+parser.descape.2=Overflow in a hex notation.
+parser.descape.3='\\x{' must be closed by '}'.
+parser.descape.4=Invalid Unicode code point.
+parser.descape.5=An anchor must not be here.
+parser.process.1=This expression is not supported in the current option setting.
+parser.quantifier.1=Invalid quantifier. A digit is expected.
+parser.quantifier.2=Invalid quantifier. Invalid quantity or a '}' is missing.
+parser.quantifier.3=Invalid quantifier. A digit or '}' is expected.
+parser.quantifier.4=Invalid quantifier. A min quantity must be <= a max quantity.
+parser.quantifier.5=Invalid quantifier. A quantity value overflow.

http://git-wip-us.apache.org/repos/asf/jena/blob/c9a7e646/jena-core/src/main/java/org/apache/jena/ext/xerces/impl/xpath/regex/message_fr.properties
----------------------------------------------------------------------
diff --git a/jena-core/src/main/java/org/apache/jena/ext/xerces/impl/xpath/regex/message_fr.properties b/jena-core/src/main/java/org/apache/jena/ext/xerces/impl/xpath/regex/message_fr.properties
new file mode 100644
index 0000000..6c1e840
--- /dev/null
+++ b/jena-core/src/main/java/org/apache/jena/ext/xerces/impl/xpath/regex/message_fr.properties
@@ -0,0 +1,58 @@
+#
+# Licensed to the Apache Software Foundation (ASF) under one or more
+# contributor license agreements.  See the NOTICE file distributed with
+# this work for additional information regarding copyright ownership.
+# The ASF licenses this file to You 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.
+#
+
+# @version $Id: message_fr.properties 595212 2007-11-15 05:28:57Z mrglavas $
+
+parser.parse.1=Caract\u00e8re erron\u00e9.
+parser.parse.2=Num\u00e9ro de r\u00e9f\u00e9rence non valide.
+parser.next.1=Un caract\u00e8re est requis apr\u00e8s \\.
+parser.next.2='?' n'est pas attendu.  '(?:', '(?=', '(?!', '(?<', '(?#', '(?>'?
+parser.next.3='(?<=' ou '(?<!' est attendu.
+parser.next.4=Commentaire sans caract\u00e8re de terminaison.
+parser.factor.1=')' attendu.
+parser.factor.2=Fin du mod\u00e8le attendue dans un groupe de modificateurs.
+parser.factor.3=':' attendu.
+parser.factor.4=Fin du mod\u00e8le inattendue dans un groupe conditionnel.
+parser.factor.5=Un mod\u00e8le conditionnel doit contenir un renvoi, une ancre, une lecture anticip\u00e9e ou une lecture diff\u00e9r\u00e9e.
+parser.factor.6=Un groupe conditionnel comporte plus de trois choix.
+parser.atom.1=Un caract\u00e8re de U+0040-U+005f doit suivre \\c.
+parser.atom.2=Une accolade ('{') est obligatoire devant une cat\u00e9gorie de caract\u00e8res.
+parser.atom.3=Un nom de propri\u00e9t\u00e9 n'est pas ferm\u00e9 par '}'.
+parser.atom.4=M\u00e9ta-caract\u00e8re inattendu.
+parser.atom.5=Propri\u00e9t\u00e9 inconnue.
+parser.cc.1=Une classe de caract\u00e8res POSIX doit \u00eatre ferm\u00e9e par ':]'.
+parser.cc.2=Fin du mod\u00e8le inattendue dans une classe de caract\u00e8res.
+parser.cc.3=Nom inconnu pour une classe de caract\u00e8res POSIX.
+parser.cc.4='-' n'est pas valide ici.
+parser.cc.5=']' est attendu.
+parser.cc.6='[' n'est pas valide dans une classe de caract\u00e8res.  Ecrire '\\['.
+parser.cc.7=']' n'est pas valide dans une classe de caract\u00e8res.  Ecrire '\\['.
+parser.cc.8='-' n'est pas valide dans un intervalle de caract\u00e8res. Ecrire '\\-'.
+parser.ope.1='[' est attendu.
+parser.ope.2=')', '-[', '+[' ou '&[' est attendu.
+parser.ope.3=Le point de code final doit \u00eatre inf\u00e9rieur au point de code initial dans l'intervalle.
+parser.descape.1=Notation hexad\u00e9cimale Unicode non valide.
+parser.descape.2=D\u00e9passement d'une notation hexad\u00e9cimale.
+parser.descape.3='\\x{' doit \u00eatre ferm\u00e9 par '}'.
+parser.descape.4=Point de code Unicode non valide.
+parser.descape.5=Une ancre ne doit pas figurer ici.
+parser.process.1=Cette expression n'est pas prise en charge dans le param\u00e8tre d'option courant.
+parser.quantifier.1=Quantifieur non valide. Valeur num\u00e9rique requise.
+parser.quantifier.2=Quantifieur non valide. Quantit\u00e9 non valide ou '}' manquant.
+parser.quantifier.3=Quantifieur non valide. Nombre ou '}' obligatoire.
+parser.quantifier.4=Quantifieur non valide. Une quantit\u00e9 minimale doit \u00eatre <= \u00e0 une quantit\u00e9 maximale.
+parser.quantifier.5=Quantifieur non valide. D\u00e9passement de quantit\u00e9.

http://git-wip-us.apache.org/repos/asf/jena/blob/c9a7e646/jena-core/src/main/java/org/apache/jena/ext/xerces/impl/xpath/regex/message_ja.properties
----------------------------------------------------------------------
diff --git a/jena-core/src/main/java/org/apache/jena/ext/xerces/impl/xpath/regex/message_ja.properties b/jena-core/src/main/java/org/apache/jena/ext/xerces/impl/xpath/regex/message_ja.properties
new file mode 100644
index 0000000..043e5fa
--- /dev/null
+++ b/jena-core/src/main/java/org/apache/jena/ext/xerces/impl/xpath/regex/message_ja.properties
@@ -0,0 +1,58 @@
+#
+# Licensed to the Apache Software Foundation (ASF) under one or more
+# contributor license agreements.  See the NOTICE file distributed with
+# this work for additional information regarding copyright ownership.
+# The ASF licenses this file to You 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.
+#
+
+# @version $Id: message_ja.properties 595212 2007-11-15 05:28:57Z mrglavas $
+
+parser.parse.1=\u4e0d\u5f53\u306a\u6587\u5b57\u3002
+parser.parse.2=\u7121\u52b9\u306a\u53c2\u7167\u756a\u53f7\u3002
+parser.next.1=\\ \u306e\u5f8c\u306b\u6587\u5b57\u304c\u5fc5\u8981\u3067\u3059\u3002
+parser.next.2='?' \u306f\u671f\u5f85\u3055\u308c\u3066\u3044\u307e\u305b\u3093\u3002'(?:' \u307e\u305f\u306f '(?=' \u307e\u305f\u306f '(?!' \u307e\u305f\u306f '(?<' \u307e\u305f\u306f '(?#' \u307e\u305f\u306f '(?>'?
+parser.next.3='(?<=' \u307e\u305f\u306f '(?<!' \u304c\u671f\u5f85\u3055\u308c\u3066\u3044\u307e\u3059\u3002
+parser.next.4=\u30b3\u30e1\u30f3\u30c8\u304c\u7d42\u7d50\u3057\u3066\u3044\u307e\u305b\u3093\u3002
+parser.factor.1=')' \u304c\u671f\u5f85\u3055\u308c\u3066\u3044\u307e\u3059\u3002
+parser.factor.2=\u4fee\u98fe\u5b50\u30b0\u30eb\u30fc\u30d7\u5185\u3067\u30d1\u30bf\u30fc\u30f3\u306e\u4e88\u671f\u3057\u306a\u3044\u7d42\u4e86\u3002
+parser.factor.3=':' \u304c\u671f\u5f85\u3055\u308c\u3066\u3044\u307e\u3059\u3002
+parser.factor.4=\u6761\u4ef6\u4ed8\u304d\u30b0\u30eb\u30fc\u30d7\u5185\u3067\u30d1\u30bf\u30fc\u30f3\u306e\u4e88\u671f\u3057\u306a\u3044\u7d42\u4e86\u3002
+parser.factor.5=\u6761\u4ef6\u4ed8\u304d\u30d1\u30bf\u30fc\u30f3\u3067\u306f\u9006\u53c2\u7167\u307e\u305f\u306f\u30a2\u30f3\u30ab\u30fc\u307e\u305f\u306f\u5148\u8aad\u307f\u304c\u671f\u5f85\u3055\u308c\u3066\u3044\u307e\u3059\u3002
+parser.factor.6=\u6761\u4ef6\u4ed8\u304d\u30b0\u30eb\u30fc\u30d7\u306b 3 \u3064\u3092\u8d85\u3048\u308b\u9078\u629e\u9805\u76ee\u304c\u3042\u308a\u307e\u3059\u3002
+parser.atom.1=\u5f8c\u306b \\c \u304c\u5fc5\u8981\u306a\u6587\u5b57\u304c U+0040-U+005f \u306b\u3042\u308a\u307e\u3059\u3002
+parser.atom.2=\u6587\u5b57\u30ab\u30c6\u30b4\u30ea\u30fc\u306e\u524d\u306b '{' \u304c\u5fc5\u8981\u3067\u3059\u3002
+parser.atom.3=\u30d7\u30ed\u30d1\u30c6\u30a3\u30fc\u540d\u304c '}' \u3067\u9589\u3058\u3089\u308c\u3066\u3044\u307e\u305b\u3093\u3002
+parser.atom.4=\u4e88\u671f\u3057\u306a\u3044\u30e1\u30bf\u6587\u5b57\u3002
+parser.atom.5=\u4e0d\u660e\u306a\u30d7\u30ed\u30d1\u30c6\u30a3\u30fc\u3002
+parser.cc.1=POSIX \u6587\u5b57\u30af\u30e9\u30b9\u306f ':]' \u3067\u9589\u3058\u3089\u308c\u3066\u3044\u306a\u3051\u308c\u3070\u306a\u308a\u307e\u305b\u3093\u3002
+parser.cc.2=\u6587\u5b57\u30af\u30e9\u30b9\u5185\u3067\u30d1\u30bf\u30fc\u30f3\u306e\u4e88\u671f\u3057\u306a\u3044\u7d42\u4e86\u3002
+parser.cc.3=POSIX \u6587\u5b57\u30af\u30e9\u30b9\u306e\u540d\u524d\u304c\u4e0d\u660e\u3067\u3059\u3002
+parser.cc.4='-' \u306f\u3053\u3053\u3067\u306f\u7121\u52b9\u3067\u3059\u3002
+parser.cc.5=']' \u304c\u671f\u5f85\u3055\u308c\u3066\u3044\u307e\u3059\u3002
+parser.cc.6='[' \u306f\u6587\u5b57\u30af\u30e9\u30b9\u5185\u3067\u306f\u7121\u52b9\u3067\u3059\u3002'\\[' \u3068\u66f8\u3044\u3066\u304f\u3060\u3055\u3044\u3002
+parser.cc.7=']' \u306f\u6587\u5b57\u30af\u30e9\u30b9\u5185\u3067\u306f\u7121\u52b9\u3067\u3059\u3002'\\]' \u3068\u66f8\u3044\u3066\u304f\u3060\u3055\u3044\u3002
+parser.cc.8='-' \u306f\u7121\u52b9\u306a\u6587\u5b57\u7bc4\u56f2\u3067\u3059\u3002'\\-' \u3068\u66f8\u3044\u3066\u304f\u3060\u3055\u3044\u3002
+parser.ope.1='[' \u304c\u671f\u5f85\u3055\u308c\u3066\u3044\u307e\u3059\u3002
+parser.ope.2=')' \u307e\u305f\u306f '-[' \u307e\u305f\u306f '+[' \u307e\u305f\u306f '&[' \u304c\u671f\u5f85\u3055\u308c\u3066\u3044\u307e\u3059\u3002
+parser.ope.3=\u7bc4\u56f2\u7d42\u4e86\u30b3\u30fc\u30c9\u30fb\u30dd\u30a4\u30f3\u30c8\u304c\u958b\u59cb\u30b3\u30fc\u30c9\u30fb\u30dd\u30a4\u30f3\u30c8\u3088\u308a\u5c0f\u3055\u3044\u5024\u306b\u306a\u3063\u3066\u3044\u307e\u3059\u3002
+parser.descape.1=\u7121\u52b9\u306a Unicode 16 \u9032\u8868\u8a18\u3002
+parser.descape.2=16 \u9032\u8868\u8a18\u3067\u30aa\u30fc\u30d0\u30fc\u30d5\u30ed\u30fc\u3002
+parser.descape.3='\\x{' \u306f '}' \u3067\u9589\u3058\u3089\u308c\u3066\u3044\u306a\u3051\u308c\u3070\u306a\u308a\u307e\u305b\u3093\u3002
+parser.descape.4=\u7121\u52b9\u306a Unicode \u30b3\u30fc\u30c9\u30fb\u30dd\u30a4\u30f3\u30c8\u3002
+parser.descape.5=\u3053\u3053\u306b\u30a2\u30f3\u30ab\u30fc\u304c\u3042\u3063\u3066\u306f\u306a\u308a\u307e\u305b\u3093\u3002
+parser.process.1=\u3053\u306e\u5f0f\u306f\u73fe\u5728\u306e\u30aa\u30d7\u30b7\u30e7\u30f3\u8a2d\u5b9a\u3067\u306f\u30b5\u30dd\u30fc\u30c8\u3055\u308c\u307e\u305b\u3093\u3002
+parser.quantifier.1=\u6570\u91cf\u8a5e\u304c\u7121\u52b9\u3067\u3059\u3002\u6570\u5b57\u304c\u671f\u5f85\u3055\u308c\u3066\u3044\u307e\u3059\u3002
+parser.quantifier.2=\u6570\u91cf\u8a5e\u304c\u7121\u52b9\u3067\u3059\u3002\u6570\u91cf\u304c\u7121\u52b9\u304b\u3001\u307e\u305f\u306f '}' \u304c\u3042\u308a\u307e\u305b\u3093\u3002
+parser.quantifier.3=\u6570\u91cf\u8a5e\u304c\u7121\u52b9\u3067\u3059\u3002\u6570\u5b57\u307e\u305f\u306f '}' \u304c\u671f\u5f85\u3055\u308c\u3066\u3044\u307e\u3059\u3002
+parser.quantifier.4=\u6570\u91cf\u8a5e\u304c\u7121\u52b9\u3067\u3059\u3002\u6700\u5c0f\u6570\u91cf\u306f\u6700\u5927\u6570\u91cf\u4ee5\u4e0b\u3067\u306a\u3051\u308c\u3070\u306a\u308a\u307e\u305b\u3093\u3002
+parser.quantifier.5=\u6570\u91cf\u8a5e\u304c\u7121\u52b9\u3067\u3059\u3002\u6570\u91cf\u5024\u304c\u30aa\u30fc\u30d0\u30fc\u30d5\u30ed\u30fc\u3057\u3066\u3044\u307e\u3059\u3002

http://git-wip-us.apache.org/repos/asf/jena/blob/c9a7e646/jena-core/src/main/java/org/apache/jena/ext/xerces/impl/xs/SchemaSymbols.java
----------------------------------------------------------------------
diff --git a/jena-core/src/main/java/org/apache/jena/ext/xerces/impl/xs/SchemaSymbols.java b/jena-core/src/main/java/org/apache/jena/ext/xerces/impl/xs/SchemaSymbols.java
new file mode 100644
index 0000000..08d2d1a
--- /dev/null
+++ b/jena-core/src/main/java/org/apache/jena/ext/xerces/impl/xs/SchemaSymbols.java
@@ -0,0 +1,215 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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.jena.ext.xerces.impl.xs;
+
+
+/**
+ * Collection of symbols used to parse a Schema Grammar.
+ *
+ * @xerces.internal 
+ *
+ * @author jeffrey rodriguez
+ * @version $Id: SchemaSymbols.java 446734 2006-09-15 20:51:23Z mrglavas $
+ */
+public final class SchemaSymbols {
+
+    // strings that's not added to the schema symbol table, because they
+    // are not symbols in the schema document.
+    // the validator can choose to add them by itself.
+
+    // the following strings (xsi:, xsd) will be added into the
+    // symbol table that comes with the parser
+
+    // xsi attributes: in validator
+    public static final String URI_XSI                        = "http://www.w3.org/2001/XMLSchema-instance".intern();
+    public static final String XSI_SCHEMALOCATION            = "schemaLocation".intern();
+    public static final String XSI_NONAMESPACESCHEMALOCATION = "noNamespaceSchemaLocation".intern();
+    public static final String XSI_TYPE                       = "type".intern();
+    public static final String XSI_NIL                        = "nil".intern();
+
+    // schema namespace
+    public static final String URI_SCHEMAFORSCHEMA            = "http://www.w3.org/2001/XMLSchema".intern();
+
+    // all possible schema element names
+    public static final String ELT_ALL                  = "all".intern();
+    public static final String ELT_ANNOTATION           = "annotation".intern();
+    public static final String ELT_ANY                  = "any".intern();
+    public static final String ELT_ANYATTRIBUTE         = "anyAttribute".intern();
+    public static final String ELT_APPINFO              = "appinfo".intern();
+    public static final String ELT_ATTRIBUTE            = "attribute".intern();
+    public static final String ELT_ATTRIBUTEGROUP       = "attributeGroup".intern();
+    public static final String ELT_CHOICE               = "choice".intern();
+    public static final String ELT_COMPLEXCONTENT       = "complexContent".intern();
+    public static final String ELT_COMPLEXTYPE          = "complexType".intern();
+    public static final String ELT_DOCUMENTATION        = "documentation".intern();
+    public static final String ELT_ELEMENT              = "element".intern();
+    public static final String ELT_ENUMERATION          = "enumeration".intern();
+    public static final String ELT_EXTENSION            = "extension".intern();
+    public static final String ELT_FIELD                = "field".intern();
+    public static final String ELT_FRACTIONDIGITS       = "fractionDigits".intern();
+    public static final String ELT_GROUP                = "group".intern();
+    public static final String ELT_IMPORT               = "import".intern();
+    public static final String ELT_INCLUDE              = "include".intern();
+    public static final String ELT_KEY                  = "key".intern();
+    public static final String ELT_KEYREF               = "keyref".intern();
+    public static final String ELT_LENGTH               = "length".intern();
+    public static final String ELT_LIST                 = "list".intern();
+    public static final String ELT_MAXEXCLUSIVE         = "maxExclusive".intern();
+    public static final String ELT_MAXINCLUSIVE         = "maxInclusive".intern();
+    public static final String ELT_MAXLENGTH            = "maxLength".intern();
+    public static final String ELT_MINEXCLUSIVE         = "minExclusive".intern();
+    public static final String ELT_MININCLUSIVE         = "minInclusive".intern();
+    public static final String ELT_MINLENGTH            = "minLength".intern();
+    public static final String ELT_NOTATION             = "notation".intern();
+    public static final String ELT_PATTERN              = "pattern".intern();
+    public static final String ELT_REDEFINE             = "redefine".intern();
+    public static final String ELT_RESTRICTION          = "restriction".intern();
+    public static final String ELT_SCHEMA               = "schema".intern();
+    public static final String ELT_SELECTOR             = "selector".intern();
+    public static final String ELT_SEQUENCE             = "sequence".intern();
+    public static final String ELT_SIMPLECONTENT        = "simpleContent".intern();
+    public static final String ELT_SIMPLETYPE           = "simpleType".intern();
+    public static final String ELT_TOTALDIGITS          = "totalDigits".intern();
+    public static final String ELT_UNION                = "union".intern();
+    public static final String ELT_UNIQUE               = "unique".intern();
+    public static final String ELT_WHITESPACE           = "whiteSpace".intern();
+
+    // all possible schema attribute names (and xml:lang defined on <schema> and <documentation>)
+    public static final String ATT_ABSTRACT             = "abstract".intern();
+    public static final String ATT_ATTRIBUTEFORMDEFAULT = "attributeFormDefault".intern();
+    public static final String ATT_BASE                 = "base".intern();
+    public static final String ATT_BLOCK                = "block".intern();
+    public static final String ATT_BLOCKDEFAULT         = "blockDefault".intern();
+    public static final String ATT_DEFAULT              = "default".intern();
+    public static final String ATT_ELEMENTFORMDEFAULT   = "elementFormDefault".intern();
+    public static final String ATT_FINAL                = "final".intern();
+    public static final String ATT_FINALDEFAULT         = "finalDefault".intern();
+    public static final String ATT_FIXED                = "fixed".intern();
+    public static final String ATT_FORM                 = "form".intern();
+    public static final String ATT_ID                   = "id".intern();
+    public static final String ATT_ITEMTYPE             = "itemType".intern();
+    public static final String ATT_MAXOCCURS            = "maxOccurs".intern();
+    public static final String ATT_MEMBERTYPES          = "memberTypes".intern();
+    public static final String ATT_MINOCCURS            = "minOccurs".intern();
+    public static final String ATT_MIXED                = "mixed".intern();
+    public static final String ATT_NAME                 = "name".intern();
+    public static final String ATT_NAMESPACE            = "namespace".intern();
+    public static final String ATT_NILLABLE             = "nillable".intern();
+    public static final String ATT_PROCESSCONTENTS      = "processContents".intern();
+    public static final String ATT_REF                  = "ref".intern();
+    public static final String ATT_REFER                = "refer".intern();
+    public static final String ATT_SCHEMALOCATION       = "schemaLocation".intern();
+    public static final String ATT_SOURCE               = "source".intern();
+    public static final String ATT_SUBSTITUTIONGROUP    = "substitutionGroup".intern();
+    public static final String ATT_SYSTEM               = "system".intern();
+    public static final String ATT_PUBLIC               = "public".intern();
+    public static final String ATT_TARGETNAMESPACE      = "targetNamespace".intern();
+    public static final String ATT_TYPE                 = "type".intern();
+    public static final String ATT_USE                  = "use".intern();
+    public static final String ATT_VALUE                = "value".intern();
+    public static final String ATT_VERSION              = "version".intern();
+    public static final String ATT_XML_LANG             = "xml:lang".intern();
+    public static final String ATT_XPATH                = "xpath".intern();
+
+    // all possible schema attribute values
+    public static final String ATTVAL_TWOPOUNDANY       = "##any";
+    public static final String ATTVAL_TWOPOUNDLOCAL     = "##local";
+    public static final String ATTVAL_TWOPOUNDOTHER     = "##other";
+    public static final String ATTVAL_TWOPOUNDTARGETNS  = "##targetNamespace";
+    public static final String ATTVAL_POUNDALL          = "#all";
+    public static final String ATTVAL_FALSE_0           = "0";
+    public static final String ATTVAL_TRUE_1            = "1";
+    public static final String ATTVAL_ANYSIMPLETYPE     = "anySimpleType";
+    public static final String ATTVAL_ANYTYPE           = "anyType";
+    public static final String ATTVAL_ANYURI            = "anyURI";
+    public static final String ATTVAL_BASE64BINARY      = "base64Binary";
+    public static final String ATTVAL_BOOLEAN           = "boolean";
+    public static final String ATTVAL_BYTE              = "byte";
+    public static final String ATTVAL_COLLAPSE          = "collapse";
+    public static final String ATTVAL_DATE              = "date";
+    public static final String ATTVAL_DATETIME          = "dateTime";
+    public static final String ATTVAL_DAY               = "gDay";
+    public static final String ATTVAL_DECIMAL           = "decimal";
+    public static final String ATTVAL_DOUBLE            = "double";
+    public static final String ATTVAL_DURATION          = "duration";
+    public static final String ATTVAL_ENTITY            = "ENTITY";
+    public static final String ATTVAL_ENTITIES          = "ENTITIES";
+    public static final String ATTVAL_EXTENSION         = "extension";
+    public static final String ATTVAL_FALSE             = "false";
+    public static final String ATTVAL_FLOAT             = "float";
+    public static final String ATTVAL_HEXBINARY         = "hexBinary";
+    public static final String ATTVAL_ID                = "ID";
+    public static final String ATTVAL_IDREF             = "IDREF";
+    public static final String ATTVAL_IDREFS            = "IDREFS";
+    public static final String ATTVAL_INT               = "int";
+    public static final String ATTVAL_INTEGER           = "integer";
+    public static final String ATTVAL_LANGUAGE          = "language";
+    public static final String ATTVAL_LAX               = "lax";
+    public static final String ATTVAL_LIST              = "list";
+    public static final String ATTVAL_LONG              = "long";
+    public static final String ATTVAL_NAME              = "Name";
+    public static final String ATTVAL_NEGATIVEINTEGER   = "negativeInteger";
+    public static final String ATTVAL_MONTH             = "gMonth";
+    public static final String ATTVAL_MONTHDAY          = "gMonthDay";
+    public static final String ATTVAL_NCNAME            = "NCName";
+    public static final String ATTVAL_NMTOKEN           = "NMTOKEN";
+    public static final String ATTVAL_NMTOKENS          = "NMTOKENS";
+    public static final String ATTVAL_NONNEGATIVEINTEGER= "nonNegativeInteger";
+    public static final String ATTVAL_NONPOSITIVEINTEGER= "nonPositiveInteger";
+    public static final String ATTVAL_NORMALIZEDSTRING  = "normalizedString";
+    public static final String ATTVAL_NOTATION          = "NOTATION";
+    public static final String ATTVAL_OPTIONAL          = "optional";
+    public static final String ATTVAL_POSITIVEINTEGER   = "positiveInteger";
+    public static final String ATTVAL_PRESERVE          = "preserve";
+    public static final String ATTVAL_PROHIBITED        = "prohibited";
+    public static final String ATTVAL_QNAME             = "QName";
+    public static final String ATTVAL_QUALIFIED         = "qualified";
+    public static final String ATTVAL_REPLACE           = "replace";
+    public static final String ATTVAL_REQUIRED          = "required";
+    public static final String ATTVAL_RESTRICTION       = "restriction";
+    public static final String ATTVAL_SHORT             = "short";
+    public static final String ATTVAL_SKIP              = "skip";
+    public static final String ATTVAL_STRICT            = "strict";
+    public static final String ATTVAL_STRING            = "string";
+    public static final String ATTVAL_SUBSTITUTION      = "substitution";
+    public static final String ATTVAL_TIME              = "time";
+    public static final String ATTVAL_TOKEN             = "token";
+    public static final String ATTVAL_TRUE              = "true";
+    public static final String ATTVAL_UNBOUNDED         = "unbounded";
+    public static final String ATTVAL_UNION             = "union";
+    public static final String ATTVAL_UNQUALIFIED       = "unqualified";
+    public static final String ATTVAL_UNSIGNEDBYTE      = "unsignedByte";
+    public static final String ATTVAL_UNSIGNEDINT       = "unsignedInt";
+    public static final String ATTVAL_UNSIGNEDLONG      = "unsignedLong";
+    public static final String ATTVAL_UNSIGNEDSHORT     = "unsignedShort";
+    public static final String ATTVAL_YEAR              = "gYear";
+    public static final String ATTVAL_YEARMONTH         = "gYearMonth";
+
+    // form qualified/unqualified
+    public static final short FORM_UNQUALIFIED = 0;
+    public static final short FORM_QUALIFIED   = 1;
+
+    // attribute use
+    public static final short USE_OPTIONAL   = 0;
+    public static final short USE_REQUIRED   = 1;
+    public static final short USE_PROHIBITED = 2;
+    
+    // maxOccurs = "unbounded"
+    public static final int OCCURRENCE_UNBOUNDED = -1;
+
+}


[16/24] jena git commit: JENA-1537: Remove dependency on Xerces. Import needed code

Posted by an...@apache.org.
http://git-wip-us.apache.org/repos/asf/jena/blob/c9a7e646/jena-core/src/main/java/org/apache/jena/ext/xerces/impl/dv/xs/XSSimpleTypeDelegate.java
----------------------------------------------------------------------
diff --git a/jena-core/src/main/java/org/apache/jena/ext/xerces/impl/dv/xs/XSSimpleTypeDelegate.java b/jena-core/src/main/java/org/apache/jena/ext/xerces/impl/dv/xs/XSSimpleTypeDelegate.java
new file mode 100644
index 0000000..f75cd1f
--- /dev/null
+++ b/jena-core/src/main/java/org/apache/jena/ext/xerces/impl/dv/xs/XSSimpleTypeDelegate.java
@@ -0,0 +1,249 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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.jena.ext.xerces.impl.dv.xs;
+
+import org.apache.jena.ext.xerces.impl.dv.*;
+import org.apache.jena.ext.xerces.xs.*;
+
+/**
+ * Base class for XSSimpleType wrapper implementations.
+ * 
+ * @xerces.internal
+ * 
+ * @version $Id: XSSimpleTypeDelegate.java 1024038 2010-10-18 22:06:35Z sandygao $
+ */
+public class XSSimpleTypeDelegate
+    implements XSSimpleType {
+
+    protected final XSSimpleType type;
+    
+    public XSSimpleTypeDelegate(XSSimpleType type) {
+        if (type == null) {
+            throw new NullPointerException();
+        }
+        this.type = type;
+    }
+    
+    public XSSimpleType getWrappedXSSimpleType() {
+        return type;
+    }
+
+    @Override
+    public XSObjectList getAnnotations() {
+        return type.getAnnotations();
+    }
+
+    @Override
+    public boolean getBounded() {
+        return type.getBounded();
+    }
+
+    @Override
+    public short getBuiltInKind() {
+        return type.getBuiltInKind();
+    }
+
+    @Override
+    public short getDefinedFacets() {
+        return type.getDefinedFacets();
+    }
+
+    @Override
+    public XSObjectList getFacets() {
+        return type.getFacets();
+    }
+
+    @Override
+    public XSObject getFacet(int facetType) {
+        return type.getFacet(facetType);
+    }
+
+    @Override
+    public boolean getFinite() {
+        return type.getFinite();
+    }
+
+    @Override
+    public short getFixedFacets() {
+        return type.getFixedFacets();
+    }
+
+    @Override
+    public XSSimpleTypeDefinition getItemType() {
+        return type.getItemType();
+    }
+
+    @Override
+    public StringList getLexicalEnumeration() {
+        return type.getLexicalEnumeration();
+    }
+
+    @Override
+    public String getLexicalFacetValue(short facetName) {
+        return type.getLexicalFacetValue(facetName);
+    }
+
+    @Override
+    public StringList getLexicalPattern() {
+        return type.getLexicalPattern();
+    }
+
+    @Override
+    public XSObjectList getMemberTypes() {
+        return type.getMemberTypes();
+    }
+
+    @Override
+    public XSObjectList getMultiValueFacets() {
+        return type.getMultiValueFacets();
+    }
+
+    @Override
+    public boolean getNumeric() {
+        return type.getNumeric();
+    }
+
+    @Override
+    public short getOrdered() {
+        return type.getOrdered();
+    }
+
+    @Override
+    public XSSimpleTypeDefinition getPrimitiveType() {
+        return type.getPrimitiveType();
+    }
+
+    @Override
+    public short getVariety() {
+        return type.getVariety();
+    }
+
+    @Override
+    public boolean isDefinedFacet(short facetName) {
+        return type.isDefinedFacet(facetName);
+    }
+
+    @Override
+    public boolean isFixedFacet(short facetName) {
+        return type.isFixedFacet(facetName);
+    }
+
+    @Override
+    public boolean derivedFrom(String namespace, String name, short derivationMethod) {
+        return type.derivedFrom(namespace, name, derivationMethod);
+    }
+
+    @Override
+    public boolean derivedFromType(XSTypeDefinition ancestorType, short derivationMethod) {
+        return type.derivedFromType(ancestorType, derivationMethod);
+    }
+
+    @Override
+    public boolean getAnonymous() {
+        return type.getAnonymous();
+    }
+
+    @Override
+    public XSTypeDefinition getBaseType() {
+        return type.getBaseType();
+    }
+
+    @Override
+    public short getFinal() {
+        return type.getFinal();
+    }
+
+    @Override
+    public short getTypeCategory() {
+        return type.getTypeCategory();
+    }
+
+    @Override
+    public boolean isFinal(short restriction) {
+        return type.isFinal(restriction);
+    }
+
+    @Override
+    public String getName() {
+        return type.getName();
+    }
+
+    @Override
+    public String getNamespace() {
+        return type.getNamespace();
+    }
+
+    @Override
+    public XSNamespaceItem getNamespaceItem() {
+        return type.getNamespaceItem();
+    }
+
+    @Override
+    public short getType() {
+        return type.getType();
+    }
+
+    @Override
+    public void applyFacets(XSFacets facets, short presentFacet, short fixedFacet, ValidationContext context) 
+        throws InvalidDatatypeFacetException {
+        type.applyFacets(facets, presentFacet, fixedFacet, context);
+    }
+
+    @Override
+    public short getPrimitiveKind() {
+        return type.getPrimitiveKind();
+    }
+
+    @Override
+    public short getWhitespace() throws DatatypeException {
+        return type.getWhitespace();
+    }
+
+    @Override
+    public boolean isEqual(Object value1, Object value2) {
+        return type.isEqual(value1, value2);
+    }
+
+    @Override
+    public boolean isIDType() {
+        return type.isIDType();
+    }
+
+    @Override
+    public void validate(ValidationContext context, ValidatedInfo validatedInfo) 
+        throws InvalidDatatypeValueException {
+        type.validate(context, validatedInfo);
+    }
+
+    @Override
+    public Object validate(String content, ValidationContext context, ValidatedInfo validatedInfo) 
+        throws InvalidDatatypeValueException {
+        return type.validate(content, context, validatedInfo);
+    }
+
+    @Override
+    public Object validate(Object content, ValidationContext context, ValidatedInfo validatedInfo) 
+        throws InvalidDatatypeValueException {
+        return type.validate(content, context, validatedInfo);
+    }
+    
+    @Override
+    public String toString() {
+        return type.toString();
+    }
+}

http://git-wip-us.apache.org/repos/asf/jena/blob/c9a7e646/jena-core/src/main/java/org/apache/jena/ext/xerces/impl/dv/xs/YearDV.java
----------------------------------------------------------------------
diff --git a/jena-core/src/main/java/org/apache/jena/ext/xerces/impl/dv/xs/YearDV.java b/jena-core/src/main/java/org/apache/jena/ext/xerces/impl/dv/xs/YearDV.java
new file mode 100644
index 0000000..0c094f5
--- /dev/null
+++ b/jena-core/src/main/java/org/apache/jena/ext/xerces/impl/dv/xs/YearDV.java
@@ -0,0 +1,129 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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.jena.ext.xerces.impl.dv.xs;
+
+import javax.xml.datatype.DatatypeConstants;
+import javax.xml.datatype.XMLGregorianCalendar;
+
+import org.apache.jena.ext.xerces.impl.dv.InvalidDatatypeValueException;
+import org.apache.jena.ext.xerces.impl.dv.ValidationContext;
+
+/**
+ * Validator for &lt;gYear&gt; datatype (W3C Schema Datatypes)
+ *
+ * @xerces.internal 
+ *
+ * @author Elena Litani
+ * @author Gopal Sharma, SUN Microsystem Inc.
+ *
+ * @version $Id: YearDV.java 937741 2010-04-25 04:25:46Z mrglavas $
+ */
+
+public class YearDV extends AbstractDateTimeDV {
+
+    /**
+     * Convert a string to a compiled form
+     *
+     * @param  content The lexical representation of time
+     * @return a valid and normalized time object
+     */
+    @Override
+    public Object getActualValue(String content, ValidationContext context) throws InvalidDatatypeValueException{
+        try{
+            return parse(content);
+        } catch(Exception ex){
+            throw new InvalidDatatypeValueException("cvc-datatype-valid.1.2.1", new Object[]{content, "gYear"});
+        }
+    }
+
+    /**
+     * Parses, validates and computes normalized version of gYear object
+     *
+     * @param str    The lexical representation of year object CCYY
+     *               with possible time zone Z or (-),(+)hh:mm
+     * @return normalized date representation
+     * @exception SchemaDateTimeException Invalid lexical representation
+     */
+    protected DateTimeData parse(String str) throws SchemaDateTimeException{
+        DateTimeData date = new DateTimeData(str, this);
+        int len = str.length();
+
+        // check for preceding '-' sign
+        int start = 0;
+        if (str.charAt(0)=='-') {
+            start = 1;
+        }
+        int sign = findUTCSign(str, start, len);
+        
+        final int length = ((sign == -1) ? len : sign) - start;
+        if (length < 4) {
+            throw new RuntimeException("Year must have 'CCYY' format");
+        }
+        else if (length > 4 && str.charAt(start) == '0') {
+            throw new RuntimeException("Leading zeros are required if the year value would otherwise have fewer than four digits; otherwise they are forbidden");
+        }
+        
+        if (sign == -1) {
+            date.year=parseIntYear(str, len);
+        }
+        else {
+            date.year=parseIntYear(str, sign);
+            getTimeZone (str, date, sign, len);
+        }
+
+        //initialize values
+        date.month=MONTH;
+        date.day=1;
+
+        //validate and normalize
+        validateDateTime(date);
+
+        //save unnormalized values
+        saveUnnormalized(date);
+        
+        if ( date.utc!=0 && date.utc!='Z' ) {
+            normalize(date);
+        }
+        date.position = 0;
+        return date;
+    }
+
+    /**
+     * Converts year object representation to String
+     *
+     * @param date   year object
+     * @return lexical representation of month: CCYY with optional time zone sign
+     */
+    @Override
+    protected String dateToString(DateTimeData date) {
+        StringBuffer message = new StringBuffer(5);
+        append(message, date.year, 4);
+        append(message, (char)date.utc, 0);
+        return message.toString();
+    }
+    
+    @Override
+    protected XMLGregorianCalendar getXMLGregorianCalendar(DateTimeData date) {
+        return datatypeFactory.newXMLGregorianCalendar(date.unNormYear, DatatypeConstants.FIELD_UNDEFINED, 
+                DatatypeConstants.FIELD_UNDEFINED, DatatypeConstants.FIELD_UNDEFINED, DatatypeConstants.FIELD_UNDEFINED, 
+                DatatypeConstants.FIELD_UNDEFINED, DatatypeConstants.FIELD_UNDEFINED, 
+                date.hasTimeZone() ? date.timezoneHr * 60 + date.timezoneMin : DatatypeConstants.FIELD_UNDEFINED);
+    }
+}
+
+

http://git-wip-us.apache.org/repos/asf/jena/blob/c9a7e646/jena-core/src/main/java/org/apache/jena/ext/xerces/impl/dv/xs/YearMonthDV.java
----------------------------------------------------------------------
diff --git a/jena-core/src/main/java/org/apache/jena/ext/xerces/impl/dv/xs/YearMonthDV.java b/jena-core/src/main/java/org/apache/jena/ext/xerces/impl/dv/xs/YearMonthDV.java
new file mode 100644
index 0000000..507ddc1
--- /dev/null
+++ b/jena-core/src/main/java/org/apache/jena/ext/xerces/impl/dv/xs/YearMonthDV.java
@@ -0,0 +1,103 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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.jena.ext.xerces.impl.dv.xs;
+
+import javax.xml.datatype.DatatypeConstants;
+import javax.xml.datatype.XMLGregorianCalendar;
+
+import org.apache.jena.ext.xerces.impl.dv.InvalidDatatypeValueException;
+import org.apache.jena.ext.xerces.impl.dv.ValidationContext;
+
+/**
+ * Validator for &lt;gYearMonth&gt; datatype (W3C Schema Datatypes)
+ *
+ * @xerces.internal 
+ *
+ * @author Elena Litani
+ * @author Gopal Sharma, SUN Microsystem Inc.
+ *
+ * @version $Id: YearMonthDV.java 937741 2010-04-25 04:25:46Z mrglavas $
+ */
+public class YearMonthDV extends AbstractDateTimeDV{
+
+    /**
+     * Convert a string to a compiled form
+     *
+     * @param  content The lexical representation of gYearMonth
+     * @return a valid and normalized gYearMonth object
+     */
+    @Override
+    public Object getActualValue(String content, ValidationContext context) throws InvalidDatatypeValueException{
+        try{
+            return parse(content);
+        } catch(Exception ex){
+            throw new InvalidDatatypeValueException("cvc-datatype-valid.1.2.1", new Object[]{content, "gYearMonth"});
+        }
+    }
+
+    /**
+     * Parses, validates and computes normalized version of gYearMonth object
+     *
+     * @param str    The lexical representation of gYearMonth object CCYY-MM
+     *               with possible time zone Z or (-),(+)hh:mm
+     * @return normalized date representation
+     * @exception SchemaDateTimeException Invalid lexical representation
+     */
+    protected DateTimeData parse(String str) throws SchemaDateTimeException{
+        DateTimeData date = new DateTimeData(str, this);
+        int len = str.length();
+
+        // get date
+        int end = getYearMonth(str, 0, len, date);
+        date.day = DAY;
+        parseTimeZone (str, end, len, date);
+
+        //validate and normalize
+
+        validateDateTime(date);
+
+        //save unnormalized values
+        saveUnnormalized(date);
+        
+        if ( date.utc!=0 && date.utc!='Z' ) {
+            normalize(date);
+        }
+        date.position = 0;
+        return date;
+    }
+
+    @Override
+    protected String dateToString(DateTimeData date) {
+        StringBuffer message = new StringBuffer(25);
+        append(message, date.year, 4);
+        message.append('-');
+        append(message, date.month, 2);
+        append(message, (char)date.utc, 0);
+        return message.toString();
+    }
+    
+    @Override
+    protected XMLGregorianCalendar getXMLGregorianCalendar(DateTimeData date) {
+        return datatypeFactory.newXMLGregorianCalendar(date.unNormYear, date.unNormMonth, DatatypeConstants.FIELD_UNDEFINED, 
+                DatatypeConstants.FIELD_UNDEFINED, DatatypeConstants.FIELD_UNDEFINED, 
+                DatatypeConstants.FIELD_UNDEFINED, DatatypeConstants.FIELD_UNDEFINED, 
+                date.hasTimeZone() ? date.timezoneHr * 60 + date.timezoneMin : DatatypeConstants.FIELD_UNDEFINED);
+    }
+}
+
+

http://git-wip-us.apache.org/repos/asf/jena/blob/c9a7e646/jena-core/src/main/java/org/apache/jena/ext/xerces/impl/dv/xs/YearMonthDurationDV.java
----------------------------------------------------------------------
diff --git a/jena-core/src/main/java/org/apache/jena/ext/xerces/impl/dv/xs/YearMonthDurationDV.java b/jena-core/src/main/java/org/apache/jena/ext/xerces/impl/dv/xs/YearMonthDurationDV.java
new file mode 100644
index 0000000..980f410
--- /dev/null
+++ b/jena-core/src/main/java/org/apache/jena/ext/xerces/impl/dv/xs/YearMonthDurationDV.java
@@ -0,0 +1,64 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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.jena.ext.xerces.impl.dv.xs;
+
+import java.math.BigInteger;
+
+import javax.xml.datatype.DatatypeConstants;
+import javax.xml.datatype.Duration;
+
+import org.apache.jena.ext.xerces.impl.dv.InvalidDatatypeValueException;
+import org.apache.jena.ext.xerces.impl.dv.ValidationContext;
+
+/**
+ * Used to validate the <yearMonthDuration> type
+ *
+ * @xerces.internal  
+ * 
+ * @author Ankit Pasricha, IBM
+ *  
+ * @version $Id: YearMonthDurationDV.java 937741 2010-04-25 04:25:46Z mrglavas $
+ */
+class YearMonthDurationDV extends DurationDV {
+    
+    @Override
+    public Object getActualValue(String content, ValidationContext context)
+        throws InvalidDatatypeValueException {
+        try {
+            return parse(content, DurationDV.YEARMONTHDURATION_TYPE);
+        } 
+        catch (Exception ex) {
+            throw new InvalidDatatypeValueException("cvc-datatype-valid.1.2.1", new Object[]{content, "yearMonthDuration"});
+        }
+    }
+    
+    @Override
+    protected Duration getDuration(DateTimeData date) {
+        int sign = 1;
+        if ( date.year<0 || date.month<0) {
+            sign = -1;
+        }
+        return datatypeFactory.newDuration(sign == 1, 
+                date.year != DatatypeConstants.FIELD_UNDEFINED?BigInteger.valueOf(sign*date.year):null, 
+                date.month != DatatypeConstants.FIELD_UNDEFINED?BigInteger.valueOf(sign*date.month):null, 
+                null,
+                null,
+                null,
+                null);
+    }
+}

http://git-wip-us.apache.org/repos/asf/jena/blob/c9a7e646/jena-core/src/main/java/org/apache/jena/ext/xerces/impl/validation/ConfigurableValidationState.java
----------------------------------------------------------------------
diff --git a/jena-core/src/main/java/org/apache/jena/ext/xerces/impl/validation/ConfigurableValidationState.java b/jena-core/src/main/java/org/apache/jena/ext/xerces/impl/validation/ConfigurableValidationState.java
new file mode 100644
index 0000000..22ca02c
--- /dev/null
+++ b/jena-core/src/main/java/org/apache/jena/ext/xerces/impl/validation/ConfigurableValidationState.java
@@ -0,0 +1,126 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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.jena.ext.xerces.impl.validation;
+
+/**
+ * <p>An extension of ValidationState which can be configured to turn 
+ * off checking for ID/IDREF errors and unparsed entity errors.</p>
+ * 
+ * @xerces.internal
+ *
+ * @author Peter McCracken, IBM
+ * @version $Id: ConfigurableValidationState.java 449320 2006-09-23 22:37:56Z mrglavas $
+ */
+@SuppressWarnings("all")
+public final class ConfigurableValidationState extends ValidationState {
+    
+    /**
+     * Whether to check for ID/IDREF errors
+     */
+    private boolean fIdIdrefChecking;
+    
+    /**
+     * Whether to check for unparsed entity errors
+     */
+    private boolean fUnparsedEntityChecking;
+    
+    /**
+     * Creates a new ConfigurableValidationState.
+     * By default, error checking for both ID/IDREFs 
+     * and unparsed entities are turned on.
+     */
+    public ConfigurableValidationState() {
+        super();
+        fIdIdrefChecking = true;
+        fUnparsedEntityChecking = true;
+    }
+    
+    /**
+     * Turns checking for ID/IDREF errors on and off.
+     * @param setting true to turn on error checking,
+     *                 false to turn off error checking
+     */
+    public void setIdIdrefChecking(boolean setting) {
+        fIdIdrefChecking = setting;
+    }
+    
+    /**
+     * Turns checking for unparsed entity errors on and off.
+     * @param setting true to turn on error checking,
+     *                 false to turn off error checking
+     */
+    public void setUnparsedEntityChecking(boolean setting) {
+        fUnparsedEntityChecking = setting;
+    }
+    
+    /**
+     * Checks if all IDREFs have a corresponding ID.
+     * @return null, if ID/IDREF checking is turned off
+     *         otherwise, returns the value of the super implementation
+     */
+    public String checkIDRefID() {
+        return (fIdIdrefChecking) ? super.checkIDRefID() : null;
+    }
+    
+    /**
+     * Checks if an ID has already been declared.
+     * @return false, if ID/IDREF checking is turned off
+     *         otherwise, returns the value of the super implementation
+     */
+    public boolean isIdDeclared(String name) {
+        return (fIdIdrefChecking) ? super.isIdDeclared(name) : false;
+    }
+    
+    /**
+     * Checks if an entity is declared.
+     * @return true, if unparsed entity checking is turned off
+     *         otherwise, returns the value of the super implementation
+     */
+    public boolean isEntityDeclared(String name) {
+        return (fUnparsedEntityChecking) ? super.isEntityDeclared(name) : true;
+    }
+    
+    /**
+     * Checks if an entity is unparsed.
+     * @return true, if unparsed entity checking is turned off
+     *         otherwise, returns the value of the super implementation
+     */
+    public boolean isEntityUnparsed(String name) {
+        return (fUnparsedEntityChecking) ? super.isEntityUnparsed(name) : true;
+    }
+    
+    /**
+     * Adds the ID, if ID/IDREF checking is enabled.
+     * @param name the ID to add
+     */
+    public void addId(String name) {
+        if (fIdIdrefChecking) {
+            super.addId(name);
+        }
+    }
+    
+    /**
+     * Adds the IDREF, if ID/IDREF checking is enabled.
+     * @param name the IDREF to add
+     */
+    public void addIdRef(String name) {
+        if (fIdIdrefChecking) {
+            super.addIdRef(name);
+        }
+    }
+}

http://git-wip-us.apache.org/repos/asf/jena/blob/c9a7e646/jena-core/src/main/java/org/apache/jena/ext/xerces/impl/validation/EntityState.java
----------------------------------------------------------------------
diff --git a/jena-core/src/main/java/org/apache/jena/ext/xerces/impl/validation/EntityState.java b/jena-core/src/main/java/org/apache/jena/ext/xerces/impl/validation/EntityState.java
new file mode 100644
index 0000000..ce06fa2
--- /dev/null
+++ b/jena-core/src/main/java/org/apache/jena/ext/xerces/impl/validation/EntityState.java
@@ -0,0 +1,47 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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.jena.ext.xerces.impl.validation;
+
+
+/**
+ * The entity state interface defines methods that must be implemented
+ * by components that store information about entity declarations, as well as by
+ * entity validator that will need to validate attributes of type entity.
+ * 
+ * @xerces.internal
+ * 
+ * @author Elena Litani, IBM
+ * @version $Id: EntityState.java 446719 2006-09-15 20:32:39Z mrglavas $
+ */
+public interface EntityState {
+    /**
+     * Query method to check if entity with this name was declared.
+     * 
+     * @param name
+     * @return true if name is a declared entity
+     */
+    public boolean isEntityDeclared (String name);
+
+    /**
+     * Query method to check if entity is unparsed.
+     * 
+     * @param name
+     * @return true if name is an unparsed entity
+     */
+    public boolean isEntityUnparsed (String name);
+}

http://git-wip-us.apache.org/repos/asf/jena/blob/c9a7e646/jena-core/src/main/java/org/apache/jena/ext/xerces/impl/validation/ValidationManager.java
----------------------------------------------------------------------
diff --git a/jena-core/src/main/java/org/apache/jena/ext/xerces/impl/validation/ValidationManager.java b/jena-core/src/main/java/org/apache/jena/ext/xerces/impl/validation/ValidationManager.java
new file mode 100644
index 0000000..70f0a61
--- /dev/null
+++ b/jena-core/src/main/java/org/apache/jena/ext/xerces/impl/validation/ValidationManager.java
@@ -0,0 +1,84 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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.jena.ext.xerces.impl.validation;
+
+import java.util.ArrayList;
+
+/**
+ * ValidationManager is a coordinator property for validators in the 
+ * pipeline. Each validator must know how to interact with
+ * this property. Validators are not required to know what kind of 
+ * other validators present in the pipeline, but should understand
+ * that there are others and that some coordination is required.
+ * 
+ * @xerces.internal
+ * 
+ * @author Elena Litani, IBM
+ * @version $Id: ValidationManager.java 606491 2007-12-22 21:00:53Z mrglavas $
+ */
+@SuppressWarnings("all")
+public class ValidationManager {
+
+    protected final ArrayList fVSs = new ArrayList();
+    protected boolean fGrammarFound = false;
+
+    // used by the DTD validator to tell other components that it has a
+    // cached DTD in hand so there's no reason to 
+    // scan external subset or entity decls.
+    protected boolean fCachedDTD = false;    
+    
+    /**
+     * Each validator should call this method to add its ValidationState into
+     * the validation manager.
+     */
+    public final void addValidationState(ValidationState vs) {
+        fVSs.add(vs);
+    }
+
+    /**
+     * Set the information required to validate entity values.
+     */
+    public final void setEntityState(EntityState state) {
+        for (int i = fVSs.size()-1; i >= 0; i--) {
+            ((ValidationState)fVSs.get(i)).setEntityState(state);
+        }
+    }
+    
+    public final void setGrammarFound(boolean grammar){
+        fGrammarFound = grammar;
+    }
+        
+    public final boolean isGrammarFound(){
+        return fGrammarFound;
+    }
+
+    public final void setCachedDTD(boolean cachedDTD) {
+        fCachedDTD = cachedDTD;
+    } // setCachedDTD(boolean)
+
+    public final boolean isCachedDTD() {
+        return fCachedDTD;
+    } // isCachedDTD():  boolean
+    
+        
+    public final void reset () {
+        fVSs.clear();
+        fGrammarFound = false;
+        fCachedDTD = false;
+    }
+}

http://git-wip-us.apache.org/repos/asf/jena/blob/c9a7e646/jena-core/src/main/java/org/apache/jena/ext/xerces/impl/validation/ValidationState.java
----------------------------------------------------------------------
diff --git a/jena-core/src/main/java/org/apache/jena/ext/xerces/impl/validation/ValidationState.java b/jena-core/src/main/java/org/apache/jena/ext/xerces/impl/validation/ValidationState.java
new file mode 100644
index 0000000..b089787
--- /dev/null
+++ b/jena-core/src/main/java/org/apache/jena/ext/xerces/impl/validation/ValidationState.java
@@ -0,0 +1,215 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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.jena.ext.xerces.impl.validation;
+
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.Locale;
+
+import org.apache.jena.ext.xerces.impl.dv.ValidationContext;
+import org.apache.jena.ext.xerces.util.SymbolTable;
+import org.apache.jena.ext.xerces.xni.NamespaceContext;
+
+/**
+ * Implementation of the ValidationContext interface. Used to establish an
+ * environment for simple type validation.
+ * 
+ * @xerces.internal
+ *
+ * @author Elena Litani, IBM
+ * @version $Id: ValidationState.java 713638 2008-11-13 04:42:18Z mrglavas $
+ */
+@SuppressWarnings("all")
+public class ValidationState implements ValidationContext {
+
+    //
+    // private data
+    //
+    private boolean fExtraChecking              = true;
+    private boolean fFacetChecking              = true;
+    private boolean fNormalize                  = true;
+    private boolean fNamespaces                 = true;
+
+    private EntityState fEntityState            = null;
+    private NamespaceContext fNamespaceContext  = null;
+    private SymbolTable fSymbolTable            = null;
+    private Locale fLocale                      = null;
+
+    //REVISIT: Should replace with a lighter structure.
+    private final HashMap fIdTable    = new HashMap();
+    private final HashMap fIdRefTable = new HashMap();
+    private final static Object fNullValue = new Object();
+
+    //
+    // public methods
+    //
+    public void setExtraChecking(boolean newValue) {
+        fExtraChecking = newValue;
+    }
+
+    public void setFacetChecking(boolean newValue) {
+        fFacetChecking = newValue;
+    }
+
+    public void setNormalizationRequired (boolean newValue) {
+          fNormalize = newValue;
+    }
+
+    public void setUsingNamespaces (boolean newValue) {
+          fNamespaces = newValue;
+    }
+
+    public void setEntityState(EntityState state) {
+        fEntityState = state;
+    }
+
+    public void setNamespaceSupport(NamespaceContext namespace) {
+        fNamespaceContext = namespace;
+    }
+
+    public void setSymbolTable(SymbolTable sTable) {
+        fSymbolTable = sTable;
+    }
+
+    /**
+     * return null if all IDREF values have a corresponding ID value;
+     * otherwise return the first IDREF value without a matching ID value.
+     */
+    public String checkIDRefID () {
+        Iterator iter = fIdRefTable.keySet().iterator();
+        String key;
+        while (iter.hasNext()) {
+            key = (String) iter.next();
+            if (!fIdTable.containsKey(key)) {
+                  return key;
+            }
+        }
+        return null;
+    }
+
+    public void reset () {
+        fExtraChecking = true;
+        fFacetChecking = true;
+        fNamespaces = true;
+        fIdTable.clear();
+        fIdRefTable.clear();
+        fEntityState = null;
+        fNamespaceContext = null;
+        fSymbolTable = null;
+    }
+
+    /**
+     * The same validation state can be used to validate more than one (schema)
+     * validation roots. Entity/Namespace/Symbol are shared, but each validation
+     * root needs its own id/idref tables. So we need this method to reset only
+     * the two tables.
+     */
+    public void resetIDTables() {
+        fIdTable.clear();
+        fIdRefTable.clear();
+    }
+
+    //
+    // implementation of ValidationContext methods
+    //
+
+    // whether to do extra id/idref/entity checking
+    @Override
+    public boolean needExtraChecking() {
+        return fExtraChecking;
+    }
+
+    // whether to validate against facets
+    @Override
+    public boolean needFacetChecking() {
+        return fFacetChecking;
+    }
+
+    @Override
+    public boolean needToNormalize (){
+        return fNormalize;
+    }
+
+    @Override
+    public boolean useNamespaces() {
+        return fNamespaces;
+    }
+
+    // entity
+    @Override
+    public boolean isEntityDeclared (String name) {
+        if (fEntityState !=null) {
+            return fEntityState.isEntityDeclared(getSymbol(name));
+        }
+        return false;
+    }
+    @Override
+    public boolean isEntityUnparsed (String name) {
+        if (fEntityState !=null) {
+            return fEntityState.isEntityUnparsed(getSymbol(name));
+        }
+        return false;
+    }
+
+    // id
+    @Override
+    public boolean isIdDeclared(String name) {
+        return fIdTable.containsKey(name);
+    }
+    @Override
+    public void addId(String name) {
+        fIdTable.put(name, fNullValue);
+    }
+
+    // idref
+    @Override
+    public void addIdRef(String name) {
+        fIdRefTable.put(name, fNullValue);
+    }
+    // get symbols
+
+    @Override
+    public String getSymbol (String symbol) {
+        if (fSymbolTable != null)
+            return fSymbolTable.addSymbol(symbol);
+        // if there is no symbol table, we return java-internalized string,
+        // because symbol table strings are also java-internalzied.
+        // this guarantees that the returned string from this method can be
+        // compared by reference with other symbol table string. -SG
+        return symbol.intern();
+    }
+    // qname, notation
+    @Override
+    public String getURI(String prefix) {
+        if (fNamespaceContext !=null) {
+            return fNamespaceContext.getURI(prefix);
+        }
+        return null;
+    }
+    
+    // Locale
+    
+    public void setLocale(Locale locale) {
+        fLocale = locale;
+    }
+    
+    @Override
+    public Locale getLocale() {
+        return fLocale;
+    }
+}

http://git-wip-us.apache.org/repos/asf/jena/blob/c9a7e646/jena-core/src/main/java/org/apache/jena/ext/xerces/impl/xpath/regex/BMPattern.java
----------------------------------------------------------------------
diff --git a/jena-core/src/main/java/org/apache/jena/ext/xerces/impl/xpath/regex/BMPattern.java b/jena-core/src/main/java/org/apache/jena/ext/xerces/impl/xpath/regex/BMPattern.java
new file mode 100644
index 0000000..b8851f8
--- /dev/null
+++ b/jena-core/src/main/java/org/apache/jena/ext/xerces/impl/xpath/regex/BMPattern.java
@@ -0,0 +1,236 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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.jena.ext.xerces.impl.xpath.regex;
+
+import java.text.CharacterIterator;
+
+/**
+ * Boyer-Moore searcher.
+ * 
+ * @xerces.internal
+ *
+ * @version $Id: BMPattern.java 572108 2007-09-02 18:48:31Z mrglavas $
+ */
+public class BMPattern {
+    final char[] pattern;
+    final int[] shiftTable;
+    final boolean ignoreCase;
+
+    public BMPattern(String pat, boolean ignoreCase) {
+        this(pat, 256, ignoreCase);
+    }
+
+    public BMPattern(String pat, int tableSize, boolean ignoreCase) {
+        this.pattern = pat.toCharArray();
+        this.shiftTable = new int[tableSize];
+        this.ignoreCase = ignoreCase;
+
+        int length = pattern.length;
+        for (int i = 0;  i < this.shiftTable.length;  i ++)
+            this.shiftTable[i] = length;
+
+        for (int i = 0;  i < length;  i ++) {
+            char ch = this.pattern[i];
+            int diff = length-i-1;
+            int index = ch % this.shiftTable.length;
+            if (diff < this.shiftTable[index])
+                this.shiftTable[index] = diff;
+            if (this.ignoreCase) {
+                ch = Character.toUpperCase(ch);
+                index = ch % this.shiftTable.length;
+                if (diff < this.shiftTable[index])
+                    this.shiftTable[index] = diff;
+                ch = Character.toLowerCase(ch);
+                index = ch % this.shiftTable.length;
+                if (diff < this.shiftTable[index])
+                    this.shiftTable[index] = diff;
+            }
+        }
+    }
+
+    /**
+     *
+     * @return -1 if <var>iterator</var> does not contain this pattern.
+     */
+    public int matches(CharacterIterator iterator, int start, int limit) {
+        if (this.ignoreCase)  return this.matchesIgnoreCase(iterator, start, limit);
+        int plength = this.pattern.length;
+        if (plength == 0)  return start;
+        int index = start+plength;
+        while (index <= limit) {
+            int pindex = plength;
+            int nindex = index+1;
+            char ch;
+            do {
+                if ((ch = iterator.setIndex(--index)) != this.pattern[--pindex])
+                    break;
+                if (pindex == 0)
+                    return index;
+            } while (pindex > 0);
+            index += this.shiftTable[ch % this.shiftTable.length]+1;
+            if (index < nindex)  index = nindex;
+        }
+        return -1;
+    }
+
+    /**
+     *
+     * @return -1 if <var>str</var> does not contain this pattern.
+     */
+    public int matches(String str, int start, int limit) {
+        if (this.ignoreCase)  return this.matchesIgnoreCase(str, start, limit);
+        int plength = this.pattern.length;
+        if (plength == 0)  return start;
+        int index = start+plength;
+        while (index <= limit) {
+            //System.err.println("Starts at "+index);
+            int pindex = plength;
+            int nindex = index+1;
+            char ch;
+            do {
+                if ((ch = str.charAt(--index)) != this.pattern[--pindex])
+                    break;
+                if (pindex == 0)
+                    return index;
+            } while (pindex > 0);
+            index += this.shiftTable[ch % this.shiftTable.length]+1;
+            if (index < nindex)  index = nindex;
+        }
+        return -1;
+    }
+    /**
+     *
+     * @return -1 if <var>chars</char> does not contain this pattern.
+     */
+    public int matches(char[] chars, int start, int limit) {
+        if (this.ignoreCase)  return this.matchesIgnoreCase(chars, start, limit);
+        int plength = this.pattern.length;
+        if (plength == 0)  return start;
+        int index = start+plength;
+        while (index <= limit) {
+            //System.err.println("Starts at "+index);
+            int pindex = plength;
+            int nindex = index+1;
+            char ch;
+            do {
+                if ((ch = chars[--index]) != this.pattern[--pindex])
+                    break;
+                if (pindex == 0)
+                    return index;
+            } while (pindex > 0);
+            index += this.shiftTable[ch % this.shiftTable.length]+1;
+            if (index < nindex)  index = nindex;
+        }
+        return -1;
+    }
+
+    int matchesIgnoreCase(CharacterIterator iterator, int start, int limit) {
+        int plength = this.pattern.length;
+        if (plength == 0)  return start;
+        int index = start+plength;
+        while (index <= limit) {
+            int pindex = plength;
+            int nindex = index+1;
+            char ch;
+            do {
+                char ch1 = ch = iterator.setIndex(--index);
+                char ch2 = this.pattern[--pindex];
+                if (ch1 != ch2) {
+                    ch1 = Character.toUpperCase(ch1);
+                    ch2 = Character.toUpperCase(ch2);
+                    if (ch1 != ch2 && Character.toLowerCase(ch1) != Character.toLowerCase(ch2))
+                        break;
+                }
+                if (pindex == 0)
+                    return index;
+            } while (pindex > 0);
+            index += this.shiftTable[ch % this.shiftTable.length]+1;
+            if (index < nindex)  index = nindex;
+        }
+        return -1;
+    }
+    
+    int matchesIgnoreCase(String text, int start, int limit) {
+        int plength = this.pattern.length;
+        if (plength == 0)  return start;
+        int index = start+plength;
+        while (index <= limit) {
+            int pindex = plength;
+            int nindex = index+1;
+            char ch;
+            do {
+                char ch1 = ch = text.charAt(--index);
+                char ch2 = this.pattern[--pindex];
+                if (ch1 != ch2) {
+                    ch1 = Character.toUpperCase(ch1);
+                    ch2 = Character.toUpperCase(ch2);
+                    if (ch1 != ch2 && Character.toLowerCase(ch1) != Character.toLowerCase(ch2))
+                        break;
+                }
+                if (pindex == 0)
+                    return index;
+            } while (pindex > 0);
+            index += this.shiftTable[ch % this.shiftTable.length]+1;
+            if (index < nindex)  index = nindex;
+        }
+        return -1;
+    }
+    int matchesIgnoreCase(char[] chars, int start, int limit) {
+        int plength = this.pattern.length;
+        if (plength == 0)  return start;
+        int index = start+plength;
+        while (index <= limit) {
+            int pindex = plength;
+            int nindex = index+1;
+            char ch;
+            do {
+                char ch1 = ch = chars[--index];
+                char ch2 = this.pattern[--pindex];
+                if (ch1 != ch2) {
+                    ch1 = Character.toUpperCase(ch1);
+                    ch2 = Character.toUpperCase(ch2);
+                    if (ch1 != ch2 && Character.toLowerCase(ch1) != Character.toLowerCase(ch2))
+                        break;
+                }
+                if (pindex == 0)
+                    return index;
+            } while (pindex > 0);
+            index += this.shiftTable[ch % this.shiftTable.length]+1;
+            if (index < nindex)  index = nindex;
+        }
+        return -1;
+    }
+
+    /*
+    public static void main(String[] argv) {
+        try {
+            int[] shiftTable = new int[256];
+            initializeBoyerMoore(argv[0], shiftTable, true);
+            int o = -1;
+            CharacterIterator ite = new java.text.StringCharacterIterator(argv[1]);
+            long start = System.currentTimeMillis();
+            //for (int i = 0;  i < 10000;  i ++)
+                o = searchIgnoreCasesWithBoyerMoore(ite, 0, argv[0], shiftTable);
+            start = System.currentTimeMillis()-start;
+            System.out.println("Result: "+o+", Elapsed: "+start);
+        } catch (Exception ex) {
+            ex.printStackTrace();
+        }
+    }*/
+}
+

http://git-wip-us.apache.org/repos/asf/jena/blob/c9a7e646/jena-core/src/main/java/org/apache/jena/ext/xerces/impl/xpath/regex/CaseInsensitiveMap.java
----------------------------------------------------------------------
diff --git a/jena-core/src/main/java/org/apache/jena/ext/xerces/impl/xpath/regex/CaseInsensitiveMap.java b/jena-core/src/main/java/org/apache/jena/ext/xerces/impl/xpath/regex/CaseInsensitiveMap.java
new file mode 100644
index 0000000..2f62626
--- /dev/null
+++ b/jena-core/src/main/java/org/apache/jena/ext/xerces/impl/xpath/regex/CaseInsensitiveMap.java
@@ -0,0 +1,162 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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.jena.ext.xerces.impl.xpath.regex;
+
+/**
+ * @xerces.internal
+ * 
+ * @version $Id: CaseInsensitiveMap.java 834653 2009-11-10 20:32:39Z mrglavas $
+ */
+final class CaseInsensitiveMap {
+
+    private static int CHUNK_SHIFT = 10;           /* 2^10 = 1k */
+    private static int CHUNK_SIZE = (1<<CHUNK_SHIFT);
+    private static int CHUNK_MASK = (CHUNK_SIZE-1);
+    private static int INITIAL_CHUNK_COUNT = 64;   /* up to 0xFFFF */
+
+    private static int[][][] caseInsensitiveMap;
+    
+    private static int LOWER_CASE_MATCH = 1;
+    private static int UPPER_CASE_MATCH = 2;
+    
+    static {
+        buildCaseInsensitiveMap();
+    }
+
+    /**
+     *  Return a list of code point characters (not including the input value)
+     *  that can be substituted in a case insensitive match
+     */
+    static public int[] get(int codePoint) {
+        return (codePoint < 0x10000) ? getMapping(codePoint) : null;
+    }
+
+    private static int[] getMapping(int codePoint) {
+        int chunk = codePoint >>> CHUNK_SHIFT;
+        int offset = codePoint & CHUNK_MASK;
+        
+        return caseInsensitiveMap[chunk][offset];
+    }
+    
+    private static void buildCaseInsensitiveMap() {
+        caseInsensitiveMap = new int[INITIAL_CHUNK_COUNT][CHUNK_SIZE][];
+        int lc, uc;
+        for (int i=0; i<0x10000; i++) {
+            lc = Character.toLowerCase((char) i);
+            uc = Character.toUpperCase((char) i);
+
+            // lower/upper case value is not the same as code point
+            if (lc != uc || lc != i) {
+                int[] map = new int[2];
+                int index = 0;
+
+                if (lc != i) {
+                    map[index++] = lc;
+                    map[index++] = LOWER_CASE_MATCH;
+                    int[] lcMap = getMapping(lc);
+                    if (lcMap != null) {
+                        map = updateMap(i, map, lc, lcMap, LOWER_CASE_MATCH);
+                    }
+                }
+                
+                if (uc != i) {
+                    if (index == map.length) {
+                        map = expandMap(map, 2);
+                    }
+                    map[index++] = uc;
+                    map[index++] = UPPER_CASE_MATCH;
+                    int[] ucMap = getMapping(uc);
+                    if (ucMap != null) {
+                        map = updateMap(i, map, uc, ucMap, UPPER_CASE_MATCH);
+                    }
+                }
+                
+                set(i, map);
+            }
+        }
+    }
+    
+    private static int[] expandMap(int[] srcMap, int expandBy) {
+        final int oldLen = srcMap.length;
+        int[] newMap = new int[oldLen + expandBy];
+        
+        System.arraycopy(srcMap, 0, newMap, 0, oldLen);
+        return newMap;
+    }
+    
+    private static void set(int codePoint, int[] map) {
+        int chunk = codePoint >>> CHUNK_SHIFT;
+        int offset = codePoint & CHUNK_MASK;
+        
+        caseInsensitiveMap[chunk][offset] = map;
+    }
+
+    private static int[] updateMap(int codePoint, int[] codePointMap,
+            int ciCodePoint, int[] ciCodePointMap, int matchType) {
+        for (int i=0; i<ciCodePointMap.length; i+=2) {
+            int c = ciCodePointMap[i];
+            int[] cMap = getMapping(c);
+            if (cMap != null) {
+                if (contains(cMap, ciCodePoint, matchType)) {
+                    if (!contains(cMap, codePoint)) {
+                        cMap = expandAndAdd(cMap, codePoint, matchType);
+                        set(c, cMap);
+                    }
+                    if (!contains(codePointMap, c)) {
+                        codePointMap = expandAndAdd(codePointMap, c,matchType);
+                    }
+                }
+            }
+        }
+        
+        if (!contains(ciCodePointMap, codePoint)) {
+            ciCodePointMap = expandAndAdd(ciCodePointMap, codePoint, matchType);
+            set(ciCodePoint, ciCodePointMap);
+        }
+
+        return codePointMap;
+    }
+    
+    private static boolean contains(int[] map, int codePoint) {
+        for (int i=0; i<map.length; i += 2) {
+            if (map[i] == codePoint) {
+                return true;
+            }
+        }
+        return false;
+    }
+
+    private static boolean contains(int[] map, int codePoint, int matchType) {
+        for (int i=0; i<map.length; i += 2) {
+            if (map[i] == codePoint && map[i+1] == matchType) {
+                return true;
+            }
+        }
+        return false;
+    }
+    
+    private static int[] expandAndAdd(int[] srcMap, int codePoint, int matchType) {
+        final int oldLen = srcMap.length;
+        int[] newMap = new int[oldLen + 2];
+        
+        System.arraycopy(srcMap, 0, newMap, 0, oldLen);
+        newMap[oldLen] = codePoint;
+        newMap[oldLen+1] = matchType;
+        return newMap;
+    }
+}

http://git-wip-us.apache.org/repos/asf/jena/blob/c9a7e646/jena-core/src/main/java/org/apache/jena/ext/xerces/impl/xpath/regex/Match.java
----------------------------------------------------------------------
diff --git a/jena-core/src/main/java/org/apache/jena/ext/xerces/impl/xpath/regex/Match.java b/jena-core/src/main/java/org/apache/jena/ext/xerces/impl/xpath/regex/Match.java
new file mode 100644
index 0000000..c6bc1f8
--- /dev/null
+++ b/jena-core/src/main/java/org/apache/jena/ext/xerces/impl/xpath/regex/Match.java
@@ -0,0 +1,185 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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.jena.ext.xerces.impl.xpath.regex;
+
+import java.text.CharacterIterator;
+
+/**
+ * An instance of this class has ranges captured in matching.
+ * 
+ * @xerces.internal
+ *
+ * @see RegularExpression#matches(char[], int, int, Match)
+ * @see RegularExpression#matches(char[], Match)
+ * @see RegularExpression#matches(java.text.CharacterIterator, Match)
+ * @see RegularExpression#matches(java.lang.String, int, int, Match)
+ * @see RegularExpression#matches(java.lang.String, Match)
+ * @author TAMURA Kent &lt;kent@trl.ibm.co.jp&gt;
+ * @version $Id: Match.java 446721 2006-09-15 20:35:34Z mrglavas $
+ */
+public class Match implements Cloneable {
+    int[] beginpos = null;
+    int[] endpos = null;
+    int nofgroups = 0;
+
+    CharacterIterator ciSource = null;
+    String strSource = null;
+    char[] charSource = null;
+
+    /**
+     * Creates an instance.
+     */
+    public Match() {
+    }
+
+    /**
+     *
+     */
+    @Override
+    public synchronized Object clone() {
+        Match ma = new Match();
+        if (this.nofgroups > 0) {
+            ma.setNumberOfGroups(this.nofgroups);
+            if (this.ciSource != null)  ma.setSource(this.ciSource);
+            if (this.strSource != null)  ma.setSource(this.strSource);
+            for (int i = 0;  i < this.nofgroups;  i ++) {
+                ma.setBeginning(i, this.getBeginning(i));
+                ma.setEnd(i, this.getEnd(i));
+            }
+        }
+        return ma;
+    }
+
+    /**
+     *
+     */
+    protected void setNumberOfGroups(int n) {
+        int oldn = this.nofgroups;
+        this.nofgroups = n;
+        if (oldn <= 0
+            || oldn < n || n*2 < oldn) {
+            this.beginpos = new int[n];
+            this.endpos = new int[n];
+        }
+        for (int i = 0;  i < n;  i ++) {
+            this.beginpos[i] = -1;
+            this.endpos[i] = -1;
+        }
+    }
+
+    /**
+     *
+     */
+    protected void setSource(CharacterIterator ci) {
+        this.ciSource = ci;
+        this.strSource = null;
+        this.charSource = null;
+    }
+    /**
+     *
+     */
+    protected void setSource(String str) {
+        this.ciSource = null;
+        this.strSource = str;
+        this.charSource = null;
+    }
+    /**
+     *
+     */
+    protected void setSource(char[] chars) {
+        this.ciSource = null;
+        this.strSource = null;
+        this.charSource = chars;
+    }
+
+    /**
+     *
+     */
+    protected void setBeginning(int index, int v) {
+        this.beginpos[index] = v;
+    }
+
+    /**
+     *
+     */
+    protected void setEnd(int index, int v) {
+        this.endpos[index] = v;
+    }
+
+    /**
+     * Return the number of regular expression groups.
+     * This method returns 1 when the regular expression has no capturing-parenthesis.
+     */
+    public int getNumberOfGroups() {
+        if (this.nofgroups <= 0)
+            throw new IllegalStateException("A result is not set.");
+        return this.nofgroups;
+    }
+
+    /**
+     * Return a start position in the target text matched to specified regular expression group.
+     *
+     * @param index Less than <code>getNumberOfGroups()</code>.
+     */
+    public int getBeginning(int index) {
+        if (this.beginpos == null)
+            throw new IllegalStateException("A result is not set.");
+        if (index < 0 || this.nofgroups <= index)
+            throw new IllegalArgumentException("The parameter must be less than "
+                                               +this.nofgroups+": "+index);
+        return this.beginpos[index];
+    }
+
+    /**
+     * Return an end position in the target text matched to specified regular expression group.
+     *
+     * @param index Less than <code>getNumberOfGroups()</code>.
+     */
+    public int getEnd(int index) {
+        if (this.endpos == null)
+            throw new IllegalStateException("A result is not set.");
+        if (index < 0 || this.nofgroups <= index)
+            throw new IllegalArgumentException("The parameter must be less than "
+                                               +this.nofgroups+": "+index);
+        return this.endpos[index];
+    }
+
+    /**
+     * Return an substring of the target text matched to specified regular expression group.
+     *
+     * @param index Less than <code>getNumberOfGroups()</code>.
+     */
+    public String getCapturedText(int index) {
+        if (this.beginpos == null)
+            throw new IllegalStateException("match() has never been called.");
+        if (index < 0 || this.nofgroups <= index)
+            throw new IllegalArgumentException("The parameter must be less than "
+                                               +this.nofgroups+": "+index);
+        String ret;
+        int begin = this.beginpos[index], end = this.endpos[index];
+        if (begin < 0 || end < 0)  return null;
+        if (this.ciSource != null) {
+            ret = REUtil.substring(this.ciSource, begin, end);
+        } else if (this.strSource != null) {
+            ret = this.strSource.substring(begin, end);
+        } else {
+            ret = new String(this.charSource, begin, end-begin);
+        }
+        return ret;
+    }
+}

http://git-wip-us.apache.org/repos/asf/jena/blob/c9a7e646/jena-core/src/main/java/org/apache/jena/ext/xerces/impl/xpath/regex/Op.java
----------------------------------------------------------------------
diff --git a/jena-core/src/main/java/org/apache/jena/ext/xerces/impl/xpath/regex/Op.java b/jena-core/src/main/java/org/apache/jena/ext/xerces/impl/xpath/regex/Op.java
new file mode 100644
index 0000000..7f5f71b
--- /dev/null
+++ b/jena-core/src/main/java/org/apache/jena/ext/xerces/impl/xpath/regex/Op.java
@@ -0,0 +1,261 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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.jena.ext.xerces.impl.xpath.regex;
+
+import java.util.Vector;
+
+/**
+ * @xerces.internal
+ * 
+ * @version $Id: Op.java 572108 2007-09-02 18:48:31Z mrglavas $
+ */
+@SuppressWarnings("all")
+class Op {
+    static final int DOT = 0;
+    static final int CHAR = 1;                  // Single character
+    static final int RANGE = 3;                 // [a-zA-Z]
+    static final int NRANGE = 4;                // [^a-zA-Z]
+    static final int ANCHOR = 5;                // ^ $ ...
+    static final int STRING = 6;                // literal String 
+    static final int CLOSURE = 7;               // X*
+    static final int NONGREEDYCLOSURE = 8;      // X*?
+    static final int QUESTION = 9;              // X?
+    static final int NONGREEDYQUESTION = 10;    // X??
+    static final int UNION = 11;                // X|Y
+    static final int CAPTURE = 15;              // ( and )
+    static final int BACKREFERENCE = 16;        // \1 \2 ...
+    static final int LOOKAHEAD = 20;            // (?=...)
+    static final int NEGATIVELOOKAHEAD = 21;    // (?!...)
+    static final int LOOKBEHIND = 22;           // (?<=...)
+    static final int NEGATIVELOOKBEHIND = 23;   // (?<!...)
+    static final int INDEPENDENT = 24;          // (?>...)
+    static final int MODIFIER = 25;             // (?ims-ims:...)
+    static final int CONDITION = 26;            // (?(..)yes|no)
+
+    static int nofinstances = 0;
+    static final boolean COUNT = false;
+
+    static Op createDot() {
+        if (Op.COUNT)  Op.nofinstances ++;
+        return new Op(Op.DOT);
+    }
+    static CharOp createChar(int data) {
+        if (Op.COUNT)  Op.nofinstances ++;
+        return new CharOp(Op.CHAR, data);
+    }
+    static CharOp createAnchor(int data) {
+        if (Op.COUNT)  Op.nofinstances ++;
+        return new CharOp(Op.ANCHOR, data);
+    }
+    static CharOp createCapture(int number, Op next) {
+        if (Op.COUNT)  Op.nofinstances ++;
+        CharOp op = new CharOp(Op.CAPTURE, number);
+        op.next = next;
+        return op;
+    }
+    static UnionOp createUnion(int size) {
+        if (Op.COUNT)  Op.nofinstances ++;
+        //System.err.println("Creates UnionOp");
+        return new UnionOp(Op.UNION, size);
+    }
+    static ChildOp createClosure(int id) {
+        if (Op.COUNT)  Op.nofinstances ++;
+        return new ModifierOp(Op.CLOSURE, id, -1);
+    }
+    static ChildOp createNonGreedyClosure() {
+        if (Op.COUNT)  Op.nofinstances ++;
+        return new ChildOp(Op.NONGREEDYCLOSURE);
+    }
+    static ChildOp createQuestion(boolean nongreedy) {
+        if (Op.COUNT)  Op.nofinstances ++;
+        return new ChildOp(nongreedy ? Op.NONGREEDYQUESTION : Op.QUESTION);
+    }
+    static RangeOp createRange(Token tok) {
+        if (Op.COUNT)  Op.nofinstances ++;
+        return new RangeOp(Op.RANGE, tok);
+    }
+    static ChildOp createLook(int type, Op next, Op branch) {
+        if (Op.COUNT)  Op.nofinstances ++;
+        ChildOp op = new ChildOp(type);
+        op.setChild(branch);
+        op.next = next;
+        return op;
+    }
+    static CharOp createBackReference(int refno) {
+        if (Op.COUNT)  Op.nofinstances ++;
+        return new CharOp(Op.BACKREFERENCE, refno);
+    }
+    static StringOp createString(String literal) {
+        if (Op.COUNT)  Op.nofinstances ++;
+        return new StringOp(Op.STRING, literal);
+    }
+    static ChildOp createIndependent(Op next, Op branch) {
+        if (Op.COUNT)  Op.nofinstances ++;
+        ChildOp op = new ChildOp(Op.INDEPENDENT);
+        op.setChild(branch);
+        op.next = next;
+        return op;
+    }
+    static ModifierOp createModifier(Op next, Op branch, int add, int mask) {
+        if (Op.COUNT)  Op.nofinstances ++;
+        ModifierOp op = new ModifierOp(Op.MODIFIER, add, mask);
+        op.setChild(branch);
+        op.next = next;
+        return op;
+    }
+    static ConditionOp createCondition(Op next, int ref, Op conditionflow, Op yesflow, Op noflow) {
+        if (Op.COUNT)  Op.nofinstances ++;
+        ConditionOp op = new ConditionOp(Op.CONDITION, ref, conditionflow, yesflow, noflow);
+        op.next = next;
+        return op;
+    }
+
+    final int type;
+    Op next = null;
+
+    protected Op(int type) {
+        this.type = type;
+    }
+
+    int size() {                                // for UNION
+        return 0;
+    }
+    Op elementAt(int index) {                   // for UNIoN
+        throw new RuntimeException("Internal Error: type="+this.type);
+    }
+    Op getChild() {                             // for CLOSURE, QUESTION
+        throw new RuntimeException("Internal Error: type="+this.type);
+    }
+                                                // ModifierOp
+    int getData() {                             // CharOp  for CHAR, BACKREFERENCE, CAPTURE, ANCHOR, 
+        throw new RuntimeException("Internal Error: type="+this.type);
+    }
+    int getData2() {                            // ModifierOp
+        throw new RuntimeException("Internal Error: type="+this.type);
+    }
+    RangeToken getToken() {                     // RANGE, NRANGE
+        throw new RuntimeException("Internal Error: type="+this.type);
+    }
+    String getString() {                        // STRING
+        throw new RuntimeException("Internal Error: type="+this.type);
+    }
+
+    // ================================================================
+    static class CharOp extends Op {
+        final int charData;
+        CharOp(int type, int data) {
+            super(type);
+            this.charData = data;
+        }
+        @Override
+        int getData() {
+            return this.charData;
+        }
+    }
+
+    // ================================================================
+    static class UnionOp extends Op {
+        final Vector branches;
+        UnionOp(int type, int size) {
+            super(type);
+            this.branches = new Vector(size);
+        }
+        void addElement(Op op) {
+            this.branches.addElement(op);
+        }
+        @Override
+        int size() {
+            return this.branches.size();
+        }
+        @Override
+        Op elementAt(int index) {
+            return (Op)this.branches.elementAt(index);
+        }
+    }
+
+    // ================================================================
+    static class ChildOp extends Op {
+        Op child;
+        ChildOp(int type) {
+            super(type);
+        }
+        void setChild(Op child) {
+            this.child = child;
+        }
+        @Override
+        Op getChild() {
+            return this.child;
+        }
+    }
+    // ================================================================
+    static class ModifierOp extends ChildOp {
+        final int v1;
+        final int v2;
+        ModifierOp(int type, int v1, int v2) {
+            super(type);
+            this.v1 = v1;
+            this.v2 = v2;
+        }
+        @Override
+        int getData() {
+            return this.v1;
+        }
+        @Override
+        int getData2() {
+            return this.v2;
+        }
+    }
+    // ================================================================
+    static class RangeOp extends Op {
+        final Token tok;
+        RangeOp(int type, Token tok) {
+            super(type);
+            this.tok = tok;
+        }
+        @Override
+        RangeToken getToken() {
+            return (RangeToken)this.tok;
+        }
+    }
+    // ================================================================
+    static class StringOp extends Op {
+        final String string;
+        StringOp(int type, String literal) {
+            super(type);
+            this.string = literal;
+        }
+        @Override
+        String getString() {
+            return this.string;
+        }
+    }
+    // ================================================================
+    static class ConditionOp extends Op {
+        final int refNumber;
+        final Op condition;
+        final Op yes;
+        final Op no;
+        ConditionOp(int type, int refno, Op conditionflow, Op yesflow, Op noflow) {
+            super(type);
+            this.refNumber = refno;
+            this.condition = conditionflow;
+            this.yes = yesflow;
+            this.no = noflow;
+        }
+    }
+}

http://git-wip-us.apache.org/repos/asf/jena/blob/c9a7e646/jena-core/src/main/java/org/apache/jena/ext/xerces/impl/xpath/regex/ParseException.java
----------------------------------------------------------------------
diff --git a/jena-core/src/main/java/org/apache/jena/ext/xerces/impl/xpath/regex/ParseException.java b/jena-core/src/main/java/org/apache/jena/ext/xerces/impl/xpath/regex/ParseException.java
new file mode 100644
index 0000000..9b405c0
--- /dev/null
+++ b/jena-core/src/main/java/org/apache/jena/ext/xerces/impl/xpath/regex/ParseException.java
@@ -0,0 +1,53 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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.jena.ext.xerces.impl.xpath.regex;
+
+/**
+ * @xerces.internal
+ *
+ * @author TAMURA Kent &lt;kent@trl.ibm.co.jp&gt;
+ * @version $Id: ParseException.java 572108 2007-09-02 18:48:31Z mrglavas $
+ */
+public class ParseException extends RuntimeException {
+    
+    /** Serialization version. */
+    static final long serialVersionUID = -7012400318097691370L;
+    
+    final int location;
+
+    /*
+    public ParseException(String mes) {
+        this(mes, -1);
+    }
+    */
+    /**
+     *
+     */
+    public ParseException(String mes, int location) {
+        super(mes);
+        this.location = location;
+    }
+
+    /**
+     *
+     * @return -1 if location information is not available.
+     */
+    public int getLocation() {
+        return this.location;
+    }
+}


[05/24] jena git commit: JENA-1537: Remove dependency on Xerces. Import needed code

Posted by an...@apache.org.
http://git-wip-us.apache.org/repos/asf/jena/blob/c9a7e646/jena-core/src/main/java/org/apache/jena/ext/xerces/xs/ItemPSVI.java
----------------------------------------------------------------------
diff --git a/jena-core/src/main/java/org/apache/jena/ext/xerces/xs/ItemPSVI.java b/jena-core/src/main/java/org/apache/jena/ext/xerces/xs/ItemPSVI.java
new file mode 100644
index 0000000..d1c72c0
--- /dev/null
+++ b/jena-core/src/main/java/org/apache/jena/ext/xerces/xs/ItemPSVI.java
@@ -0,0 +1,209 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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.jena.ext.xerces.xs;
+
+/**
+ *  Represents an abstract PSVI item for an element or an attribute 
+ * information item.
+ */
+public interface ItemPSVI {
+    /**
+     * Validity value indicating that validation has either not been performed 
+     * or that a strict assessment of validity could not be performed. 
+     */
+    public static final short VALIDITY_NOTKNOWN         = 0;
+    /**
+     * Validity value indicating that validation has been strictly assessed 
+     * and the item in question is invalid according to the rules of schema 
+     * validation. 
+     */
+    public static final short VALIDITY_INVALID          = 1;
+    /**
+     * Validation status indicating that schema validation has been performed 
+     * and the item in question is valid according to the rules of schema 
+     * validation. 
+     */
+    public static final short VALIDITY_VALID            = 2;
+    /**
+     * Validation status indicating that schema validation has been performed 
+     * and the item in question has specifically been skipped. 
+     */
+    public static final short VALIDATION_NONE           = 0;
+    /**
+     * Validation status indicating that schema validation has been performed 
+     * on the item in question under the rules of lax validation. 
+     */
+    public static final short VALIDATION_PARTIAL        = 1;
+    /**
+     * Validation status indicating that full schema validation has been 
+     * performed on the item. 
+     */
+    public static final short VALIDATION_FULL           = 2;
+    /**
+     * The nearest ancestor element information item with a 
+     * <code>[schema information]</code> property (or this element item 
+     * itself if it has such a property). For more information refer to 
+     * element validation context and attribute validation context . 
+     */
+    public String getValidationContext();
+
+    /**
+     * <code>[validity]</code>: determines the validity of the schema item 
+     * with respect to the validation being attempted. The value will be one 
+     * of the constants: <code>VALIDITY_NOTKNOWN</code>, 
+     * <code>VALIDITY_INVALID</code> or <code>VALIDITY_VALID</code>. 
+     */
+    public short getValidity();
+
+    /**
+     * <code>[validation attempted]</code>: determines the extent to which 
+     * the schema item has been validated. The value will be one of the 
+     * constants: <code>VALIDATION_NONE</code>, 
+     * <code>VALIDATION_PARTIAL</code> or <code>VALIDATION_FULL</code>. 
+     */
+    public short getValidationAttempted();
+
+    /**
+     * <code>[schema error code]</code>: a list of error codes generated from 
+     * the validation attempt or an empty <code>StringList</code> if no 
+     * errors occurred during the validation attempt. 
+     */
+    public StringList getErrorCodes();
+    
+    /**
+     * A list of error messages generated from the validation attempt or
+     * an empty <code>StringList</code> if no errors occurred during the 
+     * validation attempt. The indices of error messages in this list are 
+     * aligned with those in the <code>[schema error code]</code> list.
+     */
+    public StringList getErrorMessages();
+
+    /**
+     * <code>[schema normalized value]</code>: the normalized value of this 
+     * item after validation. 
+     * 
+     * @deprecated Use getSchemaValue().getNormalizedValue() instead
+     */
+    public String getSchemaNormalizedValue();
+
+    /**
+     * <code>[schema normalized value]</code>: Binding specific actual value 
+     * or <code>null</code> if the value is in error. 
+     * @exception XSException
+     *   NOT_SUPPORTED_ERR: Raised if the implementation does not support this 
+     *   method.
+     * 
+     * @deprecated Use getSchemaValue().getActualValue() instead
+     */
+    public Object getActualNormalizedValue()
+                                   throws XSException;
+
+    /**
+     * The actual value built-in datatype, e.g. 
+     * <code>STRING_DT, SHORT_DT</code>. If the type definition of this 
+     * value is a list type definition, this method returns 
+     * <code>LIST_DT</code>. If the type definition of this value is a list 
+     * type definition whose item type is a union type definition, this 
+     * method returns <code>LISTOFUNION_DT</code>. To query the actual value 
+     * of the list or list of union type definitions use 
+     * <code>itemValueTypes</code>. If the <code>actualNormalizedValue</code>
+     *  is <code>null</code>, this method returns <code>UNAVAILABLE_DT</code>. 
+     * @exception XSException
+     *   NOT_SUPPORTED_ERR: Raised if the implementation does not support this 
+     *   method.
+     *   
+     *  @deprecated Use getSchemaValue().getActualValueType() instead
+     */
+    public short getActualNormalizedValueType()
+                                   throws XSException;
+
+    /**
+     * In the case the actual value represents a list, i.e. the 
+     * <code>actualNormalizedValueType</code> is <code>LIST_DT</code>, the 
+     * returned array consists of one type kind which represents the itemType
+     * . For example: 
+     * <pre> &lt;simpleType name="listtype"&gt; &lt;list 
+     * itemType="positiveInteger"/&gt; &lt;/simpleType&gt; &lt;element 
+     * name="list" type="listtype"/&gt; ... &lt;list&gt;1 2 3&lt;/list&gt; </pre>
+     *  
+     * The <code>schemaNormalizedValue</code> value is "1 2 3", the 
+     * <code>actualNormalizedValueType</code> value is <code>LIST_DT</code>, 
+     * and the <code>itemValueTypes</code> is an array of size 1 with the 
+     * value <code>POSITIVEINTEGER_DT</code>. 
+     * <br> If the actual value represents a list type definition whose item 
+     * type is a union type definition, i.e. <code>LISTOFUNION_DT</code>, 
+     * for each actual value in the list the array contains the 
+     * corresponding memberType kind. For example: 
+     * <pre> &lt;simpleType 
+     * name='union_type' memberTypes="integer string"/&gt; &lt;simpleType 
+     * name='listOfUnion'&gt; &lt;list itemType='union_type'/&gt; 
+     * &lt;/simpleType&gt; &lt;element name="list" type="listOfUnion"/&gt; 
+     * ... &lt;list&gt;1 2 foo&lt;/list&gt; </pre>
+     *  The 
+     * <code>schemaNormalizedValue</code> value is "1 2 foo", the 
+     * <code>actualNormalizedValueType</code> is <code>LISTOFUNION_DT</code>
+     * , and the <code>itemValueTypes</code> is an array of size 3 with the 
+     * following values: <code>INTEGER_DT, INTEGER_DT, STRING_DT</code>. 
+     * @exception XSException
+     *   NOT_SUPPORTED_ERR: Raised if the implementation does not support this 
+     *   method.
+     *  
+     *  @deprecated Use getSchemaValue().getListValueTypes() instead
+     */
+    public ShortList getItemValueTypes()
+                                   throws XSException;
+
+    /**
+     * If this item has a simple type definition or a complex type with simple
+     * content, then return the value with respect to the simple type. If
+     * this item doesn't have a simple-typed value, the behavior of this method
+     * is not specified.
+     */
+    public XSValue getSchemaValue();
+    
+    /**
+     * <code>[type definition]</code>: an item isomorphic to the type 
+     * definition used to validate the schema item. 
+     */
+    public XSTypeDefinition getTypeDefinition();
+
+    /**
+     * <code>[member type definition]</code>: if and only if that type 
+     * definition is a simple type definition with {variety} union, or a 
+     * complex type definition whose {content type} is a simple type 
+     * definition with {variety} union, then an item isomorphic to that 
+     * member of the union's {member type definitions} which actually 
+     * validated the schema item's normalized value. 
+     */
+    public XSSimpleTypeDefinition getMemberTypeDefinition();
+
+    /**
+     * <code>[schema default]</code>: the canonical lexical representation of 
+     * the declaration's {value constraint} value. For more information 
+     * refer to element schema default and attribute schema default. 
+     */
+    public String getSchemaDefault();
+
+    /**
+     * <code>[schema specified]</code>: if true, the value was specified in 
+     * the schema. If false, the value comes from the infoset. For more 
+     * information refer to element specified and attribute specified. 
+     */
+    public boolean getIsSchemaSpecified();
+
+}

http://git-wip-us.apache.org/repos/asf/jena/blob/c9a7e646/jena-core/src/main/java/org/apache/jena/ext/xerces/xs/LSInputList.java
----------------------------------------------------------------------
diff --git a/jena-core/src/main/java/org/apache/jena/ext/xerces/xs/LSInputList.java b/jena-core/src/main/java/org/apache/jena/ext/xerces/xs/LSInputList.java
new file mode 100644
index 0000000..fb01c55
--- /dev/null
+++ b/jena-core/src/main/java/org/apache/jena/ext/xerces/xs/LSInputList.java
@@ -0,0 +1,48 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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.jena.ext.xerces.xs;
+
+import java.util.List;
+
+import org.w3c.dom.ls.LSInput;
+
+/**
+ *  The <code>LSInputList</code> interface provides the abstraction of an 
+ * ordered collection of <code>LSInput</code>s, without defining or 
+ * constraining how this collection is implemented. 
+ */
+@SuppressWarnings("rawtypes")
+public interface LSInputList extends List {
+    /**
+     *  The number of <code>LSInput</code>s in the list. The range of valid 
+     * child object indices is 0 to <code>length-1</code> inclusive. 
+     */
+    public int getLength();
+
+    /**
+     *  Returns the <code>index</code>th item in the collection or 
+     * <code>null</code> if <code>index</code> is greater than or equal to 
+     * the number of objects in the list. The index starts at 0. 
+     * @param index  index into the collection. 
+     * @return  The <code>LSInput</code> at the <code>index</code>th 
+     *   position in the <code>LSInputList</code>, or <code>null</code> if 
+     *   the index specified is not valid. 
+     */
+    public LSInput item(int index);
+
+}

http://git-wip-us.apache.org/repos/asf/jena/blob/c9a7e646/jena-core/src/main/java/org/apache/jena/ext/xerces/xs/PSVIProvider.java
----------------------------------------------------------------------
diff --git a/jena-core/src/main/java/org/apache/jena/ext/xerces/xs/PSVIProvider.java b/jena-core/src/main/java/org/apache/jena/ext/xerces/xs/PSVIProvider.java
new file mode 100644
index 0000000..f271e8e
--- /dev/null
+++ b/jena-core/src/main/java/org/apache/jena/ext/xerces/xs/PSVIProvider.java
@@ -0,0 +1,90 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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.jena.ext.xerces.xs;
+
+/**
+ * This interface provides access to the post schema validation infoset for an 
+ * API that provides a streaming document infoset, such as SAX, XNI, and 
+ * others. 
+ * <p>For implementations that would like to provide access to the PSVI in a 
+ * streaming model, a parser object should also implement the 
+ * <code>PSVIProvider</code> interface. Within the scope of the methods 
+ * handling the start and end of an element, applications may use the 
+ * <code>PSVIProvider</code> to retrieve the PSVI related to the element and 
+ * its attributes.
+ */
+public interface PSVIProvider {
+    /**
+     *  Provides the post schema validation item for the current element 
+     * information item. The method must be called by an application while 
+     * in the scope of the methods which report the start and end of an 
+     * element. For example, for SAX the method must be called within the 
+     * scope of the document handler's <code>startElement</code> or 
+     * <code>endElement</code> call. If the method is called outside of the 
+     * specified scope, the return value is undefined. 
+     * @return The post schema validation infoset for the current element. If 
+     *   an element information item is valid, then in the 
+     *   post-schema-validation infoset the following properties must be 
+     *   available for the element information item: The following 
+     *   properties are available in the scope of the method that reports 
+     *   the start of an element: {element declaration}, {validation 
+     *   context}, {notation}. The {schema information} property is 
+     *   available for the validation root. The {error codes} property is 
+     *   available if any errors occured during validation.  The following 
+     *   properties are available in the scope of the method that reports 
+     *   the end of an element: {nil}, {schema specified}, {normalized 
+     *   value},{ member type definition}, {validity}, {validation attempted}
+     *   . If the declaration has a value constraint, the property {schema 
+     *   default} is available. The {error codes} property is available if 
+     *   any errors occured during validation. Note: some processors may 
+     *   choose to provide all the PSVI properties in the scope of the 
+     *   method that reports the end of an element. 
+     */
+    public ElementPSVI getElementPSVI();
+
+    /**
+     * Provides <code>AttributePSVI</code> given the index of an attribute 
+     * information item in the current element's attribute list. The method 
+     * must be called by an application while in the scope of the methods 
+     * which report the start and end of an element at a point where the 
+     * attribute list is available. For example, for SAX the method must be 
+     * called while in the scope of the document handler's 
+     * <code>startElement</code> call. If the method is called outside of 
+     * the specified scope, the return value is undefined.
+     * @param index The attribute index. 
+     * @return The post schema validation properties of the attribute.
+     */
+    public AttributePSVI getAttributePSVI(int index);
+
+    /**
+     * Provides <code>AttributePSVI</code> given the namespace name and the 
+     * local name of an attribute information item in the current element's 
+     * attribute list. The method must be called by an application while in 
+     * the scope of the methods which report the start and end of an element 
+     * at a point where the attribute list is available. For example, for 
+     * SAX the method must be called while in the scope of the document 
+     * handler's <code>startElement</code> call. If the method is called 
+     * outside of the specified scope, the return value is undefined.
+     * @param uri The namespace name of an attribute. 
+     * @param localname The local name of an attribute. 
+     * @return The post schema validation properties of the attribute.
+     */
+    public AttributePSVI getAttributePSVIByName(String uri, 
+                                                String localname);
+
+}

http://git-wip-us.apache.org/repos/asf/jena/blob/c9a7e646/jena-core/src/main/java/org/apache/jena/ext/xerces/xs/ShortList.java
----------------------------------------------------------------------
diff --git a/jena-core/src/main/java/org/apache/jena/ext/xerces/xs/ShortList.java b/jena-core/src/main/java/org/apache/jena/ext/xerces/xs/ShortList.java
new file mode 100644
index 0000000..1c2b45e
--- /dev/null
+++ b/jena-core/src/main/java/org/apache/jena/ext/xerces/xs/ShortList.java
@@ -0,0 +1,57 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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.jena.ext.xerces.xs;
+
+import java.util.List;
+
+/**
+ *  The <code>ShortList</code> is an immutable ordered collection of 
+ * <code>unsigned short</code>. 
+ */
+@SuppressWarnings("rawtypes")
+public interface ShortList extends List {
+    /**
+     *  The number of <code>unsigned short</code>s in the list. The range of 
+     * valid child object indices is 0 to <code>length-1</code> inclusive. 
+     */
+    public int getLength();
+
+    /**
+     *  Checks if the <code>unsigned short</code> <code>item</code> is a 
+     * member of this list. 
+     * @param item  <code>unsigned short</code> whose presence in this list 
+     *   is to be tested. 
+     * @return  True if this list contains the <code>unsigned short</code> 
+     *   <code>item</code>. 
+     */
+    public boolean contains(short item);
+
+    /**
+     *  Returns the <code>index</code>th item in the collection. The index 
+     * starts at 0. 
+     * @param index  index into the collection. 
+     * @return  The <code>unsigned short</code> at the <code>index</code>th 
+     *   position in the <code>ShortList</code>. 
+     * @exception XSException
+     *   INDEX_SIZE_ERR: if <code>index</code> is greater than or equal to the 
+     *   number of objects in the list.
+     */
+    public short item(int index)
+                      throws XSException;
+
+}

http://git-wip-us.apache.org/repos/asf/jena/blob/c9a7e646/jena-core/src/main/java/org/apache/jena/ext/xerces/xs/StringList.java
----------------------------------------------------------------------
diff --git a/jena-core/src/main/java/org/apache/jena/ext/xerces/xs/StringList.java b/jena-core/src/main/java/org/apache/jena/ext/xerces/xs/StringList.java
new file mode 100644
index 0000000..581834a
--- /dev/null
+++ b/jena-core/src/main/java/org/apache/jena/ext/xerces/xs/StringList.java
@@ -0,0 +1,55 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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.jena.ext.xerces.xs;
+
+import java.util.List;
+
+/**
+ *  The <code>StringList</code> is an immutable ordered collection of 
+ * <code>GenericString</code>. 
+ */
+@SuppressWarnings("rawtypes")
+public interface StringList extends List {
+    /**
+     *  The number of <code>GenericString</code>s in the list. The range of 
+     * valid child object indices is 0 to <code>length-1</code> inclusive. 
+     */
+    public int getLength();
+
+    /**
+     *  Checks if the <code>GenericString</code> <code>item</code> is a member 
+     * of this list. 
+     * @param item  <code>GenericString</code> whose presence in this list is 
+     *   to be tested. 
+     * @return  True if this list contains the <code>GenericString</code> 
+     *   <code>item</code>. 
+     */
+    public boolean contains(String item);
+
+    /**
+     *  Returns the <code>index</code>th item in the collection or 
+     * <code>null</code> if <code>index</code> is greater than or equal to 
+     * the number of objects in the list. The index starts at 0. 
+     * @param index  index into the collection. 
+     * @return  The <code>GenericString</code> at the <code>index</code>th 
+     *   position in the <code>StringList</code>, or <code>null</code> if 
+     *   the index specified is not valid. 
+     */
+    public String item(int index);
+
+}

http://git-wip-us.apache.org/repos/asf/jena/blob/c9a7e646/jena-core/src/main/java/org/apache/jena/ext/xerces/xs/XSAnnotation.java
----------------------------------------------------------------------
diff --git a/jena-core/src/main/java/org/apache/jena/ext/xerces/xs/XSAnnotation.java b/jena-core/src/main/java/org/apache/jena/ext/xerces/xs/XSAnnotation.java
new file mode 100644
index 0000000..0912d93
--- /dev/null
+++ b/jena-core/src/main/java/org/apache/jena/ext/xerces/xs/XSAnnotation.java
@@ -0,0 +1,60 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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.jena.ext.xerces.xs;
+
+/**
+ * This interface represents the Annotation schema component.
+ */
+public interface XSAnnotation extends XSObject {
+    // TargetType
+    /**
+     * The object type is <code>org.w3c.dom.Element</code>.
+     */
+    public static final short W3C_DOM_ELEMENT           = 1;
+    /**
+     * The object type is <code>org.xml.sax.ContentHandler</code>.
+     */
+    public static final short SAX_CONTENTHANDLER        = 2;
+    /**
+     * The object type is <code>org.w3c.dom.Document</code>.
+     */
+    public static final short W3C_DOM_DOCUMENT          = 3;
+
+    /**
+     *  Write contents of the annotation to the specified object. If the 
+     * specified <code>target</code> is a DOM object, in-scope namespace 
+     * declarations for <code>annotation</code> element are added as 
+     * attribute nodes of the serialized <code>annotation</code>, otherwise 
+     * the corresponding events for all in-scope namespace declarations are 
+     * sent via the specified document handler. 
+     * @param target  A target pointer to the annotation target object, i.e. 
+     *   <code>org.w3c.dom.Document</code>, <code>org.w3c.dom.Element</code>
+     *   , <code>org.xml.sax.ContentHandler</code>. 
+     * @param targetType  A target type. 
+     * @return  True if the <code>target</code> is a recognized type and 
+     *   supported by this implementation, otherwise false. 
+     */
+    public boolean writeAnnotation(Object target, 
+                                   short targetType);
+
+    /**
+     * A text representation of the annotation.
+     */
+    public String getAnnotationString();
+
+}

http://git-wip-us.apache.org/repos/asf/jena/blob/c9a7e646/jena-core/src/main/java/org/apache/jena/ext/xerces/xs/XSAttributeDeclaration.java
----------------------------------------------------------------------
diff --git a/jena-core/src/main/java/org/apache/jena/ext/xerces/xs/XSAttributeDeclaration.java b/jena-core/src/main/java/org/apache/jena/ext/xerces/xs/XSAttributeDeclaration.java
new file mode 100644
index 0000000..871f8d1
--- /dev/null
+++ b/jena-core/src/main/java/org/apache/jena/ext/xerces/xs/XSAttributeDeclaration.java
@@ -0,0 +1,121 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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.jena.ext.xerces.xs;
+
+/**
+ * The interface represents the Attribute Declaration schema component.
+ */
+public interface XSAttributeDeclaration extends XSObject {
+    /**
+     * [type definition]: A simple type definition. 
+     */
+    public XSSimpleTypeDefinition getTypeDefinition();
+
+    /**
+     * [scope]. One of <code>SCOPE_GLOBAL</code>, <code>SCOPE_LOCAL</code>, or 
+     * <code>SCOPE_ABSENT</code>. If the scope is local, then the 
+     * <code>enclosingCTDefinition</code> is present. 
+     */
+    public short getScope();
+
+    /**
+     * The complex type definition for locally scoped declarations (see 
+     * <code>scope</code>), otherwise <code>null</code> if no such 
+     * definition exists. 
+     */
+    public XSComplexTypeDefinition getEnclosingCTDefinition();
+
+    /**
+     * Value constraint: one of <code>VC_NONE, VC_DEFAULT, VC_FIXED</code>. 
+     */
+    public short getConstraintType();
+
+    /**
+     * Value constraint: The constraint value with respect to the [type 
+     * definition], otherwise <code>null</code>. 
+     * 
+     * @deprecated Use getValueConstraintValue().getNormalizedValue() instead
+     */
+    public String getConstraintValue();
+
+    /**
+     * Value Constraint: Binding specific actual constraint value or 
+     * <code>null</code> if the value is in error or there is no value 
+     * constraint. 
+     * @exception XSException
+     *   NOT_SUPPORTED_ERR: Raised if the implementation does not support this 
+     *   method.
+     *  
+     *  @deprecated Use getValueConstraintValue().getActualValue() instead
+     */
+    public Object getActualVC()
+                                                        throws XSException;
+
+    /**
+     * The actual constraint value built-in datatype, e.g. 
+     * <code>STRING_DT, SHORT_DT</code>. If the type definition of this 
+     * value is a list type definition, this method returns 
+     * <code>LIST_DT</code>. If the type definition of this value is a list 
+     * type definition whose item type is a union type definition, this 
+     * method returns <code>LISTOFUNION_DT</code>. To query the actual 
+     * constraint value of the list or list of union type definitions use 
+     * <code>itemValueTypes</code>. If the <code>actualValue</code> is 
+     * <code>null</code>, this method returns <code>UNAVAILABLE_DT</code>. 
+     * @exception XSException
+     *   NOT_SUPPORTED_ERR: Raised if the implementation does not support this 
+     *   method.
+     *  
+     *  @deprecated Use getValueConstraintValue().getActualValueType() instead
+     */
+    public short getActualVCType()
+                                                        throws XSException;
+
+    /**
+     * In the case the actual constraint value represents a list, i.e. the 
+     * <code>actualValueType</code> is <code>LIST_DT</code>, the returned 
+     * array consists of one type kind which represents the itemType. If the 
+     * actual constraint value represents a list type definition whose item 
+     * type is a union type definition, i.e. <code>LISTOFUNION_DT</code>, 
+     * for each actual constraint value in the list the array contains the 
+     * corresponding memberType kind. For examples, see 
+     * <code>ItemPSVI.itemValueTypes</code>. 
+     * @exception XSException
+     *   NOT_SUPPORTED_ERR: Raised if the implementation does not support this 
+     *   method.
+     *   
+     *  @deprecated Use getValueConstraintValue().getListValueTypes() instead
+     */
+    public ShortList getItemValueTypes()
+                                                        throws XSException;
+
+    /**
+     * The actual value of the default or fixed value constraint.
+     */
+    public XSValue getValueConstraintValue();
+
+    /**
+     * An annotation if it exists, otherwise <code>null</code>. 
+     * If not null then the first [annotation] from the sequence of annotations.
+     */
+    public XSAnnotation getAnnotation();
+    
+    /**
+     * A sequence of [annotations] or an empty  <code>XSObjectList</code>. 
+     */
+    public XSObjectList getAnnotations();    
+}

http://git-wip-us.apache.org/repos/asf/jena/blob/c9a7e646/jena-core/src/main/java/org/apache/jena/ext/xerces/xs/XSAttributeGroupDefinition.java
----------------------------------------------------------------------
diff --git a/jena-core/src/main/java/org/apache/jena/ext/xerces/xs/XSAttributeGroupDefinition.java b/jena-core/src/main/java/org/apache/jena/ext/xerces/xs/XSAttributeGroupDefinition.java
new file mode 100644
index 0000000..f5db868
--- /dev/null
+++ b/jena-core/src/main/java/org/apache/jena/ext/xerces/xs/XSAttributeGroupDefinition.java
@@ -0,0 +1,45 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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.jena.ext.xerces.xs;
+
+/**
+ * This interface represents the Attribute Group Definition schema component.
+ */
+public interface XSAttributeGroupDefinition extends XSObject {
+    /**
+     * A set of [attribute uses] if it exists, otherwise an empty 
+     * <code>XSObjectList</code>. 
+     */
+    public XSObjectList getAttributeUses();
+
+    /**
+     * A [wildcard] if it exists, otherwise <code>null</code>. 
+     */
+    public XSWildcard getAttributeWildcard();
+
+    /**
+     * An annotation if it exists, otherwise <code>null</code>. If not null
+     * then the first [annotation] from the sequence of annotations.
+     */
+    public XSAnnotation getAnnotation();
+
+    /**
+     * A sequence of [annotations] or an empty <code>XSObjectList</code>.
+     */
+    public XSObjectList getAnnotations();    
+}

http://git-wip-us.apache.org/repos/asf/jena/blob/c9a7e646/jena-core/src/main/java/org/apache/jena/ext/xerces/xs/XSAttributeUse.java
----------------------------------------------------------------------
diff --git a/jena-core/src/main/java/org/apache/jena/ext/xerces/xs/XSAttributeUse.java b/jena-core/src/main/java/org/apache/jena/ext/xerces/xs/XSAttributeUse.java
new file mode 100644
index 0000000..c4d61bd
--- /dev/null
+++ b/jena-core/src/main/java/org/apache/jena/ext/xerces/xs/XSAttributeUse.java
@@ -0,0 +1,108 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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.jena.ext.xerces.xs;
+
+/**
+ * This interface represents the Attribute Use schema component. 
+ */
+public interface XSAttributeUse extends XSObject {
+    /**
+     * [required]: determines whether this use of an attribute declaration 
+     * requires an appropriate attribute information item to be present, or 
+     * merely allows it. 
+     */
+    public boolean getRequired();
+
+    /**
+     * [attribute declaration]: provides the attribute declaration itself, 
+     * which will in turn determine the simple type definition used. 
+     */
+    public XSAttributeDeclaration getAttrDeclaration();
+
+    /**
+     * Value Constraint: one of default, fixed, or none.
+     */
+    public short getConstraintType();
+
+    /**
+     * Value Constraint: The constraint value, otherwise <code>null</code>. 
+     * 
+     * @deprecated Use getValueConstraintValue().getNormalizedValue() instead
+     */
+    public String getConstraintValue();
+
+    /**
+     * Value Constraint: Binding specific actual constraint value or 
+     * <code>null</code> if the value is in error or there is no value 
+     * constraint. 
+     * @exception XSException
+     *   NOT_SUPPORTED_ERR: Raised if the implementation does not support this 
+     *   method.
+     * 
+     * @deprecated Use getValueConstraintValue().getActualValue() instead
+     */
+    public Object getActualVC()
+                                       throws XSException;
+
+    /**
+     * The actual constraint value built-in datatype, e.g. 
+     * <code>STRING_DT, SHORT_DT</code>. If the type definition of this 
+     * value is a list type definition, this method returns 
+     * <code>LIST_DT</code>. If the type definition of this value is a list 
+     * type definition whose item type is a union type definition, this 
+     * method returns <code>LISTOFUNION_DT</code>. To query the actual 
+     * constraint value of the list or list of union type definitions use 
+     * <code>itemValueTypes</code>. If the <code>actualNormalizedValue</code>
+     *  is <code>null</code>, this method returns <code>UNAVAILABLE_DT</code>. 
+     * @exception XSException
+     *   NOT_SUPPORTED_ERR: Raised if the implementation does not support this 
+     *   method.
+     * 
+     * @deprecated Use getValueConstraintValue().getActualValueType() instead
+     */
+    public short getActualVCType()
+                                       throws XSException;
+
+    /**
+     * In the case the actual constraint value represents a list, i.e. the 
+     * <code>actualValueType</code> is <code>LIST_DT</code>, the returned 
+     * array consists of one type kind which represents the itemType. If the 
+     * actual constraint value represents a list type definition whose item 
+     * type is a union type definition, i.e. <code>LISTOFUNION_DT</code>, 
+     * for each actual constraint value in the list the array contains the 
+     * corresponding memberType kind. For examples, see 
+     * <code>ItemPSVI.itemValueTypes</code>. 
+     * @exception XSException
+     *   NOT_SUPPORTED_ERR: Raised if the implementation does not support this 
+     *   method.
+     * 
+     * @deprecated Use getValueConstraintValue().getListValueTypes() instead
+     */
+    public ShortList getItemValueTypes()
+                                       throws XSException;
+
+    /**
+     * The actual value of the default or fixed value constraint.
+     */
+    public XSValue getValueConstraintValue();
+
+    /**
+     * A sequence of [annotations] or an empty <code>XSObjectList</code>.
+     */
+    public XSObjectList getAnnotations();    
+}

http://git-wip-us.apache.org/repos/asf/jena/blob/c9a7e646/jena-core/src/main/java/org/apache/jena/ext/xerces/xs/XSComplexTypeDefinition.java
----------------------------------------------------------------------
diff --git a/jena-core/src/main/java/org/apache/jena/ext/xerces/xs/XSComplexTypeDefinition.java b/jena-core/src/main/java/org/apache/jena/ext/xerces/xs/XSComplexTypeDefinition.java
new file mode 100644
index 0000000..d34b1b5
--- /dev/null
+++ b/jena-core/src/main/java/org/apache/jena/ext/xerces/xs/XSComplexTypeDefinition.java
@@ -0,0 +1,113 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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.jena.ext.xerces.xs;
+
+/**
+ * This interface represents the Complex Type Definition schema component.
+ */
+public interface XSComplexTypeDefinition extends XSTypeDefinition {
+    // Content Model Types
+    /**
+     * Represents an empty content type. A content type with the distinguished 
+     * value empty validates elements with no character or element 
+     * information item children. 
+     */
+    public static final short CONTENTTYPE_EMPTY         = 0;
+    /**
+     * Represents a simple content type. A content type which is simple 
+     * validates elements with character-only children. 
+     */
+    public static final short CONTENTTYPE_SIMPLE        = 1;
+    /**
+     * Represents an element-only content type. An element-only content type 
+     * validates elements with children that conform to the supplied content 
+     * model. 
+     */
+    public static final short CONTENTTYPE_ELEMENT       = 2;
+    /**
+     * Represents a mixed content type.
+     */
+    public static final short CONTENTTYPE_MIXED         = 3;
+
+    /**
+     * [derivation method]: either <code>DERIVATION_EXTENSION</code>, 
+     * <code>DERIVATION_RESTRICTION</code>, or <code>DERIVATION_NONE</code> 
+     * (see <code>XSConstants</code>). 
+     */
+    public short getDerivationMethod();
+
+    /**
+     * [abstract]: a boolean. Complex types for which <code>abstract</code> is 
+     * true must not be used as the type definition for the validation of 
+     * element information items. 
+     */
+    public boolean getAbstract();
+
+    /**
+     *  A set of attribute uses if it exists, otherwise an empty 
+     * <code>XSObjectList</code>. 
+     */
+    public XSObjectList getAttributeUses();
+
+    /**
+     * An attribute wildcard if it exists, otherwise <code>null</code>. 
+     */
+    public XSWildcard getAttributeWildcard();
+
+    /**
+     * [content type]: one of empty (<code>CONTENTTYPE_EMPTY</code>), a simple 
+     * type definition (<code>CONTENTTYPE_SIMPLE</code>), mixed (
+     * <code>CONTENTTYPE_MIXED</code>), or element-only (
+     * <code>CONTENTTYPE_ELEMENT</code>). 
+     */
+    public short getContentType();
+
+    /**
+     * A simple type definition corresponding to a simple content model, 
+     * otherwise <code>null</code>. 
+     */
+    public XSSimpleTypeDefinition getSimpleType();
+
+    /**
+     * A particle for a mixed or element-only content model, otherwise 
+     * <code>null</code>. 
+     */
+    public XSParticle getParticle();
+
+    /**
+     * [prohibited substitutions]: a subset of {extension, restriction}
+     * @param restriction  Extension or restriction constants (see 
+     *   <code>XSConstants</code>). 
+     * @return True if <code>restriction</code> is a prohibited substitution, 
+     *   otherwise false.
+     */
+    public boolean isProhibitedSubstitution(short restriction);
+
+    /**
+     *  [prohibited substitutions]: A subset of {extension, restriction} or 
+     * <code>DERIVATION_NONE</code> represented as a bit flag (see 
+     * <code>XSConstants</code>). 
+     */
+    public short getProhibitedSubstitutions();
+
+    /**
+     * A sequence of [annotations] or an empty <code>XSObjectList</code>.
+     */
+    public XSObjectList getAnnotations();
+
+}

http://git-wip-us.apache.org/repos/asf/jena/blob/c9a7e646/jena-core/src/main/java/org/apache/jena/ext/xerces/xs/XSConstants.java
----------------------------------------------------------------------
diff --git a/jena-core/src/main/java/org/apache/jena/ext/xerces/xs/XSConstants.java b/jena-core/src/main/java/org/apache/jena/ext/xerces/xs/XSConstants.java
new file mode 100644
index 0000000..f2daca9
--- /dev/null
+++ b/jena-core/src/main/java/org/apache/jena/ext/xerces/xs/XSConstants.java
@@ -0,0 +1,326 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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.jena.ext.xerces.xs;
+
+/**
+ *  This interface defines constants used by this specification.
+ */
+public interface XSConstants {
+    // XML Schema Components
+    /**
+     * The object describes an attribute declaration.
+     */
+    public static final short ATTRIBUTE_DECLARATION     = 1;
+    /**
+     * The object describes an element declaration.
+     */
+    public static final short ELEMENT_DECLARATION       = 2;
+    /**
+     * The object describes a complex type or simple type definition.
+     */
+    public static final short TYPE_DEFINITION           = 3;
+    /**
+     * The object describes an attribute use definition.
+     */
+    public static final short ATTRIBUTE_USE             = 4;
+    /**
+     * The object describes an attribute group definition.
+     */
+    public static final short ATTRIBUTE_GROUP           = 5;
+    /**
+     * The object describes a model group definition.
+     */
+    public static final short MODEL_GROUP_DEFINITION    = 6;
+    /**
+     * A model group.
+     */
+    public static final short MODEL_GROUP               = 7;
+    /**
+     * The object describes a particle.
+     */
+    public static final short PARTICLE                  = 8;
+    /**
+     * The object describes a wildcard.
+     */
+    public static final short WILDCARD                  = 9;
+    /**
+     * The object describes an identity constraint definition.
+     */
+    public static final short IDENTITY_CONSTRAINT       = 10;
+    /**
+     * The object describes a notation declaration.
+     */
+    public static final short NOTATION_DECLARATION      = 11;
+    /**
+     * The object describes an annotation.
+     */
+    public static final short ANNOTATION                = 12;
+    /**
+     * The object describes a constraining facet. Note: this object does not 
+     * describe pattern and enumeration facets.
+     */
+    public static final short FACET                     = 13;
+    /**
+     * The object describes enumeration and pattern facets. 
+     */
+    public static final short MULTIVALUE_FACET          = 14;
+
+    // Derivation constants
+    /**
+     * No constraint is available.
+     */
+    public static final short DERIVATION_NONE           = 0;
+    /**
+     * <code>XSTypeDefinition</code> final set or 
+     * <code>XSElementDeclaration</code> disallowed substitution group.
+     */
+    public static final short DERIVATION_EXTENSION      = 1;
+    /**
+     * <code>XSTypeDefinition</code> final set or 
+     * <code>XSElementDeclaration</code> disallowed substitution group.
+     */
+    public static final short DERIVATION_RESTRICTION    = 2;
+    /**
+     * <code>XSTypeDefinition</code> final set.
+     */
+    public static final short DERIVATION_SUBSTITUTION   = 4;
+    /**
+     * <code>XSTypeDefinition</code> final set.
+     */
+    public static final short DERIVATION_UNION          = 8;
+    /**
+     * <code>XSTypeDefinition</code> final set.
+     */
+    public static final short DERIVATION_LIST           = 16;
+
+    // Scope
+    /**
+     * The scope of a declaration within named model groups or attribute 
+     * groups is <code>absent</code>. The scope of such a declaration is 
+     * determined when it is used in the construction of complex type 
+     * definitions. 
+     */
+    public static final short SCOPE_ABSENT              = 0;
+    /**
+     * A scope of <code>global</code> identifies top-level declarations. 
+     */
+    public static final short SCOPE_GLOBAL              = 1;
+    /**
+     * <code>Locally scoped</code> declarations are available for use only 
+     * within the complex type.
+     */
+    public static final short SCOPE_LOCAL               = 2;
+
+    // Value Constraint
+    /**
+     * Indicates that the component does not have any value constraint.
+     */
+    public static final short VC_NONE                   = 0;
+    /**
+     * Indicates that there is a default value constraint.
+     */
+    public static final short VC_DEFAULT                = 1;
+    /**
+     * Indicates that there is a fixed value constraint for this attribute.
+     */
+    public static final short VC_FIXED                  = 2;
+
+    // Built-in types: primitive and derived
+    /**
+     * anySimpleType
+     */
+    public static final short ANYSIMPLETYPE_DT          = 1;
+    /**
+     * string
+     */
+    public static final short STRING_DT                 = 2;
+    /**
+     * boolean
+     */
+    public static final short BOOLEAN_DT                = 3;
+    /**
+     * decimal
+     */
+    public static final short DECIMAL_DT                = 4;
+    /**
+     * float
+     */
+    public static final short FLOAT_DT                  = 5;
+    /**
+     * double
+     */
+    public static final short DOUBLE_DT                 = 6;
+    /**
+     * duration
+     */
+    public static final short DURATION_DT               = 7;
+    /**
+     * dateTime
+     */
+    public static final short DATETIME_DT               = 8;
+    /**
+     * time
+     */
+    public static final short TIME_DT                   = 9;
+    /**
+     * date
+     */
+    public static final short DATE_DT                   = 10;
+    /**
+     * gYearMonth
+     */
+    public static final short GYEARMONTH_DT             = 11;
+    /**
+     * gYear
+     */
+    public static final short GYEAR_DT                  = 12;
+    /**
+     * gMonthDay
+     */
+    public static final short GMONTHDAY_DT              = 13;
+    /**
+     * gDay
+     */
+    public static final short GDAY_DT                   = 14;
+    /**
+     * gMonth
+     */
+    public static final short GMONTH_DT                 = 15;
+    /**
+     * hexBinary
+     */
+    public static final short HEXBINARY_DT              = 16;
+    /**
+     * base64Binary
+     */
+    public static final short BASE64BINARY_DT           = 17;
+    /**
+     * anyURI
+     */
+    public static final short ANYURI_DT                 = 18;
+    /**
+     * QName
+     */
+    public static final short QNAME_DT                  = 19;
+    /**
+     * NOTATION
+     */
+    public static final short NOTATION_DT               = 20;
+    /**
+     * normalizedString
+     */
+    public static final short NORMALIZEDSTRING_DT       = 21;
+    /**
+     * token
+     */
+    public static final short TOKEN_DT                  = 22;
+    /**
+     * language
+     */
+    public static final short LANGUAGE_DT               = 23;
+    /**
+     * NMTOKEN
+     */
+    public static final short NMTOKEN_DT                = 24;
+    /**
+     * Name
+     */
+    public static final short NAME_DT                   = 25;
+    /**
+     * NCName
+     */
+    public static final short NCNAME_DT                 = 26;
+    /**
+     * ID
+     */
+    public static final short ID_DT                     = 27;
+    /**
+     * IDREF
+     */
+    public static final short IDREF_DT                  = 28;
+    /**
+     * ENTITY
+     */
+    public static final short ENTITY_DT                 = 29;
+    /**
+     * integer
+     */
+    public static final short INTEGER_DT                = 30;
+    /**
+     * nonPositiveInteger
+     */
+    public static final short NONPOSITIVEINTEGER_DT     = 31;
+    /**
+     * negativeInteger
+     */
+    public static final short NEGATIVEINTEGER_DT        = 32;
+    /**
+     * long
+     */
+    public static final short LONG_DT                   = 33;
+    /**
+     * int
+     */
+    public static final short INT_DT                    = 34;
+    /**
+     * short
+     */
+    public static final short SHORT_DT                  = 35;
+    /**
+     * byte
+     */
+    public static final short BYTE_DT                   = 36;
+    /**
+     * nonNegativeInteger
+     */
+    public static final short NONNEGATIVEINTEGER_DT     = 37;
+    /**
+     * unsignedLong
+     */
+    public static final short UNSIGNEDLONG_DT           = 38;
+    /**
+     * unsignedInt
+     */
+    public static final short UNSIGNEDINT_DT            = 39;
+    /**
+     * unsignedShort
+     */
+    public static final short UNSIGNEDSHORT_DT          = 40;
+    /**
+     * unsignedByte
+     */
+    public static final short UNSIGNEDBYTE_DT           = 41;
+    /**
+     * positiveInteger
+     */
+    public static final short POSITIVEINTEGER_DT        = 42;
+    /**
+     * The type represents a list type definition whose item type (itemType) 
+     * is a union type definition
+     */
+    public static final short LISTOFUNION_DT            = 43;
+    /**
+     * The type represents a list type definition.
+     */
+    public static final short LIST_DT                   = 44;
+    /**
+     * The built-in type category is not available.
+     */
+    public static final short UNAVAILABLE_DT            = 45;
+    
+}

http://git-wip-us.apache.org/repos/asf/jena/blob/c9a7e646/jena-core/src/main/java/org/apache/jena/ext/xerces/xs/XSElementDeclaration.java
----------------------------------------------------------------------
diff --git a/jena-core/src/main/java/org/apache/jena/ext/xerces/xs/XSElementDeclaration.java b/jena-core/src/main/java/org/apache/jena/ext/xerces/xs/XSElementDeclaration.java
new file mode 100644
index 0000000..9f6e373
--- /dev/null
+++ b/jena-core/src/main/java/org/apache/jena/ext/xerces/xs/XSElementDeclaration.java
@@ -0,0 +1,189 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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.jena.ext.xerces.xs;
+
+/**
+ * The interface represents the Element Declaration schema component. 
+ */
+public interface XSElementDeclaration extends XSTerm {
+    /**
+     * [type definition]: either a simple type definition or a complex type 
+     * definition. 
+     */
+    public XSTypeDefinition getTypeDefinition();
+
+    /**
+     * [scope]. One of <code>SCOPE_GLOBAL</code>, <code>SCOPE_LOCAL</code>, or 
+     * <code>SCOPE_ABSENT</code>. If the scope is local, then the 
+     * <code>enclosingCTDefinition</code> is present. 
+     */
+    public short getScope();
+
+    /**
+     * The complex type definition for locally scoped declarations (see 
+     * <code>scope</code>), otherwise <code>null</code> if no such 
+     * definition exists. 
+     */
+    public XSComplexTypeDefinition getEnclosingCTDefinition();
+
+    /**
+     * [Value constraint]: one of <code>VC_NONE, VC_DEFAULT, VC_FIXED</code>. 
+     */
+    public short getConstraintType();
+
+    /**
+     * [Value constraint]: the constraint value with respect to the [type 
+     * definition], otherwise <code>null</code>. 
+     * 
+     * @deprecated Use getValueConstraintValue().getNormalizedValue() instead
+     */
+    public String getConstraintValue();
+
+    /**
+     * Value Constraint: Binding specific actual constraint value or 
+     * <code>null</code> if the value is in error or there is no value 
+     * constraint. 
+     * @exception XSException
+     *   NOT_SUPPORTED_ERR: Raised if the implementation does not support this 
+     *   method.
+     * 
+     * @deprecated Use getValueConstraintValue().getActualValue() instead
+     */
+    public Object getActualVC()
+                                            throws XSException;
+
+    /**
+     * The actual constraint value built-in datatype, e.g. 
+     * <code>STRING_DT, SHORT_DT</code>. If the type definition of this 
+     * value is a list type definition, this method returns 
+     * <code>LIST_DT</code>. If the type definition of this value is a list 
+     * type definition whose item type is a union type definition, this 
+     * method returns <code>LISTOFUNION_DT</code>. To query the actual 
+     * constraint value of the list or list of union type definitions use 
+     * <code>itemValueTypes</code>. If the <code>actualNormalizedValue</code>
+     *  is <code>null</code>, this method returns <code>UNAVAILABLE_DT</code>.
+     * @exception XSException
+     *   NOT_SUPPORTED_ERR: Raised if the implementation does not support this 
+     *   method.
+     * 
+     * @deprecated Use getValueConstraintValue().getActualValueType() instead
+     */
+    public short getActualVCType()
+                                            throws XSException;
+
+    /**
+     * In the case the actual constraint value represents a list, i.e. the 
+     * <code>actualValueType</code> is <code>LIST_DT</code>, the returned 
+     * array consists of one type kind which represents the itemType. If the 
+     * actual constraint value represents a list type definition whose item 
+     * type is a union type definition, i.e. <code>LISTOFUNION_DT</code>, 
+     * for each actual constraint value in the list the array contains the 
+     * corresponding memberType kind. For examples, see 
+     * <code>ItemPSVI.itemValueTypes</code>. 
+     * @exception XSException
+     *   NOT_SUPPORTED_ERR: Raised if the implementation does not support this 
+     *   method.
+     * 
+     * @deprecated Use getValueConstraintValue().getListValueTypes() instead
+     */
+    public ShortList getItemValueTypes()
+                                            throws XSException;
+
+    /**
+     * The actual value of the default or fixed value constraint.
+     */
+    public XSValue getValueConstraintValue();
+
+    /**
+     *  If nillable is true, then an element may also be valid if it carries 
+     * the namespace qualified attribute with local name <code>nil</code> 
+     * from namespace <code>http://www.w3.org/2001/XMLSchema-instance</code> 
+     * and value <code>true</code> (xsi:nil) even if it has no text or 
+     * element content despite a <code>content type</code> which would 
+     * otherwise require content. 
+     */
+    public boolean getNillable();
+
+    /**
+     * identity-constraint definitions: a set of constraint definitions if it 
+     * exists, otherwise an empty <code>XSNamedMap</code>. 
+     */
+    public XSNamedMap getIdentityConstraints();
+
+    /**
+     * [substitution group affiliation]: a top-level element definition if it 
+     * exists, otherwise <code>null</code>. 
+     */
+    public XSElementDeclaration getSubstitutionGroupAffiliation();
+
+    /**
+     * Convenience method that checks if <code>exclusion</code> is a 
+     * substitution group exclusion for this element declaration. 
+     * @param exclusion  
+     *   <code>DERIVATION_EXTENSION, DERIVATION_RESTRICTION</code> or 
+     *   <code>DERIVATION_NONE</code>. Represents final set for the element.
+     * @return True if <code>exclusion</code> is a part of the substitution 
+     *   group exclusion subset. 
+     */
+    public boolean isSubstitutionGroupExclusion(short exclusion);
+
+    /**
+     *  [substitution group exclusions]: the returned value is a bit 
+     * combination of the subset of {
+     * <code>DERIVATION_EXTENSION, DERIVATION_RESTRICTION</code>} or 
+     * <code>DERIVATION_NONE</code>. 
+     */
+    public short getSubstitutionGroupExclusions();
+
+    /**
+     * Convenience method that checks if <code>disallowed</code> is a 
+     * disallowed substitution for this element declaration. 
+     * @param disallowed {
+     *   <code>DERIVATION_SUBSTITUTION, DERIVATION_EXTENSION, DERIVATION_RESTRICTION</code>
+     *   } or <code>DERIVATION_NONE</code>. Represents a block set for the 
+     *   element.
+     * @return True if <code>disallowed</code> is a part of the substitution 
+     *   group exclusion subset. 
+     */
+    public boolean isDisallowedSubstitution(short disallowed);
+
+    /**
+     *  [disallowed substitutions]: the returned value is a bit combination of 
+     * the subset of {
+     * <code>DERIVATION_SUBSTITUTION, DERIVATION_EXTENSION, DERIVATION_RESTRICTION</code>
+     * } corresponding to substitutions disallowed by this 
+     * <code>XSElementDeclaration</code> or <code>DERIVATION_NONE</code>. 
+     */
+    public short getDisallowedSubstitutions();
+
+    /**
+     * {abstract} A boolean. 
+     */
+    public boolean getAbstract();
+
+    /**
+     * An annotation if it exists, otherwise <code>null</code>. If not null
+     * then the first [annotation] from the sequence of annotations.
+     */
+    public XSAnnotation getAnnotation();
+
+    /**
+     * A sequence of [annotations] or an empty <code>XSObjectList</code>.
+     */
+    public XSObjectList getAnnotations();    
+}

http://git-wip-us.apache.org/repos/asf/jena/blob/c9a7e646/jena-core/src/main/java/org/apache/jena/ext/xerces/xs/XSException.java
----------------------------------------------------------------------
diff --git a/jena-core/src/main/java/org/apache/jena/ext/xerces/xs/XSException.java b/jena-core/src/main/java/org/apache/jena/ext/xerces/xs/XSException.java
new file mode 100644
index 0000000..f10a239
--- /dev/null
+++ b/jena-core/src/main/java/org/apache/jena/ext/xerces/xs/XSException.java
@@ -0,0 +1,53 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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.jena.ext.xerces.xs;
+
+/**
+ * The XML Schema API operations only raise exceptions in "exceptional" 
+ * circumstances, i.e., when an operation is impossible to perform (either 
+ * for logical reasons, because data is lost, or because the implementation 
+ * has become unstable).
+ * <p>Implementations should raise other exceptions under other circumstances. 
+ * <p>Some languages and object systems do not support the concept of 
+ * exceptions. For such systems, error conditions may be indicated using 
+ * native error reporting mechanisms. For some bindings, for example, 
+ * methods may return error codes similar to those listed in the 
+ * corresponding method descriptions.
+ */
+public class XSException extends RuntimeException {
+
+    /** Serialization version. */
+    static final long serialVersionUID = 3111893084677917742L;
+    
+    public XSException(short code, String message) {
+       super(message);
+       this.code = code;
+    }
+    public short   code;
+    // ExceptionCode
+    /**
+     * If the implementation does not support the requested type of object or 
+     * operation.
+     */
+    public static final short NOT_SUPPORTED_ERR         = 1;
+    /**
+     * If index or size is negative, or greater than the allowed value
+     */
+    public static final short INDEX_SIZE_ERR            = 2;
+
+}

http://git-wip-us.apache.org/repos/asf/jena/blob/c9a7e646/jena-core/src/main/java/org/apache/jena/ext/xerces/xs/XSFacet.java
----------------------------------------------------------------------
diff --git a/jena-core/src/main/java/org/apache/jena/ext/xerces/xs/XSFacet.java b/jena-core/src/main/java/org/apache/jena/ext/xerces/xs/XSFacet.java
new file mode 100644
index 0000000..6e4774d
--- /dev/null
+++ b/jena-core/src/main/java/org/apache/jena/ext/xerces/xs/XSFacet.java
@@ -0,0 +1,69 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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.jena.ext.xerces.xs;
+
+/**
+ * Describes a constraining facet. Enumeration and pattern facets are exposed 
+ * via <code>XSMultiValueFacet</code> interface.
+ */
+public interface XSFacet extends XSObject {
+    /**
+     * The name of the facet, e.g. <code>FACET_LENGTH, FACET_TOTALDIGITS</code>
+     *  (see <code>XSSimpleTypeDefinition</code>). 
+     */
+    public short getFacetKind();
+
+    /**
+     * A value of this facet. 
+     */
+    public String getLexicalFacetValue();
+
+    /**
+     * If this facet is length, minLength, maxLength, totalDigits, or
+     * fractionDigits, and if the value can fit in "int", then return the value
+     * of the facet as an int. If the value can't fit, return -1. Use
+     * getActualFacetValue() to get the BigInteger representation. For all other
+     * facets, return 0.
+     */
+    public int getIntFacetValue();
+
+    /**
+     * If this facet is minInclusive, maxInclusive, minExclusive, or
+     * maxExclusive, then return the actual value of the facet. If this facet
+     * is length, minLength, maxLength, totalDigits, or fractionDigits, then
+     * return a BigInteger representation of the value. If this facet is
+     * whiteSpace, then return the String representation of the facet.
+     */
+    public Object getActualFacetValue();
+
+    /**
+     * [Facets]: check whether a facet is fixed. 
+     */
+    public boolean getFixed();
+
+    /**
+     * An annotation if it exists, otherwise <code>null</code>. If not null
+     * then the first [annotation] from the sequence of annotations.
+     */
+    public XSAnnotation getAnnotation();
+
+    /**
+     * A sequence of [annotations] or an empty <code>XSObjectList</code>.
+     */
+    public XSObjectList getAnnotations();    
+}

http://git-wip-us.apache.org/repos/asf/jena/blob/c9a7e646/jena-core/src/main/java/org/apache/jena/ext/xerces/xs/XSIDCDefinition.java
----------------------------------------------------------------------
diff --git a/jena-core/src/main/java/org/apache/jena/ext/xerces/xs/XSIDCDefinition.java b/jena-core/src/main/java/org/apache/jena/ext/xerces/xs/XSIDCDefinition.java
new file mode 100644
index 0000000..c2c3e2d
--- /dev/null
+++ b/jena-core/src/main/java/org/apache/jena/ext/xerces/xs/XSIDCDefinition.java
@@ -0,0 +1,69 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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.jena.ext.xerces.xs;
+
+/**
+ * This interface represents the Identity-constraint Definition schema 
+ * component.
+ */
+public interface XSIDCDefinition extends XSObject {
+    // Identity Constraints
+    /**
+     * See the definition of <code>key</code> in the identity-constraint 
+     * category.
+     */
+    public static final short IC_KEY                    = 1;
+    /**
+     * See the definition of <code>keyref</code> in the identity-constraint 
+     * category.
+     */
+    public static final short IC_KEYREF                 = 2;
+    /**
+     * See the definition of <code>unique</code> in the identity-constraint 
+     * category.
+     */
+    public static final short IC_UNIQUE                 = 3;
+
+    /**
+     * [identity-constraint category]: one of key, keyref or unique. 
+     */
+    public short getCategory();
+
+    /**
+     * [selector]: a restricted XPath 1.0 expression. 
+     */
+    public String getSelectorStr();
+
+    /**
+     * [fields]: a non-empty list of restricted  XPath 1.0 expressions. 
+     */
+    public StringList getFieldStrs();
+
+    /**
+     * [referenced key]: required if [identity-constraint category] is keyref, 
+     * <code>null</code> otherwise. An identity-constraint definition with [
+     * identity-constraint category] equal to key or unique. 
+     */
+    public XSIDCDefinition getRefKey();
+
+    /**
+     * A sequence of [annotations] or an empty  <code>XSObjectList</code>. 
+     */
+    public XSObjectList getAnnotations();
+
+}

http://git-wip-us.apache.org/repos/asf/jena/blob/c9a7e646/jena-core/src/main/java/org/apache/jena/ext/xerces/xs/XSImplementation.java
----------------------------------------------------------------------
diff --git a/jena-core/src/main/java/org/apache/jena/ext/xerces/xs/XSImplementation.java b/jena-core/src/main/java/org/apache/jena/ext/xerces/xs/XSImplementation.java
new file mode 100644
index 0000000..4eabca8
--- /dev/null
+++ b/jena-core/src/main/java/org/apache/jena/ext/xerces/xs/XSImplementation.java
@@ -0,0 +1,64 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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.jena.ext.xerces.xs;
+
+import org.w3c.dom.ls.LSInput;
+
+/**
+ * This interface allows one to retrieve an instance of <code>XSLoader</code>. 
+ * This interface should be implemented on the same object that implements 
+ * DOMImplementation.
+ */
+public interface XSImplementation {
+    /**
+     * A list containing the versions of XML Schema documents recognized by 
+     * this <code>XSImplemenation</code>.
+     */
+    public StringList getRecognizedVersions();
+
+
+    /**
+     * Creates a new XSLoader. The newly constructed loader may then be 
+     * configured and used to load XML Schemas.
+     * @param versions  A list containing the versions of XML Schema 
+     *   documents which can be loaded by the <code>XSLoader</code> or 
+     *   <code>null</code> to permit XML Schema documents of any recognized 
+     *   version to be loaded by the XSLoader. 
+     * @return  An XML Schema loader. 
+     * @exception XSException
+     *   NOT_SUPPORTED_ERR: Raised if the implementation does not support one 
+     *   of the specified versions.
+     */
+    public XSLoader createXSLoader(StringList versions)
+                                   throws XSException;
+    
+    /**
+     * Creates an immutable <code>StringList</code> from the given array of <code>String</code>s.
+     * @param values the array containing the <code>String</code> values that will be placed in the list.
+     * @return an immutable <code>StringList</code> from the given array of <code>String</code>s.
+     */
+    public StringList createStringList(String[] values);
+    
+    /**
+     * Creates an immutable <code>LSInputList</code> from the given array of <code>LSInput</code>s.
+     * @param values the array containing the <code>LSInput</code> values that will be placed in the list.
+     * @return an immutable <code>LSInputList</code> from the given array of <code>LSInput</code>s.
+     */
+    public LSInputList createLSInputList(LSInput[] values);
+
+}

http://git-wip-us.apache.org/repos/asf/jena/blob/c9a7e646/jena-core/src/main/java/org/apache/jena/ext/xerces/xs/XSLoader.java
----------------------------------------------------------------------
diff --git a/jena-core/src/main/java/org/apache/jena/ext/xerces/xs/XSLoader.java b/jena-core/src/main/java/org/apache/jena/ext/xerces/xs/XSLoader.java
new file mode 100644
index 0000000..c8adf02
--- /dev/null
+++ b/jena-core/src/main/java/org/apache/jena/ext/xerces/xs/XSLoader.java
@@ -0,0 +1,90 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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.jena.ext.xerces.xs;
+
+import org.w3c.dom.DOMConfiguration;
+import org.w3c.dom.ls.LSInput;
+
+/**
+ * An interface that provides a method to load XML Schema documents. This 
+ * interface uses the DOM Level 3 Core and Load and Save interfaces.
+ */
+public interface XSLoader {
+    /**
+     *  The configuration of a document. It maintains a table of recognized 
+     * parameters. Using the configuration, it is possible to change the 
+     * behavior of the load methods. The configuration may support the 
+     * setting of and the retrieval of the following non-boolean parameters 
+     * defined on the <code>DOMConfiguration</code> interface: 
+     * <code>error-handler</code> (<code>DOMErrorHandler</code>) and 
+     * <code>resource-resolver</code> (<code>LSResourceResolver</code>). 
+     * <br> The following list of boolean parameters is defined: 
+     * <dl>
+     * <dt>
+     * <code>"validate"</code></dt>
+     * <dd>
+     * <dl>
+     * <dt><code>true</code></dt>
+     * <dd>[required] (default) Validate an XML 
+     * Schema during loading. If validation errors are found, the error 
+     * handler is notified. </dd>
+     * <dt><code>false</code></dt>
+     * <dd>[optional] Do not 
+     * report errors during the loading of an XML Schema document. </dd>
+     * </dl></dd>
+     * </dl>
+     */
+    public DOMConfiguration getConfig();
+
+    /**
+     * Parses the content of XML Schema documents specified as the list of URI 
+     * references. If the URI contains a fragment identifier, the behavior 
+     * is not defined by this specification. 
+     * @param uriList The list of URI locations.
+     * @return An XSModel representing the schema documents.
+     */
+    public XSModel loadURIList(StringList uriList);
+
+    /**
+     *  Parses the content of XML Schema documents specified as a list of 
+     * <code>LSInput</code>s. 
+     * @param is  The list of <code>LSInput</code>s from which the XML 
+     *   Schema documents are to be read. 
+     * @return An XSModel representing the schema documents.
+     */
+    public XSModel loadInputList(LSInputList is);
+
+    /**
+     * Parse an XML Schema document from a location identified by a URI 
+     * reference. If the URI contains a fragment identifier, the behavior is 
+     * not defined by this specification. 
+     * @param uri The location of the XML Schema document to be read.
+     * @return An XSModel representing this schema.
+     */
+    public XSModel loadURI(String uri);
+
+    /**
+     *  Parse an XML Schema document from a resource identified by a 
+     * <code>LSInput</code> . 
+     * @param is  The <code>LSInput</code> from which the source 
+     *   document is to be read. 
+     * @return An XSModel representing this schema.
+     */
+    public XSModel load(LSInput is);
+
+}

http://git-wip-us.apache.org/repos/asf/jena/blob/c9a7e646/jena-core/src/main/java/org/apache/jena/ext/xerces/xs/XSModel.java
----------------------------------------------------------------------
diff --git a/jena-core/src/main/java/org/apache/jena/ext/xerces/xs/XSModel.java b/jena-core/src/main/java/org/apache/jena/ext/xerces/xs/XSModel.java
new file mode 100644
index 0000000..ab29cb8
--- /dev/null
+++ b/jena-core/src/main/java/org/apache/jena/ext/xerces/xs/XSModel.java
@@ -0,0 +1,173 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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.jena.ext.xerces.xs;
+
+/**
+ * This interface represents an XML Schema. 
+ */
+public interface XSModel {
+    /**
+     * Convenience method. Returns a list of all namespaces that belong to 
+     * this schema. The value <code>null</code> is not a valid namespace 
+     * name, but if there are components that do not have a target namespace
+     * , <code>null</code> is included in this list. 
+     */
+    public StringList getNamespaces();
+
+    /**
+     * A set of namespace schema information information items (of type 
+     * <code>XSNamespaceItem</code>), one for each namespace name which 
+     * appears as the target namespace of any schema component in the schema 
+     * used for that assessment, and one for absent if any schema component 
+     * in the schema had no target namespace. For more information see 
+     * schema information. 
+     */
+    public XSNamespaceItemList getNamespaceItems();
+
+    /**
+     * Returns a list of top-level components, i.e. element declarations, 
+     * attribute declarations, etc. Identity-constraint definitions are also
+     * considered top-level.
+     * 
+     * @param objectType The type of the declaration, i.e. 
+     *   <code>ELEMENT_DECLARATION</code>. Note that 
+     *   <code>XSTypeDefinition.SIMPLE_TYPE</code> and 
+     *   <code>XSTypeDefinition.COMPLEX_TYPE</code> can also be used as the 
+     *   <code>objectType</code> to retrieve only complex types or simple 
+     *   types, instead of all types.
+     * @return  A list of top-level definitions of the specified type in 
+     *   <code>objectType</code> or an empty <code>XSNamedMap</code> if no 
+     *   such definitions exist. 
+     */
+    public XSNamedMap getComponents(short objectType);
+
+    /**
+     * Convenience method. Returns a list of top-level component declarations 
+     * that are defined within the specified namespace, i.e. element 
+     * declarations, attribute declarations, etc. Identity-constraint
+     * definitions are also considered top-level.
+     * 
+     * @param objectType The type of the declaration, i.e. 
+     *   <code>ELEMENT_DECLARATION</code>.
+     * @param namespace The namespace to which the declaration belongs or 
+     *   <code>null</code> (for components with no target namespace).
+     * @return  A list of top-level definitions of the specified type in 
+     *   <code>objectType</code> and defined in the specified 
+     *   <code>namespace</code> or an empty <code>XSNamedMap</code>. 
+     */
+    public XSNamedMap getComponentsByNamespace(short objectType, 
+                                               String namespace);
+
+    /**
+     *  [annotations]: a set of annotations if it exists, otherwise an empty 
+     * <code>XSObjectList</code>. 
+     */
+    public XSObjectList getAnnotations();
+
+    /**
+     * Convenience method. Returns a top-level element declaration. 
+     * @param name The name of the declaration.
+     * @param namespace The namespace of the declaration, otherwise 
+     *   <code>null</code>.
+     * @return A top-level element declaration or <code>null</code> if such a 
+     *   declaration does not exist. 
+     */
+    public XSElementDeclaration getElementDeclaration(String name, 
+                                                      String namespace);
+
+    /**
+     * Convenience method. Returns a top-level attribute declaration. 
+     * @param name The name of the declaration.
+     * @param namespace The namespace of the declaration, otherwise 
+     *   <code>null</code>.
+     * @return A top-level attribute declaration or <code>null</code> if such 
+     *   a declaration does not exist. 
+     */
+    public XSAttributeDeclaration getAttributeDeclaration(String name, 
+                                                          String namespace);
+
+    /**
+     * Convenience method. Returns a top-level simple or complex type 
+     * definition. 
+     * @param name The name of the definition.
+     * @param namespace The namespace of the declaration, otherwise 
+     *   <code>null</code>.
+     * @return An <code>XSTypeDefinition</code> or <code>null</code> if such 
+     *   a definition does not exist. 
+     */
+    public XSTypeDefinition getTypeDefinition(String name, 
+                                              String namespace);
+
+    /**
+     * Convenience method. Returns a top-level attribute group definition. 
+     * @param name The name of the definition.
+     * @param namespace The namespace of the definition, otherwise 
+     *   <code>null</code>.
+     * @return A top-level attribute group definition or <code>null</code> if 
+     *   such a definition does not exist. 
+     */
+    public XSAttributeGroupDefinition getAttributeGroup(String name, 
+                                                        String namespace);
+
+    /**
+     * Convenience method. Returns a top-level model group definition. 
+     * @param name The name of the definition.
+     * @param namespace The namespace of the definition, otherwise 
+     *   <code>null</code>.
+     * @return A top-level model group definition or <code>null</code> if 
+     *   such a definition does not exist. 
+     */
+    public XSModelGroupDefinition getModelGroupDefinition(String name, 
+                                                          String namespace);
+
+    /**
+     * Convenience method. Returns a top-level notation declaration. 
+     * @param name The name of the declaration.
+     * @param namespace The namespace of the declaration, otherwise 
+     *   <code>null</code>.
+     * @return A top-level notation declaration or <code>null</code> if such 
+     *   a declaration does not exist. 
+     */
+    public XSNotationDeclaration getNotationDeclaration(String name, 
+                                                        String namespace);
+    
+    /**
+     * Convenience method. Returns an identity-constraint definition.
+     * @param name The name of the definition.
+     * @param namespace The namespace of the definition, otherwise 
+     *   <code>null</code>.
+     * @return An identity-constraint definition or <code>null</code> if such 
+     *   a declaration does not exist. 
+     */
+    public XSIDCDefinition getIDCDefinition(String name,
+                                            String namespace);
+    
+    /**
+     * Convenience method. Returns a list containing the members of the
+     * substitution group for the given <code>XSElementDeclaration</code>
+     * or an empty <code>XSObjectList</code> if the substitution group
+     * contains no members.
+     * @param head The substitution group head.
+     * @return A list containing the members of the substitution group 
+     *  for the given <code>XSElementDeclaration</code> or an empty 
+     *  <code>XSObjectList</code> if the substitution group contains 
+     *  no members.
+     */
+    public XSObjectList getSubstitutionGroup(XSElementDeclaration head);
+
+}

http://git-wip-us.apache.org/repos/asf/jena/blob/c9a7e646/jena-core/src/main/java/org/apache/jena/ext/xerces/xs/XSModelGroup.java
----------------------------------------------------------------------
diff --git a/jena-core/src/main/java/org/apache/jena/ext/xerces/xs/XSModelGroup.java b/jena-core/src/main/java/org/apache/jena/ext/xerces/xs/XSModelGroup.java
new file mode 100644
index 0000000..3bd4086
--- /dev/null
+++ b/jena-core/src/main/java/org/apache/jena/ext/xerces/xs/XSModelGroup.java
@@ -0,0 +1,63 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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.jena.ext.xerces.xs;
+
+/**
+ * This interface represents the Model Group schema component.
+ */
+public interface XSModelGroup extends XSTerm {
+    // Content model compositors
+    /**
+     * This constant value signifies a sequence operator.
+     */
+    public static final short COMPOSITOR_SEQUENCE       = 1;
+    /**
+     * This constant value signifies a choice operator.
+     */
+    public static final short COMPOSITOR_CHOICE         = 2;
+    /**
+     * This content model represents a simplified version of the SGML 
+     * &amp;-Connector and is limited to the top-level of any content model. 
+     * No element in the all content model may appear more than once.
+     */
+    public static final short COMPOSITOR_ALL            = 3;
+
+    /**
+     * [compositor]: one of all, choice or sequence. The valid constant values 
+     * are: 
+     * <code>COMPOSITOR_SEQUENCE, COMPOSITOR_CHOICE, COMPOSITOR_ALL</code>. 
+     */
+    public short getCompositor();
+
+    /**
+     *  A list of [particles] if it exists, otherwise an empty 
+     * <code>XSObjectList</code>. 
+     */
+    public XSObjectList getParticles();
+
+    /**
+     * An annotation if it exists, otherwise <code>null</code>. If not null
+     * then the first [annotation] from the sequence of annotations.
+     */
+    public XSAnnotation getAnnotation();
+
+    /**
+     * A sequence of [annotations] or an empty <code>XSObjectList</code>.
+     */
+    public XSObjectList getAnnotations();    
+}


[04/24] jena git commit: JENA-1537: Remove dependency on Xerces. Import needed code

Posted by an...@apache.org.
http://git-wip-us.apache.org/repos/asf/jena/blob/c9a7e646/jena-core/src/main/java/org/apache/jena/ext/xerces/xs/XSModelGroupDefinition.java
----------------------------------------------------------------------
diff --git a/jena-core/src/main/java/org/apache/jena/ext/xerces/xs/XSModelGroupDefinition.java b/jena-core/src/main/java/org/apache/jena/ext/xerces/xs/XSModelGroupDefinition.java
new file mode 100644
index 0000000..0817480
--- /dev/null
+++ b/jena-core/src/main/java/org/apache/jena/ext/xerces/xs/XSModelGroupDefinition.java
@@ -0,0 +1,39 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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.jena.ext.xerces.xs;
+
+/**
+ * This interface represents the Model Group Definition schema component.
+ */
+public interface XSModelGroupDefinition extends XSObject {
+    /**
+     * A model group. 
+     */
+    public XSModelGroup getModelGroup();
+
+    /**
+     * An annotation if it exists, otherwise <code>null</code>. If not null
+     * then the first [annotation] from the sequence of annotations.
+     */
+    public XSAnnotation getAnnotation();
+
+    /**
+     * A sequence of [annotations] or an empty <code>XSObjectList</code>.
+     */
+    public XSObjectList getAnnotations();    
+}

http://git-wip-us.apache.org/repos/asf/jena/blob/c9a7e646/jena-core/src/main/java/org/apache/jena/ext/xerces/xs/XSMultiValueFacet.java
----------------------------------------------------------------------
diff --git a/jena-core/src/main/java/org/apache/jena/ext/xerces/xs/XSMultiValueFacet.java b/jena-core/src/main/java/org/apache/jena/ext/xerces/xs/XSMultiValueFacet.java
new file mode 100644
index 0000000..abcd829
--- /dev/null
+++ b/jena-core/src/main/java/org/apache/jena/ext/xerces/xs/XSMultiValueFacet.java
@@ -0,0 +1,47 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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.jena.ext.xerces.xs;
+
+import org.apache.jena.ext.xerces.xs.datatypes.ObjectList;
+
+/**
+ * Describes a multi-value constraining facets: pattern and enumeration.
+ */
+public interface XSMultiValueFacet extends XSObject {
+    /**
+     * The name of the facet, i.e. <code>FACET_ENUMERATION</code> and 
+     * <code>FACET_PATTERN</code> (see <code>XSSimpleTypeDefinition</code>). 
+     */
+    public short getFacetKind();
+
+    /**
+     * Values of this facet. 
+     */
+    public StringList getLexicalFacetValues();
+
+    /**
+     * A list of XSValue objects. The actual enumeration values.
+     */
+    public ObjectList getEnumerationValues();
+
+    /**
+     * A sequence of [annotations] or an empty <code>XSObjectList</code>.
+     */
+    public XSObjectList getAnnotations();
+
+}

http://git-wip-us.apache.org/repos/asf/jena/blob/c9a7e646/jena-core/src/main/java/org/apache/jena/ext/xerces/xs/XSNamedMap.java
----------------------------------------------------------------------
diff --git a/jena-core/src/main/java/org/apache/jena/ext/xerces/xs/XSNamedMap.java b/jena-core/src/main/java/org/apache/jena/ext/xerces/xs/XSNamedMap.java
new file mode 100644
index 0000000..2594460
--- /dev/null
+++ b/jena-core/src/main/java/org/apache/jena/ext/xerces/xs/XSNamedMap.java
@@ -0,0 +1,67 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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.jena.ext.xerces.xs;
+
+import java.util.Map;
+
+/**
+ * Objects implementing the <code>XSNamedMap</code> interface are used to 
+ * represent immutable collections of XML Schema components that can be 
+ * accessed by name. Note that <code>XSNamedMap</code> does not inherit from 
+ * <code>XSObjectList</code>. The <code>XSObject</code>s in 
+ * <code>XSNamedMap</code>s are not maintained in any particular order. 
+ */
+@SuppressWarnings("all")
+public interface XSNamedMap extends Map {
+    /**
+     * The number of <code>XSObjects</code> in the <code>XSObjectList</code>. 
+     * The range of valid child object indices is 0 to <code>length-1</code> 
+     * inclusive. 
+     */
+    public int getLength();
+
+    /**
+     *  Returns the <code>index</code>th item in the collection or 
+     * <code>null</code> if <code>index</code> is greater than or equal to 
+     * the number of objects in the list. The index starts at 0. 
+     * @param index  index into the collection. 
+     * @return  The <code>XSObject</code> at the <code>index</code>th 
+     *   position in the <code>XSObjectList</code>, or <code>null</code> if 
+     *   the index specified is not valid. 
+     */
+    public XSObject item(int index);
+
+    /**
+     * Retrieves an <code>XSObject</code> specified by local name and 
+     * namespace URI.
+     * <br>Per XML Namespaces, applications must use the value <code>null</code> as the 
+     * <code>namespace</code> parameter for methods if they wish to specify 
+     * no namespace.
+     * @param namespace The namespace URI of the <code>XSObject</code> to 
+     *   retrieve, or <code>null</code> if the <code>XSObject</code> has no 
+     *   namespace. 
+     * @param localName The local name of the <code>XSObject</code> to 
+     *   retrieve.
+     * @return A <code>XSObject</code> (of any type) with the specified local 
+     *   name and namespace URI, or <code>null</code> if they do not 
+     *   identify any object in this map.
+     */
+    public XSObject itemByName(String namespace, 
+                               String localName);
+
+}

http://git-wip-us.apache.org/repos/asf/jena/blob/c9a7e646/jena-core/src/main/java/org/apache/jena/ext/xerces/xs/XSNamespaceItem.java
----------------------------------------------------------------------
diff --git a/jena-core/src/main/java/org/apache/jena/ext/xerces/xs/XSNamespaceItem.java b/jena-core/src/main/java/org/apache/jena/ext/xerces/xs/XSNamespaceItem.java
new file mode 100644
index 0000000..cca0d79
--- /dev/null
+++ b/jena-core/src/main/java/org/apache/jena/ext/xerces/xs/XSNamespaceItem.java
@@ -0,0 +1,117 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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.jena.ext.xerces.xs;
+
+/**
+ * The interface represents the namespace schema information information item. 
+ * Each namespace schema information information item corresponds to an XML 
+ * Schema with a unique namespace name.
+ */
+public interface XSNamespaceItem {
+    /**
+     * [schema namespace]: A namespace name or <code>null</code> if absent.
+     */
+    public String getSchemaNamespace();
+
+    /**
+     * [schema components]: a list of top-level components, i.e. element 
+     * declarations, attribute declarations, etc. Identity-constraint
+     * definitions are also considered top-level.
+     * 
+     * @param objectType The type of the declaration, i.e. 
+     *   <code>ELEMENT_DECLARATION</code>. Note that 
+     *   <code>XSTypeDefinition.SIMPLE_TYPE</code> and 
+     *   <code>XSTypeDefinition.COMPLEX_TYPE</code> can also be used as the 
+     *   <code>objectType</code> to retrieve only complex types or simple 
+     *   types, instead of all types.
+     * @return  A list of top-level definition of the specified type in 
+     *   <code>objectType</code> or an empty <code>XSNamedMap</code> if no 
+     *   such definitions exist. 
+     */
+    public XSNamedMap getComponents(short objectType);
+
+    /**
+     *  [annotations]: a set of annotations if it exists, otherwise an empty 
+     * <code>XSObjectList</code>.
+     */
+    public XSObjectList getAnnotations();
+
+    /**
+     * Convenience method. Returns a top-level element declaration. 
+     * @param name The name of the declaration.
+     * @return A top-level element declaration or <code>null</code> if such a 
+     *   declaration does not exist. 
+     */
+    public XSElementDeclaration getElementDeclaration(String name);
+
+    /**
+     * Convenience method. Returns a top-level attribute declaration. 
+     * @param name The name of the declaration.
+     * @return A top-level attribute declaration or <code>null</code> if such 
+     *   a declaration does not exist. 
+     */
+    public XSAttributeDeclaration getAttributeDeclaration(String name);
+
+    /**
+     * Convenience method. Returns a top-level simple or complex type 
+     * definition. 
+     * @param name The name of the definition.
+     * @return An <code>XSTypeDefinition</code> or <code>null</code> if such 
+     *   a definition does not exist. 
+     */
+    public XSTypeDefinition getTypeDefinition(String name);
+
+    /**
+     * Convenience method. Returns a top-level attribute group definition. 
+     * @param name The name of the definition.
+     * @return A top-level attribute group definition or <code>null</code> if 
+     *   such a definition does not exist. 
+     */
+    public XSAttributeGroupDefinition getAttributeGroup(String name);
+
+    /**
+     * Convenience method. Returns a top-level model group definition. 
+     * @param name The name of the definition.
+     * @return A top-level model group definition definition or 
+     *   <code>null</code> if such a definition does not exist. 
+     */
+    public XSModelGroupDefinition getModelGroupDefinition(String name);
+
+    /**
+     * Convenience method. Returns a top-level notation declaration. 
+     * @param name The name of the declaration.
+     * @return A top-level notation declaration or <code>null</code> if such 
+     *   a declaration does not exist. 
+     */
+    public XSNotationDeclaration getNotationDeclaration(String name);
+
+    /**
+     * Convenience method. Returns an identity-constraint definition.
+     * @param name The name of the definition.
+     * @return An identity-constraint definition or <code>null</code> if such 
+     *   a declaration does not exist. 
+     */
+    public XSIDCDefinition getIDCDefinition(String name);
+
+    /**
+     * [document location] - a list of location URIs for the documents that 
+     * contributed to the <code>XSModel</code>.
+     */
+    public StringList getDocumentLocations();
+
+}

http://git-wip-us.apache.org/repos/asf/jena/blob/c9a7e646/jena-core/src/main/java/org/apache/jena/ext/xerces/xs/XSNamespaceItemList.java
----------------------------------------------------------------------
diff --git a/jena-core/src/main/java/org/apache/jena/ext/xerces/xs/XSNamespaceItemList.java b/jena-core/src/main/java/org/apache/jena/ext/xerces/xs/XSNamespaceItemList.java
new file mode 100644
index 0000000..11932c4
--- /dev/null
+++ b/jena-core/src/main/java/org/apache/jena/ext/xerces/xs/XSNamespaceItemList.java
@@ -0,0 +1,46 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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.jena.ext.xerces.xs;
+
+import java.util.List;
+
+/**
+ *  The <code>XSNamesaceItemList</code> interface provides the abstraction of 
+ * an immutable ordered collection of <code>XSNamespaceItem</code>s, without 
+ * defining or constraining how this collection is implemented. 
+ */
+@SuppressWarnings("rawtypes")
+public interface XSNamespaceItemList extends List {
+    /**
+     *  The number of <code>XSNamespaceItem</code>s in the list. The range of 
+     * valid child object indices is 0 to <code>length-1</code> inclusive. 
+     */
+    public int getLength();
+
+    /**
+     *  Returns the <code>index</code>th item in the collection or 
+     * <code>null</code> if <code>index</code> is greater than or equal to 
+     * the number of objects in the list. The index starts at 0. 
+     * @param index  index into the collection. 
+     * @return  The <code>XSNamespaceItem</code> at the <code>index</code>th 
+     *   position in the <code>XSNamespaceItemList</code>, or 
+     *   <code>null</code> if the index specified is not valid. 
+     */
+    public XSNamespaceItem item(int index);
+
+}

http://git-wip-us.apache.org/repos/asf/jena/blob/c9a7e646/jena-core/src/main/java/org/apache/jena/ext/xerces/xs/XSNotationDeclaration.java
----------------------------------------------------------------------
diff --git a/jena-core/src/main/java/org/apache/jena/ext/xerces/xs/XSNotationDeclaration.java b/jena-core/src/main/java/org/apache/jena/ext/xerces/xs/XSNotationDeclaration.java
new file mode 100644
index 0000000..cca1e2b
--- /dev/null
+++ b/jena-core/src/main/java/org/apache/jena/ext/xerces/xs/XSNotationDeclaration.java
@@ -0,0 +1,46 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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.jena.ext.xerces.xs;
+
+/**
+ *  This interface represents the Notation Declaration schema component. 
+ */
+public interface XSNotationDeclaration extends XSObject {
+    /**
+     *  The URI reference representing the system identifier for the notation 
+     * declaration, if present, <code>null</code> otherwise. 
+     */
+    public String getSystemId();
+
+    /**
+     *  The string representing the public identifier for this notation 
+     * declaration, if present; <code>null</code> otherwise. 
+     */
+    public String getPublicId();
+
+    /**
+     * An annotation if it exists, otherwise <code>null</code>. If not null
+     * then the first [annotation] from the sequence of annotations.
+     */
+    public XSAnnotation getAnnotation();
+
+    /**
+     * A sequence of [annotations] or an empty <code>XSObjectList</code>.
+     */
+    public XSObjectList getAnnotations();    
+}

http://git-wip-us.apache.org/repos/asf/jena/blob/c9a7e646/jena-core/src/main/java/org/apache/jena/ext/xerces/xs/XSObject.java
----------------------------------------------------------------------
diff --git a/jena-core/src/main/java/org/apache/jena/ext/xerces/xs/XSObject.java b/jena-core/src/main/java/org/apache/jena/ext/xerces/xs/XSObject.java
new file mode 100644
index 0000000..bd09dd6
--- /dev/null
+++ b/jena-core/src/main/java/org/apache/jena/ext/xerces/xs/XSObject.java
@@ -0,0 +1,55 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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.jena.ext.xerces.xs;
+
+/**
+ * The <code>XSObject</code> is a base object for the XML Schema component 
+ * model. 
+ */
+public interface XSObject {
+    /**
+     *  The <code>type</code> of this object, i.e. 
+     * <code>ELEMENT_DECLARATION</code>. 
+     */
+    public short getType();
+
+    /**
+     * The name of type <code>NCName</code>, as defined in XML Namespaces, of 
+     * this declaration specified in the <code>{name}</code> property of the 
+     * component or <code>null</code> if the definition of this component 
+     * does not have a <code>{name}</code> property. For anonymous types, 
+     * the processor must construct and expose an anonymous type name that 
+     * is distinct from the name of every named type and the name of every 
+     * other anonymous type.
+     */
+    public String getName();
+
+    /**
+     *  The [target namespace] of this object, or <code>null</code> if it is 
+     * unspecified. 
+     */
+    public String getNamespace();
+
+    /**
+     * A namespace schema information item corresponding to the target 
+     * namespace of the component, if it is globally declared; or 
+     * <code>null</code> otherwise.
+     */
+    public XSNamespaceItem getNamespaceItem();
+
+}

http://git-wip-us.apache.org/repos/asf/jena/blob/c9a7e646/jena-core/src/main/java/org/apache/jena/ext/xerces/xs/XSObjectList.java
----------------------------------------------------------------------
diff --git a/jena-core/src/main/java/org/apache/jena/ext/xerces/xs/XSObjectList.java b/jena-core/src/main/java/org/apache/jena/ext/xerces/xs/XSObjectList.java
new file mode 100644
index 0000000..aec24ed
--- /dev/null
+++ b/jena-core/src/main/java/org/apache/jena/ext/xerces/xs/XSObjectList.java
@@ -0,0 +1,46 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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.jena.ext.xerces.xs;
+
+import java.util.List;
+
+/**
+ *  The <code>XSObjectList</code> interface provides the abstraction of an 
+ * immutable ordered collection of <code>XSObject</code>s, without defining 
+ * or constraining how this collection is implemented. 
+ */
+@SuppressWarnings("rawtypes")
+public interface XSObjectList extends List {
+    /**
+     *  The number of <code>XSObjects</code> in the list. The range of valid 
+     * child object indices is 0 to <code>length-1</code> inclusive. 
+     */
+    public int getLength();
+
+    /**
+     *  Returns the <code>index</code>th item in the collection or 
+     * <code>null</code> if <code>index</code> is greater than or equal to 
+     * the number of objects in the list. The index starts at 0. 
+     * @param index  index into the collection. 
+     * @return  The <code>XSObject</code> at the <code>index</code>th 
+     *   position in the <code>XSObjectList</code>, or <code>null</code> if 
+     *   the index specified is not valid. 
+     */
+    public XSObject item(int index);
+
+}

http://git-wip-us.apache.org/repos/asf/jena/blob/c9a7e646/jena-core/src/main/java/org/apache/jena/ext/xerces/xs/XSParticle.java
----------------------------------------------------------------------
diff --git a/jena-core/src/main/java/org/apache/jena/ext/xerces/xs/XSParticle.java b/jena-core/src/main/java/org/apache/jena/ext/xerces/xs/XSParticle.java
new file mode 100644
index 0000000..ee61a48
--- /dev/null
+++ b/jena-core/src/main/java/org/apache/jena/ext/xerces/xs/XSParticle.java
@@ -0,0 +1,52 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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.jena.ext.xerces.xs;
+
+/**
+ * This interface represents the Particle schema component.
+ */
+public interface XSParticle extends XSObject {
+    /**
+     * [min occurs]: determines the minimum number of terms that can occur. 
+     */
+    public int getMinOccurs();
+
+    /**
+     *  [max occurs]: determines the maximum number of terms that can occur. 
+     * To query for the value of unbounded use 
+     * <code>maxOccursUnbounded</code>. When the value of 
+     * <code>maxOccursUnbounded</code> is <code>true</code>, the value of 
+     * <code>maxOccurs</code> is unspecified. 
+     */
+    public int getMaxOccurs();
+
+    /**
+     * [max occurs]: whether the maxOccurs value is unbounded.
+     */
+    public boolean getMaxOccursUnbounded();
+
+    /**
+     * [term]: one of a model group, a wildcard, or an element declaration. 
+     */
+    public XSTerm getTerm();
+
+    /**
+     * A sequence of [annotations] or an empty <code>XSObjectList</code>.
+     */
+    public XSObjectList getAnnotations();    
+}

http://git-wip-us.apache.org/repos/asf/jena/blob/c9a7e646/jena-core/src/main/java/org/apache/jena/ext/xerces/xs/XSSimpleTypeDefinition.java
----------------------------------------------------------------------
diff --git a/jena-core/src/main/java/org/apache/jena/ext/xerces/xs/XSSimpleTypeDefinition.java b/jena-core/src/main/java/org/apache/jena/ext/xerces/xs/XSSimpleTypeDefinition.java
new file mode 100644
index 0000000..0c5d23f
--- /dev/null
+++ b/jena-core/src/main/java/org/apache/jena/ext/xerces/xs/XSSimpleTypeDefinition.java
@@ -0,0 +1,244 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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.jena.ext.xerces.xs;
+
+/**
+ * This interface represents the Simple Type Definition schema component. This 
+ * interface provides several query operations for facet components. Users 
+ * can either retrieve the defined facets as XML Schema components, using 
+ * the <code>facets</code> and the <code>multiValueFacets</code> attributes; 
+ * or users can separately query a facet's properties using methods such as 
+ * <code>getLexicalFacetValue</code>, <code>isFixedFacet</code>, etc. 
+ */
+public interface XSSimpleTypeDefinition extends XSTypeDefinition {
+    // Variety definitions
+    /**
+     * The variety is absent for the anySimpleType definition.
+     */
+    public static final short VARIETY_ABSENT            = 0;
+    /**
+     * <code>Atomic</code> type.
+     */
+    public static final short VARIETY_ATOMIC            = 1;
+    /**
+     * <code>List</code> type.
+     */
+    public static final short VARIETY_LIST              = 2;
+    /**
+     * <code>Union</code> type.
+     */
+    public static final short VARIETY_UNION             = 3;
+
+    // Facets
+    /**
+     * No facets defined.
+     */
+    public static final short FACET_NONE                = 0;
+    /**
+     * 4.3.1 Length
+     */
+    public static final short FACET_LENGTH              = 1;
+    /**
+     * 4.3.2 minLength. 
+     */
+    public static final short FACET_MINLENGTH           = 2;
+    /**
+     * 4.3.3 maxLength.
+     */
+    public static final short FACET_MAXLENGTH           = 4;
+    /**
+     * 4.3.4 pattern.
+     */
+    public static final short FACET_PATTERN             = 8;
+    /**
+     * 4.3.5 whitespace.
+     */
+    public static final short FACET_WHITESPACE          = 16;
+    /**
+     * 4.3.7 maxInclusive.
+     */
+    public static final short FACET_MAXINCLUSIVE        = 32;
+    /**
+     * 4.3.9 maxExclusive.
+     */
+    public static final short FACET_MAXEXCLUSIVE        = 64;
+    /**
+     * 4.3.9 minExclusive.
+     */
+    public static final short FACET_MINEXCLUSIVE        = 128;
+    /**
+     * 4.3.10 minInclusive.
+     */
+    public static final short FACET_MININCLUSIVE        = 256;
+    /**
+     * 4.3.11 totalDigits .
+     */
+    public static final short FACET_TOTALDIGITS         = 512;
+    /**
+     * 4.3.12 fractionDigits.
+     */
+    public static final short FACET_FRACTIONDIGITS      = 1024;
+    /**
+     * 4.3.5 enumeration.
+     */
+    public static final short FACET_ENUMERATION         = 2048;
+
+    /**
+     * A constant defined for the 'ordered' fundamental facet: not ordered.
+     */
+    public static final short ORDERED_FALSE             = 0;
+    /**
+     * A constant defined for the 'ordered' fundamental facet: partially 
+     * ordered.
+     */
+    public static final short ORDERED_PARTIAL           = 1;
+    /**
+     * A constant defined for the 'ordered' fundamental facet: total ordered.
+     */
+    public static final short ORDERED_TOTAL             = 2;
+    /**
+     * [variety]: one of {atomic, list, union} or absent. 
+     */
+    public short getVariety();
+
+    /**
+     * If variety is <code>atomic</code> the primitive type definition (a 
+     * built-in primitive datatype definition or the simple ur-type 
+     * definition) is available, otherwise <code>null</code>. 
+     */
+    public XSSimpleTypeDefinition getPrimitiveType();
+
+    /**
+     * Returns the closest built-in type category this type represents or 
+     * derived from. For example, if this simple type is a built-in derived 
+     * type integer the <code>INTEGER_DV</code> is returned.
+     */
+    public short getBuiltInKind();
+
+    /**
+     * If variety is <code>list</code> the item type definition (an atomic or 
+     * union simple type definition) is available, otherwise 
+     * <code>null</code>. 
+     */
+    public XSSimpleTypeDefinition getItemType();
+
+    /**
+     * If variety is <code>union</code> the list of member type definitions (a 
+     * non-empty sequence of simple type definitions) is available, 
+     * otherwise an empty <code>XSObjectList</code>. 
+     */
+    public XSObjectList getMemberTypes();
+
+    /**
+     * [facets]: all facets defined on this type. The value is a bit 
+     * combination of FACET_XXX constants of all defined facets. 
+     */
+    public short getDefinedFacets();
+
+    /**
+     * Convenience method. [Facets]: check whether a facet is defined on this 
+     * type.
+     * @param facetName  The name of the facet. 
+     * @return  True if the facet is defined, false otherwise.
+     */
+    public boolean isDefinedFacet(short facetName);
+
+    /**
+     * [facets]: all defined facets for this type which are fixed.
+     */
+    public short getFixedFacets();
+
+    /**
+     * Convenience method. [Facets]: check whether a facet is defined and 
+     * fixed on this type. 
+     * @param facetName  The name of the facet. 
+     * @return  True if the facet is fixed, false otherwise.
+     */
+    public boolean isFixedFacet(short facetName);
+
+    /**
+     * Convenience method. Returns a value of a single constraining facet for 
+     * this simple type definition. This method must not be used to retrieve 
+     * values for <code>enumeration</code> and <code>pattern</code> facets. 
+     * @param facetName The name of the facet, i.e. 
+     *   <code>FACET_LENGTH, FACET_TOTALDIGITS</code>.
+     *   To retrieve the value for a pattern or 
+     *   an enumeration, see <code>enumeration</code> and 
+     *   <code>pattern</code>.
+     * @return A value of the facet specified in <code>facetName</code> for 
+     *   this simple type definition or <code>null</code>. 
+     */
+    public String getLexicalFacetValue(short facetName);
+
+    /**
+     * A list of enumeration values if it exists, otherwise an empty 
+     * <code>StringList</code>. 
+     */
+    public StringList getLexicalEnumeration();
+
+    /**
+     * A list of pattern values if it exists, otherwise an empty 
+     * <code>StringList</code>. 
+     */
+    public StringList getLexicalPattern();
+
+    /**
+     *  Fundamental Facet: ordered. 
+     */
+    public short getOrdered();
+
+    /**
+     * Fundamental Facet: cardinality. 
+     */
+    public boolean getFinite();
+
+    /**
+     * Fundamental Facet: bounded. 
+     */
+    public boolean getBounded();
+
+    /**
+     * Fundamental Facet: numeric. 
+     */
+    public boolean getNumeric();
+
+    /**
+     *  A list of constraining facets if it exists, otherwise an empty 
+     * <code>XSObjectList</code>. Note: This method must not be used to 
+     * retrieve values for <code>enumeration</code> and <code>pattern</code> 
+     * facets. 
+     */
+    public XSObjectList getFacets();
+
+    /**
+     *  A list of enumeration and pattern constraining facets if it exists, 
+     * otherwise an empty <code>XSObjectList</code>. 
+     */
+    public XSObjectList getMultiValueFacets();
+
+    /**
+     * A constraining facet object. An instance of XSFacet or XSMultiValueFacet.
+     */
+    public XSObject getFacet(int facetType);
+
+    /**
+     * A sequence of [annotations] or an empty <code>XSObjectList</code>.
+     */
+    public XSObjectList getAnnotations();
+
+}

http://git-wip-us.apache.org/repos/asf/jena/blob/c9a7e646/jena-core/src/main/java/org/apache/jena/ext/xerces/xs/XSTerm.java
----------------------------------------------------------------------
diff --git a/jena-core/src/main/java/org/apache/jena/ext/xerces/xs/XSTerm.java b/jena-core/src/main/java/org/apache/jena/ext/xerces/xs/XSTerm.java
new file mode 100644
index 0000000..c07065a
--- /dev/null
+++ b/jena-core/src/main/java/org/apache/jena/ext/xerces/xs/XSTerm.java
@@ -0,0 +1,27 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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.jena.ext.xerces.xs;
+
+/**
+ * Describes a term that can be one of a model group, a wildcard, or an 
+ * element declaration. Objects implementing 
+ * <code>XSElementDeclaration</code>, <code>XSModelGroup</code> and 
+ * <code>XSWildcard</code> interfaces also implement this interface. 
+ */
+public interface XSTerm extends XSObject {
+}

http://git-wip-us.apache.org/repos/asf/jena/blob/c9a7e646/jena-core/src/main/java/org/apache/jena/ext/xerces/xs/XSTypeDefinition.java
----------------------------------------------------------------------
diff --git a/jena-core/src/main/java/org/apache/jena/ext/xerces/xs/XSTypeDefinition.java b/jena-core/src/main/java/org/apache/jena/ext/xerces/xs/XSTypeDefinition.java
new file mode 100644
index 0000000..f1dde67
--- /dev/null
+++ b/jena-core/src/main/java/org/apache/jena/ext/xerces/xs/XSTypeDefinition.java
@@ -0,0 +1,102 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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.jena.ext.xerces.xs;
+
+/**
+ * This interface represents a complex or simple type definition.
+ */
+public interface XSTypeDefinition extends XSObject {
+    /**
+     * The object describes a complex type.
+     */
+    public static final short COMPLEX_TYPE              = 15;
+    /**
+     * The object describes a simple type.
+     */
+    public static final short SIMPLE_TYPE               = 16;
+    /**
+     * Return whether this type definition is a simple type or complex type.
+     */
+    public short getTypeCategory();
+
+    /**
+     * {base type definition}: either a simple type definition or a complex 
+     * type definition. 
+     */
+    public XSTypeDefinition getBaseType();
+
+    /**
+     * {final}. For a complex type definition it is a subset of {extension, 
+     * restriction}. For a simple type definition it is a subset of 
+     * {extension, list, restriction, union}. 
+     * @param restriction  Extension, restriction, list, union constants 
+     *   (defined in <code>XSConstants</code>). 
+     * @return True if <code>restriction</code> is in the final set, 
+     *   otherwise false.
+     */
+    public boolean isFinal(short restriction);
+
+    /**
+     * For complex types the returned value is a bit combination of the subset 
+     * of {<code>DERIVATION_EXTENSION, DERIVATION_RESTRICTION</code>} 
+     * corresponding to <code>final</code> set of this type or 
+     * <code>DERIVATION_NONE</code>. For simple types the returned value is 
+     * a bit combination of the subset of { 
+     * <code>DERIVATION_RESTRICTION, DERIVATION_EXTENSION, DERIVATION_UNION, DERIVATION_LIST</code>
+     * } corresponding to <code>final</code> set of this type or 
+     * <code>DERIVATION_NONE</code>. 
+     */
+    public short getFinal();
+
+    /**
+     *  Convenience attribute. A boolean that specifies if the type definition 
+     * is anonymous. 
+     */
+    public boolean getAnonymous();
+
+    /**
+     * Convenience method which checks if this type is derived from the given 
+     * <code>ancestorType</code>. 
+     * @param ancestorType  An ancestor type definition. 
+     * @param derivationMethod  A bit combination representing a subset of {
+     *   <code>DERIVATION_RESTRICTION, DERIVATION_EXTENSION, DERIVATION_UNION, DERIVATION_LIST</code>
+     *   }. 
+     * @return  True if this type is derived from <code>ancestorType</code> 
+     *   using only derivation methods from the <code>derivationMethod</code>
+     *   . 
+     */
+    public boolean derivedFromType(XSTypeDefinition ancestorType, 
+                                   short derivationMethod);
+
+    /**
+     * Convenience method which checks if this type is derived from the given 
+     * ancestor type. 
+     * @param namespace  An ancestor type namespace. 
+     * @param name  An ancestor type name. 
+     * @param derivationMethod  A bit combination representing a subset of {
+     *   <code>DERIVATION_RESTRICTION, DERIVATION_EXTENSION, DERIVATION_UNION, DERIVATION_LIST</code>
+     *   }. 
+     * @return  True if this type is derived from <code>ancestorType</code> 
+     *   using only derivation methods from the <code>derivationMethod</code>
+     *   . 
+     */
+    public boolean derivedFrom(String namespace, 
+                               String name, 
+                               short derivationMethod);
+
+}

http://git-wip-us.apache.org/repos/asf/jena/blob/c9a7e646/jena-core/src/main/java/org/apache/jena/ext/xerces/xs/XSValue.java
----------------------------------------------------------------------
diff --git a/jena-core/src/main/java/org/apache/jena/ext/xerces/xs/XSValue.java b/jena-core/src/main/java/org/apache/jena/ext/xerces/xs/XSValue.java
new file mode 100644
index 0000000..a1d49ff
--- /dev/null
+++ b/jena-core/src/main/java/org/apache/jena/ext/xerces/xs/XSValue.java
@@ -0,0 +1,97 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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.jena.ext.xerces.xs;
+
+/**
+ * Represents an actual value of a simple type.
+ */
+public interface XSValue {
+    
+    /**
+     * The schema normalized value.
+     */
+    public String getNormalizedValue();
+
+    /**
+     * The actual value. <code>null</code> if the value is in error. 
+     */
+    public Object getActualValue();
+
+    /**
+     * The declared simple type definition used to validate this value.
+     * It can be a union type.
+     */
+    public XSSimpleTypeDefinition getTypeDefinition();
+
+    /**
+     * If the declared simple type definition is a union, return the member
+     * type actually used to validate the value. Otherwise null.
+     */
+    public XSSimpleTypeDefinition getMemberTypeDefinition();
+
+    /**
+     * If <code>getTypeDefinition()</code> returns a list type whose item type
+     * is a union type, then this method returns a list with the same length
+     * as the value list, for simple types that actually validated
+     * the corresponding item in the value. 
+     */
+    public XSObjectList getMemberTypeDefinitions();
+
+    /**
+     * The actual value built-in datatype, e.g. 
+     * <code>STRING_DT, SHORT_DT</code>. If the type definition of this 
+     * value is a list type definition, this method returns 
+     * <code>LIST_DT</code>. If the type definition of this value is a list 
+     * type definition whose item type is a union type definition, this 
+     * method returns <code>LISTOFUNION_DT</code>. To query the actual value 
+     * of the list or list of union type definitions use 
+     * <code>itemValueTypes()</code>.
+     */
+    public short getActualValueType();
+
+    /**
+     * In the case the actual value represents a list, i.e. the 
+     * <code>actualNormalizedValueType</code> is <code>LIST_DT</code>, the 
+     * returned array consists of one type kind which represents the itemType
+     * . For example: 
+     * <pre> &lt;simpleType name="listtype"&gt; &lt;list 
+     * itemType="positiveInteger"/&gt; &lt;/simpleType&gt; &lt;element 
+     * name="list" type="listtype"/&gt; ... &lt;list&gt;1 2 3&lt;/list&gt; </pre>
+     *  
+     * The <code>schemaNormalizedValue</code> value is "1 2 3", the 
+     * <code>actualNormalizedValueType</code> value is <code>LIST_DT</code>, 
+     * and the <code>itemValueTypes</code> is an array of size 1 with the 
+     * value <code>POSITIVEINTEGER_DT</code>. 
+     * <br> If the actual value represents a list type definition whose item 
+     * type is a union type definition, i.e. <code>LISTOFUNION_DT</code>, 
+     * for each actual value in the list the array contains the 
+     * corresponding memberType kind. For example: 
+     * <pre> &lt;simpleType 
+     * name='union_type' memberTypes="integer string"/&gt; &lt;simpleType 
+     * name='listOfUnion'&gt; &lt;list itemType='union_type'/&gt; 
+     * &lt;/simpleType&gt; &lt;element name="list" type="listOfUnion"/&gt; 
+     * ... &lt;list&gt;1 2 foo&lt;/list&gt; </pre>
+     *  The 
+     * <code>schemaNormalizedValue</code> value is "1 2 foo", the 
+     * <code>actualNormalizedValueType</code> is <code>LISTOFUNION_DT</code>
+     * , and the <code>itemValueTypes</code> is an array of size 3 with the 
+     * following values: <code>INTEGER_DT, INTEGER_DT, STRING_DT</code>. 
+     */
+    public ShortList getListValueTypes();
+
+}

http://git-wip-us.apache.org/repos/asf/jena/blob/c9a7e646/jena-core/src/main/java/org/apache/jena/ext/xerces/xs/XSWildcard.java
----------------------------------------------------------------------
diff --git a/jena-core/src/main/java/org/apache/jena/ext/xerces/xs/XSWildcard.java b/jena-core/src/main/java/org/apache/jena/ext/xerces/xs/XSWildcard.java
new file mode 100644
index 0000000..68cc912
--- /dev/null
+++ b/jena-core/src/main/java/org/apache/jena/ext/xerces/xs/XSWildcard.java
@@ -0,0 +1,87 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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.jena.ext.xerces.xs;
+
+/**
+ * This interface represents the Wildcard schema component.
+ */
+public interface XSWildcard extends XSTerm {
+    // Namespace Constraint
+    /**
+     * Namespace Constraint: any namespace is allowed.
+     */
+    public static final short NSCONSTRAINT_ANY          = 1;
+    /**
+     * Namespace Constraint: namespaces in the list are not allowed.
+     */
+    public static final short NSCONSTRAINT_NOT          = 2;
+    /**
+     * Namespace Constraint: namespaces in the list are allowed.
+     */
+    public static final short NSCONSTRAINT_LIST         = 3;
+
+    // Process contents
+    /**
+     * There must be a top-level declaration for the item available, or the 
+     * item must have an xsi:type, and the item must be valid as appropriate.
+     */
+    public static final short PC_STRICT                 = 1;
+    /**
+     * No constraints at all: the item must simply be well-formed XML. 
+     */
+    public static final short PC_SKIP                   = 2;
+    /**
+     * If the item, or any items among its [children] is an element 
+     * information item, has a uniquely determined declaration available, it 
+     * must be valid with respect to that definition, that is, validate 
+     * where you can and do not worry when you cannot.
+     */
+    public static final short PC_LAX                    = 3;
+
+    /**
+     * Namespace constraint: A constraint type: any, not, list. 
+     */
+    public short getConstraintType();
+
+    /**
+     * Namespace constraint: For <code>constraintType</code> 
+     * <code>NSCONSTRAINT_LIST</code>, the list contains allowed namespaces. 
+     * For <code>constraintType</code> <code>NSCONSTRAINT_NOT</code>, the 
+     * list contains disallowed namespaces. For <code>constraintType</code> 
+     * <code>NSCONSTRAINT_ANY</code>, the <code>StringList</code> is empty. 
+     */
+    public StringList getNsConstraintList();
+
+    /**
+     * [process contents]: one of skip, lax or strict. Valid constants values 
+     * are: <code>PC_LAX</code>, <code>PC_SKIP</code> and 
+     * <code>PC_STRICT</code>. 
+     */
+    public short getProcessContents();
+
+    /**
+     * An annotation if it exists, otherwise <code>null</code>. If not null
+     * then the first [annotation] from the sequence of annotations.
+     */
+    public XSAnnotation getAnnotation();
+
+    /**
+     * A sequence of [annotations] or an empty <code>XSObjectList</code>.
+     */
+    public XSObjectList getAnnotations();    
+}

http://git-wip-us.apache.org/repos/asf/jena/blob/c9a7e646/jena-core/src/main/java/org/apache/jena/ext/xerces/xs/datatypes/ByteList.java
----------------------------------------------------------------------
diff --git a/jena-core/src/main/java/org/apache/jena/ext/xerces/xs/datatypes/ByteList.java b/jena-core/src/main/java/org/apache/jena/ext/xerces/xs/datatypes/ByteList.java
new file mode 100644
index 0000000..d1cae22
--- /dev/null
+++ b/jena-core/src/main/java/org/apache/jena/ext/xerces/xs/datatypes/ByteList.java
@@ -0,0 +1,66 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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.jena.ext.xerces.xs.datatypes;
+
+import java.util.List;
+
+import org.apache.jena.ext.xerces.xs.XSException;
+
+/**
+ * <p>The <code>ByteList</code> is an immutable ordered collection of 
+ * <code>byte</code>.</p>
+ * 
+ * @author Ankit Pasricha, IBM
+ * 
+ * @version $Id: ByteList.java 1024038 2010-10-18 22:06:35Z sandygao $
+ */
+@SuppressWarnings("rawtypes")
+public interface ByteList extends List {
+    
+    /**
+     * The number of <code>byte</code>s in the list. The range of 
+     * valid child object indices is 0 to <code>length-1</code> inclusive. 
+     */
+    public int getLength();
+    
+    /**
+     * Checks if the <code>byte</code> <code>item</code> is a 
+     * member of this list. 
+     * @param item  <code>byte</code> whose presence in this list 
+     *   is to be tested. 
+     * @return  True if this list contains the <code>byte</code> 
+     *   <code>item</code>. 
+     */
+    public boolean contains(byte item);
+    
+    /**
+     * Returns the <code>index</code>th item in the collection. The index 
+     * starts at 0. 
+     * @param index  index into the collection. 
+     * @return  The <code>byte</code> at the <code>index</code>th 
+     *   position in the <code>ByteList</code>. 
+     * @exception XSException
+     *   INDEX_SIZE_ERR: if <code>index</code> is greater than or equal to the 
+     *   number of objects in the list or less than zero.
+     */
+    public byte item(int index) throws XSException;
+    
+    /**
+     * Construct and return a byte array for bytes contained in this list.
+     */
+    public byte[] toByteArray();
+}

http://git-wip-us.apache.org/repos/asf/jena/blob/c9a7e646/jena-core/src/main/java/org/apache/jena/ext/xerces/xs/datatypes/ObjectList.java
----------------------------------------------------------------------
diff --git a/jena-core/src/main/java/org/apache/jena/ext/xerces/xs/datatypes/ObjectList.java b/jena-core/src/main/java/org/apache/jena/ext/xerces/xs/datatypes/ObjectList.java
new file mode 100644
index 0000000..751a4f5
--- /dev/null
+++ b/jena-core/src/main/java/org/apache/jena/ext/xerces/xs/datatypes/ObjectList.java
@@ -0,0 +1,60 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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.jena.ext.xerces.xs.datatypes;
+
+import java.util.List;
+
+/**
+ * <p>The <code>ObjectList</code> is an immutable ordered collection of 
+ * <code>Object</code>.</p> 
+ * 
+ * @author Ankit Pasricha, IBM
+ * 
+ * @version $Id: ObjectList.java 744816 2009-02-16 06:03:18Z mrglavas $
+ */
+public interface ObjectList extends List<Object> {
+    
+    /**
+     * The number of <code>Object</code>s in the list. The range of 
+     * valid child object indices is 0 to <code>length-1</code> inclusive. 
+     */
+    public int getLength();
+    
+    /**
+     * Checks if the <code>Object</code> <code>item</code> is a 
+     * member of this list. 
+     * @param item  <code>Object</code> whose presence in this list 
+     *   is to be tested. 
+     * @return  True if this list contains the <code>Object</code> 
+     *   <code>item</code>. 
+     */
+    @Override
+    public boolean contains(Object item);
+    
+    /**
+     * Returns the <code>index</code>th item in the collection or 
+     * <code>null</code> if <code>index</code> is greater than or equal to 
+     * the number of objects in the list. The index starts at 0. 
+     * @param index  index into the collection. 
+     * @return  The <code>Object</code> at the <code>index</code>th 
+     *   position in the <code>ObjectList</code>, or <code>null</code> if 
+     *   the index specified is not valid - greater than or equal to the
+     *   number of items in the list or less than zero. 
+     */
+    public Object item(int index);
+    
+}

http://git-wip-us.apache.org/repos/asf/jena/blob/c9a7e646/jena-core/src/main/java/org/apache/jena/ext/xerces/xs/datatypes/XSDateTime.java
----------------------------------------------------------------------
diff --git a/jena-core/src/main/java/org/apache/jena/ext/xerces/xs/datatypes/XSDateTime.java b/jena-core/src/main/java/org/apache/jena/ext/xerces/xs/datatypes/XSDateTime.java
new file mode 100644
index 0000000..42357cc
--- /dev/null
+++ b/jena-core/src/main/java/org/apache/jena/ext/xerces/xs/datatypes/XSDateTime.java
@@ -0,0 +1,291 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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.jena.ext.xerces.xs.datatypes;
+
+import javax.xml.datatype.Duration;
+import javax.xml.datatype.XMLGregorianCalendar;
+
+/**
+ * <p>Interface to expose the values for all date-time related types. The following 
+ * table shows the methods defined for various XML Schema 1.0 built-in types. 'X' 
+ * marks whether a particular method is defined for a particular type. Accessing undefined
+ * methods may return unexpected values.
+ * 
+ * <table border="1">
+ * <br/>
+ * <tr>
+ * <td> XML Schema Datatype </td>
+ * <td> getYears() </td>
+ * <td> getMonths() </td>
+ * <td> getDays() </td>
+ * <td> getHours() </td>
+ * <td> getMinutes() </td>
+ * <td> getSeconds() </td>
+ * <td> getTimeZoneHours() </td>
+ * <td> getTimeZoneMinutes() </td>
+ * <td> getXMLGregorianCalendar() </td>
+ * <td> getDuration() </td>
+ * <td> hasTimeZone() </td>
+ * <td> normalize() </td>
+ * <td> isNormalized() </td>
+ * <td> getLexicalValue() </td>
+ * </tr>
+ * <tr>
+ * <td> gYear </td>
+ * <td>X</td>
+ * <td>-</td>
+ * <td>-</td>
+ * <td>-</td>
+ * <td>-</td>
+ * <td>-</td>
+ * <td>X</td>
+ * <td>X</td>
+ * <td>X</td>
+ * <td>-</td>
+ * <td>X</td>
+ * <td>X</td>
+ * <td>X</td>
+ * <td>X</td>
+ * </tr>
+ * <tr>
+ * <td> gMonth </td>
+ * <td>-</td>
+ * <td>X</td>
+ * <td>-</td>
+ * <td>-</td>
+ * <td>-</td>
+ * <td>-</td>
+ * <td>X</td>
+ * <td>X</td>
+ * <td>X</td>
+ * <td>-</td>
+ * <td>X</td>
+ * <td>X</td>
+ * <td>X</td>
+ * <td>X</td>
+ * </tr>
+ * <tr>
+ * <td> gDay </td>
+ * <td>-</td>
+ * <td>-</td>
+ * <td>X</td>
+ * <td>-</td>
+ * <td>-</td>
+ * <td>-</td>
+ * <td>X</td>
+ * <td>X</td>
+ * <td>X</td>
+ * <td>-</td>
+ * <td>X</td>
+ * <td>X</td>
+ * <td>X</td>
+ * <td>X</td>
+ * </tr>
+ * <tr>
+ * <td> gYearMonth </td>
+ * <td>X</td>
+ * <td>X</td>
+ * <td>-</td>
+ * <td>-</td>
+ * <td>-</td>
+ * <td>-</td>
+ * <td>X</td>
+ * <td>X</td>
+ * <td>X</td>
+ * <td>-</td>
+ * <td>X</td>
+ * <td>X</td>
+ * <td>X</td>
+ * <td>X</td>
+ * </tr>
+ * <tr>
+ * <td> gMonthDay </td>
+ * <td>-</td>
+ * <td>X</td>
+ * <td>X</td>
+ * <td>-</td>
+ * <td>-</td>
+ * <td>-</td>
+ * <td>X</td>
+ * <td>X</td>
+ * <td>X</td>
+ * <td>-</td>
+ * <td>X</td>
+ * <td>X</td>
+ * <td>X</td>
+ * <td>X</td>
+ * </tr>
+ * <tr>
+ * <td> date </td>
+ * <td>X</td>
+ * <td>X</td>
+ * <td>X</td>
+ * <td>-</td>
+ * <td>-</td>
+ * <td>-</td>
+ * <td>X</td>
+ * <td>X</td>
+ * <td>X</td>
+ * <td>-</td>
+ * <td>X</td>
+ * <td>X</td>
+ * <td>X</td>
+ * <td>X</td>
+ * </tr>
+ * <tr>
+ * <td> time </td>
+ * <td>-</td>
+ * <td>-</td>
+ * <td>-</td>
+ * <td>X</td>
+ * <td>X</td>
+ * <td>X</td>
+ * <td>X</td>
+ * <td>X</td>
+ * <td>X</td>
+ * <td>-</td>
+ * <td>X</td>
+ * <td>X</td>
+ * <td>X</td>
+ * <td>X</td>
+ * </tr>
+ * <tr>
+ * <td> datetime </td>
+ * <td>X</td>
+ * <td>X</td>
+ * <td>X</td>
+ * <td>X</td>
+ * <td>X</td>
+ * <td>X</td>
+ * <td>X</td>
+ * <td>X</td>
+ * <td>X</td>
+ * <td>-</td>
+ * <td>X</td>
+ * <td>X</td>
+ * <td>X</td>
+ * <td>X</td>
+ * </tr>
+ * <tr>
+ * <td> duration </td>
+ * <td>-</td>
+ * <td>X</td>
+ * <td>-</td>
+ * <td>-</td>
+ * <td>-</td>
+ * <td>X</td>
+ * <td>-</td>
+ * <td>-</td>
+ * <td>-</td>
+ * <td>X</td>
+ * <td>-</td>
+ * <td>-</td>
+ * <td>-</td>
+ * <td>X</td>
+ * </tr>
+ * </table>
+ * </p>
+ * 
+ * @author Ankit Pasricha, IBM
+ * 
+ * @version $Id: XSDateTime.java 447250 2006-09-18 05:27:17Z mrglavas $
+ */
+public interface XSDateTime {
+	
+    /**
+     * @return years - can be negative for date-time related types;
+     *          
+     */
+    public int getYears();
+    
+    /**
+     * @return months - can be negative only for duration types;
+     *                  For duration types, it returns years*12 + months
+     */
+    public int getMonths();
+    
+    /**
+     * @return days - cannot be negative;
+     *          
+     */
+    public int getDays();
+    
+    /**
+     * @return hours - cannot be negative;
+     *          
+     */
+    public int getHours();
+    
+    /**
+     * @return minutes - cannot be negative;
+     *          
+     */
+    public int getMinutes();
+    
+    /**
+     * @return seconds - can be negative only for durations;
+     *                   For duration types, it returns days*24*3600 + hours*3600 
+     *                                                  + minutes*60 + seconds 
+     */
+    public double getSeconds();
+    
+    /**
+     * @return boolean (true when timezone is specified in the original lexical value)
+     *                  
+     */
+    public boolean hasTimeZone();
+    
+    /**
+     * @return timezone hours (for GMT-xx:xx this will be negative),
+     *                          
+     */
+    public int getTimeZoneHours();
+    
+    /**
+     * @return timezone minutes (for GMT-xx:xx this will be negative),
+     *                          
+     */
+    public int getTimeZoneMinutes();
+    
+    /**
+     * @return the original lexical value
+     */
+    public String getLexicalValue();
+    
+    /**
+     * @return a new date-time related object with normalized values
+     *         (has no effect on objects already
+     *          normalized)
+     */
+    public XSDateTime normalize();
+    
+    /**
+     * @return whether a date-time related object is normalized or not
+     *         (value is not useful for types where timezone is not specified)
+     */
+    public boolean isNormalized();
+       
+    /**
+     * @return an un-normalized XMLGregorianCalendar (if applicable otherwise null)
+     */
+    public XMLGregorianCalendar getXMLGregorianCalendar();
+        
+    /**
+     * @return a Duration (if applicable otherwise null)
+     */
+    public Duration getDuration();
+}

http://git-wip-us.apache.org/repos/asf/jena/blob/c9a7e646/jena-core/src/main/java/org/apache/jena/ext/xerces/xs/datatypes/XSDecimal.java
----------------------------------------------------------------------
diff --git a/jena-core/src/main/java/org/apache/jena/ext/xerces/xs/datatypes/XSDecimal.java b/jena-core/src/main/java/org/apache/jena/ext/xerces/xs/datatypes/XSDecimal.java
new file mode 100644
index 0000000..a3a7a1a
--- /dev/null
+++ b/jena-core/src/main/java/org/apache/jena/ext/xerces/xs/datatypes/XSDecimal.java
@@ -0,0 +1,65 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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.jena.ext.xerces.xs.datatypes;
+
+import java.math.BigDecimal;
+import java.math.BigInteger;
+
+/**
+ * <p>Interface to expose the value of 'decimal' and related datatypes.</p>
+ * 
+ * @author Naela Nissar, IBM
+ * 
+ * @version $Id: XSDecimal.java 447250 2006-09-18 05:27:17Z mrglavas $
+ */
+public interface XSDecimal {
+     
+    /**
+     * @return the <code>BigDecimal</code> representation of this object
+     */
+    public BigDecimal getBigDecimal();
+    
+    /**
+     * @return the <code>BigInteger</code> representation of this object 
+     * @exception NumberFormatException if the value cannot be represented as a <code>BigInteger</code> 
+     */
+    public BigInteger getBigInteger() throws NumberFormatException;
+    
+    /**
+     * @return the long value representation of this object
+     * @exception NumberFormatException if the value cannot be represented as a <code>long</code>
+     */
+    public long getLong() throws NumberFormatException;
+    
+    /**
+     * @return the int value representation of this object
+     * @exception NumberFormatException if the value cannot be represented as a <code>int</code>
+     */
+    public int getInt() throws NumberFormatException;
+    
+    /**
+     * @return the short value representation of this object
+     * @exception NumberFormatException if the value cannot be represented as a <code>short</code>
+     */
+    public short getShort() throws NumberFormatException;
+    
+    /**
+     * @return the byte value representation of this object
+     * @exception NumberFormatException if the value cannot be represented as a <code>byte</code>
+     */
+    public byte getByte() throws NumberFormatException;
+}

http://git-wip-us.apache.org/repos/asf/jena/blob/c9a7e646/jena-core/src/main/java/org/apache/jena/ext/xerces/xs/datatypes/XSDouble.java
----------------------------------------------------------------------
diff --git a/jena-core/src/main/java/org/apache/jena/ext/xerces/xs/datatypes/XSDouble.java b/jena-core/src/main/java/org/apache/jena/ext/xerces/xs/datatypes/XSDouble.java
new file mode 100644
index 0000000..478db5a
--- /dev/null
+++ b/jena-core/src/main/java/org/apache/jena/ext/xerces/xs/datatypes/XSDouble.java
@@ -0,0 +1,33 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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.jena.ext.xerces.xs.datatypes;
+
+/**
+ * <p>Interface to expose the value of the 'double' datatype.</p>
+ * 
+ * @author Ankit Pasricha, IBM
+ * 
+ * @version $Id: XSDouble.java 447250 2006-09-18 05:27:17Z mrglavas $
+ */
+public interface XSDouble {
+    
+    /**
+     * @return a double value
+     */
+    public double getValue();
+    
+}

http://git-wip-us.apache.org/repos/asf/jena/blob/c9a7e646/jena-core/src/main/java/org/apache/jena/ext/xerces/xs/datatypes/XSFloat.java
----------------------------------------------------------------------
diff --git a/jena-core/src/main/java/org/apache/jena/ext/xerces/xs/datatypes/XSFloat.java b/jena-core/src/main/java/org/apache/jena/ext/xerces/xs/datatypes/XSFloat.java
new file mode 100644
index 0000000..3d16cea
--- /dev/null
+++ b/jena-core/src/main/java/org/apache/jena/ext/xerces/xs/datatypes/XSFloat.java
@@ -0,0 +1,33 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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.jena.ext.xerces.xs.datatypes;
+
+/**
+ * <p>Interface to expose value of the float datatype.</p>
+ * 
+ * @author Ankit Pasricha, IBM
+ * 
+ * @version $Id: XSFloat.java 447250 2006-09-18 05:27:17Z mrglavas $
+ */
+public interface XSFloat {
+    
+    /**
+     * @return a float value
+     */
+    public float getValue();
+    
+}

http://git-wip-us.apache.org/repos/asf/jena/blob/c9a7e646/jena-core/src/main/java/org/apache/jena/ext/xerces/xs/datatypes/package.html
----------------------------------------------------------------------
diff --git a/jena-core/src/main/java/org/apache/jena/ext/xerces/xs/datatypes/package.html b/jena-core/src/main/java/org/apache/jena/ext/xerces/xs/datatypes/package.html
new file mode 100644
index 0000000..a343690
--- /dev/null
+++ b/jena-core/src/main/java/org/apache/jena/ext/xerces/xs/datatypes/package.html
@@ -0,0 +1,306 @@
+<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
+<html>
+<head >
+<!--
+
+  Licensed to the Apache Software Foundation (ASF) under one or more
+  contributor license agreements.  See the NOTICE file distributed with
+  this work for additional information regarding copyright ownership.
+  The ASF licenses this file to You 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.
+
+-->
+</head>
+<body bgcolor="white">This package provides interfaces for accessing actual value information through PSVI for XML Schema 1.0 data types.
+<BR>
+<BR>
+The table below gives the data type to applicable interface mapping:
+<BR>
+<BR>
+<TABLE border="1">
+	<TBODY>
+		<TR>
+			<TD width="332" align="center">XML Schema Data Type</TD>
+			<TD align="center" width="202">Interface/Class</TD>
+		</TR>
+		<TR>
+			<TD width="332"></TD>
+			<TD width="202"></TD>
+		</TR>
+		<TR>
+			<TD width="332" align="center">string</TD>
+			<TD width="202" align="center">java.lang.String</TD>
+		</TR>
+		<TR>
+			<TD width="332" align="center">boolean</TD>
+			<TD width="202" align="center">java.lang.Boolean</TD>
+		</TR>
+		<TR>
+			<TD width="332" align="center">decimal</TD>
+			<TD width="202" align="center">XSDecimal</TD>
+		</TR>
+		<TR>
+			<TD width="332" align="center">float</TD>
+			<TD width="202" align="center">XSFloat</TD>
+		</TR>
+		<TR>
+			<TD width="332" align="center">double</TD>
+			<TD width="202" align="center">XSDouble</TD>
+		</TR>
+		<TR>
+			<TD width="332" align="center">duration</TD>
+			<TD width="202" align="center">XSDateTime</TD>
+		</TR>
+		<TR>
+			<TD width="332" align="center">dateTime</TD>
+			<TD width="202" align="center">XSDateTime</TD>
+		</TR>
+		<TR>
+			<TD width="332" align="center">date</TD>
+			<TD width="202" align="center">XSDateTime</TD>
+		</TR>
+		<TR>
+			<TD width="332" align="center">time</TD>
+			<TD width="202" align="center">XSDateTime</TD>
+		</TR>
+		<TR>
+			<TD width="332" align="center">gYear</TD>
+			<TD width="202" align="center">XSDateTime</TD>
+		</TR>
+		<TR>
+			<TD width="332" align="center">gMonth</TD>
+			<TD width="202" align="center">XSDateTime</TD>
+		</TR>
+		<TR>
+			<TD width="332" align="center">gDay</TD>
+			<TD width="202" align="center">XSDateTime</TD>
+		</TR>
+		<TR>
+			<TD width="332" align="center">gYearMonth</TD>
+			<TD width="202" align="center">XSDateTime</TD>
+		</TR>
+		<TR>
+			<TD width="332" align="center">gMonthDay</TD>
+			<TD width="202" align="center">XSDateTime</TD>
+		</TR>
+		<TR>
+			<TD width="332" align="center">hexBinary</TD>
+			<TD width="202" align="center">ByteList</TD>
+		</TR>
+		<TR>
+			<TD width="332" align="center">base64Binary</TD>
+			<TD width="202" align="center">ByteList</TD>
+		</TR>
+		<TR>
+			<TD width="332" align="center">anyURI</TD>
+			<TD width="202" align="center">java.lang.String</TD>
+		</TR>
+		<TR>
+			<TD width="332" align="center">QName</TD>
+			<TD width="202" align="center">XSQName</TD>
+		</TR>
+		<TR>
+			<TD width="332" align="center">NOTATION</TD>
+			<TD width="202" align="center">XSQName</TD>
+		</TR>
+		<TR>
+			<TD width="332" align="center">normalizedString</TD>
+			<TD width="202" align="center">java.lang.String</TD>
+		</TR>
+		<TR>
+			<TD width="332" align="center">token</TD>
+			<TD width="202" align="center">java.lang.String</TD>
+		</TR>
+		<TR>
+			<TD width="332" align="center">language</TD>
+			<TD width="202" align="center">java.lang.String</TD>
+		</TR>
+		<TR>
+			<TD width="332" align="center">NMTOKEN</TD>
+			<TD width="202" align="center">java.lang.String</TD>
+		</TR>
+		<TR>
+			<TD width="332" align="center">NMTOKENS</TD>
+			<TD width="202" align="center">ObjectList</TD>
+		</TR>
+		<TR>
+			<TD width="332" align="center">Name</TD>
+			<TD width="202" align="center">java.lang.String</TD>
+		</TR>
+		<TR>
+			<TD width="332" align="center">NCName</TD>
+			<TD width="202" align="center">java.lang.String</TD>
+		</TR>
+		<TR>
+			<TD width="332" align="center">ID</TD>
+			<TD width="202" align="center">java.lang.String</TD>
+		</TR>
+		<TR>
+			<TD width="332" align="center">IDREF</TD>
+			<TD width="202" align="center">java.lang.String</TD>
+		</TR>
+		<TR>
+			<TD width="332" align="center">IDREFS</TD>
+			<TD width="202" align="center">ObjectList</TD>
+		</TR>
+		<TR>
+			<TD width="332" align="center">ENTITY</TD>
+			<TD width="202" align="center">java.lang.String</TD>
+		</TR>
+		<TR>
+			<TD width="332" align="center">ENTITIES</TD>
+			<TD width="202" align="center">ObjectList</TD>
+		</TR>
+		<TR>
+			<TD width="332" align="center">list</TD>
+			<TD width="202" align="center">ObjectList</TD>
+		</TR>
+		<TR>
+			<TD width="332" align="center">integer</TD>
+			<TD width="202" align="center">XSDecimal</TD>
+		</TR>
+		<TR>
+			<TD width="332" align="center">positiveInteger</TD>
+			<TD width="202" align="center">XSDecimal</TD>
+		</TR>
+		<TR>
+			<TD width="332" align="center">negativeInteger</TD>
+			<TD width="202" align="center">XSDecimal</TD>
+		</TR>
+		<TR>
+			<TD width="332" align="center">nonPositiveInteger</TD>
+			<TD width="202" align="center">XSDecimal</TD>
+		</TR>
+		<TR>
+			<TD width="332" align="center">nonNegativeInteger</TD>
+			<TD width="202" align="center">XSDecimal</TD>
+		</TR>
+		<TR>
+			<TD width="332" align="center">unsignedShort</TD>
+			<TD width="202" align="center">XSDecimal</TD>
+		</TR>
+		<TR>
+			<TD width="332" align="center">unsignedLong</TD>
+			<TD width="202" align="center">XSDecimal</TD>
+		</TR>
+		<TR>
+			<TD width="332" align="center">unsignedByte</TD>
+			<TD width="202" align="center">XSDecimal</TD>
+		</TR>
+		<TR>
+			<TD width="332" align="center">unsignedInt</TD>
+			<TD width="202" align="center">XSDecimal</TD>
+		</TR>
+		<TR>
+			<TD width="332" align="center">long</TD>
+			<TD width="202" align="center">XSDecimal</TD>
+		</TR>
+		<TR>
+			<TD width="332" align="center">int</TD>
+			<TD width="202" align="center">XSDecimal</TD>
+		</TR>
+		<TR>
+			<TD width="332" align="center">short</TD>
+			<TD width="202" align="center">XSDecimal</TD>
+		</TR>
+		<TR>
+			<TD width="332" align="center">byte</TD>
+			<TD width="202" align="center">XSDecimal</TD>
+		</TR>
+	</TBODY>
+</TABLE>
+<P><BR>As shown above, the XSDateTime interface provides mapping to a number of decimal/integer data types. The application needs to ensure that appropriate methods for each of these types is invoked. The mapping of  these types to defined methods is shown in the table below. Accessing methods that are undefined for a type will give unexpected results.
+</P>
+
+
+<P><BR>
+</P>
+<TABLE border="1">
+	<TBODY>
+		<TR>
+			<TD width="308" align="center">XML Schema Data Type</TD>
+			<TD width="228" align="center">Applicable method in XSDateTime*</TD>
+		</TR>
+		<TR>
+			<TD width="308"></TD>
+			<TD width="228"></TD>
+		</TR>
+		<TR>
+			<TD width="332" align="center">integer</TD><TD width="202" align="center">getBigInteger()</TD>
+			
+		</TR>
+		<TR>
+			<TD width="332" align="center">positiveInteger</TD><TD width="202" align="center">getBigInteger()</TD>
+			
+		</TR>
+		<TR>
+			<TD width="332" align="center">negativeInteger</TD><TD width="202" align="center">getBigInteger()</TD>
+			
+		</TR>
+		<TR>
+			<TD width="332" align="center">nonPositiveInteger</TD><TD width="202" align="center">getBigInteger()</TD>
+			
+		</TR>
+		<TR>
+			<TD width="332" align="center">nonNegativeInteger</TD><TD width="202" align="center">getBigInteger()</TD>
+			
+		</TR>
+		<TR>
+			<TD width="332" align="center">unsignedShort</TD><TD width="202" align="center">getInt()</TD>
+			
+		</TR>
+		<TR>
+			<TD width="332" align="center">unsignedLong</TD><TD width="202" align="center">getBigInteger()</TD>
+			
+		</TR>
+		<TR>
+			<TD width="332" align="center">unsignedByte</TD><TD width="202" align="center">getShort()</TD>
+			
+		</TR>
+		<TR>
+			<TD width="332" align="center">unsignedInt</TD><TD width="202" align="center">getLong()</TD>
+			
+		</TR>
+		<TR>
+			<TD width="332" align="center">long</TD><TD width="202" align="center">getLong()</TD>
+			
+		</TR>
+		<TR>
+			<TD width="332" align="center">int</TD><TD width="202" align="center">getInt()</TD>
+			
+		</TR>
+		<TR>
+			<TD width="332" align="center">short</TD><TD width="202" align="center">getShort()</TD>
+			
+		</TR>
+		<TR>
+			<TD width="332" align="center">byte</TD><TD width="202" align="center">getByte()</TD>
+			
+		</TR>
+		<TR>
+			<TD width="308"></TD>
+			<TD width="228"></TD>
+		</TR>
+	</TBODY>
+</TABLE>
+<P><BR>* <SPAN
+	style='font-size:12.0pt;font-family:"Times New Roman";
+mso-fareast-font-family:"Times New Roman";mso-ansi-language:EN-US;mso-fareast-language:
+EN-GB;mso-bidi-language:AR-SA'>This
+shows the base method that can be called. That is, users can call this
+method and all methods returning bigger types than the base method
+according to the order: byte &lt; short &lt; int &lt; long &lt;
+BigInteger &lt; BigDecimal. For example, in the case of unsignedShort,
+users can call getInt(), getLong(), getBigInteger() and getBigDecimal()
+but NOT getShort() or getByte().</SPAN>
+</P></body>
+</html>

http://git-wip-us.apache.org/repos/asf/jena/blob/c9a7e646/jena-core/src/main/java/org/apache/jena/rdf/model/impl/Util.java
----------------------------------------------------------------------
diff --git a/jena-core/src/main/java/org/apache/jena/rdf/model/impl/Util.java b/jena-core/src/main/java/org/apache/jena/rdf/model/impl/Util.java
index ba7c969..64dc047 100644
--- a/jena-core/src/main/java/org/apache/jena/rdf/model/impl/Util.java
+++ b/jena-core/src/main/java/org/apache/jena/rdf/model/impl/Util.java
@@ -24,11 +24,11 @@ import java.util.regex.Pattern ;
 import org.apache.jena.JenaRuntime ;
 import org.apache.jena.datatypes.RDFDatatype ;
 import org.apache.jena.datatypes.xsd.XSDDatatype ;
+import org.apache.jena.ext.xerces.util.XMLChar;
 import org.apache.jena.graph.Node ;
 import org.apache.jena.rdf.model.Literal ;
 import org.apache.jena.shared.CannotEncodeCharacterException ;
 import org.apache.jena.util.SplitIRI ;
-import org.apache.xerces.util.XMLChar ;
 
 /** Some utility functions.
  */

http://git-wip-us.apache.org/repos/asf/jena/blob/c9a7e646/jena-core/src/main/java/org/apache/jena/rdfxml/xmlinput/impl/ParserSupport.java
----------------------------------------------------------------------
diff --git a/jena-core/src/main/java/org/apache/jena/rdfxml/xmlinput/impl/ParserSupport.java b/jena-core/src/main/java/org/apache/jena/rdfxml/xmlinput/impl/ParserSupport.java
index 1dbdbed..5bcd9ef 100644
--- a/jena-core/src/main/java/org/apache/jena/rdfxml/xmlinput/impl/ParserSupport.java
+++ b/jena-core/src/main/java/org/apache/jena/rdfxml/xmlinput/impl/ParserSupport.java
@@ -27,10 +27,10 @@ package org.apache.jena.rdfxml.xmlinput.impl;
 import java.util.HashMap ;
 import java.util.Map ;
 
+import org.apache.jena.ext.xerces.util.XML11Char;
+import org.apache.jena.ext.xerces.util.XMLChar;
 import org.apache.jena.iri.IRI ;
 import org.apache.jena.rdfxml.xmlinput.ARPErrorNumbers ;
-import org.apache.xerces.util.XML11Char ;
-import org.apache.xerces.util.XMLChar ;
 import org.xml.sax.SAXParseException ;
 
 public class ParserSupport implements ARPErrorNumbers, Names {

http://git-wip-us.apache.org/repos/asf/jena/blob/c9a7e646/jena-core/src/main/java/org/apache/jena/rdfxml/xmlinput/impl/RDFXMLParser.java
----------------------------------------------------------------------
diff --git a/jena-core/src/main/java/org/apache/jena/rdfxml/xmlinput/impl/RDFXMLParser.java b/jena-core/src/main/java/org/apache/jena/rdfxml/xmlinput/impl/RDFXMLParser.java
index c434930..f5e8dfd 100644
--- a/jena-core/src/main/java/org/apache/jena/rdfxml/xmlinput/impl/RDFXMLParser.java
+++ b/jena-core/src/main/java/org/apache/jena/rdfxml/xmlinput/impl/RDFXMLParser.java
@@ -23,15 +23,20 @@ import java.io.InputStreamReader;
 import java.io.Reader;
 import java.io.UTFDataFormatException;
 
+import javax.xml.parsers.SAXParser;
+import javax.xml.parsers.SAXParserFactory;
+
 import org.apache.jena.rdfxml.xmlinput.FatalParsingErrorException ;
 import org.apache.jena.rdfxml.xmlinput.SAX2RDF ;
+import org.apache.jena.shared.JenaException;
 import org.apache.jena.util.CharEncoding ;
-import org.apache.xerces.parsers.SAXParser;
-import org.apache.xerces.parsers.StandardParserConfiguration;
-import org.apache.xerces.xni.Augmentations;
+//import org.apache.xerces.parsers.SAXParser; //XMLReader
+//import org.apache.xerces.parsers.StandardParserConfiguration;
+//import org.apache.xerces.xni.Augmentations;
 import org.xml.sax.InputSource;
 import org.xml.sax.SAXException;
 import org.xml.sax.SAXParseException;
+import org.xml.sax.XMLReader;
 
 /**
  * 
@@ -39,7 +44,7 @@ import org.xml.sax.SAXParseException;
  */
 public class RDFXMLParser extends XMLHandler {
 
-    private SAXParser saxParser;
+    private XMLReader saxParser;
 
     private String readerXMLEncoding = null;
 
@@ -56,7 +61,7 @@ public class RDFXMLParser extends XMLHandler {
      * Consider using {@link SAXParserWithEncodingCheck}
      * @param rdr
      */
-    protected RDFXMLParser(SAXParser rdr) {
+    protected RDFXMLParser(XMLReader rdr) {
         super();
         saxParser = rdr;
         try {
@@ -66,67 +71,82 @@ public class RDFXMLParser extends XMLHandler {
         }
     }
 
-    public SAXParser getSAXParser() {
+    public XMLReader getSAXParser() {
         return saxParser;
     }
 
-    /**
-     * This works with an {@link RDFXMLParser} and catches and reports several
-     * common errors to do with character encoding.
-     *
-     */
-    static protected class SAXParserWithEncodingCheck extends SAXParser {
-        protected SAXParserWithEncodingCheck(StandardParserConfiguration c) {
-            super(c);
+    // JENA-1537: JDK SaxParser does not expose  xmlDecl
+//    /**
+//     * This works with an {@link RDFXMLParser} and catches and reports several
+//     * common errors to do with character encoding.
+//     *
+//     */
+//    static protected class SAXParserWithEncodingCheck extends SAXParser {
+//        protected SAXParserWithEncodingCheck(StandardParserConfiguration c) {
+//            super(c);
+////            try {
+////                setFeature("http://xml.org/sax/features/string-interning",
+////                        false);
+////            } catch (SAXException e) {
+////                // Not supported - aggh
+////                // TO DO ask on xerces list why not?
+////                // e.printStackTrace();
+////            }
+//        }
+//
+//        private RDFXMLParser rdfXmlParser;
+//
+//        @Override
+//        public void xmlDecl(String version, String encoding, String standalone,
+//                Augmentations augs) {
 //            try {
-//                setFeature("http://xml.org/sax/features/string-interning",
-//                        false);
-//            } catch (SAXException e) {
-//                // Not supported - aggh
-//                // TO DO ask on xerces list why not?
-//                // e.printStackTrace();
+//                getRdfXmlParser().setEncoding(encoding == null ? "UTF" : encoding);
+//            } catch (SAXParseException e) {
+//                throw new WrappedException(e);
 //            }
-        }
-
-        private RDFXMLParser rdfXmlParser;
-
-        @Override
-        public void xmlDecl(String version, String encoding, String standalone,
-                Augmentations augs) {
-            try {
-                getRdfXmlParser().setEncoding(encoding == null ? "UTF" : encoding);
-            } catch (SAXParseException e) {
-                throw new WrappedException(e);
-            }
-            super.xmlDecl(version, encoding, standalone, augs);
-
-        }
-
-		/**
-		 * This must be called as part of the initialization process.
-		 * @param rdfXmlParser the rdfXmlParser to set
-		 */
-		public void setRdfXmlParser(RDFXMLParser rdfXmlParser) {
-			this.rdfXmlParser = rdfXmlParser;
-		}
-
-		/**
-		 * @return the rdfXmlParser
-		 */
-		public RDFXMLParser getRdfXmlParser() {
-			if (rdfXmlParser == null) {
-				throw new IllegalStateException("setRdfXmlParser must be called as part of the initialization process");
-			}
-			return rdfXmlParser;
-		}
-    }
+//            super.xmlDecl(version, encoding, standalone, augs);
+//
+//        }
+//
+//		/**
+//		 * This must be called as part of the initialization process.
+//		 * @param rdfXmlParser the rdfXmlParser to set
+//		 */
+//		public void setRdfXmlParser(RDFXMLParser rdfXmlParser) {
+//			this.rdfXmlParser = rdfXmlParser;
+//		}
+//
+//		/**
+//		 * @return the rdfXmlParser
+//		 */
+//		public RDFXMLParser getRdfXmlParser() {
+//			if (rdfXmlParser == null) {
+//				throw new IllegalStateException("setRdfXmlParser must be called as part of the initialization process");
+//			}
+//			return rdfXmlParser;
+//		}
+//    }
 
     public static RDFXMLParser create() {
-        StandardParserConfiguration c = new StandardParserConfiguration();
-        SAXParserWithEncodingCheck msp = new SAXParserWithEncodingCheck(c);
-        RDFXMLParser a = new RDFXMLParser(msp);
-        msp.setRdfXmlParser(a);
-        return a;
+//        StandardParserConfiguration c = new StandardParserConfiguration();
+//        SAXParserWithEncodingCheck msp = new SAXParserWithEncodingCheck(c);
+        // JENA-1537
+        try { 
+            SAXParserFactory spf = SAXParserFactory.newInstance();
+            // Create a JAXP SAXParser
+            SAXParser saxParser = spf.newSAXParser();
+            // Get the encapsulated SAX XMLReader
+            XMLReader xmlreader = saxParser.getXMLReader();
+
+            RDFXMLParser a = new RDFXMLParser(xmlreader);
+            // Default.
+            a.setEncoding("UTF");
+            // JENA-1537
+            //msp.setRdfXmlParser(a);
+            return a;
+        } catch (Exception ex) {
+            throw new JenaException("Failed to create an RDFXMLParser", ex);
+        }
     }
 
 
@@ -142,7 +162,8 @@ public class RDFXMLParser extends XMLHandler {
 
         initParse(base,"");
         SAX2RDF.installHandlers(saxParser, this);
-        saxParser.reset();
+        //[JENA]
+        //saxParser.reset();
 
         initEncodingChecks(input);
         try {

http://git-wip-us.apache.org/repos/asf/jena/blob/c9a7e646/jena-core/src/main/java/org/apache/jena/rdfxml/xmloutput/impl/BaseXMLWriter.java
----------------------------------------------------------------------
diff --git a/jena-core/src/main/java/org/apache/jena/rdfxml/xmloutput/impl/BaseXMLWriter.java b/jena-core/src/main/java/org/apache/jena/rdfxml/xmloutput/impl/BaseXMLWriter.java
index 0bd4367..14ccc64 100644
--- a/jena-core/src/main/java/org/apache/jena/rdfxml/xmloutput/impl/BaseXMLWriter.java
+++ b/jena-core/src/main/java/org/apache/jena/rdfxml/xmloutput/impl/BaseXMLWriter.java
@@ -27,6 +27,7 @@ import java.util.Map.Entry ;
 import java.util.regex.Pattern ;
 
 import org.apache.jena.JenaRuntime ;
+import org.apache.jena.ext.xerces.util.XMLChar;
 import org.apache.jena.iri.IRI ;
 import org.apache.jena.iri.IRIFactory ;
 import org.apache.jena.rdf.model.* ;
@@ -38,7 +39,6 @@ import org.apache.jena.shared.* ;
 import org.apache.jena.util.CharEncoding ;
 import org.apache.jena.util.FileUtils ;
 import org.apache.jena.vocabulary.* ;
-import org.apache.xerces.util.XMLChar ;
 import org.slf4j.Logger ;
 import org.slf4j.LoggerFactory ;
 

http://git-wip-us.apache.org/repos/asf/jena/blob/c9a7e646/jena-core/src/main/java/org/apache/jena/rdfxml/xmloutput/impl/Unparser.java
----------------------------------------------------------------------
diff --git a/jena-core/src/main/java/org/apache/jena/rdfxml/xmloutput/impl/Unparser.java b/jena-core/src/main/java/org/apache/jena/rdfxml/xmloutput/impl/Unparser.java
index 0210f9e..99e3f20 100644
--- a/jena-core/src/main/java/org/apache/jena/rdfxml/xmloutput/impl/Unparser.java
+++ b/jena-core/src/main/java/org/apache/jena/rdfxml/xmloutput/impl/Unparser.java
@@ -119,6 +119,7 @@ package org.apache.jena.rdfxml.xmloutput.impl;
 import java.io.PrintWriter ;
 import java.util.* ;
 
+import org.apache.jena.ext.xerces.util.XMLChar;
 import org.apache.jena.iri.IRI ;
 import org.apache.jena.rdf.model.* ;
 import org.apache.jena.rdf.model.impl.PropertyImpl ;
@@ -128,7 +129,6 @@ import org.apache.jena.shared.JenaException ;
 import org.apache.jena.shared.PropertyNotFoundException ;
 import org.apache.jena.util.iterator.* ;
 import org.apache.jena.vocabulary.RDF ;
-import org.apache.xerces.util.XMLChar ;
 import org.slf4j.Logger ;
 import org.slf4j.LoggerFactory ;