Modified: xmlbeans/trunk/src/main/java/org/apache/xmlbeans/impl/schema/SchemaTypeLoaderImpl.java URL: http://svn.apache.org/viewvc/xmlbeans/trunk/src/main/java/org/apache/xmlbeans/impl/schema/SchemaTypeLoaderImpl.java?rev=1881992&r1=1881991&r2=1881992&view=diff ============================================================================== --- xmlbeans/trunk/src/main/java/org/apache/xmlbeans/impl/schema/SchemaTypeLoaderImpl.java (original) +++ xmlbeans/trunk/src/main/java/org/apache/xmlbeans/impl/schema/SchemaTypeLoaderImpl.java Thu Sep 24 23:11:07 2020 @@ -16,60 +16,49 @@ package org.apache.xmlbeans.impl.schema; import org.apache.xmlbeans.*; -import org.apache.xmlbeans.impl.common.SystemCache; import org.apache.xmlbeans.impl.common.QNameHelper; +import org.apache.xmlbeans.impl.common.SystemCache; import org.apache.xmlbeans.impl.common.XBeanDebug; import org.apache.xmlbeans.impl.xb.xsdschema.SchemaDocument; import javax.xml.namespace.QName; - import java.io.InputStream; -import java.util.Map; -import java.util.HashMap; -import java.util.Collections; -import java.util.ArrayList; -import java.util.List; -import java.util.IdentityHashMap; - import java.lang.ref.SoftReference; +import java.util.*; import static org.apache.xmlbeans.impl.schema.SchemaTypeSystemImpl.METADATA_PACKAGE_GEN; public class SchemaTypeLoaderImpl extends SchemaTypeLoaderBase { - private ResourceLoader _resourceLoader; - private ClassLoader _classLoader; + private final ResourceLoader _resourceLoader; + private final ClassLoader _classLoader; private final SchemaTypeLoader[] _searchPath; - private Map _classpathTypeSystems; - private Map _classLoaderTypeSystems; - private Map _elementCache; - private Map _attributeCache; - private Map _modelGroupCache; - private Map _attributeGroupCache; - private Map _idConstraintCache; - private Map _typeCache; - private Map _documentCache; - private Map _attributeTypeCache; - private Map _classnameCache; + private Map<String, SchemaTypeSystemImpl> _classpathTypeSystems; + private Map<String, SchemaTypeSystemImpl> _classLoaderTypeSystems; + private Map<QName, Object> _elementCache; + private Map<QName, Object> _attributeCache; + private Map<QName, Object> _modelGroupCache; + private Map<QName, Object> _attributeGroupCache; + private Map<QName, Object> _idConstraintCache; + private Map<QName, Object> _typeCache; + private Map<QName, Object> _documentCache; + private Map<QName, Object> _attributeTypeCache; + private Map<String, Object> _classnameCache; private final String _metadataPath; public static String METADATA_PACKAGE_LOAD = METADATA_PACKAGE_GEN; private static final Object CACHED_NOT_FOUND = new Object(); - private static final String[] basePackage = { "org.apache.xmlbeans.metadata", "schemaorg_apache_xmlbeans" }; - private static final String[] baseSchemas = { "sXMLCONFIG", "sXMLLANG", "sXMLSCHEMA", "sXMLTOOLS" }; + private static final String[] basePackage = {"org.apache.xmlbeans.metadata", "schemaorg_apache_xmlbeans"}; + private static final String[] baseSchemas = {"sXMLCONFIG", "sXMLLANG", "sXMLSCHEMA", "sXMLTOOLS"}; - - - private static class SchemaTypeLoaderCache extends SystemCache - { + private static class SchemaTypeLoaderCache extends SystemCache { // The following maintains a cache of SchemaTypeLoaders per ClassLoader per Thread. // I use soft references to allow the garbage collector to reclain the type loaders // and/pr class loaders at will. - private ThreadLocal _cachedTypeSystems = - new ThreadLocal() { protected Object initialValue() { return new ArrayList(); } }; + private final ThreadLocal<List<SoftReference<SchemaTypeLoaderImpl>>> _cachedTypeSystems = ThreadLocal.withInitial(ArrayList::new); @Override public void clearThreadLocals() { @@ -78,38 +67,28 @@ public class SchemaTypeLoaderImpl extend super.clearThreadLocals(); } - public SchemaTypeLoader getFromTypeLoaderCache(ClassLoader cl) - { - ArrayList a = (ArrayList) _cachedTypeSystems.get(); + public SchemaTypeLoader getFromTypeLoaderCache(ClassLoader cl) { + List<SoftReference<SchemaTypeLoaderImpl>> a = _cachedTypeSystems.get(); int candidate = -1; SchemaTypeLoaderImpl result = null; - for ( int i = 0 ; i < a.size() ; i++ ) - { - SchemaTypeLoaderImpl tl = (SchemaTypeLoaderImpl) ((SoftReference) a.get(i)).get(); - - if (tl == null) - { - assert i > candidate; - a.remove(i--); - } - else if (tl._classLoader == cl) - { - assert candidate == -1 && result == null; + for (int i = 0; i < a.size(); i++) { + SchemaTypeLoaderImpl tl = a.get(i).get(); + if (tl == null) { + a.remove(i--); + } else if (tl._classLoader == cl) { candidate = i; result = tl; - break; } } // Make sure the most recently accessed entry is at the beginning of the array - if (candidate > 0) - { - Object t = a.get(0); + if (candidate > 0) { + SoftReference<SchemaTypeLoaderImpl> t = a.get(0); a.set(0, a.get(candidate)); a.set(candidate, t); } @@ -117,32 +96,28 @@ public class SchemaTypeLoaderImpl extend return result; } - public void addToTypeLoaderCache(SchemaTypeLoader stl, ClassLoader cl) - { + public void addToTypeLoaderCache(SchemaTypeLoader stl, ClassLoader cl) { assert (stl instanceof SchemaTypeLoaderImpl) && ((SchemaTypeLoaderImpl) stl)._classLoader == cl; - ArrayList a = (ArrayList) _cachedTypeSystems.get(); + List<SoftReference<SchemaTypeLoaderImpl>> a = _cachedTypeSystems.get(); // Make sure this entry is at the top of the stack - if (a.size() > 0) - { - Object t = a.get(0); - a.set(0, new SoftReference(stl)); + if (a.size() > 0) { + SoftReference<SchemaTypeLoaderImpl> t = a.get(0); + a.set(0, new SoftReference<>((SchemaTypeLoaderImpl) stl)); a.add(t); + } else { + a.add(new SoftReference<>((SchemaTypeLoaderImpl) stl)); } - else - a.add(new SoftReference(stl)); } } - public static SchemaTypeLoaderImpl getContextTypeLoader ( ) - { + public static SchemaTypeLoaderImpl getContextTypeLoader() { ClassLoader cl = Thread.currentThread().getContextClassLoader(); SchemaTypeLoaderImpl result = (SchemaTypeLoaderImpl) SystemCache.get().getFromTypeLoaderCache(cl); - if (result == null) - { + if (result == null) { result = new SchemaTypeLoaderImpl( new SchemaTypeLoader[]{BuiltinSchemaTypeSystem.get()}, null, cl, null); @@ -159,12 +134,11 @@ public class SchemaTypeLoaderImpl extend /** * Initialize a SchemaTypeLoader via the given loaders and paths * - * @param searchPath the searchPath to use + * @param searchPath the searchPath to use * @param resourceLoader the resourceLoader to use - * @param classLoader the classLoader to use - * @param metadataPath the custom metadata path + * @param classLoader the classLoader to use + * @param metadataPath the custom metadata path * @return the schemaTypeLoader - * * @since XmlBeans 3.1.0 */ public static SchemaTypeLoader build(final SchemaTypeLoader[] searchPath, ResourceLoader resourceLoader, ClassLoader classLoader, String metadataPath) { @@ -173,18 +147,19 @@ public class SchemaTypeLoaderImpl extend list.add(searchPath); - ClassLoader cl = (classLoader == null) ? SchemaDocument.class.getClassLoader() : classLoader; + ClassLoader cl = (classLoader == null) ? SchemaDocument.class.getClassLoader() : classLoader; for (String prefix : basePackage) { for (String holder : baseSchemas) { String clName = prefix + ".system." + holder + ".TypeSystemHolder"; - if (cl.getResource(clName.replace(".","/")+".class") == null) { + if (cl.getResource(clName.replace(".", "/") + ".class") == null) { // if the first class isn't found in the package, continue with the next package break; } try { - Class cls = Class.forName(clName, true, cl); - list.add((SchemaTypeLoader)cls.getDeclaredField("typeSystem").get(null)); + @SuppressWarnings("unchecked") + Class<? extends SchemaTypeLoader> cls = (Class<? extends SchemaTypeLoader>) Class.forName(clName, true, cl); + list.add((SchemaTypeLoader) cls.getDeclaredField("typeSystem").get(null)); } catch (Exception e) { throw new XmlRuntimeException(e); } @@ -197,10 +172,9 @@ public class SchemaTypeLoaderImpl extend /** * Just used to avoid duplicate path entries */ - private static class SubLoaderList - { - private final List<SchemaTypeLoader> theList = new ArrayList<SchemaTypeLoader>(); - private final Map<SchemaTypeLoader,Object> seen = new IdentityHashMap<SchemaTypeLoader,Object>(); + private static class SubLoaderList { + private final List<SchemaTypeLoader> theList = new ArrayList<>(); + private final Map<SchemaTypeLoader, Object> seen = new IdentityHashMap<>(); void add(SchemaTypeLoader[] searchPath) { if (searchPath == null) { @@ -208,7 +182,7 @@ public class SchemaTypeLoaderImpl extend } for (SchemaTypeLoader stl : searchPath) { if (stl instanceof SchemaTypeLoaderImpl) { - SchemaTypeLoaderImpl sub = (SchemaTypeLoaderImpl)stl; + SchemaTypeLoaderImpl sub = (SchemaTypeLoaderImpl) stl; if (sub._classLoader != null || sub._resourceLoader != null) { add(sub); } else { @@ -235,19 +209,18 @@ public class SchemaTypeLoaderImpl extend /** * Constructs a SchemaTypeLoaderImpl that searches for objects * in the following order: - * + * <p> * (1) First on the searchPath of other SchemaTypeSystems supplied, - * in order that they are listed. + * in order that they are listed. * (2) Next on the classpath of .jar files or directories supplied, - * in the order that they are listed. When types are returned in - * this way, they are instantiated from a private typesystem. - * In other words, if a type is loaded from another SchemaTypeLoaderImpl - * that was initialized on the same file, the instance of the type will - * be different. + * in the order that they are listed. When types are returned in + * this way, they are instantiated from a private typesystem. + * In other words, if a type is loaded from another SchemaTypeLoaderImpl + * that was initialized on the same file, the instance of the type will + * be different. * (3) Finally on the classloader supplied. */ - private SchemaTypeLoaderImpl(SchemaTypeLoader[] searchPath, ResourceLoader resourceLoader, ClassLoader classLoader, String metadataPath) - { + private SchemaTypeLoaderImpl(SchemaTypeLoader[] searchPath, ResourceLoader resourceLoader, ClassLoader classLoader, String metadataPath) { _searchPath = (searchPath == null) ? EMPTY_SCHEMATYPELOADER_ARRAY : searchPath; _resourceLoader = resourceLoader; _classLoader = classLoader; @@ -255,7 +228,7 @@ public class SchemaTypeLoaderImpl extend if (metadataPath != null) { this._metadataPath = metadataPath; } else { - final String path26 = "schema" + METADATA_PACKAGE_LOAD.replace("/","_"); + final String path26 = "schema" + METADATA_PACKAGE_LOAD.replace("/", "_"); this._metadataPath = (isPath30(_classLoader)) ? METADATA_PACKAGE_LOAD : path26; } @@ -271,94 +244,84 @@ public class SchemaTypeLoaderImpl extend /** * Initializes the caches. */ - private final void initCaches() - { - _classpathTypeSystems = Collections.synchronizedMap(new HashMap()); - _classLoaderTypeSystems = Collections.synchronizedMap(new HashMap()); - _elementCache = Collections.synchronizedMap(new HashMap()); - _attributeCache = Collections.synchronizedMap(new HashMap()); - _modelGroupCache = Collections.synchronizedMap(new HashMap()); - _attributeGroupCache = Collections.synchronizedMap(new HashMap()); - _idConstraintCache = Collections.synchronizedMap(new HashMap()); - _typeCache = Collections.synchronizedMap(new HashMap()); - _documentCache = Collections.synchronizedMap(new HashMap()); - _attributeTypeCache = Collections.synchronizedMap(new HashMap()); - _classnameCache = Collections.synchronizedMap(new HashMap()); + private void initCaches() { + _classpathTypeSystems = Collections.synchronizedMap(new HashMap<>()); + _classLoaderTypeSystems = Collections.synchronizedMap(new HashMap<>()); + _elementCache = Collections.synchronizedMap(new HashMap<>()); + _attributeCache = Collections.synchronizedMap(new HashMap<>()); + _modelGroupCache = Collections.synchronizedMap(new HashMap<>()); + _attributeGroupCache = Collections.synchronizedMap(new HashMap<>()); + _idConstraintCache = Collections.synchronizedMap(new HashMap<>()); + _typeCache = Collections.synchronizedMap(new HashMap<>()); + _documentCache = Collections.synchronizedMap(new HashMap<>()); + _attributeTypeCache = Collections.synchronizedMap(new HashMap<>()); + _classnameCache = Collections.synchronizedMap(new HashMap<>()); } - SchemaTypeSystemImpl typeSystemForComponent(String searchdir, QName name) - { + SchemaTypeSystemImpl typeSystemForComponent(String searchdir, QName name) { String searchfor = searchdir + QNameHelper.hexsafedir(name) + ".xsb"; String tsname = null; - if (_resourceLoader != null) + if (_resourceLoader != null) { tsname = crackEntry(_resourceLoader, searchfor); + } - if (_classLoader != null) + if (_classLoader != null) { tsname = crackEntry(_classLoader, searchfor); + } - if (tsname != null) - return (SchemaTypeSystemImpl)typeSystemForName(tsname); + if (tsname != null) { + return (SchemaTypeSystemImpl) typeSystemForName(tsname); + } return null; } - public SchemaTypeSystem typeSystemForName(String name) - { - if (_resourceLoader != null) - { + public SchemaTypeSystem typeSystemForName(String name) { + if (_resourceLoader != null) { SchemaTypeSystem result = getTypeSystemOnClasspath(name); - if (result != null) + if (result != null) { return result; + } } - if (_classLoader != null) - { + if (_classLoader != null) { SchemaTypeSystem result = getTypeSystemOnClassloader(name); - if (result != null) + if (result != null) { return result; + } } return null; } - SchemaTypeSystemImpl typeSystemForClassname(String searchdir, String name) - { + SchemaTypeSystemImpl typeSystemForClassname(String searchdir, String name) { String searchfor = searchdir + name.replace('.', '/') + ".xsb"; - if (_resourceLoader != null) - { + if (_resourceLoader != null) { String tsname = crackEntry(_resourceLoader, searchfor); - if (tsname != null) + if (tsname != null) { return getTypeSystemOnClasspath(tsname); + } } - if (_classLoader != null) - { + if (_classLoader != null) { String tsname = crackEntry(_classLoader, searchfor); - if (tsname != null) + if (tsname != null) { return getTypeSystemOnClassloader(tsname); + } } return null; } - SchemaTypeSystemImpl getTypeSystemOnClasspath(String name) - { - SchemaTypeSystemImpl result = (SchemaTypeSystemImpl)_classpathTypeSystems.get(name); - if (result == null) - { - result = new SchemaTypeSystemImpl(_resourceLoader, name, this); - _classpathTypeSystems.put(name, result); - } - return result; + SchemaTypeSystemImpl getTypeSystemOnClasspath(String name) { + return _classpathTypeSystems.computeIfAbsent(name, n -> new SchemaTypeSystemImpl(_resourceLoader, n, this)); } - SchemaTypeSystemImpl getTypeSystemOnClassloader(String name) - { + SchemaTypeSystemImpl getTypeSystemOnClassloader(String name) { XBeanDebug.trace(XBeanDebug.TRACE_SCHEMA_LOADING, "Finding type system " + name + " on classloader", 0); - SchemaTypeSystemImpl result = (SchemaTypeSystemImpl)_classLoaderTypeSystems.get(name); - if (result == null) - { + SchemaTypeSystemImpl result = _classLoaderTypeSystems.get(name); + if (result == null) { XBeanDebug.trace(XBeanDebug.TRACE_SCHEMA_LOADING, "Type system " + name + " not cached - consulting field", 0); result = SchemaTypeSystemImpl.forName(name, _classLoader); _classLoaderTypeSystems.put(name, result); @@ -366,62 +329,51 @@ public class SchemaTypeLoaderImpl extend return result; } - static String crackEntry(ResourceLoader loader, String searchfor) - { + static String crackEntry(ResourceLoader loader, String searchfor) { InputStream is = loader.getResourceAsStream(searchfor); - if (is == null) - return null; - return crackPointer(is); + return is == null ? null : crackPointer(is); } - static String crackEntry(ClassLoader loader, String searchfor) - { + static String crackEntry(ClassLoader loader, String searchfor) { InputStream stream = loader.getResourceAsStream(searchfor); - if (stream == null) - return null; - return crackPointer(stream); + return stream == null ? null : crackPointer(stream); } - static String crackPointer(InputStream stream) - { + static String crackPointer(InputStream stream) { return SchemaTypeSystemImpl.crackPointer(stream); } - public boolean isNamespaceDefined(String namespace) - { - for (int i = 0; i < _searchPath.length; i++) - if (_searchPath[i].isNamespaceDefined(namespace)) + public boolean isNamespaceDefined(String namespace) { + for (SchemaTypeLoader schemaTypeLoader : _searchPath) { + if (schemaTypeLoader.isNamespaceDefined(namespace)) { return true; + } + } SchemaTypeSystem sts = typeSystemForComponent(_metadataPath + "/namespace/", new QName(namespace, "xmlns")); return (sts != null); } - public SchemaType.Ref findTypeRef(QName name) - { - /** - * The maps are synchronized, we use two accesses to the cache (one read - * and one write), but the code inbetween is not synchronized. The - * assumption is that the underlying datastructures (the search path and - * the classloader) do not change, so two threads running the code in - * parallel will come up with the same result. - */ + public SchemaType.Ref findTypeRef(QName name) { + // The maps are synchronized, we use two accesses to the cache (one read and one write), but the code in-between + // is not synchronized. The assumption is that the underlying datastructures (the search path and the classloader) + // do not change, so two threads running the code in parallel will come up with the same result. Object cached = _typeCache.get(name); - if (cached == CACHED_NOT_FOUND) + if (cached == CACHED_NOT_FOUND) { return null; + } SchemaType.Ref result = (SchemaType.Ref) cached; - if (result == null) - { - for (int i = 0; i < _searchPath.length; i++) - if (null != (result = _searchPath[i].findTypeRef(name))) + if (result == null) { + for (SchemaTypeLoader schemaTypeLoader : _searchPath) { + if (null != (result = schemaTypeLoader.findTypeRef(name))) { break; - if (result == null) - { + } + } + if (result == null) { SchemaTypeSystem ts = typeSystemForComponent(_metadataPath + "/type/", name); - if (ts != null) - { + if (ts != null) { result = ts.findTypeRef(name); - assert(result != null) : "Type system registered type " + QNameHelper.pretty(name) + " but does not return it"; + assert (result != null) : "Type system registered type " + QNameHelper.pretty(name) + " but does not return it"; } } _typeCache.put(name, result == null ? CACHED_NOT_FOUND : result); @@ -429,26 +381,25 @@ public class SchemaTypeLoaderImpl extend return result; } - public SchemaType typeForClassname(String classname) - { + public SchemaType typeForClassname(String classname) { classname = classname.replace('$', '.'); Object cached = _classnameCache.get(classname); - if (cached == CACHED_NOT_FOUND) + if (cached == CACHED_NOT_FOUND) { return null; + } SchemaType result = (SchemaType) cached; - if (result == null) - { - for (int i = 0; i < _searchPath.length; i++) - if (null != (result = _searchPath[i].typeForClassname(classname))) + if (result == null) { + for (SchemaTypeLoader schemaTypeLoader : _searchPath) { + if (null != (result = schemaTypeLoader.typeForClassname(classname))) { break; - if (result == null) - { + } + } + if (result == null) { SchemaTypeSystem ts = typeSystemForClassname(_metadataPath + "/javaname/", classname); - if (ts != null) - { + if (ts != null) { result = ts.typeForClassname(classname); - assert(result != null) : "Type system registered type " + classname + " but does not return it"; + assert (result != null) : "Type system registered type " + classname + " but does not return it"; } } _classnameCache.put(classname, result == null ? CACHED_NOT_FOUND : result); @@ -456,24 +407,23 @@ public class SchemaTypeLoaderImpl extend return result; } - public SchemaType.Ref findDocumentTypeRef(QName name) - { + public SchemaType.Ref findDocumentTypeRef(QName name) { Object cached = _documentCache.get(name); - if (cached == CACHED_NOT_FOUND) + if (cached == CACHED_NOT_FOUND) { return null; + } SchemaType.Ref result = (SchemaType.Ref) cached; - if (result == null) - { - for (int i = 0; i < _searchPath.length; i++) - if (null != (result = _searchPath[i].findDocumentTypeRef(name))) + if (result == null) { + for (SchemaTypeLoader schemaTypeLoader : _searchPath) { + if (null != (result = schemaTypeLoader.findDocumentTypeRef(name))) { break; - if (result == null) - { + } + } + if (result == null) { SchemaTypeSystem ts = typeSystemForComponent(_metadataPath + "/element/", name); - if (ts != null) - { + if (ts != null) { result = ts.findDocumentTypeRef(name); - assert(result != null) : "Type system registered element " + QNameHelper.pretty(name) + " but does not contain document type"; + assert (result != null) : "Type system registered element " + QNameHelper.pretty(name) + " but does not contain document type"; } } _documentCache.put(name, result == null ? CACHED_NOT_FOUND : result); @@ -481,24 +431,23 @@ public class SchemaTypeLoaderImpl extend return result; } - public SchemaType.Ref findAttributeTypeRef(QName name) - { + public SchemaType.Ref findAttributeTypeRef(QName name) { Object cached = _attributeTypeCache.get(name); - if (cached == CACHED_NOT_FOUND) + if (cached == CACHED_NOT_FOUND) { return null; + } SchemaType.Ref result = (SchemaType.Ref) cached; - if (result == null) - { - for (int i = 0; i < _searchPath.length; i++) - if (null != (result = _searchPath[i].findAttributeTypeRef(name))) + if (result == null) { + for (SchemaTypeLoader schemaTypeLoader : _searchPath) { + if (null != (result = schemaTypeLoader.findAttributeTypeRef(name))) { break; - if (result == null) - { + } + } + if (result == null) { SchemaTypeSystem ts = typeSystemForComponent(_metadataPath + "/attribute/", name); - if (ts != null) - { + if (ts != null) { result = ts.findAttributeTypeRef(name); - assert(result != null) : "Type system registered attribute " + QNameHelper.pretty(name) + " but does not contain attribute type"; + assert (result != null) : "Type system registered attribute " + QNameHelper.pretty(name) + " but does not contain attribute type"; } } _attributeTypeCache.put(name, result == null ? CACHED_NOT_FOUND : result); @@ -506,24 +455,23 @@ public class SchemaTypeLoaderImpl extend return result; } - public SchemaGlobalElement.Ref findElementRef(QName name) - { + public SchemaGlobalElement.Ref findElementRef(QName name) { Object cached = _elementCache.get(name); - if (cached == CACHED_NOT_FOUND) + if (cached == CACHED_NOT_FOUND) { return null; + } SchemaGlobalElement.Ref result = (SchemaGlobalElement.Ref) cached; - if (result == null) - { - for (int i = 0; i < _searchPath.length; i++) - if (null != (result = _searchPath[i].findElementRef(name))) + if (result == null) { + for (SchemaTypeLoader schemaTypeLoader : _searchPath) { + if (null != (result = schemaTypeLoader.findElementRef(name))) { break; - if (result == null) - { + } + } + if (result == null) { SchemaTypeSystem ts = typeSystemForComponent(_metadataPath + "/element/", name); - if (ts != null) - { + if (ts != null) { result = ts.findElementRef(name); - assert(result != null) : "Type system registered element " + QNameHelper.pretty(name) + " but does not return it"; + assert (result != null) : "Type system registered element " + QNameHelper.pretty(name) + " but does not return it"; } } _elementCache.put(name, result == null ? CACHED_NOT_FOUND : result); @@ -531,24 +479,23 @@ public class SchemaTypeLoaderImpl extend return result; } - public SchemaGlobalAttribute.Ref findAttributeRef(QName name) - { + public SchemaGlobalAttribute.Ref findAttributeRef(QName name) { Object cached = _attributeCache.get(name); - if (cached == CACHED_NOT_FOUND) + if (cached == CACHED_NOT_FOUND) { return null; + } SchemaGlobalAttribute.Ref result = (SchemaGlobalAttribute.Ref) cached; - if (result == null) - { - for (int i = 0; i < _searchPath.length; i++) - if (null != (result = _searchPath[i].findAttributeRef(name))) + if (result == null) { + for (SchemaTypeLoader schemaTypeLoader : _searchPath) { + if (null != (result = schemaTypeLoader.findAttributeRef(name))) { break; - if (result == null) - { + } + } + if (result == null) { SchemaTypeSystem ts = typeSystemForComponent(_metadataPath + "/attribute/", name); - if (ts != null) - { + if (ts != null) { result = ts.findAttributeRef(name); - assert(result != null) : "Type system registered attribute " + QNameHelper.pretty(name) + " but does not return it"; + assert (result != null) : "Type system registered attribute " + QNameHelper.pretty(name) + " but does not return it"; } } _attributeCache.put(name, result == null ? CACHED_NOT_FOUND : result); @@ -556,24 +503,23 @@ public class SchemaTypeLoaderImpl extend return result; } - public SchemaModelGroup.Ref findModelGroupRef(QName name) - { + public SchemaModelGroup.Ref findModelGroupRef(QName name) { Object cached = _modelGroupCache.get(name); - if (cached == CACHED_NOT_FOUND) + if (cached == CACHED_NOT_FOUND) { return null; + } SchemaModelGroup.Ref result = (SchemaModelGroup.Ref) cached; - if (result == null) - { - for (int i = 0; i < _searchPath.length; i++) - if (null != (result = _searchPath[i].findModelGroupRef(name))) + if (result == null) { + for (SchemaTypeLoader schemaTypeLoader : _searchPath) { + if (null != (result = schemaTypeLoader.findModelGroupRef(name))) { break; - if (result == null) - { + } + } + if (result == null) { SchemaTypeSystem ts = typeSystemForComponent(_metadataPath + "/modelgroup/", name); - if (ts != null) - { + if (ts != null) { result = ts.findModelGroupRef(name); - assert(result != null) : "Type system registered model group " + QNameHelper.pretty(name) + " but does not return it"; + assert (result != null) : "Type system registered model group " + QNameHelper.pretty(name) + " but does not return it"; } } _modelGroupCache.put(name, result == null ? CACHED_NOT_FOUND : result); @@ -581,24 +527,23 @@ public class SchemaTypeLoaderImpl extend return result; } - public SchemaAttributeGroup.Ref findAttributeGroupRef(QName name) - { + public SchemaAttributeGroup.Ref findAttributeGroupRef(QName name) { Object cached = _attributeGroupCache.get(name); - if (cached == CACHED_NOT_FOUND) + if (cached == CACHED_NOT_FOUND) { return null; + } SchemaAttributeGroup.Ref result = (SchemaAttributeGroup.Ref) cached; - if (result == null) - { - for (int i = 0; i < _searchPath.length; i++) - if (null != (result = _searchPath[i].findAttributeGroupRef(name))) + if (result == null) { + for (SchemaTypeLoader schemaTypeLoader : _searchPath) { + if (null != (result = schemaTypeLoader.findAttributeGroupRef(name))) { break; - if (result == null) - { + } + } + if (result == null) { SchemaTypeSystem ts = typeSystemForComponent(_metadataPath + "/attributegroup/", name); - if (ts != null) - { + if (ts != null) { result = ts.findAttributeGroupRef(name); - assert(result != null) : "Type system registered attribute group " + QNameHelper.pretty(name) + " but does not return it"; + assert (result != null) : "Type system registered attribute group " + QNameHelper.pretty(name) + " but does not return it"; } } _attributeGroupCache.put(name, result == null ? CACHED_NOT_FOUND : result); @@ -606,24 +551,23 @@ public class SchemaTypeLoaderImpl extend return result; } - public SchemaIdentityConstraint.Ref findIdentityConstraintRef(QName name) - { + public SchemaIdentityConstraint.Ref findIdentityConstraintRef(QName name) { Object cached = _idConstraintCache.get(name); - if (cached == CACHED_NOT_FOUND) + if (cached == CACHED_NOT_FOUND) { return null; + } SchemaIdentityConstraint.Ref result = (SchemaIdentityConstraint.Ref) cached; - if (result == null) - { - for (int i = 0; i < _searchPath.length; i++) - if (null != (result = _searchPath[i].findIdentityConstraintRef(name))) + if (result == null) { + for (SchemaTypeLoader schemaTypeLoader : _searchPath) { + if (null != (result = schemaTypeLoader.findIdentityConstraintRef(name))) { break; - if (result == null) - { + } + } + if (result == null) { SchemaTypeSystem ts = typeSystemForComponent(_metadataPath + "/identityconstraint/", name); - if (ts != null) - { + if (ts != null) { result = ts.findIdentityConstraintRef(name); - assert(result != null) : "Type system registered identity constraint " + QNameHelper.pretty(name) + " but does not return it"; + assert (result != null) : "Type system registered identity constraint " + QNameHelper.pretty(name) + " but does not return it"; } } _idConstraintCache.put(name, result == null ? CACHED_NOT_FOUND : result); @@ -631,27 +575,29 @@ public class SchemaTypeLoaderImpl extend return result; } - public InputStream getSourceAsStream(String sourceName) - { + public InputStream getSourceAsStream(String sourceName) { InputStream result = null; - if (!sourceName.startsWith("/")) + if (!sourceName.startsWith("/")) { sourceName = "/" + sourceName; + } - if (_resourceLoader != null) + if (_resourceLoader != null) { result = _resourceLoader.getResourceAsStream(_metadataPath + "/src" + sourceName); + } - if (result == null && _classLoader != null) + if (result == null && _classLoader != null) { return _classLoader.getResourceAsStream(_metadataPath + "/src" + sourceName); + } return result; } private static final SchemaTypeLoader[] EMPTY_SCHEMATYPELOADER_ARRAY = new SchemaTypeLoader[0]; - static - { - if (SystemCache.get() instanceof SystemCache) + static { + if (SystemCache.get() != null) { SystemCache.set(new SchemaTypeLoaderCache()); + } } }
Modified: xmlbeans/trunk/src/main/java/org/apache/xmlbeans/impl/store/Cur.java URL: http://svn.apache.org/viewvc/xmlbeans/trunk/src/main/java/org/apache/xmlbeans/impl/store/Cur.java?rev=1881992&r1=1881991&r2=1881992&view=diff ============================================================================== --- xmlbeans/trunk/src/main/java/org/apache/xmlbeans/impl/store/Cur.java (original) +++ xmlbeans/trunk/src/main/java/org/apache/xmlbeans/impl/store/Cur.java Thu Sep 24 23:11:07 2020 @@ -28,6 +28,8 @@ import javax.xml.namespace.QName; import java.io.PrintStream; import java.util.Map; +import static org.apache.xmlbeans.impl.values.TypeStore.WS_PRESERVE; + // DOM Level 3 @@ -2303,7 +2305,7 @@ public final class Cur { String getCharsAsString() { assert isNormal() && _xobj != null; - return getCharsAsString(Locale.WS_PRESERVE); + return getCharsAsString(WS_PRESERVE); } String getCharsAsString(int wsr) { @@ -3190,8 +3192,8 @@ public final class Cur { private final boolean _stripWhitespace; private final boolean _stripComments; private final boolean _stripProcinsts; - private final Map<String,String> _substituteNamespaces; - private final Map<String,String> _additionalNamespaces; + private final Map<String, String> _substituteNamespaces; + private final Map<String, String> _additionalNamespaces; private String _doctypeName; private String _doctypePublicId; Modified: xmlbeans/trunk/src/main/java/org/apache/xmlbeans/impl/store/Cursor.java URL: http://svn.apache.org/viewvc/xmlbeans/trunk/src/main/java/org/apache/xmlbeans/impl/store/Cursor.java?rev=1881992&r1=1881991&r2=1881992&view=diff ============================================================================== --- xmlbeans/trunk/src/main/java/org/apache/xmlbeans/impl/store/Cursor.java (original) +++ xmlbeans/trunk/src/main/java/org/apache/xmlbeans/impl/store/Cursor.java Thu Sep 24 23:11:07 2020 @@ -37,6 +37,8 @@ import java.util.Collection; import java.util.Map; import java.util.function.Supplier; +import static org.apache.xmlbeans.impl.values.TypeStore.WS_PRESERVE; + public final class Cursor implements XmlCursor, ChangeListener { static final int ROOT = Cur.ROOT; static final int ELEM = Cur.ELEM; @@ -1047,7 +1049,7 @@ public final class Cursor implements Xml // If there are no children (hopefully the common case), I can get the text faster. if (_cur.hasChildren()) { - return Locale.getTextValue(_cur, Locale.WS_PRESERVE, chars, offset, max); + return Locale.getTextValue(_cur, WS_PRESERVE, chars, offset, max); } // Fast way Modified: xmlbeans/trunk/src/main/java/org/apache/xmlbeans/impl/store/Locale.java URL: http://svn.apache.org/viewvc/xmlbeans/trunk/src/main/java/org/apache/xmlbeans/impl/store/Locale.java?rev=1881992&r1=1881991&r2=1881992&view=diff ============================================================================== --- xmlbeans/trunk/src/main/java/org/apache/xmlbeans/impl/store/Locale.java (original) +++ xmlbeans/trunk/src/main/java/org/apache/xmlbeans/impl/store/Locale.java Thu Sep 24 23:11:07 2020 @@ -21,8 +21,6 @@ import org.apache.xmlbeans.impl.common.* import org.apache.xmlbeans.impl.store.Cur.Locations; import org.apache.xmlbeans.impl.store.DomImpl.Dom; import org.apache.xmlbeans.impl.store.Saaj.SaajCallback; -import org.apache.xmlbeans.impl.values.TypeStore; -import org.apache.xmlbeans.xml.stream.XMLEvent; import org.w3c.dom.*; import org.xml.sax.*; import org.xml.sax.ext.DeclHandler; @@ -40,6 +38,9 @@ import java.lang.ref.ReferenceQueue; import java.lang.ref.SoftReference; import java.util.HashMap; import java.util.Map; +import java.util.Objects; + +import static org.apache.xmlbeans.impl.values.TypeStore.*; public final class Locale implements DOMImplementation, SaajCallback, XmlLocale { @@ -52,11 +53,6 @@ public final class Locale static final int PROCINST = Cur.PROCINST; static final int TEXT = Cur.TEXT; - static final int WS_UNSPECIFIED = TypeStore.WS_UNSPECIFIED; - static final int WS_PRESERVE = TypeStore.WS_PRESERVE; - static final int WS_REPLACE = TypeStore.WS_REPLACE; - static final int WS_COLLAPSE = TypeStore.WS_COLLAPSE; - static final String _xsi = "http://www.w3.org/2001/XMLSchema-instance"; static final String _schema = "http://www.w3.org/2001/XMLSchema"; static final String _openFragUri = "http://www.openuri.org/fragment"; @@ -286,15 +282,7 @@ public final class Locale return false; } - if (n1.getNamespaceURI() == n2.getNamespaceURI()) { - return true; - } - - if (n1.getNamespaceURI() == null || n2.getNamespaceURI() == null) { - return false; - } - - return n1.getNamespaceURI().equals(n2.getNamespaceURI()); + return Objects.equals(n1.getNamespaceURI(), n2.getNamespaceURI()); } private static void addNamespace(StringBuffer sb, QName name) { @@ -341,12 +329,12 @@ public final class Locale sb.append(" got "); addNamespace(sb, name); } else if (namespacesSame(docElemName, name)) { - sb.append(": document element local name mismatch "); - sb.append("expected " + docElemName.getLocalPart()); - sb.append(" got " + name.getLocalPart()); + sb.append(": document element local name mismatch expected ") + .append(docElemName.getLocalPart()) + .append(" got ") + .append(name.getLocalPart()); } else { - sb.append(": document element mismatch "); - sb.append("got "); + sb.append(": document element mismatch got "); sb.append(QNameHelper.pretty(name)); } } @@ -448,8 +436,6 @@ public final class Locale // Move to next token - assert k != ATTR; - if (k != TEXT) { start.toEnd(); } @@ -521,7 +507,7 @@ public final class Locale public static DOMImplementation newDomImplementation(SchemaTypeLoader stl, XmlOptions options) { - return (DOMImplementation) getLocale(stl, options); + return getLocale(stl, options); } // @@ -566,9 +552,8 @@ public final class Locale Cur parse(String s, SchemaType type, XmlOptions options) throws XmlException { - Reader r = new StringReader(s); - try { + try (Reader r = new StringReader(s)) { Cur c = getSaxLoader(options).load(this, new InputSource(r), options); @@ -579,11 +564,6 @@ public final class Locale assert false : "StringReader should not throw IOException"; throw new XmlException(e.getMessage(), e); - } finally { - try { - r.close(); - } catch (IOException e) { - } } } @@ -640,14 +620,6 @@ public final class Locale return x; } - private static void lineNumber(XMLEvent xe, LoadContext context) { - org.apache.xmlbeans.xml.stream.Location loc = xe.getLocation(); - - if (loc != null) { - context.lineNumber(loc.getLineNumber(), loc.getColumnNumber(), -1); - } - } - private static void lineNumber(XMLStreamReader xsr, LoadContext context) { javax.xml.stream.Location loc = xsr.getLocation(); @@ -1037,7 +1009,7 @@ public final class Locale // // - private class XmlSaxHandlerImpl + private static class XmlSaxHandlerImpl extends SaxHandler implements XmlSaxHandler { XmlSaxHandlerImpl(Locale l, SchemaType type, XmlOptions options) { @@ -1096,8 +1068,8 @@ public final class Locale } } - private SchemaType _type; - private XmlOptions _options; + private final SchemaType _type; + private final XmlOptions _options; } public static XmlSaxHandler newSaxHandler(SchemaTypeLoader stl, @@ -1163,7 +1135,7 @@ public final class Locale static private class DocProps extends XmlDocumentProperties { - private HashMap _map = new HashMap(); + private final HashMap<Object, Object> _map = new HashMap<>(); public Object put(Object key, Object value) { return _map.put(key, value); @@ -1182,7 +1154,6 @@ public final class Locale c.push(); while (c.toParent()) { - ; } DocProps props = (DocProps) c.getBookmark(DocProps.class); @@ -1305,7 +1276,7 @@ public final class Locale return processWhiteSpaceRule(s, wsr); } } - } else if (wsr == Locale.WS_COLLAPSE) { + } else if (wsr == WS_COLLAPSE) { if (CharUtil.isWhiteSpace(s.charAt(0)) || CharUtil.isWhiteSpace(s.charAt(l - 1))) { return processWhiteSpaceRule(s, wsr); @@ -1352,7 +1323,7 @@ public final class Locale return; } - if (_wsr == Locale.WS_PRESERVE) { + if (_wsr == WS_PRESERVE) { CharUtil.getString(_sb, src, off, cch); return; } @@ -1384,7 +1355,7 @@ public final class Locale start = i + 1; - if (_wsr == Locale.WS_REPLACE) { + if (_wsr == WS_REPLACE) { _sb.append(' '); } else if (_state == NOSPACE_STATE) { _state = SPACE_SEEN_STATE; @@ -1414,26 +1385,22 @@ public final class Locale private int _wsr; private char[] _srcBuf = new char[1024]; - private StringBuffer _sb; + private final StringBuffer _sb; } - private static ThreadLocal tl_scrubBuffer = - new ThreadLocal() { - protected Object initialValue() { - return new SoftReference(new ScrubBuffer()); - } - }; + private static final ThreadLocal<SoftReference<ScrubBuffer>> tl_scrubBuffer = + ThreadLocal.withInitial(() -> new SoftReference<>(new ScrubBuffer())); public static void clearThreadLocals() { tl_scrubBuffer.remove(); } static ScrubBuffer getScrubBuffer(int wsr) { - SoftReference softRef = (SoftReference) tl_scrubBuffer.get(); - ScrubBuffer scrubBuffer = (ScrubBuffer) (softRef).get(); + SoftReference<ScrubBuffer> softRef = tl_scrubBuffer.get(); + ScrubBuffer scrubBuffer = softRef.get(); if (scrubBuffer == null) { scrubBuffer = new ScrubBuffer(); - tl_scrubBuffer.set(new SoftReference(scrubBuffer)); + tl_scrubBuffer.set(new SoftReference<>(scrubBuffer)); } scrubBuffer.init(wsr); @@ -1756,14 +1723,10 @@ public final class Locale return false; } - static void applyNamespaces(Cur c, Map namespaces) { + static void applyNamespaces(Cur c, Map<String, String> namespaces) { assert c.isContainer(); - java.util.Iterator i = namespaces.keySet().iterator(); - - while (i.hasNext()) { - String prefix = (String) i.next(); - + for (String prefix : namespaces.keySet()) { // Usually, this is the predefined xml namespace if (!prefix.toLowerCase().startsWith("xml")) { if (c.namespaceForPrefix(prefix, false) == null) { @@ -1773,7 +1736,7 @@ public final class Locale c.createAttr(c._locale.createXmlns(prefix)); c.next(); - c.insertString((String) namespaces.get(prefix)); + c.insertString(namespaces.get(prefix)); c.pop(); } Modified: xmlbeans/trunk/src/main/java/org/apache/xmlbeans/impl/store/Xobj.java URL: http://svn.apache.org/viewvc/xmlbeans/trunk/src/main/java/org/apache/xmlbeans/impl/store/Xobj.java?rev=1881992&r1=1881991&r2=1881992&view=diff ============================================================================== --- xmlbeans/trunk/src/main/java/org/apache/xmlbeans/impl/store/Xobj.java (original) +++ xmlbeans/trunk/src/main/java/org/apache/xmlbeans/impl/store/Xobj.java Thu Sep 24 23:11:07 2020 @@ -1114,7 +1114,7 @@ abstract class Xobj implements TypeStore Object src = getChars(p, cch); - if (wsr == Locale.WS_PRESERVE) { + if (wsr == WS_PRESERVE) { return CharUtil.getString(src, _locale._offSrc, _locale._cchSrc); } @@ -1130,20 +1130,18 @@ abstract class Xobj implements TypeStore if (offset == posMax()) { offset = -1; } - return getCharsAsString(offset, cch, - Locale.WS_PRESERVE); + return getCharsAsString(offset, cch, WS_PRESERVE); } String getCharsValueAsString(int off, int cch) { - return getCharsAsString(off + 1, cch, - Locale.WS_PRESERVE); + return getCharsAsString(off + 1, cch, WS_PRESERVE); } String getValueAsString(int wsr) { if (!hasChildren()) { Object src = getFirstChars(); - if (wsr == Locale.WS_PRESERVE) { + if (wsr == WS_PRESERVE) { String s = CharUtil.getString(src, _locale._offSrc, _locale._cchSrc); // Cache string to be able to use it later again @@ -1200,7 +1198,7 @@ abstract class Xobj implements TypeStore } String getValueAsString() { - return getValueAsString(Locale.WS_PRESERVE); + return getValueAsString(WS_PRESERVE); } // Returns just chars just after the begin tag ... does not get all the text if there are @@ -1537,7 +1535,7 @@ abstract class Xobj implements TypeStore // when I make the store capable of handling strong simple types this // can be done ... - String value = getValueAsString(Locale.WS_COLLAPSE); + String value = getValueAsString(WS_COLLAPSE); String prefix, localname; @@ -1930,7 +1928,7 @@ abstract class Xobj implements TypeStore return false; } - String value = a.getValueAsString(Locale.WS_COLLAPSE); + String value = a.getValueAsString(WS_COLLAPSE); return value.equals("true") || value.equals("1"); } finally { @@ -1989,17 +1987,17 @@ abstract class Xobj implements TypeStore public <T extends XmlObject> void find_all_element_users(QName name, List<T> fillMeUp) { for (Xobj x = _firstChild; x != null; x = x._nextSibling) { if (x.isElem() && x._name.equals(name)) { - fillMeUp.add((T)x.getUser()); + fillMeUp.add((T) x.getUser()); } } } @SuppressWarnings("unchecked") @Override - public <T extends XmlObject> void find_all_element_users(QNameSet names, List<T> fillMeUp) { + public <T extends XmlObject> void find_all_element_users(QNameSet names, List<T> fillMeUp) { for (Xobj x = _firstChild; x != null; x = x._nextSibling) { if (x.isElem() && names.contains(x._name)) { - fillMeUp.add((T)x.getUser()); + fillMeUp.add((T) x.getUser()); } } } @@ -2345,9 +2343,9 @@ abstract class Xobj implements TypeStore find_all_element_users(elementName, elementsUser); List<Xobj> elements = elementsUser.stream() - .map(x -> (TypeStoreUser)x) + .map(x -> (TypeStoreUser) x) .map(TypeStoreUser::get_store) - .map(x -> (Xobj)x) + .map(x -> (Xobj) x) .collect(Collectors.toList()); assert elements.size() == n; Modified: xmlbeans/trunk/src/main/java/org/apache/xmlbeans/impl/tool/BaseSchemaResourceManager.java URL: http://svn.apache.org/viewvc/xmlbeans/trunk/src/main/java/org/apache/xmlbeans/impl/tool/BaseSchemaResourceManager.java?rev=1881992&r1=1881991&r2=1881992&view=diff ============================================================================== --- xmlbeans/trunk/src/main/java/org/apache/xmlbeans/impl/tool/BaseSchemaResourceManager.java (original) +++ xmlbeans/trunk/src/main/java/org/apache/xmlbeans/impl/tool/BaseSchemaResourceManager.java Thu Sep 24 23:11:07 2020 @@ -15,23 +15,20 @@ package org.apache.xmlbeans.impl.tool; -import org.apache.xmlbeans.impl.xb.xsdownload.DownloadedSchemasDocument; +import org.apache.xmlbeans.XmlBeans; +import org.apache.xmlbeans.XmlOptions; +import org.apache.xmlbeans.impl.common.IOUtil; +import org.apache.xmlbeans.impl.util.HexBin; import org.apache.xmlbeans.impl.xb.xsdownload.DownloadedSchemaEntry; +import org.apache.xmlbeans.impl.xb.xsdownload.DownloadedSchemasDocument; import org.apache.xmlbeans.impl.xb.xsdownload.DownloadedSchemasDocument.DownloadedSchemas; -import org.apache.xmlbeans.impl.util.HexBin; -import org.apache.xmlbeans.impl.common.IOUtil; -import org.apache.xmlbeans.XmlOptions; -import org.apache.xmlbeans.XmlBeans; +import org.apache.xmlbeans.impl.xb.xsdschema.SchemaDocument; +import org.apache.xmlbeans.impl.xb.xsdschema.SchemaDocument.Schema; +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; -import java.io.ByteArrayOutputStream; -import java.io.ByteArrayInputStream; -import java.util.Set; -import java.util.HashSet; -import java.util.Iterator; -import java.util.Map; -import java.util.HashMap; import java.net.URI; import java.net.URISyntaxException; import java.net.URL; @@ -39,146 +36,121 @@ import java.net.URLConnection; import java.security.DigestInputStream; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; -import org.apache.xmlbeans.impl.xb.xsdschema.SchemaDocument.Schema; -import org.apache.xmlbeans.impl.xb.xsdschema.SchemaDocument; - -public abstract class BaseSchemaResourceManager extends SchemaImportResolver -{ +public abstract class BaseSchemaResourceManager extends SchemaImportResolver { private static final String USER_AGENT = "XMLBeans/" + XmlBeans.getVersion() + " (" + XmlBeans.getTitle() + ")"; private String _defaultCopyDirectory; private DownloadedSchemasDocument _importsDoc; - private Map _resourceForFilename = new HashMap(); - private Map _resourceForURL = new HashMap(); - private Map _resourceForNamespace = new HashMap(); - private Map _resourceForDigest = new HashMap(); - private Map _resourceForCacheEntry = new HashMap(); - private Set _redownloadSet = new HashSet(); + private final Map<String, SchemaResource> _resourceForFilename = new HashMap<>(); + private final Map<String, SchemaResource> _resourceForURL = new HashMap<>(); + private final Map<String, SchemaResource> _resourceForNamespace = new HashMap<>(); + private final Map<String, SchemaResource> _resourceForDigest = new HashMap<>(); + private final Map<DownloadedSchemaEntry, SchemaResource> _resourceForCacheEntry = new HashMap<>(); + private Set<SchemaResource> _redownloadSet = new HashSet<>(); - protected BaseSchemaResourceManager() - { + protected BaseSchemaResourceManager() { // concrete subclasses should call init in their constructors } - protected final void init() - { - if (fileExists(getIndexFilename())) - { - try - { - _importsDoc = DownloadedSchemasDocument.Factory.parse( inputStreamForFile( getIndexFilename() ) ); - } - catch (IOException e) - { + protected final void init() { + if (fileExists(getIndexFilename())) { + try { + _importsDoc = DownloadedSchemasDocument.Factory.parse(inputStreamForFile(getIndexFilename())); + } catch (IOException e) { _importsDoc = null; - } - catch (Exception e) - { - throw (IllegalStateException)(new IllegalStateException("Problem reading xsdownload.xml: please fix or delete this file")).initCause(e); + } catch (Exception e) { + throw new IllegalStateException("Problem reading xsdownload.xml: please fix or delete this file", e); } } - if (_importsDoc == null) - { - try - { + if (_importsDoc == null) { + try { _importsDoc = DownloadedSchemasDocument.Factory.parse( "<dls:downloaded-schemas xmlns:dls='http://www.bea.com/2003/01/xmlbean/xsdownload' defaultDirectory='" + getDefaultSchemaDir() + "'/>" ); - } - catch (Exception e) - { - throw (IllegalStateException)(new IllegalStateException()).initCause(e); + } catch (Exception e) { + throw new IllegalStateException(e); } } String defaultDir = _importsDoc.getDownloadedSchemas().getDefaultDirectory(); - if (defaultDir == null) - defaultDir = getDefaultSchemaDir();; + if (defaultDir == null) { + defaultDir = getDefaultSchemaDir(); + } _defaultCopyDirectory = defaultDir; // now initialize data structures DownloadedSchemaEntry[] entries = _importsDoc.getDownloadedSchemas().getEntryArray(); - for (int i = 0; i < entries.length; i++) - { - updateResource(entries[i]); + for (DownloadedSchemaEntry entry : entries) { + updateResource(entry); } } - public final void writeCache() throws IOException - { + public final void writeCache() throws IOException { InputStream input = _importsDoc.newInputStream(new XmlOptions().setSavePrettyPrint()); writeInputStreamToFile(input, getIndexFilename()); } - public final void processAll(boolean sync, boolean refresh, boolean imports) - { - if (refresh) - { - _redownloadSet = new HashSet(); - } - else - { - _redownloadSet = null; - } + public final void processAll(boolean sync, boolean refresh, boolean imports) { + _redownloadSet = refresh ? new HashSet<>() : null; String[] allFilenames = getAllXSDFilenames(); - if (sync) + if (sync) { syncCacheWithLocalXsdFiles(allFilenames, false); + } - SchemaResource[] starters = (SchemaResource[]) - _resourceForFilename.values().toArray(new SchemaResource[0]); + SchemaResource[] starters = _resourceForFilename.values().toArray(new SchemaResource[0]); - if (refresh) + if (refresh) { redownloadEntries(starters); + } - if (imports) + if (imports) { resolveImports(starters); + } _redownloadSet = null; } - public final void process(String[] uris, String[] filenames, boolean sync, boolean refresh, boolean imports) - { - if (refresh) - { - _redownloadSet = new HashSet(); - } - else - { - _redownloadSet = null; - } + public final void process(String[] uris, String[] filenames, boolean sync, boolean refresh, boolean imports) { + _redownloadSet = refresh ? new HashSet<>() : null; - if (filenames.length > 0) + if (filenames.length > 0) { syncCacheWithLocalXsdFiles(filenames, true); - else if (sync) + } else if (sync) { syncCacheWithLocalXsdFiles(getAllXSDFilenames(), false); + } - Set starterset = new HashSet(); + Set<SchemaResource> starterset = new HashSet<>(); - for (int i = 0; i < uris.length; i++) - { - SchemaResource resource = (SchemaResource)lookupResource(null, uris[i]); - if (resource != null) + for (String s : uris) { + SchemaResource resource = (SchemaResource) lookupResource(null, s); + if (resource != null) { starterset.add(resource); + } } - for (int i = 0; i < filenames.length; i++) - { - SchemaResource resource = (SchemaResource)_resourceForFilename.get(filenames); - if (resource != null) + for (String filename : filenames) { + SchemaResource resource = _resourceForFilename.get(filename); + if (resource != null) { starterset.add(resource); + } } - SchemaResource[] starters = (SchemaResource[]) - starterset.toArray(new SchemaResource[0]); + SchemaResource[] starters = starterset.toArray(new SchemaResource[0]); - if (refresh) + if (refresh) { redownloadEntries(starters); + } - if (imports) + if (imports) { resolveImports(starters); + } _redownloadSet = null; } @@ -186,56 +158,49 @@ public abstract class BaseSchemaResource /** * Adds items to the cache that point to new files that aren't * described in the cache, and optionally deletes old entries. - * + * <p> * If an old file is gone and a new file is * found with exactly the same contents, the cache entry is moved * to point to the new file. */ - public final void syncCacheWithLocalXsdFiles(String[] filenames, boolean deleteOnlyMentioned) - { - Set seenResources = new HashSet(); - Set vanishedResources = new HashSet(); - - for (int i = 0; i < filenames.length; i++) - { - String filename = filenames[i]; + public final void syncCacheWithLocalXsdFiles(String[] filenames, boolean deleteOnlyMentioned) { + Set<SchemaResource> seenResources = new HashSet<>(); + Set<SchemaResource> vanishedResources = new HashSet<>(); + for (String filename : filenames) { // first, if the filename matches exactly, trust the filename - SchemaResource resource = (SchemaResource)_resourceForFilename.get(filename); - if (resource != null) - { - if (fileExists(filename)) + SchemaResource resource = _resourceForFilename.get(filename); + if (resource != null) { + if (fileExists(filename)) { seenResources.add(resource); - else + } else { vanishedResources.add(resource); + } continue; } // new file that is not in the index? // not if the digest is known to the index and the original file is gone - that's a rename! String digest = null; - try - { + try { digest = shaDigestForFile(filename); - resource = (SchemaResource)_resourceForDigest.get(digest); - if (resource != null) - { + resource = _resourceForDigest.get(digest); + if (resource != null) { String oldFilename = resource.getFilename(); - if (!fileExists(oldFilename)) - { + if (!fileExists(oldFilename)) { warning("File " + filename + " is a rename of " + oldFilename); resource.setFilename(filename); seenResources.add(resource); - if (_resourceForFilename.get(oldFilename) == resource) + if (_resourceForFilename.get(oldFilename) == resource) { _resourceForFilename.remove(oldFilename); - if (_resourceForFilename.containsKey(filename)) + } + if (_resourceForFilename.containsKey(filename)) { _resourceForFilename.put(filename, resource); + } continue; } } - } - catch (IOException e) - { + } catch (IOException e) { // unable to read digest... no problem, ignore then } @@ -243,68 +208,65 @@ public abstract class BaseSchemaResource DownloadedSchemaEntry newEntry = addNewEntry(); newEntry.setFilename(filename); warning("Caching information on new local file " + filename); - if (digest != null) + if (digest != null) { newEntry.setSha1(digest); + } seenResources.add(updateResource(newEntry)); } - if (deleteOnlyMentioned) + if (deleteOnlyMentioned) { deleteResourcesInSet(vanishedResources, true); - else + } else { deleteResourcesInSet(seenResources, false); + } } /** * Iterates through every entry and refetches it from its primary URL, * if known. Replaces the contents of the file if the data is different. */ - private void redownloadEntries(SchemaResource[] resources) - { - for (int i = 0; i < resources.length; i++) - { - redownloadResource(resources[i]); + private void redownloadEntries(SchemaResource[] resources) { + for (SchemaResource resource : resources) { + redownloadResource(resource); } } - private void deleteResourcesInSet(Set seenResources, boolean setToDelete) - { - Set seenCacheEntries = new HashSet(); - for (Iterator i = seenResources.iterator(); i.hasNext(); ) - { - SchemaResource resource = (SchemaResource)i.next(); + private void deleteResourcesInSet(Set<SchemaResource> seenResources, boolean setToDelete) { + Set<DownloadedSchemaEntry> seenCacheEntries = new HashSet<>(); + for (SchemaResource resource : seenResources) { seenCacheEntries.add(resource._cacheEntry); } DownloadedSchemas downloadedSchemas = _importsDoc.getDownloadedSchemas(); - for (int i = 0; i < downloadedSchemas.sizeOfEntryArray(); i++) - { + for (int i = 0; i < downloadedSchemas.sizeOfEntryArray(); i++) { DownloadedSchemaEntry cacheEntry = downloadedSchemas.getEntryArray(i); - if (seenCacheEntries.contains(cacheEntry) == setToDelete) - { - SchemaResource resource = (SchemaResource)_resourceForCacheEntry.get(cacheEntry); - warning("Removing obsolete cache entry for " + resource.getFilename()); + if (seenCacheEntries.contains(cacheEntry) == setToDelete) { + SchemaResource resource = _resourceForCacheEntry.get(cacheEntry); - if (resource != null) - { + if (resource != null) { + warning("Removing obsolete cache entry for " + resource.getFilename()); _resourceForCacheEntry.remove(cacheEntry); - if (resource == _resourceForFilename.get(resource.getFilename())) + if (resource == _resourceForFilename.get(resource.getFilename())) { _resourceForFilename.remove(resource.getFilename()); + } - if (resource == _resourceForDigest.get(resource.getSha1())) + if (resource == _resourceForDigest.get(resource.getSha1())) { _resourceForDigest.remove(resource.getSha1()); + } - if (resource == _resourceForNamespace.get(resource.getNamespace())) + if (resource == _resourceForNamespace.get(resource.getNamespace())) { _resourceForNamespace.remove(resource.getNamespace()); + } // Finally, any or all URIs String[] urls = resource.getSchemaLocationArray(); - for (int j = 0; j < urls.length; j++) - { - if (resource == _resourceForURL.get(urls[j])) - _resourceForURL.remove(urls[j]); + for (String url : urls) { + if (resource == _resourceForURL.get(url)) { + _resourceForURL.remove(url); + } } } @@ -314,141 +276,130 @@ public abstract class BaseSchemaResource } } - private SchemaResource updateResource(DownloadedSchemaEntry entry) - { + private SchemaResource updateResource(DownloadedSchemaEntry entry) { // The file String filename = entry.getFilename(); - if (filename == null) + if (filename == null) { return null; + } SchemaResource resource = new SchemaResource(entry); _resourceForCacheEntry.put(entry, resource); - if (!_resourceForFilename.containsKey(filename)) + if (!_resourceForFilename.containsKey(filename)) { _resourceForFilename.put(filename, resource); + } // The digest String digest = resource.getSha1(); - if (digest != null) - { - if (!_resourceForDigest.containsKey(digest)) + if (digest != null) { + if (!_resourceForDigest.containsKey(digest)) { _resourceForDigest.put(digest, resource); + } } // Next, the namespace String namespace = resource.getNamespace(); - if (namespace != null) - { - if (!_resourceForNamespace.containsKey(namespace)) + if (namespace != null) { + if (!_resourceForNamespace.containsKey(namespace)) { _resourceForNamespace.put(namespace, resource); + } } // Finally, any or all URIs String[] urls = resource.getSchemaLocationArray(); - for (int j = 0; j < urls.length; j++) - { - if (!_resourceForURL.containsKey(urls[j])) - _resourceForURL.put(urls[j], resource); + for (String url : urls) { + if (!_resourceForURL.containsKey(url)) { + _resourceForURL.put(url, resource); + } } return resource; } - private static DigestInputStream digestInputStream(InputStream input) - { + private static DigestInputStream digestInputStream(InputStream input) { MessageDigest sha; - try - { + try { sha = MessageDigest.getInstance("SHA"); + } catch (NoSuchAlgorithmException e) { + throw new IllegalStateException(e); } - catch (NoSuchAlgorithmException e) - { - throw (IllegalStateException)(new IllegalStateException().initCause(e)); - } - - DigestInputStream str = new DigestInputStream(input, sha); - return str; + return new DigestInputStream(input, sha); } - private DownloadedSchemaEntry addNewEntry() - { + private DownloadedSchemaEntry addNewEntry() { return _importsDoc.getDownloadedSchemas().addNewEntry(); } - private class SchemaResource implements SchemaImportResolver.SchemaResource - { - SchemaResource(DownloadedSchemaEntry entry) - { + private class SchemaResource implements SchemaImportResolver.SchemaResource { + SchemaResource(DownloadedSchemaEntry entry) { _cacheEntry = entry; } DownloadedSchemaEntry _cacheEntry; - public void setFilename(String filename) - { + public void setFilename(String filename) { _cacheEntry.setFilename(filename); } - public String getFilename() - { + public String getFilename() { return _cacheEntry.getFilename(); } - public Schema getSchema() - { - if (!fileExists(getFilename())) + public Schema getSchema() { + if (!fileExists(getFilename())) { redownloadResource(this); + } - try - { + try { return SchemaDocument.Factory.parse(inputStreamForFile(getFilename())).getSchema(); - } - catch (Exception e) - { + } catch (Exception e) { return null; // return null if _any_ problems reading schema file } } - public String getSha1() - { + public String getSha1() { return _cacheEntry.getSha1(); } - public String getNamespace() - { + public String getNamespace() { return _cacheEntry.getNamespace(); } - public void setNamespace(String namespace) - { + public void setNamespace(String namespace) { _cacheEntry.setNamespace(namespace); } - public String getSchemaLocation() - { - if (_cacheEntry.sizeOfSchemaLocationArray() > 0) + public String getSchemaLocation() { + if (_cacheEntry.sizeOfSchemaLocationArray() > 0) { return _cacheEntry.getSchemaLocationArray(0); + } return null; } - public String[] getSchemaLocationArray() - { + public String[] getSchemaLocationArray() { return _cacheEntry.getSchemaLocationArray(); } - public int hashCode() - { + public int hashCode() { return getFilename().hashCode(); } - public boolean equals(Object obj) - { - return this == obj || getFilename().equals(((SchemaResource)obj).getFilename()); + public boolean equals(Object obj) { + if (this == obj) { + return true; + } + + if (!(obj instanceof SchemaResource)) { + return false; + } + + SchemaResource sr = (SchemaResource) obj; + return getFilename().equals(sr.getFilename()); } - public void addSchemaLocation(String schemaLocation) - { + public void addSchemaLocation(String schemaLocation) { _cacheEntry.addSchemaLocation(schemaLocation); } } @@ -458,74 +409,72 @@ public abstract class BaseSchemaResource * given import. Should return a SchemaResource whose * "equals" relationship reveals when a SchemaResource is * duplicated and shouldn't be examined again. - * + * <p> * Returns null if the resource reference should be ignored. */ - public SchemaImportResolver.SchemaResource lookupResource(String nsURI, String schemaLocation) - { + public SchemaImportResolver.SchemaResource lookupResource(String nsURI, String schemaLocation) { SchemaResource result = fetchFromCache(nsURI, schemaLocation); - if (result != null) - { - if (_redownloadSet != null) - { + if (result != null) { + if (_redownloadSet != null) { redownloadResource(result); } return result; } - if (schemaLocation == null) - { + if (schemaLocation == null) { warning("No cached schema for namespace '" + nsURI + "', and no url specified"); return null; } result = copyOrIdentifyDuplicateURL(schemaLocation, nsURI); - if (_redownloadSet != null) + if (_redownloadSet != null) { _redownloadSet.add(result); + } return result; } - private SchemaResource fetchFromCache(String nsURI, String schemaLocation) - { + private SchemaResource fetchFromCache(String nsURI, String schemaLocation) { SchemaResource result; - if (schemaLocation != null) - { - result = (SchemaResource)_resourceForURL.get(schemaLocation); - if (result != null) + if (schemaLocation != null) { + result = _resourceForURL.get(schemaLocation); + if (result != null) { return result; + } } - if (nsURI != null) - { - result = (SchemaResource)_resourceForNamespace.get(nsURI); - if (result != null) + if (nsURI != null) { + result = _resourceForNamespace.get(nsURI); + if (result != null) { return result; + } } return null; } - private String uniqueFilenameForURI(String schemaLocation) throws IOException, URISyntaxException - { - String localFilename = new URI( schemaLocation ).getRawPath(); + private String uniqueFilenameForURI(String schemaLocation) throws IOException, URISyntaxException { + String localFilename = new URI(schemaLocation).getRawPath(); int i = localFilename.lastIndexOf('/'); - if (i >= 0) + if (i >= 0) { localFilename = localFilename.substring(i + 1); - if (localFilename.endsWith(".xsd")) + } + if (localFilename.endsWith(".xsd")) { localFilename = localFilename.substring(0, localFilename.length() - 4); - if (localFilename.length() == 0) + } + if (localFilename.length() == 0) { localFilename = "schema"; + } // TODO: remove other unsafe characters for filenames? String candidateFilename = localFilename; int suffix = 1; - while (suffix < 1000) - { + while (suffix < 1000) { String candidate = _defaultCopyDirectory + "/" + candidateFilename + ".xsd"; - if (!fileExists(candidate)) + if (!fileExists(candidate)) { return candidate; + } suffix += 1; candidateFilename = localFilename + suffix; } @@ -533,54 +482,47 @@ public abstract class BaseSchemaResource throw new IOException("Problem with filename " + localFilename + ".xsd"); } - private void redownloadResource(SchemaResource resource) - { - if (_redownloadSet != null) - { - if (_redownloadSet.contains(resource)) + private void redownloadResource(SchemaResource resource) { + if (_redownloadSet != null) { + if (_redownloadSet.contains(resource)) { return; + } _redownloadSet.add(resource); } String filename = resource.getFilename(); String schemaLocation = resource.getSchemaLocation(); - String digest = null; + String digest; // nothing to do? - if (schemaLocation == null || filename == null) + if (schemaLocation == null || filename == null) { return; + } ByteArrayOutputStream buffer = new ByteArrayOutputStream(); - try - { - URL url = new URL( schemaLocation ); + try { + URL url = new URL(schemaLocation); URLConnection conn = url.openConnection(); conn.addRequestProperty("User-Agent", USER_AGENT); conn.addRequestProperty("Accept", "application/xml, text/xml, */*"); DigestInputStream input = digestInputStream(conn.getInputStream()); IOUtil.copyCompletely(input, buffer); digest = HexBin.bytesToString(input.getMessageDigest().digest()); - } - catch (Exception e) - { + } catch (Exception e) { warning("Could not copy remote resource " + schemaLocation + ":" + e.getMessage()); return; } - if (digest.equals(resource.getSha1()) && fileExists(filename)) - { + if (digest.equals(resource.getSha1()) && fileExists(filename)) { warning("Resource " + filename + " is unchanged from " + schemaLocation + "."); return; } - try - { + try { InputStream source = new ByteArrayInputStream(buffer.toByteArray()); writeInputStreamToFile(source, filename); - } - catch (IOException e) - { + } catch (IOException e) { warning("Could not write to file " + filename + " for " + schemaLocation + ":" + e.getMessage()); return; } @@ -588,47 +530,38 @@ public abstract class BaseSchemaResource warning("Refreshed " + filename + " from " + schemaLocation); } - private SchemaResource copyOrIdentifyDuplicateURL(String schemaLocation, String namespace) - { + private SchemaResource copyOrIdentifyDuplicateURL(String schemaLocation, String namespace) { String targetFilename; String digest; SchemaResource result; - try - { + try { targetFilename = uniqueFilenameForURI(schemaLocation); - } - catch (URISyntaxException e) - { + } catch (URISyntaxException e) { warning("Invalid URI '" + schemaLocation + "':" + e.getMessage()); return null; - } - catch (IOException e) - { + } catch (IOException e) { warning("Could not create local file for " + schemaLocation + ":" + e.getMessage()); return null; } - try - { - URL url = new URL( schemaLocation ); + try { + URL url = new URL(schemaLocation); DigestInputStream input = digestInputStream(url.openStream()); writeInputStreamToFile(input, targetFilename); digest = HexBin.bytesToString(input.getMessageDigest().digest()); - } - catch (Exception e) - { + } catch (Exception e) { warning("Could not copy remote resource " + schemaLocation + ":" + e.getMessage()); return null; } - result = (SchemaResource)_resourceForDigest.get(digest); - if (result != null) - { + result = _resourceForDigest.get(digest); + if (result != null) { deleteFile(targetFilename); result.addSchemaLocation(schemaLocation); - if (!_resourceForURL.containsKey(schemaLocation)) + if (!_resourceForURL.containsKey(schemaLocation)) { _resourceForURL.put(schemaLocation, result); + } return result; } @@ -637,8 +570,9 @@ public abstract class BaseSchemaResource DownloadedSchemaEntry newEntry = addNewEntry(); newEntry.setFilename(targetFilename); newEntry.setSha1(digest); - if (namespace != null) + if (namespace != null) { newEntry.setNamespace(namespace); + } newEntry.addSchemaLocation(schemaLocation); return updateResource(newEntry); } @@ -646,23 +580,26 @@ public abstract class BaseSchemaResource /** * Updates actual namespace in the table. */ - public void reportActualNamespace(SchemaImportResolver.SchemaResource rresource, String actualNamespace) - { - SchemaResource resource = (SchemaResource)rresource; + public void reportActualNamespace(SchemaImportResolver.SchemaResource rresource, String actualNamespace) { + SchemaResource resource = (SchemaResource) rresource; String oldNamespace = resource.getNamespace(); - if (oldNamespace != null && _resourceForNamespace.get(oldNamespace) == resource) + if (oldNamespace != null && _resourceForNamespace.get(oldNamespace) == resource) { _resourceForNamespace.remove(oldNamespace); - if (!_resourceForNamespace.containsKey(actualNamespace)) + } + if (!_resourceForNamespace.containsKey(actualNamespace)) { _resourceForNamespace.put(actualNamespace, resource); + } resource.setNamespace(actualNamespace); } - private String shaDigestForFile(String filename) throws IOException - { + private String shaDigestForFile(String filename) throws IOException { DigestInputStream str = digestInputStream(inputStreamForFile(filename)); byte[] dummy = new byte[4096]; - for (int i = 1; i > 0; i = str.read(dummy)); + int i = 1; + while (i > 0) { + i = str.read(dummy); + } str.close(); @@ -671,13 +608,11 @@ public abstract class BaseSchemaResource // SOME METHODS TO OVERRIDE ============================ - protected String getIndexFilename() - { + protected String getIndexFilename() { return "./xsdownload.xml"; } - protected String getDefaultSchemaDir() - { + protected String getDefaultSchemaDir() { return "./schema"; } Modified: xmlbeans/trunk/src/main/java/org/apache/xmlbeans/impl/values/JavaBase64Holder.java URL: http://svn.apache.org/viewvc/xmlbeans/trunk/src/main/java/org/apache/xmlbeans/impl/values/JavaBase64Holder.java?rev=1881992&r1=1881991&r2=1881992&view=diff ============================================================================== --- xmlbeans/trunk/src/main/java/org/apache/xmlbeans/impl/values/JavaBase64Holder.java (original) +++ xmlbeans/trunk/src/main/java/org/apache/xmlbeans/impl/values/JavaBase64Holder.java Thu Sep 24 23:11:07 2020 @@ -132,6 +132,6 @@ public abstract class JavaBase64Holder e } byte[] res = md5.digest(_value); - return hashcode = res[0] << 24 + res[1] << 16 + res[2] << 8 + res[3]; + return hashcode = (res[0] << 24) | (res[1] << 16) | (res[2] << 8) | res[3]; } } Modified: xmlbeans/trunk/src/main/java/org/apache/xmlbeans/impl/values/JavaHexBinaryHolder.java URL: http://svn.apache.org/viewvc/xmlbeans/trunk/src/main/java/org/apache/xmlbeans/impl/values/JavaHexBinaryHolder.java?rev=1881992&r1=1881991&r2=1881992&view=diff ============================================================================== --- xmlbeans/trunk/src/main/java/org/apache/xmlbeans/impl/values/JavaHexBinaryHolder.java (original) +++ xmlbeans/trunk/src/main/java/org/apache/xmlbeans/impl/values/JavaHexBinaryHolder.java Thu Sep 24 23:11:07 2020 @@ -133,7 +133,7 @@ public abstract class JavaHexBinaryHolde } byte[] res = md5.digest(_value); - return hashcode = res[0] << 24 + res[1] << 16 + res[2] << 8 + res[3]; + return hashcode = (res[0] << 24) | (res[1] << 16) | (res[2] << 8) | res[3]; } } --------------------------------------------------------------------- To unsubscribe, e-mail: [email protected] For additional commands, e-mail: [email protected]
