jena-commits mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From a...@apache.org
Subject [21/24] jena git commit: JENA-1537: Remove dependency on Xerces. Import needed code
Date Fri, 04 May 2018 09:03:22 GMT
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;
+    }
+}


Mime
View raw message