>
* Excludes paths from scanning - excellent for minizing path scanning on web application
*/
private boolean allowedPaths;
+
+ /**
+ * Enable classpath scanning for service sets loaded via GuiceContext.getLoader()
+ * It's a great way to enable testing in jdk 12 where test classes using service loading and jdk no longer reads service loaders from meta-inf/services
+ *
+ * Try to only use in test to load test modules. otherwise it may be a bad design
+ */
+ private boolean serviceLoadWithClassPath;
/**
* Configures the Guice Context and Reflection Identifier
@@ -88,28 +93,13 @@ public GuiceConfig()
//No Config
}
- /**
- * Enable classpath scanning for service sets loaded via GuiceContext.getLoader()
- * It's a great way to enable testing in jdk 12 where test classes using service loading and jdk no longer reads service loaders from meta-inf/services
- *
- * Try to only use in test to load test modules. otherwise it may be a bad design
- *
- */
+ @Override
public boolean isServiceLoadWithClassPath()
{
return serviceLoadWithClassPath;
}
- /**
- * Enable classpath scanning for service sets loaded via GuiceContext.getLoader()
- * It's a great way to enable testing in jdk 12 where test classes using service loading and jdk no longer reads service loaders from meta-inf/services
- *
- * Try to only use in test to load test modules. otherwise it may be a bad design
- *
- * @param serviceLoadWithClassPath Should scanning with classpath instead of SPI be used?
- *
- * @return this
- */
+ @Override
@SuppressWarnings("unchecked")
public J setServiceLoadWithClassPath(boolean serviceLoadWithClassPath)
{
@@ -124,224 +114,121 @@ public J setServiceLoadWithClassPath(boolean serviceLoadWithClassPath)
return (J) this;
}
- /**
- * Enable classpath scanning for service sets loaded via GuiceContext.getLoader()
- * It's a great way to enable testing in jdk 12 where test classes using service loading and jdk no longer reads service loaders from meta-inf/services
- *
- * Try to only use in test to load test modules. otherwise it may be a bad design
- */
- private boolean serviceLoadWithClassPath;
- /**
- * If field scanning should be enabled
- *
- * @return mandatory result
- */
+ @Override
public boolean isFieldScanning()
{
return fieldScanning;
}
- /**
- * Enables scanning of fields
- *
- * @param fieldScanning
- * If field scanning should happen
- *
- * @return Mandatory field scanning
- */
+ @Override
@SuppressWarnings("unchecked")
- @NotNull
+
public J setFieldScanning(boolean fieldScanning)
{
this.fieldScanning = fieldScanning;
return (J) this;
}
- /**
- * Enables scanning of field annotations
- *
- * @return not null
- */
+ @Override
public boolean isAnnotationScanning()
{
return annotationScanning;
}
- /**
- * Enables scanning of field annotations
- *
- * @param annotationScanning
- * if the field annotation scanning
- *
- * @return the field annotation scanning
- */
+ @Override
@SuppressWarnings("unchecked")
- @NotNull
+
public J setAnnotationScanning(boolean annotationScanning)
{
this.annotationScanning = annotationScanning;
return (J) this;
}
- /**
- * If method info should be kept
- *
- * @return always this
- */
+ @Override
public boolean isMethodInfo()
{
return methodInfo;
}
- /**
- * Sets if method info should be kept
- *
- * @param methodInfo
- * if method information should be collected
- *
- * @return always this
- */
+ @Override
@SuppressWarnings("unchecked")
- @NotNull
+
public J setMethodInfo(boolean methodInfo)
{
this.methodInfo = methodInfo;
return (J) this;
}
- /**
- * Sets to ignore field visibility
- *
- * @return if field visibility is being used
- */
+ @Override
public boolean isIgnoreFieldVisibility()
{
return ignoreFieldVisibility;
}
- /**
- * Sets to ignore field visibility
- *
- * @param ignoreFieldVisibility
- * if the field should be visible
- *
- * @return always this
- */
+ @Override
@SuppressWarnings("unchecked")
- @NotNull
+
public J setIgnoreFieldVisibility(boolean ignoreFieldVisibility)
{
this.ignoreFieldVisibility = ignoreFieldVisibility;
return (J) this;
}
- /**
- * Sets to ignore method visibility
- *
- * @return if method is visibility ignored
- */
+ @Override
public boolean isIgnoreMethodVisibility()
{
return ignoreMethodVisibility;
}
- /**
- * Sets to ignore method visibility
- *
- * @param ignoreMethodVisibility
- * the ignore method
- *
- * @return always This
- */
+ @Override
@SuppressWarnings("unchecked")
- @NotNull
+
public J setIgnoreMethodVisibility(boolean ignoreMethodVisibility)
{
this.ignoreMethodVisibility = ignoreMethodVisibility;
return (J) this;
}
- /**
- * Sets if packages must be white listed.
- *
- * Use META-INF/services/com.guicedee.guiceinjection.scanners.IPackageContentsScanner to register your packages
- *
- * @return if whitelisting is enabled
- */
+ @Override
public boolean isIncludePackages()
{
return includePackages;
}
- /**
- * Sets if packages must be white listed.
- * *
- * * Use META-INF/services/com.guicedee.guiceinjection.scanners.IPackageContentsScanner to register your packages
- *
- * @param includePackages
- * if packages should be white listed
- *
- * @return Always this
- */
+ @Override
@SuppressWarnings("unchecked")
- @NotNull
+
public J setIncludePackages(boolean includePackages)
{
this.includePackages = includePackages;
return (J) this;
}
- /**
- * Returns the field information included in the scan result
- *
- * @return if field info is included
- */
+ @Override
public boolean isFieldInfo()
{
return fieldInfo;
}
- /**
- * Sets if the field info should be in the field result
- *
- * @param fieldInfo
- * if field info should be scanned
- *
- * @return always this object
- */
+ @Override
@SuppressWarnings("unchecked")
- @NotNull
+
public J setFieldInfo(boolean fieldInfo)
{
this.fieldInfo = fieldInfo;
return (J) this;
}
- /**
- * Method isVerbose returns the verbose of this GuiceConfig object.
- *
- * Whether or not to log very verbose
- *
- * @return the verbose (type boolean) of this GuiceConfig object.
- */
+ @Override
public boolean isVerbose()
{
return verbose;
}
- /**
- * Method setVerbose sets the verbose of this GuiceConfig object.
- *
- * Whether or not to log very verbose
- *
- * @param verbose
- * the verbose of this GuiceConfig object.
- *
- * @return J
- */
+ @Override
@SuppressWarnings("unchecked")
- @NotNull
+
public J setVerbose(boolean verbose)
{
this.verbose = verbose;
@@ -349,82 +236,45 @@ public J setVerbose(boolean verbose)
return (J) this;
}
- /**
- * Method isClasspathScanning returns the classpathScanning of this GuiceConfig object.
- *
- * If classpath scanning is enabled.
- *
- * @return the classpathScanning (type boolean) of this GuiceConfig object.
- */
+ @Override
public boolean isClasspathScanning()
{
return classpathScanning;
}
- /**
- * Method setClasspathScanning sets the classpathScanning of this GuiceConfig object.
- *
- * If classpath scanning is enabled.
- *
- * @param classpathScanning
- * the classpathScanning of this GuiceConfig object.
- *
- * @return J
- */
+ @Override
@SuppressWarnings("unchecked")
- @NotNull
+
public J setClasspathScanning(boolean classpathScanning)
{
this.classpathScanning = classpathScanning;
return (J) this;
}
- /**
- * Excludes modules and jars from scanning - may and may not make it faster depending on your pc
- *
- * @return is modules/jars are excluded from scans
- */
+ @Override
public boolean isExcludeModulesAndJars()
{
return excludeModulesAndJars;
}
- /**
- * Excludes modules and jars from scanning - may and may not make it faster depending on your pc
- *
- * @param excludeModulesAndJars
- * to exclude them
- *
- * @return J
- */
+ @Override
@SuppressWarnings("unchecked")
- @NotNull
+
public J setExcludeModulesAndJars(boolean excludeModulesAndJars)
{
this.excludeModulesAndJars = excludeModulesAndJars;
return (J) this;
}
- /**
- * Excludes paths from scanning - excellent for minizing path scanning on web application
- *
- * @return boolean
- */
+ @Override
public boolean isExcludePaths()
{
return excludePaths;
}
- /**
- * Excludes paths from scanning - excellent for minizing path scanning on web application
- *
- * @param excludePaths
- * If the default paths must be automatically excluded
- *
- * @return J
- */
+ @Override
@SuppressWarnings("unchecked")
- @NotNull
+
public J setExcludePaths(boolean excludePaths)
{
this.excludePaths = excludePaths;
@@ -457,39 +307,26 @@ public String toString()
'}';
}
- /**
- * Method isAllowPaths returns the allowed Paths of this GuiceConfig object.
- *
- * Excludes paths from scanning - excellent for minizing path scanning on web application
- *
- * @return the whitelistPaths (type boolean) of this GuiceConfig object.
- */
+ @Override
public boolean isAllowPaths()
{
return allowedPaths;
}
- /**
- * Method setAllowPaths sets the allowed Paths of this GuiceConfig object.
- *
- * Excludes paths from scanning - excellent for minizing path scanning on web application
- *
- * @param allowedPaths
- * the allowedPaths of this GuiceConfig object.
- *
- * @return GuiceConfig J
- */
- public GuiceConfig setAllowPaths(boolean allowedPaths)
+ @Override
+ public J setAllowPaths(boolean allowedPaths)
{
this.allowedPaths = allowedPaths;
- return this;
+ return (J)this;
}
+ @Override
public boolean isIgnoreClassVisibility()
{
return ignoreClassVisibility;
}
+ @Override
@SuppressWarnings("unchecked")
public J setIgnoreClassVisibility(boolean ignoreClassVisibility)
{
@@ -497,110 +334,56 @@ public J setIgnoreClassVisibility(boolean ignoreClassVisibility)
return (J) this;
}
- /**
- * Include module/jars from being loaded - uses ModuleInclusions for jdk9 and JarInclusions for jdk8
- *
- * @return
- */
+ @Override
public boolean isIncludeModuleAndJars() {
return includeModuleAndJars;
}
- /**
- * Include module/jars from being loaded - uses ModuleInclusions for jdk9 and JarInclusions for jdk8
- *
- * @param includeModuleAndJars
- * @return
- */
- public GuiceConfig setIncludeModuleAndJars(boolean includeModuleAndJars) {
+ @Override
+ public J setIncludeModuleAndJars(boolean includeModuleAndJars) {
this.includeModuleAndJars = includeModuleAndJars;
- return this;
+ return (J)this;
}
- /**
- * Method isPathScanning returns the pathScanning of this GuiceConfig object.
- *
- * If the path should be scanned
- *
- * @return the pathScanning (type boolean) of this GuiceConfig object.
- */
+ @Override
public boolean isPathScanning()
{
return pathScanning;
}
- /**
- * Method setPathScanning sets the pathScanning of this GuiceConfig object.
- *
- * If the path should be scanned
- *
- * @param pathScanning
- * the pathScanning of this GuiceConfig object.
- *
- * @return GuiceConfig J
- */
- public GuiceConfig setPathScanning(boolean pathScanning)
+ @Override
+ public J setPathScanning(boolean pathScanning)
{
this.pathScanning = pathScanning;
- return this;
+ return (J)this;
}
- /**
- * Method isExcludeParentModules returns the excludeParentModules of this GuiceConfig object.
- *
- * Property to use when everything is found in the boot module
- *
- * @return the excludeParentModules (type boolean) of this GuiceConfig object.
- */
+ @Override
@SuppressWarnings("unused")
public boolean isExcludeParentModules()
{
return excludeParentModules;
}
- /**
- * Method setExcludeParentModules sets the excludeParentModules of this GuiceConfig object.
- *
- * Property to use when everything is found in the boot module
- *
- * @param excludeParentModules
- * the excludeParentModules of this GuiceConfig object.
- *
- * @return GuiceConfig J
- */
+ @Override
@SuppressWarnings("unused")
- public GuiceConfig setExcludeParentModules(boolean excludeParentModules)
+ public J setExcludeParentModules(boolean excludeParentModules)
{
this.excludeParentModules = excludeParentModules;
- return this;
+ return (J)this;
}
- /**
- * Method isRejectPackages returns the excludePackages of this GuiceConfig object.
- *
- * Excludes packages from scanning - excellent for minimizing path scanning on web application
- *
- * @return the excludePackages (type boolean) of this GuiceConfig object.
- */
+ @Override
public boolean isRejectPackages()
{
return excludePackages;
}
- /**
- * Method setExcludePackages sets the excludePackages of this GuiceConfig object.
- *
- * Excludes packages from scanning - excellent for minimizing path scanning on web application
- *
- * @param excludePackages
- * the excludePackages of this GuiceConfig object.
- *
- * @return GuiceConfig J
- */
- public GuiceConfig setExcludePackages(boolean excludePackages)
+ @Override
+ public J setExcludePackages(boolean excludePackages)
{
this.excludePackages = excludePackages;
- return this;
+ return (J)this;
}
diff --git a/src/main/java/com/guicedee/guicedinjection/GuiceContext.java b/src/main/java/com/guicedee/guicedinjection/GuiceContext.java
index b6731cb..41fe3a0 100644
--- a/src/main/java/com/guicedee/guicedinjection/GuiceContext.java
+++ b/src/main/java/com/guicedee/guicedinjection/GuiceContext.java
@@ -18,20 +18,19 @@
import com.google.common.base.*;
import com.google.inject.*;
-import com.guicedee.guicedinjection.abstractions.*;
+import com.guicedee.client.*;
import com.guicedee.guicedinjection.interfaces.*;
-import com.guicedee.guicedinjection.interfaces.annotations.*;
-import com.guicedee.logger.*;
import io.github.classgraph.*;
-import jakarta.validation.constraints.*;
+import lombok.extern.java.*;
-import java.lang.annotation.*;
import java.util.*;
import java.util.concurrent.*;
import java.util.logging.*;
import java.util.regex.Pattern;
-import static com.guicedee.guicedinjection.properties.GlobalProperties.*;
+import static com.guicedee.guicedinjection.properties.GlobalProperties.getSystemPropertyOrEnvironment;
+import static java.util.stream.Collectors.groupingBy;
+import static java.util.stream.Collectors.toSet;
/**
* Provides an interface for reflection and injection in one.
@@ -42,1044 +41,944 @@
* @version 1.0
* @since Nov 14, 2016
*/
+@Log
@SuppressWarnings("MissingClassJavaDoc")
-public class GuiceContext>
+public class GuiceContext> implements IGuiceContext
{
- /**
- * Field log
- */
- private static final Logger log = LogFactory.getLog("GuiceContext");
- /**
- * This particular instance of the class
- */
- private static final GuiceContext> instance = new GuiceContext<>();
- /**
- * A list of all the loaded singleton sets
- */
- private static final Map allLoadedServices = Collections.synchronizedMap(new LinkedHashMap<>());
- /**
- * The building injector
- */
- public static boolean buildingInjector = false;
- /**
- * A standard default waiting time for threads
- */
- public static long defaultWaitTime = 2;
- /**
- * The default wait unit for the thread time
- */
- public static TimeUnit defaultWaitUnit = TimeUnit.SECONDS;
- /**
- * The configuration object
- */
- private static GuiceConfig> config;
- /**
- * The physical injector for the JVM container
- */
- private Injector injector;
- /**
- * The actual scanner
- */
- private ClassGraph scanner;
- /**
- * The scan result built from everything - the core scanner.
- */
- private ScanResult scanResult;
- /**
- * If the scan should run async
- */
- private boolean async;
-
- /**
- * Creates a new Guice context. Not necessary
- */
- private GuiceContext()
- {
- //No config required
- }
-
- /**
- * Reference the Injector Directly
- *
- * @return The global Guice Injector Object, Never Null, Instantiates the Injector if not configured
- */
- @NotNull
- public static synchronized Injector inject()
- {
- if (GuiceContext.buildingInjector)
- {
- log.log(Level.SEVERE, "The injector is being called recursively during build. Place such actions in a IGuicePostStartup or use the IGuicePreStartup Service Loader.");
- System.exit(1);
- }
- if (GuiceContext.instance().injector == null)
- {
- try
- {
- GuiceContext.buildingInjector = true;
- GuiceContext.log.info("Starting up Guice Context");
- GuiceContext.instance()
- .loadConfiguration();
- if (GuiceContext.instance()
- .getConfig()
- .isPathScanning() ||
- GuiceContext.instance()
- .getConfig()
- .isClasspathScanning())
- {
- GuiceContext.instance()
- .loadScanner();
- }
- GuiceContext.instance()
- .loadPreStartups();
-
- List cModules = new ArrayList<>();
- cModules.add(new GuiceInjectorModule());
- GuiceContext.instance().injector = Guice.createInjector(cModules);
- GuiceContext.buildingInjector = false;
- GuiceContext.instance()
- .loadPostStartups();
-
- Runtime.getRuntime()
- .addShutdownHook(new Thread(GuiceContext::destroy));
-
- GuiceContext.log.config("Injection System Ready");
- }
- catch (Throwable e)
- {
- GuiceContext.log.log(Level.SEVERE, "Exception creating Injector : " + e.getMessage(), e);
- throw new RuntimeException("Unable to boot Guice Injector", e);
- }
- }
- GuiceContext.buildingInjector = false;
- return GuiceContext.instance().injector;
- }
-
- /**
- * Gets a new injected instance of a class
- *
- * @param The type to retrieve
- * @param type The physical class object
- * @return The scoped object
- */
- @NotNull
- public static T get(@NotNull Class type)
- {
- return get(type, null);
- }
-
- /**
- * Gets a new injected instance of a class
- *
- * @param The type to retrieve
- * @param type The physical class object
- * @return The scoped object
- * @deprecated For get()
- */
- @NotNull
- @Deprecated()
- public static T getInstance(@NotNull Class type)
- {
- return get(type, null);
- }
-
- /**
- * Gets a new injected instance of a class
- *
- * @param The type to retrieve
- * @param type The physical class object
- * @return The scoped object
- * @deprecated For get()
- */
- @NotNull
- @Deprecated()
- public static T getInstance(@NotNull Key type)
- {
- return get(type);
- }
-
- /**
- * Gets a new injected instance of a class
- *
- * @param The type to retrieve
- * @param type The physical class object
- * @return The scoped object
- * @deprecated For get()
- */
- @NotNull
- @Deprecated()
- public static T getInstance(@NotNull Class type, Class extends Annotation> annotation)
- {
- return get(type, annotation);
- }
-
- private static boolean isEntityType(Class> clazz)
- {
- try
- {
- for (Annotation annotation : clazz.getAnnotations())
- {
- if (annotation.annotationType()
- .getCanonicalName()
- .equalsIgnoreCase("jakarta.persistence.Entity"))
- {
- return true;
- }
- }
- }catch (NullPointerException npe )
- {
- return false;
- }
- return false;
- }
-
- private static boolean isNotEnhanceable(Class> clazz)
- {
- return clazz.isAnnotationPresent(INotEnhanceable.class);
- }
-
- private static boolean isNotInjectable(Class> clazz)
- {
- return clazz.isAnnotationPresent(INotInjectable.class);
- }
-
- /**
- * Gets a new injected instance of a class
- *
- * @param The type to retrieve
- * @param type The physical class object
- * @param annotation The annotation to fetch
- * @return The scoped object
- */
- public static T get(@NotNull Class type, Class extends Annotation> annotation)
- {
- if (annotation == null)
- {
- return get(Key.get(type));
- }
- return get(Key.get(type, annotation));
- }
-
- /**
- * Gets a new specified instance from a give key
- *
- * @param The type to retrieve
- * @param type The physical class object
- * @return The scoped object
- */
- @SuppressWarnings("unchecked")
- @NotNull
- public static T get(@NotNull Key type)
- {
- Class clazz = (Class) type.getTypeLiteral()
- .getRawType();
- T instance;
- boolean isEntityType = isEntityType(clazz);
- if (isNotEnhanceable(clazz) || isEntityType)
- {
- try
- {
- instance = clazz.getDeclaredConstructor()
- .newInstance();
- if (!isNotInjectable(clazz))
- {
- inject().injectMembers(instance);
- }
- }
- catch (Exception e)
- {
- log.log(Level.SEVERE, "Unable to construct [" + clazz.getCanonicalName() + "]. Not Enhanceable or an Entity.", e);
- throw new RuntimeException(e);
- }
- }
- else
- {
- instance = inject().getInstance(type);
- }
- return instance;
- }
-
- /**
- * Execute on Destroy
- */
- @SuppressWarnings("unused")
- public static void destroy()
- {
- Set destroyers = GuiceContext.instance()
- .getLoader(IGuicePreDestroy.class, true, ServiceLoader.load(IGuicePreDestroy.class));
- for (IGuicePreDestroy destroyer : destroyers)
- {
- IGuicePreDestroy instance = GuiceContext.get(destroyer.getClass());
- instance.onDestroy();
- }
- if (GuiceContext.instance().scanResult != null)
- {
- GuiceContext.instance().scanResult.close();
- }
- if (GuiceContext.instance().scanResult != null)
- {
- GuiceContext.instance().scanResult.close();
- }
- GuiceContext.instance().scanResult = null;
- GuiceContext.instance().scanner = null;
- GuiceContext.instance().injector = null;
- }
-
- /**
- * Returns the Java version as an int value.
- *
- * @return the Java version as an int value (8, 9, etc.)
- * @since 12130
- */
- private static int getJavaVersion()
- {
- String version = getSystemPropertyOrEnvironment("java.version","11");
- if (version.startsWith("1."))
- {
- version = version.substring(2);
- }
- // Allow these formats:
- // 1.8.0_72-ea
- // 9-ea
- // 9
- // 9.0.1
- int dotPos = version.indexOf('.');
- int dashPos = version.indexOf('-');
- String value = version.substring(0, dotPos > -1 ? dotPos : dashPos > -1 ? dashPos : version.length());
- return Integer.parseInt(value);
- }
-
- /**
- * Returns the current scan result
- *
- * @return The physical Scan Result from the complete class scanner
- */
- @NotNull
- public ScanResult getScanResult()
- {
- if (scanResult == null)
- {
- loadScanner();
- }
- return scanResult;
- }
-
- /**
- * Sets the current scan result
- *
- * @param scanResult The physical Scan Result from the complete class scanner
- */
- @SuppressWarnings("unused")
- public void setScanResult(ScanResult scanResult)
- {
- GuiceContext.instance().scanResult = scanResult;
- }
-
- /**
- * Returns the actual context instance, provides access to methods existing a bit deeper
- *
- * @return The singleton instance of this
- */
- public static GuiceContext> instance()
- {
- return GuiceContext.instance;
- }
-
- private static boolean configured;
-
- /**
- * Loads the IGuiceConfigurator
- */
- private void loadConfiguration()
- {
- if (!configured)
- {
- if (GuiceContext.config == null)
- {
- GuiceContext.config = new GuiceConfig<>();
- }
- Set guiceConfigurators = loadIGuiceConfigs();
- for (IGuiceConfigurator guiceConfigurator : guiceConfigurators)
- {
- GuiceContext.log.config("Loading IGuiceConfigurator - " +
- guiceConfigurator.getClass()
- .getCanonicalName());
- GuiceContext.config = guiceConfigurator.configure(GuiceContext.config);
- }
- GuiceContext.log.config("IGuiceConfigurator : " + GuiceContext.config.toString());
- configured = true;
- }
- }
-
-
- /**
- * Returns a complete list of generic exclusions
- *
- * @return A string list of packages to be scanned
- */
- @SuppressWarnings("unchecked")
- private String[] getJarsExclusionList()
- {
- Set strings = new TreeSet<>();
- Set exclusions = loadJarRejectScanners();
- if (exclusions.iterator()
- .hasNext())
- {
- for (IGuiceScanJarExclusions exclusion : exclusions)
- {
- Set searches = exclusion.excludeJars();
- strings.addAll(searches);
- }
- GuiceContext.log.log(Level.FINE, "IGuiceScanJarExclusions - " + strings.toString());
- }
- return strings.toArray(new String[0]);
- }
-
- /**
- * Returns a complete list of generic exclusions
- *
- * @return A string list of packages to be scanned
- */
- @SuppressWarnings("unchecked")
- private String[] getJarsInclusionList()
- {
- Set strings = new TreeSet<>();
- Set exclusions = loadJarInclusionScanners();
- if (exclusions.iterator()
- .hasNext())
- {
- for (IGuiceScanJarInclusions exclusion : exclusions)
- {
- Set searches = exclusion.includeJars();
- strings.addAll(searches);
- }
- GuiceContext.log.log(Level.FINE, "IGuiceScanJarExclusions - " + strings.toString());
- }
- return strings.toArray(new String[0]);
- }
-
-
- /**
- * Starts up Guice and the scanner
- */
- private synchronized void loadScanner()
- {
- if (scanner == null)
- {
- scanner = new ClassGraph();
- Stopwatch stopwatch = Stopwatch.createStarted();
- GuiceContext.log.info("Loading Classpath Scanner");
- loadConfiguration();
- scanner = configureScanner(scanner);
- try
- {
- if (async)
- {
- scanResult = scanner.scan(Runtime.getRuntime()
- .availableProcessors());
- }
- else
- {
- scanResult = scanner.scan();
- }
- stopwatch.stop();
- Map fileScans = quickScanFiles();
- fileScans.forEach((key, value) ->
- scanResult.getResourcesWithLeafName(key)
- .forEachByteArrayIgnoringIOException(value));
- quickScanFilesPattern().forEach(
- (key, value) ->
- scanResult.getResourcesMatchingPattern(key)
- .forEachByteArrayIgnoringIOException(value));
-
- }
- catch (Exception mpe)
- {
- GuiceContext.log.log(Level.SEVERE, "Unable to run scanner", mpe);
- }
- GuiceContext.log.fine("Loaded Classpath Scanner - Took [" + stopwatch.elapsed(TimeUnit.MILLISECONDS) + "] millis.");
- }
- }
-
- /**
- * Configures the scanner from its setup
- *
- * @param graph The ClassGraph to apply the configuration to
- */
- private ClassGraph configureScanner(ClassGraph graph)
- {
- if (config.isAllowPaths())
- {
- String[] paths = getPathsList();
- if (paths.length != 0)
- {
- graph = graph.acceptPaths(paths);
- }
- }
- if (GuiceContext.config.isExcludePaths())
- {
- String[] blacklistList = getPathsBlacklistList();
- if (blacklistList.length != 0)
- {
- graph = graph.rejectPaths(blacklistList);
- }
- }
-
- if (GuiceContext.config.isExcludeModulesAndJars())
- {
- if (getJavaVersion() < 9)
- {
- String[] jarRejections = getJarsExclusionList();
- if (jarRejections.length != 0)
- {
- graph = graph.rejectJars(jarRejections);
- }
- }
- else
- {
- String[] modulesRejection = getModulesExclusionList();
- if (modulesRejection.length != 0)
- {
- graph = graph.rejectModules(modulesRejection);
- }
- else
- {
- graph = graph.ignoreParentModuleLayers();
- }
- }
- }
-
- if (GuiceContext.config.isIncludeModuleAndJars())
- {
- if (getJavaVersion() < 9)
- {
- String[] jarRejections = getJarsInclusionList();
- log.config("Accepted Jars for Scanning : " + Arrays.toString(jarRejections));
- if (jarRejections.length != 0)
- {
- graph = graph.acceptJars(jarRejections);
- }
- }
- else
- {
- String[] modulesRejection = getModulesInclusionsList();
- log.config("Accepted Modules for Scanning : " + Arrays.toString(modulesRejection));
- if (modulesRejection.length != 0)
- {
- graph = graph.acceptModules(modulesRejection);
- }
- else
- {
- graph = graph.ignoreParentModuleLayers();
- }
- }
- }
-
- if (GuiceContext.config.isIncludePackages())
- {
- String[] packages = getPackagesList();
- if (packages.length != 0)
- {
- graph = graph.acceptPackages(packages);
- }
- }
- if (GuiceContext.config.isRejectPackages())
- {
- String[] packages = getBlacklistPackages();
- if (packages.length != 0)
- {
- graph = graph.rejectPackages(packages);
- }
- }
- if (GuiceContext.config.isExcludeParentModules())
- {
- graph = graph.ignoreParentModuleLayers();
- }
- if (GuiceContext.config.isFieldInfo())
- {
- graph = graph.enableClassInfo();
- graph = graph.enableFieldInfo();
- }
- if (GuiceContext.config.isAnnotationScanning())
- {
- graph = graph.enableClassInfo();
- graph = graph.enableAnnotationInfo();
- }
- if (GuiceContext.config.isMethodInfo())
- {
- graph = graph.enableClassInfo();
- graph = graph.enableMethodInfo();
- }
- if (GuiceContext.config.isIgnoreFieldVisibility())
- {
- graph = graph.enableClassInfo();
- graph = graph.ignoreFieldVisibility();
- }
- if (GuiceContext.config.isIgnoreMethodVisibility())
- {
- graph = graph.enableClassInfo();
- graph = graph.ignoreMethodVisibility();
- }
- if (GuiceContext.config.isClasspathScanning())
- {
- graph = graph.enableClassInfo();
- }
- if (GuiceContext.config.isVerbose())
- {
- graph = graph.verbose();
- }
- if (GuiceContext.config.isIgnoreClassVisibility())
- {
- graph = graph.ignoreClassVisibility();
- }
- return graph;
- }
-
- /**
- * Returns a complete list of generic exclusions
- *
- * @return A string list of packages to be scanned
- */
- private String[] getPackagesList()
- {
- Set strings = new LinkedHashSet<>();
- Set exclusions = getLoader(IPackageContentsScanner.class, true, ServiceLoader.load(IPackageContentsScanner.class));
- if (exclusions.iterator()
- .hasNext())
- {
- for (IPackageContentsScanner exclusion : exclusions)
- {
- GuiceContext.log.log(Level.CONFIG, "Loading IPackageContentsScanner - " +
- exclusion.getClass()
- .getCanonicalName());
- Set searches = exclusion.searchFor();
- strings.addAll(searches);
- }
- GuiceContext.log.log(Level.FINE, "IPackageScanningContentsScanner - " + strings.toString());
- }
- return strings.toArray(new String[0]);
- }
-
- /**
- * Returns a complete list of generic exclusions
- *
- * @return A string list of packages to be scanned
- */
- private String[] getBlacklistPackages()
- {
- Set strings = new LinkedHashSet<>();
- Set exclusions = getLoader(IPackageRejectListScanner.class, true, ServiceLoader.load(IPackageRejectListScanner.class));
- if (exclusions.iterator()
- .hasNext())
- {
- for (IPackageRejectListScanner exclusion : exclusions)
- {
- GuiceContext.log.log(Level.CONFIG, "Loading IPackageContentsScanner - " +
- exclusion.getClass()
- .getCanonicalName());
- Set searches = exclusion.exclude();
- strings.addAll(searches);
- }
- GuiceContext.log.log(Level.FINE, "IPackageScanningContentsScanner - " + strings.toString());
- }
- return strings.toArray(new String[0]);
- }
-
- /*
- * Returns a complete list of generic exclusions
- *
- * @return A string list of packages to be scanned
- */
- private String[] getPathsList()
- {
- Set strings = new TreeSet<>();
- Set exclusions = getLoader(IPathContentsScanner.class, true, ServiceLoader.load(IPathContentsScanner.class));
- if (exclusions.iterator()
- .hasNext())
- {
- for (IPathContentsScanner exclusion : exclusions)
- {
- GuiceContext.log.log(Level.CONFIG, "Loading IPathScanningContentsScanner - " +
- exclusion.getClass()
- .getCanonicalName());
- Set searches = exclusion.searchFor();
- strings.addAll(searches);
- }
- GuiceContext.log.log(Level.FINE, "IPathScanningContentsScanner - " + strings.toString());
- }
- return strings.toArray(new String[0]);
- }
-
- /**
- * Returns a complete list of generic exclusions
- *
- * @return A string list of packages to be scanned
- */
- private String[] getPathsBlacklistList()
- {
- Set strings = new TreeSet<>();
- Set exclusions = loadPathRejectScanners();
- if (exclusions.iterator()
- .hasNext())
- {
- for (IPathContentsRejectListScanner exclusion : exclusions)
- {
- GuiceContext.log.log(Level.CONFIG, "Loading IPathContentsRejectListScanner - " +
- exclusion.getClass()
- .getCanonicalName());
- Set searches = exclusion.searchFor();
- strings.addAll(searches);
- }
- GuiceContext.log.log(Level.FINE, "IPathContentsRejectListScanner - " + strings.toString());
- }
- return strings.toArray(new String[0]);
- }
-
- /**
- * Returns a complete list of generic exclusions
- *
- * @return A string list of packages to be scanned
- */
- @SuppressWarnings("unchecked")
- private String[] getModulesExclusionList()
- {
- Set strings = new TreeSet<>();
- Set exclusions = getLoader(IGuiceScanModuleExclusions.class, true, ServiceLoader.load(IGuiceScanModuleExclusions.class));
- if (exclusions.iterator()
- .hasNext())
- {
- for (IGuiceScanModuleExclusions> exclusion : exclusions)
- {
- Set searches = exclusion.excludeModules();
- strings.addAll(searches);
- }
- GuiceContext.log.log(Level.FINE, "IGuiceScanModuleExclusions - " + strings.toString());
- }
- return strings.toArray(new String[0]);
- }
-
-
- /**
- * Returns a complete list of generic exclusions
- *
- * @return A string list of packages to be scanned
- */
- @SuppressWarnings("unchecked")
- private String[] getModulesInclusionsList()
- {
- Set strings = new TreeSet<>();
- Set exclusions = getLoader(IGuiceScanModuleInclusions.class, true, ServiceLoader.load(IGuiceScanModuleInclusions.class));
- if (exclusions.iterator()
- .hasNext())
- {
- for (IGuiceScanModuleInclusions> exclusion : exclusions)
- {
- Set searches = exclusion.includeModules();
- strings.addAll(searches);
- }
- GuiceContext.log.log(Level.FINE, "IGuiceScanModuleInclusions - " + strings.toString());
- }
- return strings.toArray(new String[0]);
- }
-
- /**
- * Registers the quick scan files
- */
- private Map quickScanFiles()
- {
- Map fileScans = new HashMap<>();
- Set fileScanners = getLoader(IFileContentsScanner.class, true, ServiceLoader.load(IFileContentsScanner.class));
- for (IFileContentsScanner fileScanner : fileScanners)
- {
- GuiceContext.log.log(Level.CONFIG, "Loading IFileContentsScanner - " +
- fileScanner.getClass()
- .getCanonicalName());
- fileScans.putAll(fileScanner.onMatch());
- }
- return fileScans;
- }
-
- /**
- * Registers the quick scan files
- */
- private Map quickScanFilesPattern()
- {
- Map fileScans = new HashMap<>();
- Set fileScanners = getLoader(IFileContentsPatternScanner.class, true, ServiceLoader.load(IFileContentsPatternScanner.class));
- for (IFileContentsPatternScanner fileScanner : fileScanners)
- {
- GuiceContext.log.log(Level.CONFIG, "Loading IFileContentsPatternScanner - " +
- fileScanner.getClass()
- .getCanonicalName());
- fileScans.putAll(fileScanner.onMatch());
- }
- return fileScans;
- }
-
- /**
- * A set
- *
- * @param loaderType The service type
- * @param The type
- * @param dontInject Don't inject
- * @return A set of them
- */
- @SuppressWarnings("unchecked")
- @NotNull
- public Set getLoader(Class loaderType,
- @SuppressWarnings("unused")
- boolean dontInject, ServiceLoader serviceLoader)
- {
- if (!getAllLoadedServices().containsKey(loaderType))
- {
- Set loader = IDefaultService.loaderToSetNoInjection(serviceLoader);
- getAllLoadedServices().put(loaderType, loader);
- }
- return getAllLoadedServices().get(loaderType);
- }
-
- /**
- * Returns the current classpath scanner
- *
- * @return Default processors count
- */
- @SuppressWarnings("unused")
- public ClassGraph getScanner()
- {
- return scanner;
- }
-
- /**
- * Sets the classpath scanner
- *
- * @param scanner Sets the scanner to a specific instance
- */
- @SuppressWarnings("unused")
- public static void setScanner(ClassGraph scanner)
- {
- GuiceContext.instance().scanner = scanner;
- }
-
- /**
- * Method loadPostStartups ...
- */
- private void loadPostStartups()
- {
- Set startupSet = loadPostStartupServices();
-
- Map> postStartupGroups = new TreeMap<>();
- for (IGuicePostStartup> postStartup : startupSet)
- {
- Integer sortOrder = postStartup.sortOrder();
- postStartupGroups.computeIfAbsent(sortOrder, k -> new TreeSet<>())
- .add(postStartup);
- }
-
- for (Map.Entry> entry : postStartupGroups.entrySet())
- {
- Integer key = entry.getKey();
- Set value = entry.getValue();
- if (value.size() == 1)
- {
- //run in order
- for (IGuicePostStartup> iGuicePostStartup : value)
- {
- try
- {
- iGuicePostStartup.postLoad();
- }
- catch (Throwable T)
- {
- log.log(Level.SEVERE, "Cannot execute post startup - " + iGuicePostStartup.getClass()
- .getCanonicalName(), T);
- }
- }
- }
- else
- {
- try
- {
- value.parallelStream()
- .forEach(IGuicePostStartup::postLoad);
- }
- catch (Throwable T)
- {
- log.log(Level.SEVERE, "Cannot execute post startup - ", T);
- }
- }
- GuiceContext.log.fine("Completed with Post Startups Key [" + key + "]");
- }
- }
-
- /**
- * Returns the Guice Config Instance
- *
- * @return The singleton Guice Config instance. Also available with @Inject
- */
- public GuiceConfig> getConfig()
- {
- if (GuiceContext.config == null)
- {
- GuiceContext.config = new GuiceConfig<>();
- }
- return GuiceContext.config;
- }
-
- /**
- * Loads the service lists of post startup's for manual additions
- *
- * @return The list of guice post startups
- */
- public @NotNull
- Set loadPostStartupServices()
- {
- return getLoader(IGuicePostStartup.class, ServiceLoader.load(IGuicePostStartup.class));
- }
-
- /**
- * Loads the service lists of post startup's for manual additions
- *
- * @return The list of guice post startups
- */
- public @NotNull
- Set loadPathRejectScanners()
- {
- return getLoader(IPathContentsRejectListScanner.class, true, ServiceLoader.load(IPathContentsRejectListScanner.class));
- }
-
-
- /**
- * Loads the service lists of post startup's for manual additions
- *
- * @return The list of guice post startups
- */
- public @NotNull
- Set loadJarRejectScanners()
- {
- return getLoader(IGuiceScanJarExclusions.class, true, ServiceLoader.load(IGuiceScanJarExclusions.class));
- }
-
-
- /**
- * Loads the service lists of post startup's for manual additions
- *
- * @return The list of guice post startups
- */
- public @NotNull
- Set loadJarInclusionScanners()
- {
- return getLoader(IGuiceScanJarInclusions.class, true, ServiceLoader.load(IGuiceScanJarInclusions.class));
- }
-
-
- /**
- * Returns the set of service lists of pre startup's for manual additions
- *
- * @return The list of guice post startups
- */
- public @NotNull
- Set loadPreStartupServices()
- {
- return getLoader(IGuicePreStartup.class, true, ServiceLoader.load(IGuicePreStartup.class));
- }
-
- /**
- * Loads the service lists of post startup's for manual additions
- *
- * @return The list of guice post startups
- */
- public @NotNull
- Set loadIGuiceModules()
- {
- return getLoader(IGuiceModule.class, true, ServiceLoader.load(IGuiceModule.class));
- }
-
- /**
- * Loads the service lists of guice configurators (before pre-startup) for manual additions
- *
- * @return The list of guice configs
- */
- public @NotNull
- Set loadIGuiceConfigs()
- {
- return getLoader(IGuiceConfigurator.class, true, ServiceLoader.load(IGuiceConfigurator.class));
- }
-
- /**
- * Method loadPreStartups gets the pre startups and loads them up
- */
- private void loadPreStartups()
- {
- Set preStartups = loadPreStartupServices();
- List startups = new ArrayList<>(preStartups);
- startups.sort(Comparator.comparing(IGuicePreStartup::sortOrder));
- for (IGuicePreStartup startup : startups)
- {
- GuiceContext.log.config("Loading IGuicePreStartup - " +
- startup.getClass()
- .getCanonicalName());
- startup.onStartup();
- }
- }
-
- /**
- * Returns the loader for anything that is located locally in guice context
- * replacing with set load methods instead for each type
- *
- * @param loaderType The service type
- * @param The type
- * @return A set of them
- */
- @SuppressWarnings("unchecked")
- @NotNull
- public > Set getLoader(Class loaderType, ServiceLoader serviceLoader)
- {
- if (!getAllLoadedServices().containsKey(loaderType))
- {
- Set loader;
- if (GuiceContext.buildingInjector || injector == null)
- {
- loader = IDefaultService.loaderToSetNoInjection(serviceLoader);
- }
- else
- {
- loader = IDefaultService.loaderToSet(serviceLoader);
- }
- getAllLoadedServices().put(loaderType, loader);
- }
- return getAllLoadedServices().get(loaderType);
- }
-
- /**
- * Method getAllLoadedServices returns the allLoadedServices of this GuiceContext object.
- *
- * A list of all the loaded singleton sets
- *
- * @return the allLoadedServices (type Map Class, Set ) of this GuiceContext object.
- */
- @SuppressWarnings("WeakerAccess")
- @NotNull
- public static Map getAllLoadedServices()
- {
- return allLoadedServices;
- }
-
- /**
- * If this scanner is registered to run asynchronously
- *
- * @return
- */
- public boolean isAsync()
- {
- return async;
- }
-
- /**
- * Sets if the scanner must run asynchronously
- *
- * @param async
- */
- public void setAsync(boolean async)
- {
- this.async = async;
- }
+ /**
+ * This particular instance of the class
+ */
+ private static final GuiceContext> instance = new GuiceContext<>();
+
+ /**
+ * A list of all the loaded singleton sets
+ */
+ //private static final Map allLoadedServices = new LinkedHashMap<>();
+ /**
+ * The building injector
+ */
+ public static boolean buildingInjector = false;
+ /**
+ * The configuration object
+ */
+ private static final GuiceConfig> config = new GuiceConfig<>();
+ /**
+ * The physical injector for the JVM container
+ */
+ private Injector injector;
+ /**
+ * The actual scanner
+ */
+ private ClassGraph scanner;
+ /**
+ * The scan result built from everything - the core scanner.
+ */
+ private ScanResult scanResult;
+ /**
+ * If the scan should run async
+ */
+ private boolean async = true;
+ /**
+ * If this context is configured
+ */
+ private static boolean configured;
+
+ /**
+ * Creates a new Guice context. Not necessary
+ */
+ private GuiceContext()
+ {
+ //No config required
+ }
+
+
+ /**
+ * Reference the Injector Directly
+ *
+ * @return The global Guice Injector Object, Never Null, Instantiates the Injector if not configured
+ */
+
+ public synchronized Injector inject()
+ {
+ if (GuiceContext.buildingInjector)
+ {
+ log.log(Level.SEVERE, "The injector is being called recursively during build. Place such actions in a IGuicePostStartup or use the IGuicePreStartup Service Loader.");
+ System.exit(1);
+ }
+ if (GuiceContext.instance().injector == null)
+ {
+ try
+ {
+ GuiceContext.buildingInjector = true;
+ GuiceContext.log.info("Starting up Guice Context");
+ GuiceContext
+ .instance()
+ .loadConfiguration();
+ if (GuiceContext
+ .instance()
+ .getConfig()
+ .isPathScanning() || GuiceContext
+ .instance()
+ .getConfig()
+ .isClasspathScanning())
+ {
+ GuiceContext
+ .instance()
+ .loadScanner();
+ }
+ GuiceContext
+ .instance()
+ .loadPreStartups();
+
+ List cModules = new ArrayList<>(modules);
+ Set iGuiceModules = GuiceContext
+ .instance()
+ .loadIGuiceModules();
+ cModules.addAll(iGuiceModules);
+
+ //cModules.add(new GuiceInjectorModule());
+ log.config("Modules - " + Arrays.toString(cModules.toArray()));
+ GuiceContext.instance().injector = Guice.createInjector(cModules);
+ GuiceContext.buildingInjector = false;
+ GuiceContext
+ .instance()
+ .loadPostStartups();
+
+ Runtime
+ .getRuntime()
+ .addShutdownHook(new Thread()
+ {
+ public void run()
+ {
+ IGuiceContext
+ .getContext()
+ .destroy();
+ }
+ });
+
+ GuiceContext.log.config("Injection System Ready");
+ }
+ catch (Throwable e)
+ {
+ GuiceContext.log.log(Level.SEVERE, "Exception creating Injector : " + e.getMessage(), e);
+ throw new RuntimeException("Unable to boot Guice Injector", e);
+ }
+ }
+ GuiceContext.buildingInjector = false;
+ return GuiceContext.instance().injector;
+ }
+
+ private static Set destroyers = GuiceContext
+ .instance()
+ .getLoader(IGuicePreDestroy.class, false, ServiceLoader.load(IGuicePreDestroy.class));
+
+ /**
+ * Execute on Destroy
+ */
+ @SuppressWarnings("unused")
+ public void destroy()
+ {
+ try
+ {
+ for (IGuicePreDestroy destroyer : destroyers)
+ {
+ try
+ {
+ destroyer.onDestroy();
+ }
+ catch (Throwable T)
+ {
+ log.log(Level.SEVERE,
+ "Could not run destroyer [" + destroyer
+ .getClass()
+ .getCanonicalName() + "]");
+ }
+ }
+ }
+ catch (Throwable T)
+ {
+ log.log(Level.SEVERE, "Could not run destroyers", T);
+ }
+ if (GuiceContext.instance().scanResult != null)
+ {
+ GuiceContext.instance().scanResult.close();
+ }
+ if (GuiceContext.instance().scanResult != null)
+ {
+ GuiceContext.instance().scanResult.close();
+ }
+ GuiceContext.instance().scanResult = null;
+ GuiceContext.instance().scanner = null;
+ GuiceContext.instance().injector = null;
+ }
+
+ /**
+ * Returns the Java version as an int value.
+ *
+ * @return the Java version as an int value (8, 9, etc.)
+ * @since 12130
+ */
+ private static int getJavaVersion()
+ {
+ String version = getSystemPropertyOrEnvironment("java.version", "11");
+ if (version.startsWith("1."))
+ {
+ version = version.substring(2);
+ }
+ // Allow these formats:
+ // 1.8.0_72-ea
+ // 9-ea
+ // 9
+ // 9.0.1
+ int dotPos = version.indexOf('.');
+ int dashPos = version.indexOf('-');
+ String value = version.substring(0, dotPos > -1 ? dotPos : dashPos > -1 ? dashPos : version.length());
+ return Integer.parseInt(value);
+ }
+
+ /**
+ * Returns the current scan result
+ *
+ * @return The physical Scan Result from the complete class scanner
+ */
+
+ public ScanResult getScanResult()
+ {
+ if (scanResult == null)
+ {
+ loadScanner();
+ }
+ return scanResult;
+ }
+
+ /**
+ * Sets the current scan result
+ *
+ * @param scanResult The physical Scan Result from the complete class scanner
+ */
+ @SuppressWarnings("unused")
+ public void setScanResult(ScanResult scanResult)
+ {
+ GuiceContext.instance().scanResult = scanResult;
+ }
+
+ /**
+ * Returns the actual context instance, provides access to methods existing a bit deeper
+ *
+ * @return The singleton instance of this
+ */
+ public static GuiceContext> instance()
+ {
+ return GuiceContext.instance;
+ }
+
+ /**
+ * Loads the IGuiceConfigurator
+ */
+ private void loadConfiguration()
+ {
+ if (!configured)
+ {
+ Set guiceConfigurators = loadIGuiceConfigs();
+ for (IGuiceConfigurator guiceConfigurator : guiceConfigurators)
+ {
+ GuiceContext.log.config("Loading IGuiceConfigurator - " + guiceConfigurator
+ .getClass()
+ .getCanonicalName());
+ guiceConfigurator.configure(GuiceContext.config);
+ }
+ if (!GuiceContext.config.isIncludeModuleAndJars())
+ {
+ log.warning("Scanning is not restricted to modules and may incur a performance impact. Consider registering your module with GuiceContext.registerModule() to auto enable, or SPI IGuiceConfiguration");
+ }
+ GuiceContext.log.config("IGuiceConfigurator : " + GuiceContext.config.toString());
+ configured = true;
+ }
+ }
+
+ /**
+ * Returns a complete list of generic exclusions
+ *
+ * @return A string list of packages to be scanned
+ */
+ @SuppressWarnings("unchecked")
+ private String[] getJarsExclusionList()
+ {
+ Set strings = new TreeSet<>();
+ Set exclusions = loadJarRejectScanners();
+ if (exclusions
+ .iterator()
+ .hasNext())
+ {
+ for (IGuiceScanJarExclusions exclusion : exclusions)
+ {
+ Set searches = exclusion.excludeJars();
+ strings.addAll(searches);
+ }
+ GuiceContext.log.log(Level.FINE, "IGuiceScanJarExclusions - " + strings.toString());
+ }
+ return strings.toArray(new String[0]);
+ }
+
+ /**
+ * Returns a complete list of generic exclusions
+ *
+ * @return A string list of packages to be scanned
+ */
+ @SuppressWarnings("unchecked")
+ private String[] getJarsInclusionList()
+ {
+ Set strings = new TreeSet<>();
+ Set exclusions = loadJarInclusionScanners();
+ if (exclusions
+ .iterator()
+ .hasNext())
+ {
+ for (IGuiceScanJarInclusions exclusion : exclusions)
+ {
+ Set searches = exclusion.includeJars();
+ strings.addAll(searches);
+ }
+ GuiceContext.log.log(Level.FINE, "IGuiceScanJarExclusions - " + strings.toString());
+ }
+ return strings.toArray(new String[0]);
+ }
+
+
+ /**
+ * Starts up Guice and the scanner
+ */
+ private synchronized void loadScanner()
+ {
+ if (scanner == null)
+ {
+ scanner = new ClassGraph();
+ Stopwatch stopwatch = Stopwatch.createStarted();
+ GuiceContext.log.info("Loading Classpath Scanner");
+ loadConfiguration();
+ scanner = configureScanner(scanner);
+ try
+ {
+ if (async)
+ {
+ scanResult = scanner.scan(Runtime
+ .getRuntime()
+ .availableProcessors());
+ }
+ else
+ {
+ scanResult = scanner.scan();
+ }
+ stopwatch.stop();
+ Map fileScans = quickScanFiles();
+ fileScans.forEach((key, value) -> scanResult
+ .getResourcesWithLeafName(key)
+ .forEachByteArrayIgnoringIOException(value));
+ quickScanFilesPattern().forEach((key, value) -> scanResult
+ .getResourcesMatchingPattern(key)
+ .forEachByteArrayIgnoringIOException(value));
+
+ }
+ catch (Exception mpe)
+ {
+ GuiceContext.log.log(Level.SEVERE, "Unable to run scanner", mpe);
+ }
+ GuiceContext.log.fine("Loaded Classpath Scanner - Took [" + stopwatch.elapsed(TimeUnit.MILLISECONDS) + "] millis.");
+ }
+ }
+
+ /**
+ * Configures the scanner from its setup
+ *
+ * @param graph The ClassGraph to apply the configuration to
+ */
+ private ClassGraph configureScanner(ClassGraph graph)
+ {
+ if (config.isAllowPaths())
+ {
+ String[] paths = getPathsList();
+ if (paths.length != 0)
+ {
+ graph = graph.acceptPaths(paths);
+ }
+ }
+ if (GuiceContext.config.isExcludePaths())
+ {
+ String[] blacklistList = getPathsBlacklistList();
+ if (blacklistList.length != 0)
+ {
+ graph = graph.rejectPaths(blacklistList);
+ }
+ }
+
+ if (GuiceContext.config.isExcludeModulesAndJars())
+ {
+ if (getJavaVersion() < 9)
+ {
+ String[] jarRejections = getJarsExclusionList();
+ if (jarRejections.length != 0)
+ {
+ graph = graph.rejectJars(jarRejections);
+ }
+ }
+ else
+ {
+ String[] modulesRejection = getModulesExclusionList();
+ if (modulesRejection.length != 0)
+ {
+ graph = graph.rejectModules(modulesRejection);
+ }
+ else
+ {
+ graph = graph.ignoreParentModuleLayers();
+ }
+ }
+ }
+
+ if (GuiceContext.config.isIncludeModuleAndJars())
+ {
+ if (getJavaVersion() < 9)
+ {
+ String[] jarRejections = getJarsInclusionList();
+ log.config("Accepted Jars for Scanning : " + Arrays.toString(jarRejections));
+ if (jarRejections.length != 0)
+ {
+ graph = graph.acceptJars(jarRejections);
+ }
+ }
+ else
+ {
+ String[] modulesRejection = getModulesInclusionsList();
+ log.config("Accepted Modules for Scanning : " + Arrays.toString(modulesRejection));
+ if (modulesRejection.length != 0)
+ {
+ graph = graph.acceptModules(modulesRejection);
+ }
+ else
+ {
+ graph = graph.ignoreParentModuleLayers();
+ }
+ }
+ }
+
+ if (GuiceContext.config.isIncludePackages())
+ {
+ String[] packages = getPackagesList();
+ if (packages.length != 0)
+ {
+ graph = graph.acceptPackages(packages);
+ }
+ }
+ if (GuiceContext.config.isRejectPackages())
+ {
+ String[] packages = getBlacklistPackages();
+ if (packages.length != 0)
+ {
+ graph = graph.rejectPackages(packages);
+ }
+ }
+ if (GuiceContext.config.isExcludeParentModules())
+ {
+ graph = graph.ignoreParentModuleLayers();
+ }
+ if (GuiceContext.config.isFieldInfo())
+ {
+ graph = graph.enableClassInfo();
+ graph = graph.enableFieldInfo();
+ }
+ if (GuiceContext.config.isAnnotationScanning())
+ {
+ graph = graph.enableClassInfo();
+ graph = graph.enableAnnotationInfo();
+ }
+ if (GuiceContext.config.isMethodInfo())
+ {
+ graph = graph.enableClassInfo();
+ graph = graph.enableMethodInfo();
+ }
+ if (GuiceContext.config.isIgnoreFieldVisibility())
+ {
+ graph = graph.enableClassInfo();
+ graph = graph.ignoreFieldVisibility();
+ }
+ if (GuiceContext.config.isIgnoreMethodVisibility())
+ {
+ graph = graph.enableClassInfo();
+ graph = graph.ignoreMethodVisibility();
+ }
+ if (GuiceContext.config.isClasspathScanning())
+ {
+ graph = graph.enableClassInfo();
+ }
+ if (GuiceContext.config.isVerbose())
+ {
+ graph = graph.verbose();
+ }
+ if (GuiceContext.config.isIgnoreClassVisibility())
+ {
+ graph = graph.ignoreClassVisibility();
+ }
+ return graph;
+ }
+
+ /**
+ * Returns a complete list of generic exclusions
+ *
+ * @return A string list of packages to be scanned
+ */
+ private String[] getPackagesList()
+ {
+ Set strings = new LinkedHashSet<>();
+ Set exclusions = getLoader(IPackageContentsScanner.class, true, ServiceLoader.load(IPackageContentsScanner.class));
+ if (exclusions
+ .iterator()
+ .hasNext())
+ {
+ for (IPackageContentsScanner exclusion : exclusions)
+ {
+ GuiceContext.log.log(Level.CONFIG,
+ "Loading IPackageContentsScanner - " + exclusion
+ .getClass()
+ .getCanonicalName());
+ Set searches = exclusion.searchFor();
+ strings.addAll(searches);
+ }
+ GuiceContext.log.log(Level.FINE, "IPackageScanningContentsScanner - " + strings.toString());
+ }
+ return strings.toArray(new String[0]);
+ }
+
+ /**
+ * Returns a complete list of generic exclusions
+ *
+ * @return A string list of packages to be scanned
+ */
+ private String[] getBlacklistPackages()
+ {
+ Set strings = new LinkedHashSet<>();
+ Set exclusions = getLoader(IPackageRejectListScanner.class, true, ServiceLoader.load(IPackageRejectListScanner.class));
+ if (exclusions
+ .iterator()
+ .hasNext())
+ {
+ for (IPackageRejectListScanner exclusion : exclusions)
+ {
+ GuiceContext.log.log(Level.CONFIG,
+ "Loading IPackageContentsScanner - " + exclusion
+ .getClass()
+ .getCanonicalName());
+ Set searches = exclusion.exclude();
+ strings.addAll(searches);
+ }
+ GuiceContext.log.log(Level.FINE, "IPackageScanningContentsScanner - " + strings.toString());
+ }
+ return strings.toArray(new String[0]);
+ }
+
+ /*
+ * Returns a complete list of generic exclusions
+ *
+ * @return A string list of packages to be scanned
+ */
+ private String[] getPathsList()
+ {
+ Set strings = new TreeSet<>();
+ Set exclusions = getLoader(IPathContentsScanner.class, true, ServiceLoader.load(IPathContentsScanner.class));
+ if (exclusions
+ .iterator()
+ .hasNext())
+ {
+ for (IPathContentsScanner exclusion : exclusions)
+ {
+ GuiceContext.log.log(Level.CONFIG,
+ "Loading IPathScanningContentsScanner - " + exclusion
+ .getClass()
+ .getCanonicalName());
+ Set searches = exclusion.searchFor();
+ strings.addAll(searches);
+ }
+ GuiceContext.log.log(Level.FINE, "IPathScanningContentsScanner - " + strings.toString());
+ }
+ return strings.toArray(new String[0]);
+ }
+
+ /**
+ * Returns a complete list of generic exclusions
+ *
+ * @return A string list of packages to be scanned
+ */
+ private String[] getPathsBlacklistList()
+ {
+ Set strings = new TreeSet<>();
+ Set exclusions = loadPathRejectScanners();
+ if (exclusions
+ .iterator()
+ .hasNext())
+ {
+ for (IPathContentsRejectListScanner exclusion : exclusions)
+ {
+ GuiceContext.log.log(Level.CONFIG,
+ "Loading IPathContentsRejectListScanner - " + exclusion
+ .getClass()
+ .getCanonicalName());
+ Set searches = exclusion.searchFor();
+ strings.addAll(searches);
+ }
+ GuiceContext.log.log(Level.FINE, "IPathContentsRejectListScanner - " + strings.toString());
+ }
+ return strings.toArray(new String[0]);
+ }
+
+ /**
+ * Returns a complete list of generic exclusions
+ *
+ * @return A string list of packages to be scanned
+ */
+ @SuppressWarnings("unchecked")
+ private String[] getModulesExclusionList()
+ {
+ Set strings = new TreeSet<>();
+ Set exclusions = getLoader(IGuiceScanModuleExclusions.class, true, ServiceLoader.load(IGuiceScanModuleExclusions.class));
+ if (exclusions
+ .iterator()
+ .hasNext())
+ {
+ for (IGuiceScanModuleExclusions> exclusion : exclusions)
+ {
+ Set searches = exclusion.excludeModules();
+ strings.addAll(searches);
+ }
+ GuiceContext.log.log(Level.FINE, "IGuiceScanModuleExclusions - " + strings.toString());
+ }
+ return strings.toArray(new String[0]);
+ }
+
+ /**
+ * Returns a complete list of generic exclusions
+ *
+ * @return A string list of packages to be scanned
+ */
+ @SuppressWarnings("unchecked")
+ private String[] getModulesInclusionsList()
+ {
+ Set strings = new TreeSet<>();
+ strings.addAll(registerModuleForScanning);
+ Set exclusions = getLoader(IGuiceScanModuleInclusions.class, true, ServiceLoader.load(IGuiceScanModuleInclusions.class));
+ if (exclusions
+ .iterator()
+ .hasNext())
+ {
+ for (IGuiceScanModuleInclusions> exclusion : exclusions)
+ {
+ Set searches = exclusion.includeModules();
+ strings.addAll(searches);
+ }
+ GuiceContext.log.log(Level.FINE, "IGuiceScanModuleInclusions - " + strings.toString());
+ }
+ return strings.toArray(new String[0]);
+ }
+
+ /**
+ * Registers the quick scan files
+ */
+ private Map quickScanFiles()
+ {
+ Map fileScans = new HashMap<>();
+ Set fileScanners = getLoader(IFileContentsScanner.class, true, ServiceLoader.load(IFileContentsScanner.class));
+ for (IFileContentsScanner fileScanner : fileScanners)
+ {
+ GuiceContext.log.log(Level.CONFIG,
+ "Loading IFileContentsScanner - " + fileScanner
+ .getClass()
+ .getCanonicalName());
+ fileScans.putAll(fileScanner.onMatch());
+ }
+ return fileScans;
+ }
+
+ /**
+ * Registers the quick scan files
+ */
+ private Map quickScanFilesPattern()
+ {
+ Map fileScans = new HashMap<>();
+ Set fileScanners = getLoader(IFileContentsPatternScanner.class, true, ServiceLoader.load(IFileContentsPatternScanner.class));
+ for (IFileContentsPatternScanner fileScanner : fileScanners)
+ {
+ GuiceContext.log.log(Level.CONFIG,
+ "Loading IFileContentsPatternScanner - " + fileScanner
+ .getClass()
+ .getCanonicalName());
+ fileScans.putAll(fileScanner.onMatch());
+ }
+ return fileScans;
+ }
+
+ /**
+ * A set
+ *
+ * @param loaderType The service type
+ * @param The type
+ * @param dontInject Don't inject
+ * @return A set of them
+ */
+ @SuppressWarnings("unchecked")
+
+ public Set getLoader(Class loaderType, @SuppressWarnings("unused") boolean dontInject, ServiceLoader serviceLoader)
+ {
+ if (!IGuiceContext
+ .getAllLoadedServices()
+ .containsKey(loaderType))
+ {
+ Set loader = IGuiceContext.loaderToSetNoInjection(serviceLoader);
+ IGuiceContext
+ .getAllLoadedServices()
+ .put(loaderType, loader);
+ }
+ return IGuiceContext
+ .getAllLoadedServices()
+ .get(loaderType);
+ }
+
+ @Override
+ public boolean isBuildingInjector()
+ {
+ return buildingInjector;
+ }
+
+ /**
+ * Returns the current classpath scanner
+ *
+ * @return Default processors count
+ */
+ @SuppressWarnings("unused")
+ public ClassGraph getScanner()
+ {
+ return scanner;
+ }
+
+ /**
+ * Sets the classpath scanner
+ *
+ * @param scanner Sets the scanner to a specific instance
+ */
+ @SuppressWarnings("unused")
+ public static void setScanner(ClassGraph scanner)
+ {
+ GuiceContext.instance().scanner = scanner;
+ }
+
+ /**
+ * Method loadPostStartups ...
+ */
+ private void loadPostStartups()
+ {
+ Set startupSet = loadPostStartupServices();
+ Map> groupedPostStartup = startupSet.stream()
+ .collect(groupingBy(IGuicePostStartup::sortOrder, toSet()));
+ /* Map>> postStartupGroups = new TreeMap<>();
+
+ for (IGuicePostStartup> postStartup : startupSet)
+ {
+ Integer sortOrder = postStartup.sortOrder();
+ postStartupGroups
+ .computeIfAbsent(sortOrder, k -> new TreeSet<>())
+ .add(postStartup);
+ }
+*/
+ for (Map.Entry> entry : groupedPostStartup.entrySet())
+ {
+ Integer key = entry.getKey();
+ Set value = entry.getValue();
+ if (value.size() == 1)
+ {
+ //run in order
+ for (IGuicePostStartup> iGuicePostStartup : value)
+ {
+ try
+ {
+ iGuicePostStartup.postLoad();
+ }
+ catch (Throwable T)
+ {
+ log.log(Level.SEVERE,
+ "Cannot execute post startup - " + iGuicePostStartup
+ .getClass()
+ .getCanonicalName(),
+ T);
+ }
+ }
+ }
+ else
+ {
+ log.info("Starting Post Startup Group [" + key + "] in Parallel");
+ List> futures = new ArrayList<>();
+ for (IGuicePostStartup> iGuicePostStartup : value)
+ {
+ futures.add(CompletableFuture.runAsync(iGuicePostStartup::postLoad));
+ }
+ try
+ {
+ CompletableFuture.allOf(futures.toArray(new CompletableFuture[]{})).join();
+ }
+ catch (Exception e)
+ {
+ log.log(Level.SEVERE, "Exception in completing post startups", e);
+ }
+ }
+ GuiceContext.log.fine("Completed with Post Startups Key [" + key + "]");
+ }
+ }
+
+ /**
+ * Returns the Guice Config Instance
+ *
+ * @return The singleton Guice Config instance. Also available with @Inject
+ */
+ public GuiceConfig> getConfig()
+ {
+ return GuiceContext.config;
+ }
+
+ /**
+ * Loads the service lists of post startup's for manual additions
+ *
+ * @return The list of guice post startups
+ */
+ public Set loadPostStartupServices()
+ {
+ return new TreeSet<>(getLoader(IGuicePostStartup.class, ServiceLoader.load(IGuicePostStartup.class)));
+ }
+
+ /**
+ * Loads the service lists of post startup's for manual additions
+ *
+ * @return The list of guice post startups
+ */
+ public Set loadPathRejectScanners()
+ {
+ return getLoader(IPathContentsRejectListScanner.class, true, ServiceLoader.load(IPathContentsRejectListScanner.class));
+ }
+
+
+ /**
+ * Loads the service lists of post startup's for manual additions
+ *
+ * @return The list of guice post startups
+ */
+ public Set loadJarRejectScanners()
+ {
+ return getLoader(IGuiceScanJarExclusions.class, true, ServiceLoader.load(IGuiceScanJarExclusions.class));
+ }
+
+
+ /**
+ * Loads the service lists of post startup's for manual additions
+ *
+ * @return The list of guice post startups
+ */
+ public Set loadJarInclusionScanners()
+ {
+ return getLoader(IGuiceScanJarInclusions.class, true, ServiceLoader.load(IGuiceScanJarInclusions.class));
+ }
+
+
+ /**
+ * Returns the set of service lists of pre startup's for manual additions
+ *
+ * @return The list of guice post startups
+ */
+ public Set loadPreStartupServices()
+ {
+ return new TreeSet<>(getLoader(IGuicePreStartup.class, true, ServiceLoader.load(IGuicePreStartup.class)));
+ }
+
+ /**
+ * Loads the service lists of post startup's for manual additions
+ *
+ * @return The list of guice post startups
+ */
+ public Set loadIGuiceModules()
+ {
+ return new TreeSet<>(getLoader(IGuiceModule.class, true, ServiceLoader.load(IGuiceModule.class)));
+ }
+
+ /**
+ * Loads the service lists of guice configurators (before pre-startup) for manual additions
+ *
+ * @return The list of guice configs
+ */
+ public Set loadIGuiceConfigs()
+ {
+ return getLoader(IGuiceConfigurator.class, true, ServiceLoader.load(IGuiceConfigurator.class));
+ }
+
+ /**
+ * Method loadPreStartups gets the pre startups and loads them up
+ */
+ private void loadPreStartups()
+ {
+ Set preStartups = loadPreStartupServices();
+ for (IGuicePreStartup startup : preStartups)
+ {
+ GuiceContext.log.config("Loading IGuicePreStartup - " + startup
+ .getClass()
+ .getCanonicalName());
+ startup.onStartup();
+ }
+ }
+
+ /**
+ * Returns the loader for anything that is located locally in guice context
+ * replacing with set load methods instead for each type
+ *
+ * @param loaderType The service type
+ * @param The type
+ * @return A set of them
+ */
+ @SuppressWarnings("unchecked")
+
+ public > Set getLoader(Class loaderType, ServiceLoader serviceLoader)
+ {
+ if (!IGuiceContext
+ .getAllLoadedServices()
+ .containsKey(loaderType))
+ {
+ Set loader;
+ if (GuiceContext.buildingInjector || injector == null)
+ {
+ loader = IGuiceContext.loaderToSetNoInjection(serviceLoader);
+ }
+ else
+ {
+ loader = IGuiceContext.loaderToSet(serviceLoader);
+ }
+ IGuiceContext
+ .getAllLoadedServices()
+ .put(loaderType, loader);
+ }
+ return IGuiceContext
+ .getAllLoadedServices()
+ .get(loaderType);
+ }
+
+ /**
+ * If this scanner is registered to run asynchronously
+ *
+ * @return
+ */
+ public boolean isAsync()
+ {
+ return async;
+ }
+
+ /**
+ * Sets if the scanner must run asynchronously
+ *
+ * @param async
+ */
+ public void setAsync(boolean async)
+ {
+ this.async = async;
+ }
}
diff --git a/src/main/java/com/guicedee/guicedinjection/JobService.java b/src/main/java/com/guicedee/guicedinjection/JobService.java
new file mode 100644
index 0000000..f03ecb0
--- /dev/null
+++ b/src/main/java/com/guicedee/guicedinjection/JobService.java
@@ -0,0 +1,389 @@
+package com.guicedee.guicedinjection;
+
+import com.google.inject.Singleton;
+import com.guicedee.guicedinjection.interfaces.*;
+import lombok.Getter;
+import lombok.Setter;
+import lombok.extern.java.Log;
+
+import java.util.Map;
+import java.util.Set;
+import java.util.concurrent.*;
+import java.util.logging.Level;
+
+
+/**
+ * Manages All Concurrent Threaded Jobs that execute asynchronously outside of the EE Context
+ */
+
+@Singleton
+@Log
+public class JobService implements IGuicePreDestroy, IJobService
+{
+ private final Map serviceMap = new ConcurrentHashMap<>();
+ private final Map pollingMap = new ConcurrentHashMap<>();
+ private final Map maxQueueCount = new ConcurrentHashMap<>();
+
+ private final ExecutorServiceSupplier executorServiceSupplier = new ExecutorServiceSupplier();
+
+ @Getter
+ @Setter
+ private static long defaultWaitTime = 120;
+ @Getter
+ @Setter
+ private static TimeUnit defaultWaitUnit = TimeUnit.SECONDS;
+
+ public static final JobService INSTANCE = new JobService();
+ private static ExecutorService jobCleanup = null;
+
+ static
+ {
+ jobCleanup = INSTANCE.jobCleanup();
+ }
+
+ public JobService()
+ {
+ //No config required
+ }
+
+ /**
+ * Gets a list of all job pools currently registered
+ *
+ * @return
+ */
+ @Override
+ public Set getJobPools()
+ {
+ return serviceMap.keySet();
+ }
+
+ /**
+ * Returns the list of repeating task pools registered
+ *
+ * @return
+ */
+ @Override
+ public Set getPollingPools()
+ {
+ return pollingMap.keySet();
+ }
+
+ /**
+ * Completes and Removes all jobs running from the given pool
+ *
+ * @param pool The pool to remove
+ */
+ @Override
+ public ExecutorService removeJob(String pool)
+ {
+ ExecutorService es = serviceMap.get(pool);
+ if (es == null)
+ {
+ log.warning("Pool " + pool + " was not registered");
+ return null;
+ }
+ waitForJob(pool);
+ serviceMap.remove(pool);
+ return es;
+ }
+
+ /**
+ * Completes and Removes all jobs running from the given pool
+ *
+ * @param pool The pool to remove
+ */
+ public ExecutorService removeJobNoWait(String pool)
+ {
+ ExecutorService es = serviceMap.get(pool);
+ if (es == null)
+ {
+ log.warning("Pool " + pool + " was not registered");
+ return null;
+ }
+ waitForJob(pool,1L,TimeUnit.MILLISECONDS);
+ serviceMap.remove(pool);
+ return es;
+ }
+
+ /**
+ * Completes and Removes all jobs running from the given pool
+ *
+ * @param pool The pool name to remove
+ */
+ @Override
+ public ScheduledExecutorService removePollingJob(String pool)
+ {
+ ScheduledExecutorService es = pollingMap.get(pool);
+ if (es == null)
+ {
+ log.warning("Repeating Pool " + pool + " was not registered");
+ return null;
+ }
+ waitForJob(pool);
+ pollingMap.remove(pool);
+ return es;
+ }
+
+ /**
+ * Registers a new job pool with a specific service
+ *
+ * @param name
+ * @param executorService
+ */
+ @Override
+ public ExecutorService registerJobPool(String name, ExecutorService executorService)
+ {
+ if (serviceMap.containsKey(name))
+ {
+ removeJob(name);
+ }
+ serviceMap.put(name, executorService);
+ if (!maxQueueCount.containsKey(name))
+ {
+ maxQueueCount.put(name, 20);
+ }
+ if (executorService instanceof ForkJoinPool)
+ {
+ ForkJoinPool pool = (ForkJoinPool) executorService;
+ }
+ else if (executorService instanceof ThreadPoolExecutor)
+ {
+ ThreadPoolExecutor executor = (ThreadPoolExecutor) executorService;
+ executor.setMaximumPoolSize(maxQueueCount.get(name));
+ executor.setKeepAliveTime(defaultWaitTime, defaultWaitUnit);
+ executor.setRejectedExecutionHandler(new ThreadPoolExecutor.DiscardPolicy());
+ }
+
+ return executorService;
+ }
+
+ /**
+ * Registers a repeating task to be registered and monitored
+ *
+ * @param name The name of the pool
+ * @param executorService The service executor
+ */
+ @Override
+ public ScheduledExecutorService registerJobPollingPool(String name, ScheduledExecutorService executorService)
+ {
+ if (pollingMap.containsKey(name))
+ {
+ removeJob(name);
+ }
+ pollingMap.put(name, executorService);
+ return executorService;
+ }
+
+ /**
+ * Adds a static run once job to the monitored collections
+ *
+ * @param jobPoolName
+ * @param thread
+ */
+ @Override
+ public ExecutorService addJob(String jobPoolName, Runnable thread)
+ {
+ if (!serviceMap.containsKey(jobPoolName) || serviceMap
+ .get(jobPoolName)
+ .isTerminated() || serviceMap
+ .get(jobPoolName)
+ .isShutdown())
+ {
+ registerJobPool(jobPoolName, executorServiceSupplier.get());
+ }
+
+ ExecutorService service = serviceMap.get(jobPoolName);
+ if (getCurrentTaskCount(service) >= maxQueueCount.get(jobPoolName))
+ {
+ log.log(Level.FINER, maxQueueCount + " Hit - Finishing before next run");
+ removeJob(jobPoolName);
+ service = registerJobPool(jobPoolName, executorServiceSupplier.get());
+ }
+ service.execute(thread);
+ return service;
+ }
+
+ /**
+ * Adds a static run once job to the monitored collections
+ *
+ * @param jobPoolName
+ * @param thread
+ */
+ @Override
+ public Future> addTask(String jobPoolName, Callable> thread)
+ {
+ if (!serviceMap.containsKey(jobPoolName) || serviceMap
+ .get(jobPoolName)
+ .isTerminated() || serviceMap
+ .get(jobPoolName)
+ .isShutdown())
+ {
+ registerJobPool(jobPoolName, executorServiceSupplier.get());
+ }
+
+ ExecutorService service = serviceMap.get(jobPoolName);
+ if (getCurrentTaskCount(service) >= maxQueueCount.get(jobPoolName))
+ {
+ log.log(Level.FINER, maxQueueCount + " Hit - Finishing before next run");
+ removeJob(jobPoolName);
+ service = registerJobPool(jobPoolName, executorServiceSupplier.get());
+ }
+ return service.submit(thread);
+ }
+
+ @Override
+ public void waitForJob(String jobName)
+ {
+ waitForJob(jobName, defaultWaitTime, defaultWaitUnit);
+ }
+
+ @Override
+ public void waitForJob(String jobName, long timeout, TimeUnit unit)
+ {
+ if (!serviceMap.containsKey(jobName))
+ {
+ return;
+ }
+ ExecutorService service = serviceMap.get(jobName);
+ service.shutdown();
+ try
+ {
+ service.awaitTermination(timeout, unit);
+ }
+ catch (InterruptedException e)
+ {
+ log.log(Level.WARNING, "Thread didn't close cleanly, make sure running times are acceptable", e);
+ service.shutdownNow();
+ }
+ if (!service.isTerminated())
+ {
+ service.shutdownNow();
+ }
+ service.close();
+ }
+
+ private ExecutorService jobCleanup()
+ {
+ ScheduledExecutorService jobsShutdownNotClosed = addPollingJob("JobsShutdownNotClosed", () -> {
+ for (String jobPool : getJobPools())
+ {
+ ExecutorService executorService = serviceMap.get(jobPool);
+ if (executorService.isShutdown() && !executorService.isTerminated())
+ {
+ log.fine("Closing unfinished job - " + jobPool);
+ removeJob(jobPool);
+ }
+ if (executorService.isShutdown() && executorService.isTerminated())
+ {
+ log.fine("Cleaning terminated job - " + jobPool);
+ executorService.close();
+ serviceMap.remove(jobPool);
+ }
+ }
+ }, 2, TimeUnit.MINUTES);
+
+ return jobsShutdownNotClosed;
+ }
+
+ /**
+ * Adds a static run once job to the monitored collections
+ *
+ * @param jobPoolName
+ * @param thread
+ */
+ @Override
+ public ScheduledExecutorService addPollingJob(String jobPoolName, Runnable thread, long delay, TimeUnit unit)
+ {
+ if (!pollingMap.containsKey(jobPoolName) || pollingMap
+ .get(jobPoolName)
+ .isTerminated() || pollingMap
+ .get(jobPoolName)
+ .isShutdown())
+ {
+ registerJobPollingPool(jobPoolName,
+ Executors.newScheduledThreadPool(Runtime
+ .getRuntime()
+ .availableProcessors()));
+ }
+ ScheduledExecutorService service = pollingMap.get(jobPoolName);
+ service.scheduleAtFixedRate(thread, 1L, delay, unit);
+ return service;
+ }
+
+ /**
+ * Adds a static run once job to the monitored collections
+ *
+ * @param jobPoolName
+ * @param thread
+ */
+ @Override
+ public ScheduledExecutorService addPollingJob(String jobPoolName, Runnable thread, long initialDelay, long delay, TimeUnit unit)
+ {
+ if (!pollingMap.containsKey(jobPoolName) || pollingMap
+ .get(jobPoolName)
+ .isTerminated() || pollingMap
+ .get(jobPoolName)
+ .isShutdown())
+ {
+ registerJobPollingPool(jobPoolName,
+ Executors.newScheduledThreadPool(Runtime
+ .getRuntime()
+ .availableProcessors()));
+ }
+ ScheduledExecutorService service = pollingMap.get(jobPoolName);
+ service.scheduleAtFixedRate(thread, initialDelay, delay, unit);
+ return service;
+ }
+
+ /**
+ * Shutdowns
+ */
+ @Override
+ public void destroy()
+ {
+ log.config("Destroying all running jobs...");
+ serviceMap.forEach((key, value) -> {
+ log.config("Shutting Down [" + key + "]");
+ removeJob(key);
+ });
+ pollingMap.forEach((key, value) -> {
+ log.config("Shutting Down Poll Job [" + key + "]");
+ removePollingJob(key);
+ });
+ log.config("All jobs destroyed");
+ }
+
+ private int getCurrentTaskCount(ExecutorService service)
+ {
+ if (service instanceof ForkJoinPool)
+ {
+ ForkJoinPool pool = (ForkJoinPool) service;
+ return (int) pool.getQueuedTaskCount();
+ }
+ else if (service instanceof ThreadPoolExecutor)
+ {
+ ThreadPoolExecutor executor = (ThreadPoolExecutor) service;
+ return (int) executor.getTaskCount();
+ }
+ return 0;
+ }
+
+ public void setMaxQueueCount(String queueName, int queueCount)
+ {
+ maxQueueCount.put(queueName, queueCount);
+ }
+
+ @Override
+ public void onDestroy()
+ {
+ destroy();
+ }
+
+ @Override
+ public Integer sortOrder()
+ {
+ return Integer.MIN_VALUE + 8;
+ }
+
+
+}
diff --git a/src/main/java/com/guicedee/guicedinjection/SysStreamsLogger.java b/src/main/java/com/guicedee/guicedinjection/SysStreamsLogger.java
deleted file mode 100644
index 174601a..0000000
--- a/src/main/java/com/guicedee/guicedinjection/SysStreamsLogger.java
+++ /dev/null
@@ -1,188 +0,0 @@
-package com.guicedee.guicedinjection;
-import java.io.IOException;
-import java.io.PrintStream;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import static com.guicedee.guicedinjection.properties.GlobalProperties.*;
-
-public class SysStreamsLogger {
- private static Logger sysOutLogger = LoggerFactory.getLogger("SYSOUT");
- private static Logger sysErrLogger = LoggerFactory.getLogger("SYSERR");
-
- public static final PrintStream sysout = System.out;
- public static final PrintStream syserr = System.err;
-
- protected static final String LINE_SEPERATOR = getSystemPropertyOrEnvironment("line.separator","\n");
-
- public static void bindSystemStreams() {
- // Enable autoflush
- System.setOut(new PrintStream(new LoggingOutputStream(sysOutLogger, false), true));
- System.setErr(new PrintStream(new LoggingOutputStream(sysErrLogger, true), true));
- }
-
- public static void unbindSystemStreams() {
- System.setOut(sysout);
- System.setErr(syserr);
- }
-
- private static class LoggingOutputStream extends java.io.OutputStream {
-
- protected Logger log;
- protected boolean isError;
-
- /**
- * Used to maintain the contract of {@link #close()}.
- */
- protected boolean hasBeenClosed = false;
-
- /**
- * The internal buffer where data is stored.
- */
- protected byte[] buf;
-
- /**
- * The number of valid bytes in the buffer. This value is always in the
- * range 0 through buf.length; elements
- * buf[0] through buf[count-1] contain valid byte
- * data.
- */
- protected int count;
-
- /**
- * Remembers the size of the buffer for speed.
- */
- private int bufLength;
-
- /**
- * The default number of bytes in the buffer. =2048
- */
- public static final int DEFAULT_BUFFER_LENGTH = 2048;
-
- private LoggingOutputStream() {
- // illegal
- }
-
- /**
- * Creates the LoggingOutputStream to flush to the given Category.
- *
- * @param log
- * the Logger to write to
- *
- * @param isError
- * the if true write to error, else info
- *
- * @exception IllegalArgumentException
- * if cat == null or priority == null
- */
- public LoggingOutputStream(Logger log, boolean isError) throws IllegalArgumentException {
- if (log == null) {
- throw new IllegalArgumentException("log == null");
- }
-
- this.isError = isError;
- this.log = log;
- bufLength = DEFAULT_BUFFER_LENGTH;
- buf = new byte[DEFAULT_BUFFER_LENGTH];
- count = 0;
- }
-
- /**
- * Closes this output stream and releases any system resources
- * associated with this stream. The general contract of
- * close
is that it closes the output stream. A closed
- * stream cannot perform output operations and cannot be reopened.
- */
- @Override
- public void close() {
- flush();
- hasBeenClosed = true;
- }
-
- /**
- * Writes the specified byte to this output stream. The general contract
- * for write
is that one byte is written to the output
- * stream. The byte to be written is the eight low-order bits of the
- * argument b
. The 24 high-order bits of b
are
- * ignored.
- *
- * @param b
- * the byte
to write
- */
- @Override
- public void write(final int b) throws IOException {
- if (hasBeenClosed) {
- throw new IOException("The stream has been closed.");
- }
-
- // don't log nulls
- if (b == 0) {
- return;
- }
-
- // would this be writing past the buffer?
- if (count == bufLength) {
- // grow the buffer
- final int newBufLength = bufLength + DEFAULT_BUFFER_LENGTH;
- final byte[] newBuf = new byte[newBufLength];
-
- System.arraycopy(buf, 0, newBuf, 0, bufLength);
-
- buf = newBuf;
- bufLength = newBufLength;
- }
-
- buf[count] = (byte) b;
- count++;
- }
-
- /**
- * Flushes this output stream and forces any buffered output bytes to be
- * written out. The general contract of flush
is that
- * calling it is an indication that, if any bytes previously written
- * have been buffered by the implementation of the output stream, such
- * bytes should immediately be written to their intended destination.
- */
- @Override
- public void flush() {
-
- if (count == 0) {
- return;
- }
-
- // don't print out blank lines; flushing from PrintStream puts out
- // these
- if (count == LINE_SEPERATOR.length()) {
- if (((char) buf[0]) == LINE_SEPERATOR.charAt(0) && ((count == 1) || // <-
- // Unix
- // &
- // Mac,
- // ->
- // Windows
- ((count == 2) && ((char) buf[1]) == LINE_SEPERATOR.charAt(1)))) {
- reset();
- return;
- }
- }
-
- final byte[] theBytes = new byte[count];
-
- System.arraycopy(buf, 0, theBytes, 0, count);
-
- if (isError) {
- log.error(new String(theBytes));
- } else {
- log.info(new String(theBytes));
- }
-
- reset();
- }
-
- private void reset() {
- // not resetting the buffer -- assuming that if it grew that it
- // will likely grow similarly again
- count = 0;
- }
- }
-}
\ No newline at end of file
diff --git a/src/main/java/com/guicedee/guicedinjection/abstractions/GuiceInjectorModule.java b/src/main/java/com/guicedee/guicedinjection/abstractions/GuiceInjectorModule.java
deleted file mode 100644
index 178a605..0000000
--- a/src/main/java/com/guicedee/guicedinjection/abstractions/GuiceInjectorModule.java
+++ /dev/null
@@ -1,244 +0,0 @@
-/*
- * Copyright (C) 2017 GedMarc
- *
- * This program is free software: you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation, either version 3 of the License, or
- * (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program. If not, see .
- */
-package com.guicedee.guicedinjection.abstractions;
-
-import com.google.inject.AbstractModule;
-import com.google.inject.Binder;
-import com.google.inject.Binding;
-import com.google.inject.Key;
-import com.google.inject.Module;
-import com.google.inject.Provider;
-import com.google.inject.Scope;
-import com.google.inject.TypeLiteral;
-import com.google.inject.binder.AnnotatedBindingBuilder;
-import com.google.inject.binder.AnnotatedConstantBindingBuilder;
-import com.google.inject.binder.LinkedBindingBuilder;
-import com.google.inject.matcher.Matcher;
-import com.google.inject.spi.Message;
-import com.google.inject.spi.ProvisionListener;
-import com.google.inject.spi.TypeListener;
-import com.guicedee.guicedinjection.GuiceContext;
-import com.guicedee.guicedinjection.interfaces.IGuiceDefaultBinder;
-import com.guicedee.guicedinjection.interfaces.IGuiceModule;
-import com.guicedee.logger.LogFactory;
-
-import java.lang.annotation.Annotation;
-import java.lang.reflect.Method;
-import java.util.*;
-import java.util.logging.Level;
-import java.util.logging.Logger;
-
-/**
- * Exposes the abstract module methods as public
- *
- * @author GedMarc
- * @since 12 Dec 2016
- */
-public class GuiceInjectorModule
- extends AbstractModule
- implements IGuiceModule {
-
- /**
- * Field log
- */
- private static final Logger log = LogFactory.getLog("GuiceInjectorModule");
-
- /**
- * Constructs a new instance of the module
- */
- public GuiceInjectorModule() {
- //Nothing Needed
- }
-
- /**
- * Executes the runBinders method
- */
- @Override
- public void configure() {
- runBinders();
- }
-
- /**
- * Executes the linked binders to perform any custom binding
- */
- @SuppressWarnings("unchecked")
- private void runBinders() {
- Set loader = GuiceContext.instance()
- .getLoader(IGuiceDefaultBinder.class, true, ServiceLoader.load(IGuiceDefaultBinder.class));
- for (IGuiceDefaultBinder binder : loader) {
- log.log(Level.CONFIG, "Loading IGuiceDefaultBinder - " + binder.getClass());
- binder.onBind(this);
- }
-
- Set iGuiceModules = GuiceContext.instance().loadIGuiceModules();
- Set guicy = new TreeSet<>();
- guicy.addAll(iGuiceModules);
-
- for (IGuiceModule> iGuiceModule : guicy)
- {
- log.log(Level.CONFIG, "Loading IGuice Module - " + iGuiceModule.getClass()
- .getSimpleName());
- Module mod = (Module) iGuiceModule;
- install(mod);
- }
- }
-
- /**
- * Gets direct access to the underlying {@code Binder}.
- */
- @Override
- public Binder binder() {
- return super.binder();
- }
-
- /**
- * @see Binder#bindScope(Class, Scope)
- */
- @Override
- public void bindScope(Class extends Annotation> scopeAnnotation, Scope scope) {
- super.bindScope(scopeAnnotation, scope);
- }
-
- /**
- * @see Binder#bind(Key)
- */
- @Override
- public LinkedBindingBuilder bind(Key key) {
- return super.bind(key);
- }
-
- /**
- * @see Binder#bind(TypeLiteral)
- */
- @Override
- public AnnotatedBindingBuilder bind(TypeLiteral typeLiteral) {
- return super.bind(typeLiteral);
- }
-
- /**
- * @see Binder#bind(Class)
- */
- @Override
- public AnnotatedBindingBuilder bind(Class clazz) {
- return super.bind(clazz);
- }
-
- /**
- * @see Binder#bindConstant()
- */
- @Override
- public AnnotatedConstantBindingBuilder bindConstant() {
- return super.bindConstant();
- }
-
- /**
- * @see Binder#install(Module)
- */
- @Override
- public void install(Module module) {
- super.install(module);
- }
-
- /**
- * @see Binder#addError(String, Object[])
- */
- @Override
- public void addError(String message, Object... arguments) {
- super.addError(message, arguments);
- }
-
- /**
- * @see Binder#addError(Throwable)
- */
- @Override
- public void addError(Throwable t) {
- super.addError(t);
- }
-
- /**
- * @see Binder#addError(Message)
- * @since 2.0
- */
- @Override
- public void addError(Message message) {
- super.addError(message);
- }
-
- /**
- * @see Binder#requestInjection(Object)
- * @since 2.0
- */
- @Override
- public void requestInjection(Object instance) {
- super.requestInjection(instance);
- }
-
- /**
- * @see Binder#requestStaticInjection(Class[])
- */
- @Override
- public void requestStaticInjection(Class>... types) {
- super.requestStaticInjection(types);
- }
-
- /**
- * @see Binder#bindInterceptor(com.google.inject.matcher.Matcher,
- * com.google.inject.matcher.Matcher, org.aopalliance.intercept.MethodInterceptor[])
- */
- @Override
- public void bindInterceptor(Matcher super Class>> classMatcher, Matcher super Method> methodMatcher, org.aopalliance.intercept.MethodInterceptor... interceptors) {
- binder().bindInterceptor(classMatcher, methodMatcher, interceptors);
- }
-
- /**
- * @see Binder#getProvider(Key)
- * @since 2.0
- */
- @Override
- public Provider getProvider(Key key) {
- return super.getProvider(key);
- }
-
- /**
- * @see Binder#getProvider(Class)
- * @since 2.0
- */
- @Override
- public Provider getProvider(Class type) {
- return super.getProvider(type);
- }
-
- /**
- * @see Binder#bindListener(com.google.inject.matcher.Matcher, com.google.inject.spi.TypeListener)
- * @since 2.0
- */
- @Override
- public void bindListener(Matcher super TypeLiteral>> typeMatcher, TypeListener listener) {
- super.bindListener(typeMatcher, listener);
- }
-
- /**
- * @see Binder#bindListener(com.google.inject.matcher.Matcher, com.google.inject.spi.TypeListener)
- * @since 2.0
- */
- @Override
- public void bindListener(Matcher super Binding>> bindingMatcher, ProvisionListener... listener) {
- super.bindListener(bindingMatcher, listener);
- }
-
-
-}
diff --git a/src/main/java/com/guicedee/guicedinjection/exceptions/ExcelRenderingException.java b/src/main/java/com/guicedee/guicedinjection/exceptions/ExcelRenderingException.java
deleted file mode 100644
index 0ed3df8..0000000
--- a/src/main/java/com/guicedee/guicedinjection/exceptions/ExcelRenderingException.java
+++ /dev/null
@@ -1,31 +0,0 @@
-package com.guicedee.guicedinjection.exceptions;
-
-
-public class ExcelRenderingException extends RuntimeException {
-
- private static final long serialVersionUID = 1L;
-
- public ExcelRenderingException()
- {
- }
-
- public ExcelRenderingException(String message)
- {
- super(message);
- }
-
- public ExcelRenderingException(String message, Throwable cause)
- {
- super(message, cause);
- }
-
- public ExcelRenderingException(Throwable cause)
- {
- super(cause);
- }
-
- public ExcelRenderingException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace)
- {
- super(message, cause, enableSuppression, writableStackTrace);
- }
-}
diff --git a/src/main/java/com/guicedee/guicedinjection/exceptions/JsonRenderException.java b/src/main/java/com/guicedee/guicedinjection/exceptions/JsonRenderException.java
deleted file mode 100644
index b948d18..0000000
--- a/src/main/java/com/guicedee/guicedinjection/exceptions/JsonRenderException.java
+++ /dev/null
@@ -1,59 +0,0 @@
-package com.guicedee.guicedinjection.exceptions;
-
-public class JsonRenderException extends RuntimeException
-{
- private static final long serialVersionUID = 1L;
-
- /**
- * Instantiates a new Module exception.
- */
- public JsonRenderException()
- {
- //No config required
- }
-
- /**
- * Instantiates a new Module exception.
- *
- * @param message the message
- */
- public JsonRenderException(String message)
- {
- super(message);
- }
-
- /**
- * Instantiates a new Module exception.
- *
- * @param message the message
- * @param cause the cause
- */
- public JsonRenderException(String message, Throwable cause)
- {
- super(message, cause);
- }
-
- /**
- * Instantiates a new Module exception.
- *
- * @param cause the cause
- */
- public JsonRenderException(Throwable cause)
- {
- super(cause);
- }
-
- /**
- * Instantiates a new Module exception.
- *
- * @param message the message
- * @param cause the cause
- * @param enableSuppression the enable suppression
- * @param writableStackTrace the writable stack trace
- */
- public JsonRenderException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace)
- {
- super(message, cause, enableSuppression, writableStackTrace);
- }
-
-}
diff --git a/src/main/java/com/guicedee/guicedinjection/exceptions/XmlRenderException.java b/src/main/java/com/guicedee/guicedinjection/exceptions/XmlRenderException.java
deleted file mode 100644
index b9444db..0000000
--- a/src/main/java/com/guicedee/guicedinjection/exceptions/XmlRenderException.java
+++ /dev/null
@@ -1,59 +0,0 @@
-package com.guicedee.guicedinjection.exceptions;
-
-public class XmlRenderException extends RuntimeException
-{
- private static final long serialVersionUID = 1L;
-
- /**
- * Instantiates a new Module exception.
- */
- public XmlRenderException()
- {
- //No config required
- }
-
- /**
- * Instantiates a new Module exception.
- *
- * @param message the message
- */
- public XmlRenderException(String message)
- {
- super(message);
- }
-
- /**
- * Instantiates a new Module exception.
- *
- * @param message the message
- * @param cause the cause
- */
- public XmlRenderException(String message, Throwable cause)
- {
- super(message, cause);
- }
-
- /**
- * Instantiates a new Module exception.
- *
- * @param cause the cause
- */
- public XmlRenderException(Throwable cause)
- {
- super(cause);
- }
-
- /**
- * Instantiates a new Module exception.
- *
- * @param message the message
- * @param cause the cause
- * @param enableSuppression the enable suppression
- * @param writableStackTrace the writable stack trace
- */
- public XmlRenderException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace)
- {
- super(message, cause, enableSuppression, writableStackTrace);
- }
-
-}
diff --git a/src/main/java/com/guicedee/guicedinjection/implementations/GuiceContextProvision.java b/src/main/java/com/guicedee/guicedinjection/implementations/GuiceContextProvision.java
new file mode 100644
index 0000000..55f37f4
--- /dev/null
+++ b/src/main/java/com/guicedee/guicedinjection/implementations/GuiceContextProvision.java
@@ -0,0 +1,15 @@
+package com.guicedee.guicedinjection.implementations;
+
+import com.guicedee.client.*;
+import com.guicedee.guicedinjection.*;
+import com.guicedee.guicedinjection.interfaces.*;
+
+public class GuiceContextProvision implements IGuiceProvider
+{
+ @Override
+ public IGuiceContext get()
+ {
+ return GuiceContext.instance();
+ }
+
+}
diff --git a/src/main/java/com/guicedee/guicedinjection/implementations/GuiceDefaultModuleExclusions.java b/src/main/java/com/guicedee/guicedinjection/implementations/GuiceDefaultModuleExclusions.java
index 6341e12..b629aed 100644
--- a/src/main/java/com/guicedee/guicedinjection/implementations/GuiceDefaultModuleExclusions.java
+++ b/src/main/java/com/guicedee/guicedinjection/implementations/GuiceDefaultModuleExclusions.java
@@ -3,7 +3,6 @@
import com.guicedee.guicedinjection.interfaces.IGuiceScanJarExclusions;
import com.guicedee.guicedinjection.interfaces.IGuiceScanModuleExclusions;
-import jakarta.validation.constraints.NotNull;
import java.util.HashSet;
import java.util.Set;
@@ -11,7 +10,7 @@ public class GuiceDefaultModuleExclusions
implements IGuiceScanModuleExclusions, IGuiceScanJarExclusions
{
@Override
- public @NotNull
+ public
Set excludeModules()
{
Set strings = new HashSet<>();
@@ -101,7 +100,7 @@ Set excludeModules()
}
@Override
- public @NotNull Set excludeJars() {
+ public Set excludeJars() {
Set strings = new HashSet<>();
strings.add("activation-*");
strings.add("adal4j-*");
diff --git a/src/main/java/com/guicedee/guicedinjection/implementations/GuiceDefaultModuleInclusions.java b/src/main/java/com/guicedee/guicedinjection/implementations/GuiceDefaultModuleInclusions.java
index 0897d12..bfbffd7 100644
--- a/src/main/java/com/guicedee/guicedinjection/implementations/GuiceDefaultModuleInclusions.java
+++ b/src/main/java/com/guicedee/guicedinjection/implementations/GuiceDefaultModuleInclusions.java
@@ -1,7 +1,6 @@
package com.guicedee.guicedinjection.implementations;
import com.guicedee.guicedinjection.interfaces.IGuiceScanModuleInclusions;
-import jakarta.validation.constraints.NotNull;
import java.util.HashSet;
import java.util.Set;
@@ -10,8 +9,7 @@ public class GuiceDefaultModuleInclusions
implements IGuiceScanModuleInclusions
{
@Override
- public @NotNull
- Set includeModules()
+ public Set includeModules()
{
Set strings = new HashSet<>();
return strings;
diff --git a/src/main/java/com/guicedee/guicedinjection/implementations/JobServiceProvision.java b/src/main/java/com/guicedee/guicedinjection/implementations/JobServiceProvision.java
new file mode 100644
index 0000000..0631fda
--- /dev/null
+++ b/src/main/java/com/guicedee/guicedinjection/implementations/JobServiceProvision.java
@@ -0,0 +1,14 @@
+package com.guicedee.guicedinjection.implementations;
+
+import com.guicedee.guicedinjection.*;
+import com.guicedee.guicedinjection.interfaces.*;
+
+public class JobServiceProvision implements IJobServiceProvider
+{
+ @Override
+ public IJobService get()
+ {
+ return JobService.INSTANCE;
+ }
+
+}
diff --git a/src/main/java/com/guicedee/guicedinjection/injections/ContextBinderGuice.java b/src/main/java/com/guicedee/guicedinjection/injections/ContextBinderGuice.java
index 37ae739..c628429 100644
--- a/src/main/java/com/guicedee/guicedinjection/injections/ContextBinderGuice.java
+++ b/src/main/java/com/guicedee/guicedinjection/injections/ContextBinderGuice.java
@@ -1,14 +1,16 @@
package com.guicedee.guicedinjection.injections;
+import com.google.inject.AbstractModule;
import com.google.inject.Singleton;
import com.guicedee.guicedinjection.GuiceConfig;
import com.guicedee.guicedinjection.GuiceContext;
-import com.guicedee.guicedinjection.abstractions.GuiceInjectorModule;
-import com.guicedee.guicedinjection.interfaces.IGuiceDefaultBinder;
-import com.guicedee.guicedinjection.interfaces.JobService;
+
+import com.guicedee.guicedinjection.JobService;
+import com.guicedee.guicedinjection.interfaces.*;
import com.guicedee.guicedinjection.properties.GlobalProperties;
import io.github.classgraph.ScanResult;
-import com.guicedee.logger.LogFactory;
+import lombok.extern.java.Log;
+
import java.util.logging.Logger;
@@ -16,36 +18,34 @@
* Binds the basic objects for the Guice Context to be injected everywhere
*/
@SuppressWarnings("unused")
+@Log
public class ContextBinderGuice
- implements IGuiceDefaultBinder {
- private static final Logger log = LogFactory.getLog("GuiceContextBinder");
-
- public ContextBinderGuice() {
- //No config required
- }
-
- @Override
- public void onBind(GuiceInjectorModule module) {
- ContextBinderGuice.log.fine("Bound GuiceConfig.class");
- module.bind(GuiceConfig.class)
- .toProvider(() -> GuiceContext.instance()
- .getConfig())
- .in(Singleton.class);
-
- ContextBinderGuice.log.fine("Bound GlobalProperties.class");
- module.bind(GlobalProperties.class)
- .asEagerSingleton();
-
- ContextBinderGuice.log.fine("Bound ScanResult.class");
- module.bind(ScanResult.class)
- .toProvider(() -> GuiceContext.instance()
- .getScanResult())
- .in(Singleton.class);
-
- ContextBinderGuice.log.fine("Bound JobService.class");
- module.bind(JobService.class)
- .asEagerSingleton();
- }
-
-
+ extends AbstractModule
+ implements IGuiceModule {
+ public ContextBinderGuice() {
+ //No config required
+ }
+
+ @Override
+ public void configure() {
+ ContextBinderGuice.log.fine("Bound GuiceConfig.class");
+ bind(GuiceConfig.class)
+ .toProvider(() -> GuiceContext.instance().getConfig());
+
+ ContextBinderGuice.log.fine("Bound GlobalProperties.class");
+ bind(GlobalProperties.class)
+ .asEagerSingleton();
+
+ ContextBinderGuice.log.fine("Bound ScanResult.class");
+ bind(ScanResult.class)
+ .toProvider(() -> GuiceContext.instance()
+ .getScanResult())
+ .in(Singleton.class);
+
+ ContextBinderGuice.log.fine("Bound JobService.class");
+ bind(IJobService.class)
+ .toInstance(JobService.INSTANCE);
+ bind(JobService.class)
+ .toInstance(JobService.INSTANCE);
+ }
}
diff --git a/src/main/java/com/guicedee/guicedinjection/interfaces/IDefaultBinder.java b/src/main/java/com/guicedee/guicedinjection/interfaces/IDefaultBinder.java
deleted file mode 100644
index 33f7b4e..0000000
--- a/src/main/java/com/guicedee/guicedinjection/interfaces/IDefaultBinder.java
+++ /dev/null
@@ -1,36 +0,0 @@
-/*
- * Copyright (C) 2017 GedMarc
- *
- * This program is free software: you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation, either version 3 of the License, or
- * (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program. If not, see .
- */
-package com.guicedee.guicedinjection.interfaces;
-
-import com.google.inject.AbstractModule;
-
-/**
- * @param The module to bind
- * @author GedMarc
- */
-@FunctionalInterface
-public interface IDefaultBinder {
-
- /**
- * Performs the binding with the injection module that is required
- *
- * @param module The module being passed in
- */
- void onBind(M module);
-
-
-}
diff --git a/src/main/java/com/guicedee/guicedinjection/interfaces/IDefaultService.java b/src/main/java/com/guicedee/guicedinjection/interfaces/IDefaultService.java
deleted file mode 100644
index 128cf3b..0000000
--- a/src/main/java/com/guicedee/guicedinjection/interfaces/IDefaultService.java
+++ /dev/null
@@ -1,185 +0,0 @@
-package com.guicedee.guicedinjection.interfaces;
-
-import com.guicedee.guicedinjection.GuiceConfig;
-import com.guicedee.guicedinjection.GuiceContext;
-import com.guicedee.logger.LogFactory;
-import io.github.classgraph.ClassInfo;
-
-import jakarta.validation.constraints.NotNull;
-
-import java.util.*;
-import java.util.concurrent.ConcurrentHashMap;
-import java.util.logging.Level;
-
-import static com.guicedee.guicedinjection.GuiceContext.*;
-/**
- * Supplies standard set changer and comparable's for services
- *
- * @param
- */
-public interface IDefaultService>
- extends Comparable, Comparator {
- Map> loaderClasses = new ConcurrentHashMap<>();
-
- /**
- * Method loaderToSet, converts a ServiceLoader into a TreeSet
- *
- * @param loader of type ServiceLoader
- * @return Set
- */
- @SuppressWarnings("unchecked")
- @NotNull
- static > Set loaderToSet(ServiceLoader loader) {
- @SuppressWarnings("rawtypes")
- Set loadeds = new HashSet<>();
-
- String type = loader.toString();
- type = type.replace("java.util.ServiceLoader[", "");
- type = type.substring(0, type.length() - 1);
-
- if (!loaderClasses.containsKey(type)) {
- GuiceConfig> config = GuiceContext.instance().getConfig();
- if (config.isServiceLoadWithClassPath()) {
- for (ClassInfo classInfo : instance()
- .getScanResult()
- .getClassesImplementing(type)) {
- Class load = (Class) classInfo.loadClass();
- loadeds.add(load);
- }
- }
- try {
- for (T newInstance : loader) {
- loadeds.add(newInstance.getClass());
- }
- } catch (Throwable T) {
- LogFactory.getLog("IDefaultService").log(Level.SEVERE, "Unable to provide instance of " + type + " to TreeSet", T);
- }
- loaderClasses.put(type, loadeds);
- }
-
- Set outcomes = new TreeSet<>();
- for (Class> aClass : loaderClasses.get(type)) {
- outcomes.add((T) GuiceContext.get(aClass));
- }
- return outcomes;
- }
-
- static > Set> loadClassSet(ServiceLoader loader) {
- String type = loader.toString();
- type = type.replace("java.util.ServiceLoader[", "");
- type = type.substring(0, type.length() - 1);
-
- if (!loaderClasses.containsKey(type)) {
- Set loadeds = new HashSet<>();
- GuiceConfig> config = GuiceContext.instance().getConfig();
- if (config.isServiceLoadWithClassPath()) {
- for (ClassInfo classInfo : instance()
- .getScanResult()
- .getClassesImplementing(type)) {
- @SuppressWarnings("unchecked")
- Class load = (Class) classInfo.loadClass();
- loadeds.add(load);
- }
- }
- try {
- for (T newInstance : loader) {
- //noinspection unchecked
- loadeds.add((Class) newInstance.getClass());
- }
- } catch (Throwable T) {
- LogFactory.getLog("IDefaultService").log(Level.SEVERE, "Unable to provide instance of " + type + " to TreeSet", T);
- }
- loaderClasses.put(type, loadeds);
- }
- //noinspection unchecked
- return (Set)loaderClasses.get(type);
- }
-
- /**
- * Method loaderToSet, converts a ServiceLoader into a TreeSet
- *
- * @param loader of type ServiceLoader
- * @return Set
- */
- @SuppressWarnings("unchecked")
- @NotNull
- static Set loaderToSetNoInjection(ServiceLoader loader) {
- Set> loadeds = new HashSet<>();
- GuiceConfig config = GuiceContext.instance().getConfig();
- String type = loader.toString();
- type = type.replace("java.util.ServiceLoader[", "");
- type = type.substring(0, type.length() - 1);
- if (config.isServiceLoadWithClassPath() && !buildingInjector) {
- for (ClassInfo classInfo : instance()
- .getScanResult()
- .getClassesImplementing(type)) {
- Class load = (Class) classInfo.loadClass();
- loadeds.add(load);
- }
- }
- Set> completed = new LinkedHashSet<>();
- Set output = new LinkedHashSet<>();
- try {
- for (T newInstance : loader) {
- output.add(newInstance);
- completed.add((Class) newInstance.getClass());
- }
- } catch (Throwable T) {
- LogFactory.getLog("IDefaultService").log(Level.SEVERE, "Cannot load services - ", T);
- }
- for (Class newInstance : loadeds) {
- if (completed.contains(newInstance)) {
- continue;
- }
- try {
- output.add((T) newInstance.getDeclaredConstructor());
- } catch (NoSuchMethodException e) {
- LogFactory.getLog("IDefaultService")
- .log(Level.SEVERE, "Cannot load a service through default constructor", e);
- }
- }
- return output;
- }
-
- /**
- * Method compare ...
- *
- * @param o1 of type J
- * @param o2 of type J
- * @return int
- */
- @Override
- default int compare(J o1, J o2) {
- if (o1 == null || o2 == null) {
- return -1;
- }
- return o1.sortOrder()
- .compareTo(o2.sortOrder());
- }
-
- /**
- * Default Sort Order 100
- *
- * @return 100
- */
- default Integer sortOrder() {
- return 100;
- }
-
- /**
- * Method compareTo ...
- *
- * @param o of type J
- * @return int
- */
- @Override
- default int compareTo(@NotNull J o) {
- int sort = sortOrder().compareTo(o.sortOrder());
- if (sort == 0) {
- return -1;
- }
- return sort;
- }
-
-
-}
diff --git a/src/main/java/com/guicedee/guicedinjection/interfaces/IFileContentsPatternScanner.java b/src/main/java/com/guicedee/guicedinjection/interfaces/IFileContentsPatternScanner.java
deleted file mode 100644
index fed1766..0000000
--- a/src/main/java/com/guicedee/guicedinjection/interfaces/IFileContentsPatternScanner.java
+++ /dev/null
@@ -1,20 +0,0 @@
-package com.guicedee.guicedinjection.interfaces;
-
-import io.github.classgraph.ResourceList;
-
-import java.util.Map;
-import java.util.regex.Pattern;
-
-/**
- * Marks the class as a file scanner
- */
-@FunctionalInterface
-public interface IFileContentsPatternScanner
-{
- /**
- * Returns a contents processor to run on match
- *
- * @return the maps of file identifiers and contents
- */
- Map onMatch();
-}
diff --git a/src/main/java/com/guicedee/guicedinjection/interfaces/IFileContentsScanner.java b/src/main/java/com/guicedee/guicedinjection/interfaces/IFileContentsScanner.java
deleted file mode 100644
index 97fdaa1..0000000
--- a/src/main/java/com/guicedee/guicedinjection/interfaces/IFileContentsScanner.java
+++ /dev/null
@@ -1,19 +0,0 @@
-package com.guicedee.guicedinjection.interfaces;
-
-import io.github.classgraph.ResourceList;
-
-import java.util.Map;
-
-/**
- * Marks the class as a file scanner
- */
-@FunctionalInterface
-public interface IFileContentsScanner
-{
- /**
- * Returns a contents processor to run on match
- *
- * @return the maps of file identifiers and contents
- */
- Map onMatch();
-}
diff --git a/src/main/java/com/guicedee/guicedinjection/interfaces/IGuiceConfigurator.java b/src/main/java/com/guicedee/guicedinjection/interfaces/IGuiceConfigurator.java
deleted file mode 100644
index d20f73c..0000000
--- a/src/main/java/com/guicedee/guicedinjection/interfaces/IGuiceConfigurator.java
+++ /dev/null
@@ -1,19 +0,0 @@
-package com.guicedee.guicedinjection.interfaces;
-
-import com.guicedee.guicedinjection.GuiceConfig;
-
-/**
- * Service Locator Interface for granular configuration of the GuiceContext and Injector
- */
-@FunctionalInterface
-public interface IGuiceConfigurator {
- /**
- * Configuers the guice instance
- *
- * @param config The configuration object coming in
- * @return The required guice configuration
- */
- GuiceConfig configure(GuiceConfig config);
-
-
-}
diff --git a/src/main/java/com/guicedee/guicedinjection/interfaces/IGuiceContextInternalBinder.java b/src/main/java/com/guicedee/guicedinjection/interfaces/IGuiceContextInternalBinder.java
deleted file mode 100644
index 77ce68e..0000000
--- a/src/main/java/com/guicedee/guicedinjection/interfaces/IGuiceContextInternalBinder.java
+++ /dev/null
@@ -1,9 +0,0 @@
-package com.guicedee.guicedinjection.interfaces;
-
-import com.google.inject.AbstractModule;
-
-@SuppressWarnings("unused")
-public interface IGuiceContextInternalBinder
- extends IDefaultBinder {
-
-}
diff --git a/src/main/java/com/guicedee/guicedinjection/interfaces/IGuiceDefaultBinder.java b/src/main/java/com/guicedee/guicedinjection/interfaces/IGuiceDefaultBinder.java
deleted file mode 100644
index 4ee0bec..0000000
--- a/src/main/java/com/guicedee/guicedinjection/interfaces/IGuiceDefaultBinder.java
+++ /dev/null
@@ -1,8 +0,0 @@
-package com.guicedee.guicedinjection.interfaces;
-
-import com.guicedee.guicedinjection.abstractions.GuiceInjectorModule;
-
-public interface IGuiceDefaultBinder, M extends GuiceInjectorModule>
- extends IDefaultService, IDefaultBinder {
-
-}
diff --git a/src/main/java/com/guicedee/guicedinjection/interfaces/IGuiceModule.java b/src/main/java/com/guicedee/guicedinjection/interfaces/IGuiceModule.java
deleted file mode 100644
index 68252ed..0000000
--- a/src/main/java/com/guicedee/guicedinjection/interfaces/IGuiceModule.java
+++ /dev/null
@@ -1,9 +0,0 @@
-package com.guicedee.guicedinjection.interfaces;
-
-/**
- * Service Locator for configuring the module
- */
-public interface IGuiceModule>
- extends IDefaultService {
-
-}
diff --git a/src/main/java/com/guicedee/guicedinjection/interfaces/IGuicePostStartup.java b/src/main/java/com/guicedee/guicedinjection/interfaces/IGuicePostStartup.java
deleted file mode 100644
index be9f839..0000000
--- a/src/main/java/com/guicedee/guicedinjection/interfaces/IGuicePostStartup.java
+++ /dev/null
@@ -1,47 +0,0 @@
-/*
- * Copyright (C) 2017 GedMarc
- *
- * This program is free software: you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation, either version 3 of the License, or
- * (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program. If not, see .
- */
-package com.guicedee.guicedinjection.interfaces;
-
-/**
- * Executes immediately after Guice has been initialized
- *
- * @author GedMarc
- * @since 15 May 2017
- */
-public interface IGuicePostStartup>
- extends IDefaultService, Runnable {
-
- /**
- * Runs immediately after the post load
- */
- void postLoad();
-
- /**
- * Sets the order in which this must run, default 100.
- *
- * @return the sort order to return
- */
- @Override
- default Integer sortOrder() {
- return 50;
- }
-
- default void run() {
- postLoad();
- }
-
-}
diff --git a/src/main/java/com/guicedee/guicedinjection/interfaces/IGuicePreDestroy.java b/src/main/java/com/guicedee/guicedinjection/interfaces/IGuicePreDestroy.java
deleted file mode 100644
index c2637c5..0000000
--- a/src/main/java/com/guicedee/guicedinjection/interfaces/IGuicePreDestroy.java
+++ /dev/null
@@ -1,31 +0,0 @@
-/*
- * Copyright (C) 2017 GedMarc
- *
- * This program is free software: you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation, either version 3 of the License, or
- * (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program. If not, see .
- */
-package com.guicedee.guicedinjection.interfaces;
-
-/**
- * Initializes before Guice has been injected
- *
- * @author GedMarc
- * @since 15 May 2017
- */
-public interface IGuicePreDestroy> extends IDefaultService
-{
- /**
- * Runs on startup
- */
- void onDestroy();
-}
diff --git a/src/main/java/com/guicedee/guicedinjection/interfaces/IGuicePreStartup.java b/src/main/java/com/guicedee/guicedinjection/interfaces/IGuicePreStartup.java
deleted file mode 100644
index 0f1fd4f..0000000
--- a/src/main/java/com/guicedee/guicedinjection/interfaces/IGuicePreStartup.java
+++ /dev/null
@@ -1,47 +0,0 @@
-/*
- * Copyright (C) 2017 GedMarc
- *
- * This program is free software: you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation, either version 3 of the License, or
- * (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program. If not, see .
- */
-package com.guicedee.guicedinjection.interfaces;
-
-import com.guicedee.guicedinjection.interfaces.annotations.INotInjectable;
-
-/**
- * Initializes before Guice has been injected
- *
- * @author GedMarc
- * @since 15 May 2017
- */
-@INotInjectable
-public interface IGuicePreStartup>
- extends IDefaultService {
-
- /**
- * Runs on startup
- */
- void onStartup();
-
- /**
- * Sort order for startup, Default 100.
- *
- * @return the sort order never null
- */
- @Override
- default Integer sortOrder() {
- return 100;
- }
-
-
-}
diff --git a/src/main/java/com/guicedee/guicedinjection/interfaces/IGuiceScanJarExclusions.java b/src/main/java/com/guicedee/guicedinjection/interfaces/IGuiceScanJarExclusions.java
deleted file mode 100644
index a7e23c6..0000000
--- a/src/main/java/com/guicedee/guicedinjection/interfaces/IGuiceScanJarExclusions.java
+++ /dev/null
@@ -1,20 +0,0 @@
-package com.guicedee.guicedinjection.interfaces;
-
-import jakarta.validation.constraints.NotNull;
-import java.util.Set;
-
-/**
- * Marks JAR files referenced from libraries to be excluded from all scans
- */
-@FunctionalInterface
-public interface IGuiceScanJarExclusions>
- extends IDefaultService {
- /**
- * Excludes the given jars for scanning
- *
- * @return
- */
- @NotNull Set excludeJars();
-
-
-}
diff --git a/src/main/java/com/guicedee/guicedinjection/interfaces/IGuiceScanJarInclusions.java b/src/main/java/com/guicedee/guicedinjection/interfaces/IGuiceScanJarInclusions.java
deleted file mode 100644
index d52a0c0..0000000
--- a/src/main/java/com/guicedee/guicedinjection/interfaces/IGuiceScanJarInclusions.java
+++ /dev/null
@@ -1,21 +0,0 @@
-package com.guicedee.guicedinjection.interfaces;
-
-import jakarta.validation.constraints.NotNull;
-
-import java.util.Set;
-
-/**
- * Marks JAR files referenced from libraries to be excluded from all scans
- */
-@FunctionalInterface
-public interface IGuiceScanJarInclusions>
- extends IDefaultService {
- /**
- * Excludes the given jars for scanning
- *
- * @return
- */
- @NotNull Set includeJars();
-
-
-}
diff --git a/src/main/java/com/guicedee/guicedinjection/interfaces/IGuiceScanModuleExclusions.java b/src/main/java/com/guicedee/guicedinjection/interfaces/IGuiceScanModuleExclusions.java
deleted file mode 100644
index 051cbe1..0000000
--- a/src/main/java/com/guicedee/guicedinjection/interfaces/IGuiceScanModuleExclusions.java
+++ /dev/null
@@ -1,20 +0,0 @@
-package com.guicedee.guicedinjection.interfaces;
-
-import jakarta.validation.constraints.NotNull;
-import java.util.Set;
-
-/**
- * Marks JAR files referenced from libraries to be excluded from all scans
- */
-@FunctionalInterface
-public interface IGuiceScanModuleExclusions>
- extends IDefaultService {
- /**
- * Excludes the given jars for scanning
- *
- * @return A set
- */
- @NotNull Set