You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@uima.apache.org by re...@apache.org on 2024/09/26 09:18:57 UTC

(uima-uimaj) 01/01: Issue #385: Allow import of type systems published through SPI

This is an automated email from the ASF dual-hosted git repository.

rec pushed a commit to branch feature/385-Allow-import-of-type-systems-published-through-SPI
in repository https://gitbox.apache.org/repos/asf/uima-uimaj.git

commit 086552fe758df7226fd425fe6b88309599a74542
Author: Richard Eckart de Castilho <re...@apache.org>
AuthorDate: Thu Sep 26 11:18:50 2024 +0200

    Issue #385: Allow import of type systems published through SPI
    
    - Enhance the Import_impl to look up descriptors via the type system description SPI
    - Bit of cleaning up in related classes
---
 .../fit/factory/TypeSystemDescriptionFactory.java  | 46 ++++++-----
 .../resource/metadata/impl/ImportResolver.java     | 38 ++++-----
 .../uima/resource/metadata/impl/Import_impl.java   | 90 ++++++++++++++--------
 ...TypeSystemDescriptionImportResolverAdapter.java |  4 +-
 .../uima/spi/TypeSystemDescriptionProvider.java    | 30 ++++++++
 .../java/org/apache/uima/util/TypeSystemUtil.java  | 82 ++++++++++----------
 6 files changed, 170 insertions(+), 120 deletions(-)

diff --git a/uimafit-core/src/main/java/org/apache/uima/fit/factory/TypeSystemDescriptionFactory.java b/uimafit-core/src/main/java/org/apache/uima/fit/factory/TypeSystemDescriptionFactory.java
index 1b611d88f..ba90428e8 100644
--- a/uimafit-core/src/main/java/org/apache/uima/fit/factory/TypeSystemDescriptionFactory.java
+++ b/uimafit-core/src/main/java/org/apache/uima/fit/factory/TypeSystemDescriptionFactory.java
@@ -26,7 +26,6 @@ import java.io.IOException;
 import java.util.ArrayList;
 import java.util.HashMap;
 import java.util.List;
-import java.util.Map;
 import java.util.ServiceLoader;
 import java.util.WeakHashMap;
 
