Class ClassScanningLoader

java.lang.Object
org.daiitech.naftah.playground.utils.ClassScanningLoader

public final class ClassScanningLoader extends Object
Utility responsible for reconstructing ClassScanningResult and ClassScanningIndex instances from a serialized JSON snapshot.

This loader is primarily used by the Naftah Playground environment, where runtime classpath scanning results are precomputed and shipped as JSON instead of being generated at runtime.

The loader supports:

  • Plain JSON and GZIP-compressed JSON inputs
  • Sync and async reconstruction modes
  • Reflection-based restoration of classes, methods, and constructors

Reconstructed metadata includes:

  • Class loader mappings
  • Class registries (accessible / instantiable classes)
  • JVM methods and constructors
  • Built-in function descriptors and metadata

Failure strategy: Any unresolved class, method, or constructor is skipped or replaced with safe defaults to ensure partial recovery instead of full failure.

Threading note: Async methods create a temporary thread pool per invocation.

Author:
Chakib Daii
  • Field Details

    • CLASS_CACHE

      private static final Map<String,Class<?>> CLASS_CACHE
      Thread-safe cache of resolved Class objects indexed by fully qualified class name.

      This cache is used to avoid repeated and expensive class-loading operations for the same class name during runtime resolution/deserialization.

      Entries are stored indefinitely for the lifetime of the JVM.

  • Constructor Details

    • ClassScanningLoader

      private ClassScanningLoader()
      Private constructor to prevent instantiation. Throws NaftahBugError if called.
  • Method Details

    • loadClassScanningResultFromJson

      public static ClassScanningResult loadClassScanningResultFromJson(Path path, boolean async) throws Exception
      Loads and reconstructs a ClassScanningResult from a JSON snapshot file.

      The input file may be either:

      • Plain JSON
      • GZIP-compressed JSON (auto-detected via header)

      When async = true, reconstruction of major sections (classes, functions, metadata) is performed in parallel using a temporary executor service.

      Parameters:
      path - the snapshot file path
      async - whether to reconstruct the result using parallel execution
      Returns:
      the reconstructed ClassScanningResult
      Throws:
      Exception - if the file cannot be read or parsed
    • loadClassScanningResultFromJson

      public static ClassScanningResult loadClassScanningResultFromJson(javax.json.JsonObject obj)
      Reconstructs a ClassScanningResult from its JSON representation.

      The JSON must match the structure produced by the Naftah class scanning export system.

      This method performs synchronous reconstruction of:

      • Class loader mappings
      • Class registries
      • JVM functions and constructors
      • Built-in functions
      Parameters:
      obj - serialized class scanning snapshot
      Returns:
      reconstructed ClassScanningResult
    • loadClassScanningResultFromJsonAsync

      public static ClassScanningResult loadClassScanningResultFromJsonAsync(javax.json.JsonObject obj)
      Reconstructs a ClassScanningResult from JSON using parallel execution.

      Each major section of the snapshot is loaded concurrently using a fixed thread pool sized to the available CPU cores.

      The executor is created per invocation and shut down after completion.

      This method is functionally equivalent to the synchronous loader but optimized for large snapshots and browser-playground workloads.

      Parameters:
      obj - serialized class scanning snapshot
      Returns:
      reconstructed ClassScanningResult
    • loadClassScanningIndexFromJson

      public static ClassScanningIndex loadClassScanningIndexFromJson(Path path, boolean async) throws Exception
      Loads a lightweight ClassScanningIndex from a JSON snapshot file.

      The index version contains only minimal metadata required for fast lookup:

      • Class names
      • Class qualifiers
      • Localized (Arabic) qualifiers
      • Built-in function metadata

      This is a reduced form of ClassScanningResult intended for fast startup and lightweight runtime usage.

      Parameters:
      path - snapshot file path
      async - whether to use parallel reconstruction
      Returns:
      reconstructed ClassScanningIndex
      Throws:
      Exception - if loading or parsing fails
    • loadClassScanningIndexFromJson

      public static ClassScanningIndex loadClassScanningIndexFromJson(javax.json.JsonObject obj)
      Reconstructs a ClassScanningIndex from JSON.

      This method extracts only lightweight metadata and does not resolve full class or method structures.

      Parameters:
      obj - serialized index snapshot
      Returns:
      reconstructed index
    • loadClassScanningIndexFromJsonAsync

      public static ClassScanningIndex loadClassScanningIndexFromJsonAsync(javax.json.JsonObject obj)
      Asynchronously reconstructs a ClassScanningIndex.

      Uses a temporary thread pool to parallelize parsing of metadata sections.

      Parameters:
      obj - serialized index snapshot
      Returns:
      reconstructed index
    • loadFromJson

      public static <R> R loadFromJson(Path path, Function<javax.json.JsonObject,R> loader) throws Exception
      Generic JSON snapshot loader that handles file IO, compression detection, and parsing.

      This method:

      1. Detects GZIP compression via magic bytes
      2. Parses JSON using JsonReader
      3. Delegates conversion to the provided loader function

      Performance diagnostics are logged at TRACE level.

      Type Parameters:
      R - return type
      Parameters:
      path - input snapshot file
      loader - function that converts parsed JSON into a target object
      Returns:
      reconstructed object
      Throws:
      Exception - on IO or parsing failure
    • toClassLoaders

      private static Map<String,ClassLoader> toClassLoaders(javax.json.JsonObject obj)
      Reconstructs the exported class loader mapping.

      Each entry associates a class name with the URLs that were used to load it when the snapshot was generated.

      Parameters:
      obj - the root JSON object
      Returns:
      a map of class names to reconstructed class loaders, or null if no class loader information is present
    • toClassMap

      private static Map<String,Class<?>> toClassMap(javax.json.JsonObject obj)
      Converts a JSON object containing class names into a map of resolved Class instances.

      Classes are loaded without initialization using safeClass(String).

      Parameters:
      obj - the JSON representation
      Returns:
      a map of aliases to resolved classes, or null
    • toSet

      private static Set<String> toSet(javax.json.JsonArray arr)
      Converts a JSON array of strings into a Set.
      Parameters:
      arr - the JSON array
      Returns:
      a set containing all string values, or null if the array is null
    • toMap

      private static Map<String,String> toMap(javax.json.JsonObject obj)
      Converts a JSON object containing string values into a Map.
      Parameters:
      obj - the JSON object
      Returns:
      a map containing all key-value pairs, or null if the object is null
    • toJvmFunctions

      private static Map<String,List<JvmFunction>> toJvmFunctions(javax.json.JsonObject obj)
      Reconstructs JVM function metadata from its serialized form.

      Each function is restored by resolving its declaring class, parameter types, and backing Method instance.

      Parameters:
      obj - the serialized JVM functions
      Returns:
      the reconstructed JVM function registry
    • toJvmClassInitializers

      private static Map<String,List<JvmClassInitializer>> toJvmClassInitializers(javax.json.JsonObject obj)
      Reconstructs JVM constructor metadata from its serialized form.

      Each initializer is restored by resolving its declaring class, parameter types, and backing Constructor instance.

      Parameters:
      obj - the serialized JVM class initializers
      Returns:
      the reconstructed JVM class initializer registry
    • toBuiltinFunctions

      private static Map<String,List<BuiltinFunction>> toBuiltinFunctions(javax.json.JsonObject obj)
      Reconstructs built-in function metadata from its serialized form.

      Each entry is converted into a BuiltinFunction by restoring its backing method, provider information, and function descriptor.

      Parameters:
      obj - the serialized built-in functions
      Returns:
      the reconstructed built-in function registry
    • toBuiltinFunctionArray

      private static BuiltinFunctionInfo[] toBuiltinFunctionArray(javax.json.JsonArray arr)
      Converts a JSON array of serialized built-in function metadata into an array of BuiltinFunctionInfo objects.

      Each JSON element is expected to contain the following structure:

      • methodName - the JVM method name
      • className - declaring class name
      • methodParameterTypes - array of parameter type names
      • canonicalKey - canonical function identifier
      • qualifiedAliases - array of fully qualified alias names

      The returned array preserves the original JSON order. Each index corresponds directly to the input array index.

      Failure behavior:

      • If the input array is null, an empty array is returned.
      • If an individual element fails to parse, it is skipped and the corresponding array slot remains null.
      • Parsing errors do not interrupt the overall conversion process.

      This method is used as part of the lightweight ClassScanningIndex reconstruction pipeline where only metadata (not executable reflection objects) is required.

      Parameters:
      arr - JSON array of built-in function metadata
      Returns:
      an array of BuiltinFunctionInfo, possibly containing null entries
    • deserializeProvider

      private static NaftahFunctionProvider deserializeProvider(javax.json.JsonObject o)
      Reconstructs a NaftahFunctionProvider descriptor from JSON.
      Parameters:
      o - the serialized provider descriptor
      Returns:
      the reconstructed provider descriptor, or null
    • deserializeFunction

      private static NaftahFunction deserializeFunction(javax.json.JsonObject o)
      Reconstructs a NaftahFunction descriptor from JSON.
      Parameters:
      o - the serialized function descriptor
      Returns:
      the reconstructed function descriptor, or null
    • toStringArray

      private static String[] toStringArray(javax.json.JsonArray arr)
      Converts a JsonArray containing string values into a String[].

      If the provided array is null, an empty array is returned.

      Parameters:
      arr - the JSON array to convert, or null
      Returns:
      a new array containing all string values from the JSON array, or an empty array if arr is null
    • toClassArray

      private static Class<?>[] toClassArray(javax.json.JsonArray arr)
      Converts a JSON array of class names into an array of resolved classes.

      Unresolvable classes are replaced with Object via safeClass(String).

      Parameters:
      arr - the JSON array of fully qualified class names
      Returns:
      the resolved class array, never null
    • findMethod

      private static Method findMethod(Class<?> clazz, String name, Class<?>[] params)
      Attempts to locate a declared method.
      Parameters:
      clazz - the declaring class
      name - the method name
      params - the parameter types
      Returns:
      the matching method, or null if it cannot be found
    • findConstructor

      private static Constructor<?> findConstructor(Class<?> clazz, Class<?>[] params)
      Attempts to locate a declared constructor.
      Parameters:
      clazz - the declaring class
      params - the constructor parameter types
      Returns:
      the matching constructor, or null if it cannot be found
    • safeClass

      private static Class<?> safeClass(String name)
      Resolves a class by name using ClassUtils, with caching and safe fallback.

      If resolution fails, Object is returned instead of throwing an exception, ensuring partial reconstruction of the snapshot.

      Results are cached in CLASS_CACHE for the lifetime of the JVM.

      Parameters:
      name - fully qualified class name
      Returns:
      resolved class or Object if resolution fails