@@ -81,14 +80,14 @@ public final class TypeSystemDescriptionFactory {
    */
   public static TypeSystemDescription createTypeSystemDescription(String... descriptorNames) {
 
-    TypeSystemDescription typeSystem = new TypeSystemDescription_impl();
-    List<Import> imports = new ArrayList<>();
-    for (String descriptorName : descriptorNames) {
-      Import imp = new Import_impl();
+    var typeSystem = new TypeSystemDescription_impl();
+    var imports = new ArrayList<Import>();
+    for (var descriptorName : descriptorNames) {
+      var imp = new Import_impl();
       imp.setName(descriptorName);
       imports.add(imp);
     }
-    Import[] importArray = new Import[imports.size()];
+    var importArray = new Import[imports.size()];
     typeSystem.setImports(imports.toArray(importArray));
     return typeSystem;
   }
@@ -103,14 +102,14 @@ public final class TypeSystemDescriptionFactory {
   public static TypeSystemDescription createTypeSystemDescriptionFromPath(
           String... descriptorURIs) {
 
-    TypeSystemDescription typeSystem = new TypeSystemDescription_impl();
-    List<Import> imports = new ArrayList<>();
-    for (String descriptorURI : descriptorURIs) {
-      Import imp = new Import_impl();
+    var typeSystem = new TypeSystemDescription_impl();
+    var imports = new ArrayList<Import>();
+    for (var descriptorURI : descriptorURIs) {
+      var imp = new Import_impl();
       imp.setLocation(descriptorURI);
       imports.add(imp);
     }
-    Import[] importArray = new Import[imports.size()];
+    var importArray = new Import[imports.size()];
     typeSystem.setImports(imports.toArray(importArray));
     return typeSystem;
   }
@@ -127,12 +126,12 @@ public final class TypeSystemDescriptionFactory {
   public static TypeSystemDescription createTypeSystemDescription()
           throws ResourceInitializationException {
 
-    ClassLoader cl = ClassLoaderUtils.findClassloader();
-    TypeSystemDescription tsd = typeDescriptorByClassloader.get(cl);
+    var cl = ClassLoaderUtils.findClassloader();
+    var tsd = typeDescriptorByClassloader.get(cl);
     if (tsd == null) {
       synchronized (CREATE_LOCK) {
-        ResourceManager resMgr = ResourceManagerFactory.newResourceManager();
-        List<TypeSystemDescription> tsdList = new ArrayList<>();
+        var resMgr = ResourceManagerFactory.newResourceManager();
+        var tsdList = new ArrayList<TypeSystemDescription>();
 
         loadTypeSystemDescriptionsFromScannedLocations(tsdList, resMgr);
         loadTypeSystemDescriptionsFromSPIs(tsdList);
@@ -147,9 +146,9 @@ public final class TypeSystemDescriptionFactory {
 
   static void loadTypeSystemDescriptionsFromScannedLocations(List<TypeSystemDescription> tsdList,
           ResourceManager aResMgr) throws ResourceInitializationException {
-    for (String location : scanTypeDescriptors()) {
+    for (var location : scanTypeDescriptors()) {
       try {
-        TypeSystemDescription description = typeDescriptors.get(location);
+        var description = typeDescriptors.get(location);
 
         if (description == PLACEHOLDER) {
           // If the description has not yet been loaded, load it
@@ -169,10 +168,9 @@ public final class TypeSystemDescriptionFactory {
   }
 
   static void loadTypeSystemDescriptionsFromSPIs(List<TypeSystemDescription> tsdList) {
-    ServiceLoader<TypeSystemDescriptionProvider> loader = ServiceLoader
-            .load(TypeSystemDescriptionProvider.class);
+    var loader = ServiceLoader.load(TypeSystemDescriptionProvider.class);
     loader.forEach(provider -> {
-      for (TypeSystemDescription desc : provider.listTypeSystemDescriptions()) {
+      for (var desc : provider.listTypeSystemDescriptions()) {
         tsdList.add(desc);
         LOG.debug("Loaded SPI-provided type system at [{}]", desc.getSourceUrlString());
       }
@@ -191,8 +189,8 @@ public final class TypeSystemDescriptionFactory {
   public static String[] scanTypeDescriptors() throws ResourceInitializationException {
 
     synchronized (SCAN_LOCK) {
-      ClassLoader cl = ClassLoaderUtils.findClassloader();
-      String[] typeDescriptorLocations = typeDescriptorLocationsByClassloader.get(cl);
+      var cl = ClassLoaderUtils.findClassloader();
+      var typeDescriptorLocations = typeDescriptorLocationsByClassloader.get(cl);
 
       if (typeDescriptorLocations == null) {
         typeDescriptorLocations = scanDescriptors(MetaDataType.TYPE_SYSTEM);
@@ -210,10 +208,10 @@ public final class TypeSystemDescriptionFactory {
     // We "intern" the location strings because we will use them as keys in the WeakHashMap
     // caching the parsed type systems. As part of this process, we put a PLACEHOLDER into the
     // map which is replaced when the type system is actually loaded
-    Map<String, String> locationStrings = new HashMap<>();
+    var locationStrings = new HashMap<String, String>();
     typeDescriptors.keySet().stream().forEach(loc -> locationStrings.put(loc, loc));
     for (int i = 0; i < typeDescriptorLocations.length; i++) {
-      String existingLocString = locationStrings.get(typeDescriptorLocations[i]);
+      var existingLocString = locationStrings.get(typeDescriptorLocations[i]);
       if (existingLocString == null) {
         typeDescriptors.put(typeDescriptorLocations[i], PLACEHOLDER);
         locationStrings.put(typeDescriptorLocations[i], typeDescriptorLocations[i]);
diff --git a/uimaj-core/src/main/java/org/apache/uima/resource/metadata/impl/ImportResolver.java b/uimaj-core/src/main/java/org/apache/uima/resource/metadata/impl/ImportResolver.java
index 6dcd26a09..3a58f3afa 100644
--- a/uimaj-core/src/main/java/org/apache/uima/resource/metadata/impl/ImportResolver.java
+++ b/uimaj-core/src/main/java/org/apache/uima/resource/metadata/impl/ImportResolver.java
@@ -19,12 +19,12 @@
 package org.apache.uima.resource.metadata.impl;
 
 import static java.util.Arrays.asList;
+import static java.util.Collections.newSetFromMap;
 import static java.util.stream.Collectors.toList;
 
 import java.io.IOException;
 import java.net.URL;
 import java.util.Collection;
-import java.util.Collections;
 import java.util.Deque;
 import java.util.HashSet;
 import java.util.IdentityHashMap;
@@ -39,7 +39,6 @@ import org.apache.uima.resource.ResourceManager;
 import org.apache.uima.resource.impl.ResourceManager_impl;
 import org.apache.uima.resource.metadata.Import;
 import org.apache.uima.resource.metadata.MetaDataObject;
-import org.apache.uima.resource.metadata.TypeSystemDescription;
 import org.apache.uima.util.InvalidXMLException;
 import org.apache.uima.util.XMLInputSource;
 import org.apache.uima.util.XMLizable;
@@ -82,11 +81,7 @@ class ImportResolver<DESCRIPTOR extends MetaDataObject, COLLECTIBLE extends Meta
    *          {@code null} then a new default resource manager is created.
    * @throws InvalidXMLException
    *           if an import could not be processed.
-   * @deprecated Exists only to support a deprecated methods like
-   *             {@link TypeSystemDescription#resolveImports(Collection, ResourceManager)}.
-   * @forRemoval 4.0.0
    */
-  @Deprecated(since = "3.3.0")
   void resolveImports(DESCRIPTOR aDesc, Collection<String> aAlreadyImportedURLs,
           ResourceManager aResourceManager) throws InvalidXMLException {
     DescriptorAdapter<DESCRIPTOR, COLLECTIBLE> wrapper = adapterFactory.apply(aDesc);
@@ -95,23 +90,23 @@ class ImportResolver<DESCRIPTOR extends MetaDataObject, COLLECTIBLE extends Meta
       return;
     }
 
-    Set<COLLECTIBLE> originalTypes = Collections.newSetFromMap(new IdentityHashMap<>());
+    Set<COLLECTIBLE> originalTypes = newSetFromMap(new IdentityHashMap<>());
     originalTypes.addAll(asList(wrapper.getCollectibles()));
 
-    ResourceManager resourceManager = aResourceManager;
+    var resourceManager = aResourceManager;
     if (aResourceManager == null) {
       resourceManager = UIMAFramework.newDefaultResourceManager();
     }
 
-    Set<String> alreadyImportedURLs = new HashSet<>();
-    Deque<String> stack = new LinkedList<>();
+    var alreadyImportedURLs = new HashSet<String>();
+    var stack = new LinkedList<String>();
 
     if (aAlreadyImportedURLs != null) {
       alreadyImportedURLs.addAll(aAlreadyImportedURLs);
       aAlreadyImportedURLs.forEach(stack::push);
     }
 
-    Map<Key, COLLECTIBLE> collectedObjects = new LinkedHashMap<>();
+    var collectedObjects = new LinkedHashMap<Key, COLLECTIBLE>();
 
     stack.push(wrapper.unwrap().getSourceUrlString());
     resolveImports(wrapper, new HashSet<>(), collectedObjects, stack, resourceManager);
@@ -143,20 +138,17 @@ class ImportResolver<DESCRIPTOR extends MetaDataObject, COLLECTIBLE extends Meta
           Set<String> aAlreadyVisited, Map<Key, COLLECTIBLE> aAllCollectedObjects,
           Deque<String> aStack, ResourceManager aResourceManager) throws InvalidXMLException {
 
+    collectAll(aWrapper, aAllCollectedObjects);
+
     if (aAlreadyVisited.contains(aWrapper.unwrap().getSourceUrlString())) {
-      collectAll(aWrapper, aAllCollectedObjects);
       return;
     }
 
-    Import[] imports = aWrapper.getImports();
-
+    var imports = aWrapper.getImports();
     if (imports.length == 0) {
-      collectAll(aWrapper, aAllCollectedObjects);
       return;
     }
 
-    collectAll(aWrapper, aAllCollectedObjects);
-
     Map<String, XMLizable> importCache = ((ResourceManager_impl) aResourceManager).getImportCache();
     for (var imp : imports) {
       // make sure Import's relative path base is set, to allow for users who create new import
@@ -170,7 +162,7 @@ class ImportResolver<DESCRIPTOR extends MetaDataObject, COLLECTIBLE extends Meta
         continue;
       }
 
-      URL absUrl = imp.findAbsoluteUrl(aResourceManager);
+      var absUrl = imp.findAbsoluteUrl(aResourceManager);
       String absUrlString = absUrl.toString();
 
       // Loop cancellation - skip imports of descriptors that lie on the path from the
@@ -182,10 +174,10 @@ class ImportResolver<DESCRIPTOR extends MetaDataObject, COLLECTIBLE extends Meta
       aStack.push(absUrlString);
 
       synchronized (importCache) {
-        DescriptorAdapter<DESCRIPTOR, COLLECTIBLE> importedTSAdapter = adapterFactory
+        var importedDescriptionAdapter = adapterFactory
                 .apply(getOrLoadDescription(imp, absUrl, importCache, aWrapper));
 
-        resolveImports(importedTSAdapter, aAlreadyVisited, aAllCollectedObjects, aStack,
+        resolveImports(importedDescriptionAdapter, aAlreadyVisited, aAllCollectedObjects, aStack,
                 aResourceManager);
       }
 
@@ -208,7 +200,7 @@ class ImportResolver<DESCRIPTOR extends MetaDataObject, COLLECTIBLE extends Meta
           throws InvalidXMLException {
     Class<DESCRIPTOR> descClass = aWrapper.getDescriptorClass();
 
-    XMLizable cachedDescriptor = aImportCache.get(aAbsUrl.toString());
+    var cachedDescriptor = aImportCache.get(aAbsUrl.toString());
     if (descClass.isInstance(cachedDescriptor)) {
       return descClass.cast(cachedDescriptor);
     }
@@ -219,9 +211,9 @@ class ImportResolver<DESCRIPTOR extends MetaDataObject, COLLECTIBLE extends Meta
   private DESCRIPTOR loadDescriptor(Import aImport, URL aAbsUrl,
           Map<String, XMLizable> aImportCache, ParserFunction<DESCRIPTOR> aParserFunction)
           throws InvalidXMLException {
-    String urlString = aAbsUrl.toString();
+    var urlString = aAbsUrl.toString();
     try {
-      XMLInputSource input = new XMLInputSource(aAbsUrl);
+      var input = new XMLInputSource(aAbsUrl);
       DESCRIPTOR descriptor = aParserFunction.apply(input);
       aImportCache.put(urlString, descriptor);
       return descriptor;
diff --git a/uimaj-core/src/main/java/org/apache/uima/resource/metadata/impl/Import_impl.java b/uimaj-core/src/main/java/org/apache/uima/resource/metadata/impl/Import_impl.java
index ae74fe152..c8fd3c3e4 100644
--- a/uimaj-core/src/main/java/org/apache/uima/resource/metadata/impl/Import_impl.java
+++ b/uimaj-core/src/main/java/org/apache/uima/resource/metadata/impl/Import_impl.java
@@ -21,10 +21,12 @@ package org.apache.uima.resource.metadata.impl;
 
 import java.net.MalformedURLException;
 import java.net.URL;
+import java.util.ServiceLoader;
 
 import org.apache.uima.UIMAFramework;
 import org.apache.uima.resource.ResourceManager;
 import org.apache.uima.resource.metadata.Import;
+import org.apache.uima.spi.TypeSystemDescriptionProvider;
 import org.apache.uima.util.InvalidXMLException;
 import org.apache.uima.util.Level;
 import org.apache.uima.util.XMLParser;
@@ -54,7 +56,6 @@ public class Import_impl extends MetaDataObject_impl implements Import {
    * the value if the evaluation succeeds (later fetches may not have the settings defined!) Leave
    * value unmodified if any settings are undefined.
    */
-
   @Override
   public String getName() {
     if (mName != null && mName.contains("${")) {
@@ -98,38 +99,65 @@ public class Import_impl extends MetaDataObject_impl implements Import {
   public URL findAbsoluteUrl(ResourceManager aResourceManager) throws InvalidXMLException {
     String location, name;
     if ((location = getLocation()) != null) {
-      try {
-        URL url = new URL(getRelativePathBase(), location);
-        UIMAFramework.getLogger(this.getClass()).logrb(Level.CONFIG, this.getClass().getName(),
-                "findAbsoluteUrl", LOG_RESOURCE_BUNDLE, "UIMA_import_by__CONFIG",
-                new Object[] { "location", url });
-        return url;
-      } catch (MalformedURLException e) {
-        throw new InvalidXMLException(InvalidXMLException.MALFORMED_IMPORT_URL,
-                new Object[] { location, getSourceUrlString() }, e);
-      }
-    } else if ((name = getName()) != null) {
-      String filename = name.replace('.', '/') + byNameSuffix;
-      URL url;
-      try {
-        url = aResourceManager.resolveRelativePath(filename);
-        UIMAFramework.getLogger(this.getClass()).logrb(Level.CONFIG, this.getClass().getName(),
-                "findAbsoluteUrl", LOG_RESOURCE_BUNDLE, "UIMA_import_by__CONFIG",
-                new Object[] { "name", url });
-      } catch (MalformedURLException e) {
-        throw new InvalidXMLException(InvalidXMLException.IMPORT_BY_NAME_TARGET_NOT_FOUND,
-                new Object[] { filename, getSourceUrlString() }, e);
-      }
-      if (url == null) {
-        throw new InvalidXMLException(InvalidXMLException.IMPORT_BY_NAME_TARGET_NOT_FOUND,
-                new Object[] { filename, getSourceUrlString() });
+      return findResourceUrlByLocation(location);
+    }
+
+    if ((name = getName()) != null) {
+      return findResouceUrlByName(aResourceManager, name);
+    }
+
+    // no name or location -- this should be caught at XML parse time but we still need to
+    // check here in case object was modified or was created programmatically.
+    throw new InvalidXMLException(InvalidXMLException.IMPORT_MUST_HAVE_NAME_XOR_LOCATION,
+            new Object[] { getSourceUrlString() });
+  }
+
+  private URL findResouceUrlByName(ResourceManager aResourceManager, String name)
+          throws InvalidXMLException {
+    var filename = name.replace('.', '/') + byNameSuffix;
+    URL url;
+
+    // Try loading through the classpath
+    try {
+      url = aResourceManager.resolveRelativePath(filename);
+      UIMAFramework.getLogger(this.getClass()).logrb(Level.CONFIG, this.getClass().getName(),
+              "findAbsoluteUrl", LOG_RESOURCE_BUNDLE, "UIMA_import_by__CONFIG",
+              new Object[] { "name", url });
+    } catch (MalformedURLException e) {
+      throw new InvalidXMLException(InvalidXMLException.IMPORT_BY_NAME_TARGET_NOT_FOUND,
+              new Object[] { filename, getSourceUrlString() }, e);
+    }
+
+    // If that fails, try loading through the SPIs
+    if (url == null) {
+      var providers = ServiceLoader.load(TypeSystemDescriptionProvider.class);
+      for (var provider : providers) {
+        var maybeTypeSystemUrl = provider.findTypeSystemUrl(name);
+        if (maybeTypeSystemUrl.isPresent()) {
+          url = maybeTypeSystemUrl.get();
+          break;
+        }
       }
+    }
+
+    if (url == null) {
+      throw new InvalidXMLException(InvalidXMLException.IMPORT_BY_NAME_TARGET_NOT_FOUND,
+              new Object[] { filename, getSourceUrlString() });
+    }
+
+    return url;
+  }
+
+  private URL findResourceUrlByLocation(String location) throws InvalidXMLException {
+    try {
+      var url = new URL(getRelativePathBase(), location);
+      UIMAFramework.getLogger(this.getClass()).logrb(Level.CONFIG, this.getClass().getName(),
+              "findAbsoluteUrl", LOG_RESOURCE_BUNDLE, "UIMA_import_by__CONFIG",
+              new Object[] { "location", url });
       return url;
-    } else {
-      // no name or location -- this should be caught at XML parse time but we still need to
-      // check here in case object was modified or was created progrmatically.
-      throw new InvalidXMLException(InvalidXMLException.IMPORT_MUST_HAVE_NAME_XOR_LOCATION,
-              new Object[] { getSourceUrlString() });
+    } catch (MalformedURLException e) {
+      throw new InvalidXMLException(InvalidXMLException.MALFORMED_IMPORT_URL,
+              new Object[] { location, getSourceUrlString() }, e);
     }
   }
 
diff --git a/uimaj-core/src/main/java/org/apache/uima/resource/metadata/impl/TypeSystemDescriptionImportResolverAdapter.java b/uimaj-core/src/main/java/org/apache/uima/resource/metadata/impl/TypeSystemDescriptionImportResolverAdapter.java
index 35048b107..4a1e790bf 100644
--- a/uimaj-core/src/main/java/org/apache/uima/resource/metadata/impl/TypeSystemDescriptionImportResolverAdapter.java
+++ b/uimaj-core/src/main/java/org/apache/uima/resource/metadata/impl/TypeSystemDescriptionImportResolverAdapter.java
@@ -18,6 +18,8 @@
  */
 package org.apache.uima.resource.metadata.impl;
 
+import static org.apache.uima.resource.metadata.Import.EMPTY_IMPORTS;
+
 import java.util.Collection;
 
 import org.apache.uima.UIMAFramework;
@@ -43,7 +45,7 @@ class TypeSystemDescriptionImportResolverAdapter
 
   @Override
   public void clearImports() {
-    delegate.setImports(Import.EMPTY_IMPORTS);
+    delegate.setImports(EMPTY_IMPORTS);
   }
 
   @Override
diff --git a/uimaj-core/src/main/java/org/apache/uima/spi/TypeSystemDescriptionProvider.java b/uimaj-core/src/main/java/org/apache/uima/spi/TypeSystemDescriptionProvider.java
index 0672a66c6..ee31bffdd 100644
--- a/uimaj-core/src/main/java/org/apache/uima/spi/TypeSystemDescriptionProvider.java
+++ b/uimaj-core/src/main/java/org/apache/uima/spi/TypeSystemDescriptionProvider.java
@@ -18,10 +18,40 @@
  */
 package org.apache.uima.spi;
 
+import static java.util.Optional.empty;
+
+import java.net.URL;
 import java.util.List;
+import java.util.Optional;
 
+import org.apache.uima.resource.metadata.Import;
 import org.apache.uima.resource.metadata.TypeSystemDescription;
 
 public interface TypeSystemDescriptionProvider {
+  /**
+   * @return the type system descriptions exported by this provider. The provider should resolve any
+   *         imports in the type systems before returning them. Also, the provider should internally
+   *         cache the parsed type systems instead of parsing them on every call to this method.
+   */
   List<TypeSystemDescription> listTypeSystemDescriptions();
+
+  /**
+   * @param aName
+   *          the name of the type system. This should be something like
+   *          {@code some.package.TypeSystem} just as you would put it into the
+   *          {@link Import#setName(String)} of a {@link Import} for a name-based import.
+   * @return the type system description(s) exported from the given location. The provider should
+   *         resolve any imports in the type systems before returning them.
+   * 
+   * @apiNote For backwards compatibility, this is currently a default method, so implementations do
+   *          not have to provide it - although by-name importing type systems provided via SPIs
+   *          will not work then unless the type systems are also simply available via the
+   *          classpath. However, in the next major version, the default implementation will be
+   *          removed so implementers have to provide it.a
+   * @forRemoval 4.0.0 (just the default implementation)
+   * @since 3.6.0
+   */
+  default Optional<URL> findTypeSystemUrl(String aName) {
+    return empty();
+  }
 }
diff --git a/uimaj-core/src/main/java/org/apache/uima/util/TypeSystemUtil.java b/uimaj-core/src/main/java/org/apache/uima/util/TypeSystemUtil.java
index 5c050440a..784c668c2 100644
--- a/uimaj-core/src/main/java/org/apache/uima/util/TypeSystemUtil.java
+++ b/uimaj-core/src/main/java/org/apache/uima/util/TypeSystemUtil.java
@@ -19,21 +19,23 @@
 
 package org.apache.uima.util;
 
+import static java.lang.Character.isDigit;
+import static java.lang.Character.isLetter;
+import static org.apache.uima.UIMAFramework.getLogger;
+import static org.apache.uima.cas.CAS.TYPE_NAME_ANNOTATION;
+import static org.apache.uima.cas.CAS.TYPE_NAME_FS_ARRAY;
+import static org.apache.uima.cas.CAS.TYPE_NAME_STRING;
+import static org.apache.uima.cas.CAS.TYPE_NAME_TOP;
+
 import java.io.IOException;
-import java.net.URL;
 import java.util.ArrayList;
-import java.util.Iterator;
 import java.util.List;
 import java.util.StringTokenizer;
 
-import org.apache.uima.ResourceSpecifierFactory;
 import org.apache.uima.UIMAFramework;
-import org.apache.uima.cas.CAS;
 import org.apache.uima.cas.Feature;
 import org.apache.uima.cas.Type;
 import org.apache.uima.cas.TypeSystem;
-import org.apache.uima.cas.impl.LowLevelTypeSystem;
-import org.apache.uima.resource.ResourceManager;
 import org.apache.uima.resource.impl.ResourceManager_impl;
 import org.apache.uima.resource.metadata.AllowedValue;
 import org.apache.uima.resource.metadata.FeatureDescription;
@@ -61,7 +63,6 @@ public class TypeSystemUtil {
    * }
    * </pre>
    * 
-   * 
    * @param aContext
    *          a context class. If the locations are not absolute, then they are looked up relative
    *          to this context class as per {@link Class#getResource(String)}.
@@ -72,26 +73,26 @@ public class TypeSystemUtil {
   public static List<TypeSystemDescription> loadTypeSystemDescriptionsFromClasspath(
           Class<?> aContext, String... typeSystemDescriptionLocations) {
 
-    ResourceManager resMgr = new ResourceManager_impl(aContext.getClassLoader());
+    var resMgr = new ResourceManager_impl(aContext.getClassLoader());
     try {
-      List<TypeSystemDescription> typeSystemDescriptions = new ArrayList<>();
+      var typeSystemDescriptions = new ArrayList<TypeSystemDescription>();
 
-      for (String typeSystem : typeSystemDescriptionLocations) {
-        URL resource = aContext.getResource(typeSystem);
+      for (var typeSystem : typeSystemDescriptionLocations) {
+        var resource = aContext.getResource(typeSystem);
         if (resource == null) {
-          UIMAFramework.getLogger()
-                  .error("Unable to locate type system description as a resource [{}]", typeSystem);
+          getLogger().error("Unable to locate type system description as a resource [{}]",
+                  typeSystem);
           continue;
         }
 
         try {
-          TypeSystemDescription tsd = UIMAFramework.getXMLParser()
+          var tsd = UIMAFramework.getXMLParser()
                   .parseTypeSystemDescription(new XMLInputSource(resource));
           tsd.resolveImports(resMgr);
           typeSystemDescriptions.add(tsd);
         } catch (InvalidXMLException | IOException e) {
-          UIMAFramework.getLogger().error("Error loading type system description [{}] from [{}]",
-                  typeSystem, resource, e);
+          getLogger().error("Error loading type system description [{}] from [{}]", typeSystem,
+                  resource, e);
         }
       }
 
@@ -109,18 +110,18 @@ public class TypeSystemUtil {
    * @return a TypeSystemDescription that is equivalent to <code>aTypeSystem</code>
    */
   public static TypeSystemDescription typeSystem2TypeSystemDescription(TypeSystem aTypeSystem) {
-    ResourceSpecifierFactory fact = UIMAFramework.getResourceSpecifierFactory();
-    TypeSystemDescription tsDesc = fact.createTypeSystemDescription();
-    Iterator<Type> typeIter = aTypeSystem.getTypeIterator();
-    List<TypeDescription> typeDescs = new ArrayList<>();
+    var fact = UIMAFramework.getResourceSpecifierFactory();
+    var tsDesc = fact.createTypeSystemDescription();
+    var typeIter = aTypeSystem.getTypeIterator();
+    var typeDescs = new ArrayList<TypeDescription>();
     while (typeIter.hasNext()) {
-      Type type = typeIter.next();
-      if (!type.getName().startsWith("uima.cas") && !type.getName().equals("uima.tcas.Annotation")
+      var type = typeIter.next();
+      if (!type.getName().startsWith("uima.cas") && !type.getName().equals(TYPE_NAME_ANNOTATION)
               && !type.isArray()) {
         typeDescs.add(type2TypeDescription(type, aTypeSystem));
       }
     }
-    TypeDescription[] typeDescArr = new TypeDescription[typeDescs.size()];
+    var typeDescArr = new TypeDescription[typeDescs.size()];
     typeDescs.toArray(typeDescArr);
     tsDesc.setTypes(typeDescArr);
 
@@ -137,29 +138,29 @@ public class TypeSystemUtil {
    * @return a TypeDescription that is equivalent to <code>aType</code>
    */
   public static TypeDescription type2TypeDescription(Type aType, TypeSystem aTypeSystem) {
-    TypeDescription typeDesc = UIMAFramework.getResourceSpecifierFactory().createTypeDescription();
+    var typeDesc = UIMAFramework.getResourceSpecifierFactory().createTypeDescription();
     typeDesc.setName(aType.getName());
-    Type superType = aTypeSystem.getParent(aType);
+    var superType = aTypeSystem.getParent(aType);
     typeDesc.setSupertypeName(superType.getName());
     // special handling for string subtypes (which have "allowed values", rather than features)
-    Type stringType = aTypeSystem.getType("uima.cas.String");
+    var stringType = aTypeSystem.getType(TYPE_NAME_STRING);
     if (aTypeSystem.subsumes(stringType, aType)) {
-      String[] allowedValues = getAllowedValuesForType(aType, aTypeSystem);
-      AllowedValue[] avObjs = new AllowedValue[allowedValues.length];
+      var allowedValues = getAllowedValuesForType(aType, aTypeSystem);
+      var avObjs = new AllowedValue[allowedValues.length];
       for (int i = 0; i < allowedValues.length; i++) {
-        AllowedValue av = UIMAFramework.getResourceSpecifierFactory().createAllowedValue();
+        var av = UIMAFramework.getResourceSpecifierFactory().createAllowedValue();
         av.setString(allowedValues[i]);
         avObjs[i] = av;
       }
       typeDesc.setAllowedValues(avObjs);
     } else {
-      List<FeatureDescription> featDescs = new ArrayList<>();
-      for (Feature feat : aType.getFeatures()) {
+      var featDescs = new ArrayList<FeatureDescription>();
+      for (var feat : aType.getFeatures()) {
         if (!superType.getFeatures().contains(feat)) {
           featDescs.add(feature2FeatureDescription(feat));
         }
       }
-      FeatureDescription[] featDescArr = new FeatureDescription[featDescs.size()];
+      var featDescArr = new FeatureDescription[featDescs.size()];
       featDescs.toArray(featDescArr);
       typeDesc.setFeatures(featDescArr);
     }
@@ -174,19 +175,18 @@ public class TypeSystemUtil {
    * @return a FeatureDescription that is equivalent to <code>aFeature</code>
    */
   public static FeatureDescription feature2FeatureDescription(Feature aFeature) {
-    FeatureDescription featDesc = UIMAFramework.getResourceSpecifierFactory()
-            .createFeatureDescription();
+    var featDesc = UIMAFramework.getResourceSpecifierFactory().createFeatureDescription();
     featDesc.setName(aFeature.getShortName());
     if (aFeature.isMultipleReferencesAllowed()) {
       featDesc.setMultipleReferencesAllowed(true);
     }
-    Type rangeType = aFeature.getRange();
+    var rangeType = aFeature.getRange();
     // special check for array range types, which are represented in the CAS as
     // elementType[] but in the descriptor as an FSArray with an <elementType>
     if (rangeType.isArray() && !rangeType.getComponentType().isPrimitive()) {
-      featDesc.setRangeTypeName(CAS.TYPE_NAME_FS_ARRAY);
-      String elementTypeName = rangeType.getComponentType().getName();
-      if (!CAS.TYPE_NAME_TOP.equals(elementTypeName)) {
+      featDesc.setRangeTypeName(TYPE_NAME_FS_ARRAY);
+      var elementTypeName = rangeType.getComponentType().getName();
+      if (!TYPE_NAME_TOP.equals(elementTypeName)) {
         featDesc.setElementType(elementTypeName);
       }
     } else {
@@ -205,7 +205,7 @@ public class TypeSystemUtil {
    * @return array of allowed values for <code>aType</code> TODO - this should be a method on Type.
    */
   public static String[] getAllowedValuesForType(Type aType, TypeSystem aTypeSystem) {
-    LowLevelTypeSystem lts = aTypeSystem.getLowLevelTypeSystem();
+    var lts = aTypeSystem.getLowLevelTypeSystem();
     return lts.ll_getStringSet(lts.ll_getCodeForType(aType));
   }
 
@@ -273,10 +273,10 @@ public class TypeSystemUtil {
   }
 
   private static boolean isIdentifierStart(char c) {
-    return Character.isLetter(c);
+    return isLetter(c);
   }
 
   private static boolean isIdentifierChar(char c) {
-    return (Character.isLetter(c) || Character.isDigit(c) || (c == '_'));
+    return (isLetter(c) || isDigit(c) || (c == '_'));
   }
 }