From 688fdd97d15dc842fd7cf8aba284cf280a9529fb Mon Sep 17 00:00:00 2001 From: Marc Magon Date: Thu, 28 Dec 2023 04:48:16 +0200 Subject: [PATCH 01/23] Guiced Injection - Version 2 Candidate --- pom.xml | 159 +++++---- src/jre11/java/module-info.java | 57 +-- .../guicedee/guicedinjection/GuiceConfig.java | 327 +++--------------- .../guicedinjection/GuiceContext.java | 301 +++++++++++----- .../{interfaces => }/JobService.java | 222 +++++++----- .../abstractions/GuiceInjectorModule.java | 19 +- .../injections/ContextBinderGuice.java | 70 ++-- .../interfaces/IDefaultBinder.java | 36 -- .../interfaces/IDefaultService.java | 185 ---------- .../IFileContentsPatternScanner.java | 20 -- .../interfaces/IFileContentsScanner.java | 19 - .../interfaces/IGuiceConfigurator.java | 19 - .../IGuiceContextInternalBinder.java | 9 - .../interfaces/IGuiceDefaultBinder.java | 8 - .../interfaces/IGuiceModule.java | 9 - .../interfaces/IGuicePostStartup.java | 47 --- .../interfaces/IGuicePreDestroy.java | 31 -- .../interfaces/IGuicePreStartup.java | 47 --- .../interfaces/IGuiceScanJarExclusions.java | 20 -- .../interfaces/IGuiceScanJarInclusions.java | 21 -- .../IGuiceScanModuleExclusions.java | 20 -- .../IGuiceScanModuleInclusions.java | 20 -- .../interfaces/IPackageContentsScanner.java | 117 ------- .../interfaces/IPackageRejectListScanner.java | 117 ------- .../IPathContentsRejectListScanner.java | 70 ---- .../interfaces/IPathContentsScanner.java | 70 ---- .../interfaces/IServiceEnablement.java | 17 - .../interfaces/ObjectBinderKeys.java | 44 --- .../annotations/INotEnhanceable.java | 19 - .../annotations/INotInjectable.java | 16 - .../json/LocalDateDeserializer.java | 10 +- .../json/LocalDateTimeDeserializer.java | 7 +- .../json/ObjectMapperBinder.java | 198 ++++++----- .../json/OffsetDateTimeDeserializer.java | 16 +- .../json/OffsetTimeDeserializer.java | 6 +- .../json/ZonedDateTimeDeserializer.java | 40 +-- .../properties/GlobalProperties.java | 5 +- .../representations/ICopyable.java | 12 +- .../representations/excel/ExcelReader.java | 6 +- .../guicedinjection/FileSearchTest.java | 3 +- .../guicedinjection/GlobalPropertiesTest.java | 4 +- .../guicedinjection/GuiceContextTest.java | 6 +- .../guicedinjection/IGuiceConfigTest.java | 8 +- .../IGuiceContextTestConfigurator.java | 3 +- 44 files changed, 722 insertions(+), 1738 deletions(-) rename src/main/java/com/guicedee/guicedinjection/{interfaces => }/JobService.java (75%) delete mode 100644 src/main/java/com/guicedee/guicedinjection/interfaces/IDefaultBinder.java delete mode 100644 src/main/java/com/guicedee/guicedinjection/interfaces/IDefaultService.java delete mode 100644 src/main/java/com/guicedee/guicedinjection/interfaces/IFileContentsPatternScanner.java delete mode 100644 src/main/java/com/guicedee/guicedinjection/interfaces/IFileContentsScanner.java delete mode 100644 src/main/java/com/guicedee/guicedinjection/interfaces/IGuiceConfigurator.java delete mode 100644 src/main/java/com/guicedee/guicedinjection/interfaces/IGuiceContextInternalBinder.java delete mode 100644 src/main/java/com/guicedee/guicedinjection/interfaces/IGuiceDefaultBinder.java delete mode 100644 src/main/java/com/guicedee/guicedinjection/interfaces/IGuiceModule.java delete mode 100644 src/main/java/com/guicedee/guicedinjection/interfaces/IGuicePostStartup.java delete mode 100644 src/main/java/com/guicedee/guicedinjection/interfaces/IGuicePreDestroy.java delete mode 100644 src/main/java/com/guicedee/guicedinjection/interfaces/IGuicePreStartup.java delete mode 100644 src/main/java/com/guicedee/guicedinjection/interfaces/IGuiceScanJarExclusions.java delete mode 100644 src/main/java/com/guicedee/guicedinjection/interfaces/IGuiceScanJarInclusions.java delete mode 100644 src/main/java/com/guicedee/guicedinjection/interfaces/IGuiceScanModuleExclusions.java delete mode 100644 src/main/java/com/guicedee/guicedinjection/interfaces/IGuiceScanModuleInclusions.java delete mode 100644 src/main/java/com/guicedee/guicedinjection/interfaces/IPackageContentsScanner.java delete mode 100644 src/main/java/com/guicedee/guicedinjection/interfaces/IPackageRejectListScanner.java delete mode 100644 src/main/java/com/guicedee/guicedinjection/interfaces/IPathContentsRejectListScanner.java delete mode 100644 src/main/java/com/guicedee/guicedinjection/interfaces/IPathContentsScanner.java delete mode 100644 src/main/java/com/guicedee/guicedinjection/interfaces/IServiceEnablement.java delete mode 100644 src/main/java/com/guicedee/guicedinjection/interfaces/ObjectBinderKeys.java delete mode 100644 src/main/java/com/guicedee/guicedinjection/interfaces/annotations/INotEnhanceable.java delete mode 100644 src/main/java/com/guicedee/guicedinjection/interfaces/annotations/INotInjectable.java diff --git a/pom.xml b/pom.xml index 7f8b6f2..bd80779 100644 --- a/pom.xml +++ b/pom.xml @@ -4,17 +4,16 @@ https://maven.apache.org/xsd/maven-4.0.0.xsd"> com.guicedee - dev-kit - 0.0.0_0-SNAPSHOT - ../../../ + parent + 2.0.0-SNAPSHOT 4.0.0 com.guicedee - guiced-injection + guice-injection jar - 0.0.0_0-SNAPSHOT + 2.0.0-SNAPSHOT Guiced Injector Guice Injection allows you to access multiple Guice Binders and Modules across separate archives. Allowing you to configure your applications with injection from multiple dependancies. Servlets, EJB's, and @@ -44,15 +43,56 @@ import pom + + com.guicedee + jakarta-bom + ${guicedee.version} + import + pom + + + com.guicedee + google-bom + ${guicedee.version} + import + pom + + + com.guicedee + apache-bom + ${guicedee.version} + import + pom + + + com.guicedee + tests-bom + ${guicedee.version} + import + pom + + com.guicedee - guiced-log-master + guice-inject-client + + org.projectlombok + lombok + provided + + + + io.github.classgraph classgraph @@ -64,12 +104,12 @@ - com.guicedee.services + org.apache.commons commons-lang3 - com.guicedee.services + jakarta.xml.bind jakarta.xml.bind-api @@ -79,8 +119,8 @@ - com.guicedee.services - slf4j + org.slf4j + slf4j-api @@ -93,7 +133,6 @@ jackson-datatype-jsr310 - com.guicedee.services json @@ -107,8 +146,8 @@ - com.guicedee.services - javax.inject + jakarta.inject + jakarta.inject-api @@ -121,73 +160,59 @@ guava - - - - https://github.com/GedMarc?tab=repositories - + + org.slf4j + jcl-over-slf4j + - - Github - https://github.com/GedMarc/GuiceInjection/issues - + + org.junit.jupiter + junit-jupiter-api + test + - - TeamCity - http://jwebmp.com/teamcity - + + + + org.moditect + moditect-maven-plugin + + org.codehaus.mojo flatten-maven-plugin + - - ossrh - direct - true - true - flatter.pom - - - - - flatten - verify - - flatten - - - - - flatten.clean - clean - - clean - - - + + org.apache.maven.plugins + maven-javadoc-plugin - com.coderplus.maven.plugins - copy-rename-maven-plugin - 1.0 - - - copy-file - verify - - copy - - - flatter.pom - dependency-reduced-pom.xml - - - + org.apache.maven.plugins + maven-compiler-plugin + ${maven.compiler.version} + true + + + + org.projectlombok + lombok + ${lombok.version} + + + + lombok.launch.AnnotationProcessorHider$AnnotationProcessor + + + true + + + diff --git a/src/jre11/java/module-info.java b/src/jre11/java/module-info.java index 47e8c8a..7131fbb 100644 --- a/src/jre11/java/module-info.java +++ b/src/jre11/java/module-info.java @@ -1,42 +1,44 @@ import com.guicedee.guicedinjection.json.*; module com.guicedee.guicedinjection { + + requires transitive com.guicedee.client; + requires transitive com.google.guice; requires transitive io.github.classgraph; - + requires transitive com.fasterxml.jackson.databind; requires transitive com.fasterxml.jackson.annotation; - - requires transitive com.guicedee.logmaster; - + requires transitive com.fasterxml.jackson.datatype.jsr310; + //requires transitive com.guicedee.logmaster; + requires transitive org.apache.commons.lang3; - requires transitive jakarta.xml.bind; - - requires static java.sql; - requires static org.json; - requires static org.apache.poi.ooxml; - requires static org.apache.poi.poi; - - requires static java.xml; - - requires static org.slf4j; - requires transitive com.fasterxml.jackson.datatype.jsr310; - - exports com.guicedee.guicedinjection; - exports com.guicedee.guicedinjection.interfaces; + requires transitive jakarta.xml.bind; + + requires static java.sql; + requires static org.json; + requires static org.apache.poi.ooxml; + requires static org.apache.poi.poi; + + requires static java.xml; + + requires static org.slf4j; + requires static lombok; + + + exports com.guicedee.guicedinjection; exports com.guicedee.guicedinjection.exceptions; - exports com.guicedee.guicedinjection.interfaces.annotations; exports com.guicedee.guicedinjection.abstractions; exports com.guicedee.guicedinjection.pairing; exports com.guicedee.guicedinjection.json; exports com.guicedee.guicedinjection.properties; exports com.guicedee.guicedinjection.representations; - + uses com.guicedee.guicedinjection.interfaces.IPackageContentsScanner; uses com.guicedee.guicedinjection.interfaces.IFileContentsScanner; uses com.guicedee.guicedinjection.interfaces.IFileContentsPatternScanner; uses com.guicedee.guicedinjection.interfaces.IGuiceConfigurator; - uses com.guicedee.guicedinjection.interfaces.IGuiceDefaultBinder; + //uses com.guicedee.guicedinjection.interfaces.IGuiceDefaultBinder; uses com.guicedee.guicedinjection.interfaces.IGuicePreStartup; uses com.guicedee.guicedinjection.interfaces.IGuicePreDestroy; uses com.guicedee.guicedinjection.interfaces.IGuiceModule; @@ -48,19 +50,18 @@ uses com.guicedee.guicedinjection.interfaces.IPackageRejectListScanner; uses com.guicedee.guicedinjection.interfaces.IGuiceScanJarExclusions; uses com.guicedee.guicedinjection.interfaces.IGuiceScanJarInclusions; - + provides com.guicedee.guicedinjection.interfaces.IGuiceScanModuleExclusions with com.guicedee.guicedinjection.implementations.GuiceDefaultModuleExclusions; provides com.guicedee.guicedinjection.interfaces.IGuiceScanJarExclusions with com.guicedee.guicedinjection.implementations.GuiceDefaultModuleExclusions; - - provides com.guicedee.guicedinjection.interfaces.IGuiceDefaultBinder with com.guicedee.guicedinjection.injections.ContextBinderGuice, ObjectMapperBinder; + + provides com.guicedee.guicedinjection.interfaces.IGuiceModule with com.guicedee.guicedinjection.injections.ContextBinderGuice, ObjectMapperBinder; //provides com.guicedee.guicedinjection.interfaces.IGuiceModule with com.guicedee.guicedinjection.abstractions.GuiceInjectorModule; - provides com.guicedee.guicedinjection.interfaces.IGuicePreDestroy with com.guicedee.guicedinjection.interfaces.JobService; - + provides java.net.spi.URLStreamHandlerProvider with com.guicedee.guicedinjection.urls.JrtUrlHandler; - + opens com.guicedee.guicedinjection to com.fasterxml.jackson.databind; opens com.guicedee.guicedinjection.properties to com.fasterxml.jackson.databind; opens com.guicedee.guicedinjection.json to com.fasterxml.jackson.databind; - + opens com.guicedee.guicedinjection.pairing; } diff --git a/src/main/java/com/guicedee/guicedinjection/GuiceConfig.java b/src/main/java/com/guicedee/guicedinjection/GuiceConfig.java index 856cd2c..68dd78c 100644 --- a/src/main/java/com/guicedee/guicedinjection/GuiceConfig.java +++ b/src/main/java/com/guicedee/guicedinjection/GuiceConfig.java @@ -3,14 +3,15 @@ import com.google.inject.Singleton; import jakarta.validation.constraints.NotNull; +import lombok.Getter; +import lombok.Setter; /** * The configuration class for Guice Context and the Classpath Scanner */ @SuppressWarnings({"WeakerAccess", "unused", "UnusedReturnValue"}) @Singleton -public class GuiceConfig> -{ +public class GuiceConfig> implements com.guicedee.guicedinjection.interfaces.IGuiceConfig { /** * Property to use when everything is found in the boot module */ @@ -79,6 +80,14 @@ public class GuiceConfig> * 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 +97,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,32 +118,14 @@ 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) @@ -158,24 +134,13 @@ public J setFieldScanning(boolean 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) @@ -184,24 +149,13 @@ public J setAnnotationScanning(boolean 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) @@ -210,24 +164,13 @@ public J setMethodInfo(boolean 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) @@ -236,24 +179,13 @@ public J setIgnoreFieldVisibility(boolean 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) @@ -262,28 +194,13 @@ public J setIgnoreMethodVisibility(boolean 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) @@ -292,24 +209,13 @@ public J setIncludePackages(boolean 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) @@ -318,28 +224,13 @@ public J setFieldInfo(boolean 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) @@ -349,28 +240,13 @@ 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) @@ -379,24 +255,13 @@ public J setClasspathScanning(boolean 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) @@ -405,24 +270,13 @@ public J setExcludeModulesAndJars(boolean 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) @@ -457,39 +311,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 +338,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..fb43d7f 100644 --- a/src/main/java/com/guicedee/guicedinjection/GuiceContext.java +++ b/src/main/java/com/guicedee/guicedinjection/GuiceContext.java @@ -21,9 +21,9 @@ import com.guicedee.guicedinjection.abstractions.*; 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.Log; import java.lang.annotation.*; import java.util.*; @@ -42,13 +42,10 @@ * @version 1.0 * @since Nov 14, 2016 */ +@Log @SuppressWarnings("MissingClassJavaDoc") public class GuiceContext> { - /** - * Field log - */ - private static final Logger log = LogFactory.getLog("GuiceContext"); /** * This particular instance of the class */ @@ -118,33 +115,32 @@ public static synchronized Injector inject() GuiceContext.buildingInjector = true; GuiceContext.log.info("Starting up Guice Context"); GuiceContext.instance() - .loadConfiguration(); + .loadConfiguration(); if (GuiceContext.instance() - .getConfig() - .isPathScanning() || - GuiceContext.instance() - .getConfig() - .isClasspathScanning()) + .getConfig() + .isPathScanning() || + GuiceContext.instance() + .getConfig() + .isClasspathScanning()) { GuiceContext.instance() - .loadScanner(); + .loadScanner(); } GuiceContext.instance() - .loadPreStartups(); + .loadPreStartups(); List cModules = new ArrayList<>(); cModules.add(new GuiceInjectorModule()); GuiceContext.instance().injector = Guice.createInjector(cModules); GuiceContext.buildingInjector = false; GuiceContext.instance() - .loadPostStartups(); + .loadPostStartups(); Runtime.getRuntime() - .addShutdownHook(new Thread(GuiceContext::destroy)); + .addShutdownHook(new Thread(GuiceContext::destroy)); GuiceContext.log.config("Injection System Ready"); - } - catch (Throwable e) + } catch (Throwable e) { GuiceContext.log.log(Level.SEVERE, "Exception creating Injector : " + e.getMessage(), e); throw new RuntimeException("Unable to boot Guice Injector", e); @@ -219,13 +215,13 @@ private static boolean isEntityType(Class clazz) for (Annotation annotation : clazz.getAnnotations()) { if (annotation.annotationType() - .getCanonicalName() - .equalsIgnoreCase("jakarta.persistence.Entity")) + .getCanonicalName() + .equalsIgnoreCase("jakarta.persistence.Entity")) { return true; } } - }catch (NullPointerException npe ) + } catch (NullPointerException npe) { return false; } @@ -271,7 +267,7 @@ public static T get(@NotNull Class type, Class anno public static T get(@NotNull Key type) { Class clazz = (Class) type.getTypeLiteral() - .getRawType(); + .getRawType(); T instance; boolean isEntityType = isEntityType(clazz); if (isNotEnhanceable(clazz) || isEntityType) @@ -279,19 +275,17 @@ public static T get(@NotNull Key type) try { instance = clazz.getDeclaredConstructor() - .newInstance(); + .newInstance(); if (!isNotInjectable(clazz)) { inject().injectMembers(instance); } - } - catch (Exception e) + } catch (Exception e) { log.log(Level.SEVERE, "Unable to construct [" + clazz.getCanonicalName() + "]. Not Enhanceable or an Entity.", e); throw new RuntimeException(e); } - } - else + } else { instance = inject().getInstance(type); } @@ -305,7 +299,7 @@ public static T get(@NotNull Key type) public static void destroy() { Set destroyers = GuiceContext.instance() - .getLoader(IGuicePreDestroy.class, true, ServiceLoader.load(IGuicePreDestroy.class)); + .getLoader(IGuicePreDestroy.class, true, ServiceLoader.load(IGuicePreDestroy.class)); for (IGuicePreDestroy destroyer : destroyers) { IGuicePreDestroy instance = GuiceContext.get(destroyer.getClass()); @@ -332,7 +326,7 @@ public static void destroy() */ private static int getJavaVersion() { - String version = getSystemPropertyOrEnvironment("java.version","11"); + String version = getSystemPropertyOrEnvironment("java.version", "11"); if (version.startsWith("1.")) { version = version.substring(2); @@ -401,9 +395,9 @@ private void loadConfiguration() for (IGuiceConfigurator guiceConfigurator : guiceConfigurators) { GuiceContext.log.config("Loading IGuiceConfigurator - " + - guiceConfigurator.getClass() - .getCanonicalName()); - GuiceContext.config = guiceConfigurator.configure(GuiceContext.config); + guiceConfigurator.getClass() + .getCanonicalName()); + GuiceContext.config = (GuiceConfig) guiceConfigurator.configure(GuiceContext.config); } GuiceContext.log.config("IGuiceConfigurator : " + GuiceContext.config.toString()); configured = true; @@ -422,7 +416,7 @@ private String[] getJarsExclusionList() Set strings = new TreeSet<>(); Set exclusions = loadJarRejectScanners(); if (exclusions.iterator() - .hasNext()) + .hasNext()) { for (IGuiceScanJarExclusions exclusion : exclusions) { @@ -445,7 +439,7 @@ private String[] getJarsInclusionList() Set strings = new TreeSet<>(); Set exclusions = loadJarInclusionScanners(); if (exclusions.iterator() - .hasNext()) + .hasNext()) { for (IGuiceScanJarInclusions exclusion : exclusions) { @@ -475,24 +469,22 @@ private synchronized void loadScanner() if (async) { scanResult = scanner.scan(Runtime.getRuntime() - .availableProcessors()); - } - else + .availableProcessors()); + } else { scanResult = scanner.scan(); } stopwatch.stop(); Map fileScans = quickScanFiles(); fileScans.forEach((key, value) -> - scanResult.getResourcesWithLeafName(key) - .forEachByteArrayIgnoringIOException(value)); + scanResult.getResourcesWithLeafName(key) + .forEachByteArrayIgnoringIOException(value)); quickScanFilesPattern().forEach( - (key, value) -> - scanResult.getResourcesMatchingPattern(key) - .forEachByteArrayIgnoringIOException(value)); + (key, value) -> + scanResult.getResourcesMatchingPattern(key) + .forEachByteArrayIgnoringIOException(value)); - } - catch (Exception mpe) + } catch (Exception mpe) { GuiceContext.log.log(Level.SEVERE, "Unable to run scanner", mpe); } @@ -533,15 +525,13 @@ private ClassGraph configureScanner(ClassGraph graph) { graph = graph.rejectJars(jarRejections); } - } - else + } else { String[] modulesRejection = getModulesExclusionList(); if (modulesRejection.length != 0) { graph = graph.rejectModules(modulesRejection); - } - else + } else { graph = graph.ignoreParentModuleLayers(); } @@ -558,16 +548,14 @@ private ClassGraph configureScanner(ClassGraph graph) { graph = graph.acceptJars(jarRejections); } - } - else + } else { String[] modulesRejection = getModulesInclusionsList(); log.config("Accepted Modules for Scanning : " + Arrays.toString(modulesRejection)); if (modulesRejection.length != 0) { graph = graph.acceptModules(modulesRejection); - } - else + } else { graph = graph.ignoreParentModuleLayers(); } @@ -644,13 +632,13 @@ private String[] getPackagesList() Set strings = new LinkedHashSet<>(); Set exclusions = getLoader(IPackageContentsScanner.class, true, ServiceLoader.load(IPackageContentsScanner.class)); if (exclusions.iterator() - .hasNext()) + .hasNext()) { for (IPackageContentsScanner exclusion : exclusions) { GuiceContext.log.log(Level.CONFIG, "Loading IPackageContentsScanner - " + - exclusion.getClass() - .getCanonicalName()); + exclusion.getClass() + .getCanonicalName()); Set searches = exclusion.searchFor(); strings.addAll(searches); } @@ -669,13 +657,13 @@ private String[] getBlacklistPackages() Set strings = new LinkedHashSet<>(); Set exclusions = getLoader(IPackageRejectListScanner.class, true, ServiceLoader.load(IPackageRejectListScanner.class)); if (exclusions.iterator() - .hasNext()) + .hasNext()) { for (IPackageRejectListScanner exclusion : exclusions) { GuiceContext.log.log(Level.CONFIG, "Loading IPackageContentsScanner - " + - exclusion.getClass() - .getCanonicalName()); + exclusion.getClass() + .getCanonicalName()); Set searches = exclusion.exclude(); strings.addAll(searches); } @@ -694,13 +682,13 @@ private String[] getPathsList() Set strings = new TreeSet<>(); Set exclusions = getLoader(IPathContentsScanner.class, true, ServiceLoader.load(IPathContentsScanner.class)); if (exclusions.iterator() - .hasNext()) + .hasNext()) { for (IPathContentsScanner exclusion : exclusions) { GuiceContext.log.log(Level.CONFIG, "Loading IPathScanningContentsScanner - " + - exclusion.getClass() - .getCanonicalName()); + exclusion.getClass() + .getCanonicalName()); Set searches = exclusion.searchFor(); strings.addAll(searches); } @@ -719,13 +707,13 @@ private String[] getPathsBlacklistList() Set strings = new TreeSet<>(); Set exclusions = loadPathRejectScanners(); if (exclusions.iterator() - .hasNext()) + .hasNext()) { for (IPathContentsRejectListScanner exclusion : exclusions) { GuiceContext.log.log(Level.CONFIG, "Loading IPathContentsRejectListScanner - " + - exclusion.getClass() - .getCanonicalName()); + exclusion.getClass() + .getCanonicalName()); Set searches = exclusion.searchFor(); strings.addAll(searches); } @@ -745,7 +733,7 @@ private String[] getModulesExclusionList() Set strings = new TreeSet<>(); Set exclusions = getLoader(IGuiceScanModuleExclusions.class, true, ServiceLoader.load(IGuiceScanModuleExclusions.class)); if (exclusions.iterator() - .hasNext()) + .hasNext()) { for (IGuiceScanModuleExclusions exclusion : exclusions) { @@ -769,7 +757,7 @@ private String[] getModulesInclusionsList() Set strings = new TreeSet<>(); Set exclusions = getLoader(IGuiceScanModuleInclusions.class, true, ServiceLoader.load(IGuiceScanModuleInclusions.class)); if (exclusions.iterator() - .hasNext()) + .hasNext()) { for (IGuiceScanModuleInclusions exclusion : exclusions) { @@ -791,8 +779,8 @@ private Map quickScanFiles() for (IFileContentsScanner fileScanner : fileScanners) { GuiceContext.log.log(Level.CONFIG, "Loading IFileContentsScanner - " + - fileScanner.getClass() - .getCanonicalName()); + fileScanner.getClass() + .getCanonicalName()); fileScans.putAll(fileScanner.onMatch()); } return fileScans; @@ -808,8 +796,8 @@ private Map quickScanFilesPattern() for (IFileContentsPatternScanner fileScanner : fileScanners) { GuiceContext.log.log(Level.CONFIG, "Loading IFileContentsPatternScanner - " + - fileScanner.getClass() - .getCanonicalName()); + fileScanner.getClass() + .getCanonicalName()); fileScans.putAll(fileScanner.onMatch()); } return fileScans; @@ -831,7 +819,7 @@ public Set getLoader(Class loaderType, { if (!getAllLoadedServices().containsKey(loaderType)) { - Set loader = IDefaultService.loaderToSetNoInjection(serviceLoader); + Set loader = loaderToSetNoInjection(serviceLoader); getAllLoadedServices().put(loaderType, loader); } return getAllLoadedServices().get(loaderType); @@ -871,7 +859,7 @@ private void loadPostStartups() { Integer sortOrder = postStartup.sortOrder(); postStartupGroups.computeIfAbsent(sortOrder, k -> new TreeSet<>()) - .add(postStartup); + .add(postStartup); } for (Map.Entry> entry : postStartupGroups.entrySet()) @@ -886,22 +874,19 @@ private void loadPostStartups() try { iGuicePostStartup.postLoad(); - } - catch (Throwable T) + } catch (Throwable T) { log.log(Level.SEVERE, "Cannot execute post startup - " + iGuicePostStartup.getClass() - .getCanonicalName(), T); + .getCanonicalName(), T); } } - } - else + } else { try { value.parallelStream() - .forEach(IGuicePostStartup::postLoad); - } - catch (Throwable T) + .forEach(IGuicePostStartup::postLoad); + } catch (Throwable T) { log.log(Level.SEVERE, "Cannot execute post startup - ", T); } @@ -1015,8 +1000,8 @@ private void loadPreStartups() for (IGuicePreStartup startup : startups) { GuiceContext.log.config("Loading IGuicePreStartup - " + - startup.getClass() - .getCanonicalName()); + startup.getClass() + .getCanonicalName()); startup.onStartup(); } } @@ -1038,11 +1023,10 @@ public > Set getLoader(Class loaderType, ServiceLo Set loader; if (GuiceContext.buildingInjector || injector == null) { - loader = IDefaultService.loaderToSetNoInjection(serviceLoader); - } - else + loader = loaderToSetNoInjection(serviceLoader); + } else { - loader = IDefaultService.loaderToSet(serviceLoader); + loader = loaderToSet(serviceLoader); } getAllLoadedServices().put(loaderType, loader); } @@ -1082,4 +1066,151 @@ public void setAsync(boolean async) { this.async = async; } + + Map> loaderClasses = new ConcurrentHashMap<>(); + + /** + * Method loaderToSet, converts a ServiceLoader into a TreeSet + * + * @param loader of type ServiceLoader + * @return Set + */ + @SuppressWarnings("unchecked") + @NotNull + public > 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) + { + log.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; + } + + public > 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) + { + log.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 + public 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) + { + log.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) + { + log + .log(Level.SEVERE, "Cannot load a service through default constructor", e); + } + } + return output; + } } diff --git a/src/main/java/com/guicedee/guicedinjection/interfaces/JobService.java b/src/main/java/com/guicedee/guicedinjection/JobService.java similarity index 75% rename from src/main/java/com/guicedee/guicedinjection/interfaces/JobService.java rename to src/main/java/com/guicedee/guicedinjection/JobService.java index 8b04c99..daf572e 100644 --- a/src/main/java/com/guicedee/guicedinjection/interfaces/JobService.java +++ b/src/main/java/com/guicedee/guicedinjection/JobService.java @@ -1,9 +1,13 @@ -package com.guicedee.guicedinjection.interfaces; +package com.guicedee.guicedinjection; import com.google.inject.Singleton; -import com.guicedee.guicedinjection.GuiceContext; -import com.guicedee.logger.LogFactory; +import com.guicedee.guicedinjection.interfaces.IGuicePreDestroy; +import lombok.Getter; +import lombok.Setter; +import lombok.extern.java.Log; +import java.sql.Time; +import java.time.temporal.ChronoUnit; import java.util.Map; import java.util.Set; import java.util.concurrent.Callable; @@ -24,141 +28,174 @@ */ @Singleton +@Log public class JobService - implements IGuicePreDestroy { - private static final Logger log = LogFactory.getLog("JobService"); + implements IGuicePreDestroy +{ private final Map serviceMap = new ConcurrentHashMap<>(); private final Map pollingMap = new ConcurrentHashMap<>(); private final Map maxQueueCount = new ConcurrentHashMap<>(); - - public JobService() { + + @Getter + @Setter + private static long defaultWaitTime = 120; + @Getter + @Setter + private static TimeUnit defaultWaitUnit = TimeUnit.SECONDS; + + @Getter + private static final JobService INSTANCE = new JobService(); + + JobService() + { //No config required } - + /** * Gets a list of all job pools currently registered * * @return */ - public Set getJobPools() { + public Set getJobPools() + { return serviceMap.keySet(); } - + /** * Returns the list of repeating task pools registered * * @return */ - public Set getPollingPools() { + public Set getPollingPools() + { return pollingMap.keySet(); } - + /** * Completes and Removes all jobs running from the given pool * * @param pool The pool to remove */ - public ExecutorService removeJob(String pool) { + public ExecutorService removeJob(String pool) + { ExecutorService es = serviceMap.get(pool); - if (es == null) { + if (es == null) + { log.warning("Pool " + pool + " was not registered"); return null; } - + es.shutdown(); - try { + try + { log.finer("Waiting for pool " + pool + " to shutdown cleanly."); - es.awaitTermination(GuiceContext.defaultWaitTime, GuiceContext.defaultWaitUnit); - } catch (Exception e) { + es.awaitTermination(defaultWaitTime, defaultWaitUnit); + } catch (Exception e) + { log.log(Level.SEVERE, "Couldn't shut down pool" + pool + " cleanly in 60 seconds. Forcing."); } - if (!es.isShutdown()) { + if (!es.isShutdown()) + { es.shutdownNow(); } serviceMap.remove(pool); return es; } - + /** * Completes and Removes all jobs running from the given pool * * @param pool The pool name to remove */ - public ScheduledExecutorService removePollingJob(String pool) { + public ScheduledExecutorService removePollingJob(String pool) + { ScheduledExecutorService es = pollingMap.get(pool); - if (es == null) { + if (es == null) + { log.warning("Repeating Pool " + pool + " was not registered"); return null; } es.shutdown(); - try { + try + { log.finer("Waiting for repeating pool " + pool + " to shutdown cleanly."); - es.awaitTermination(GuiceContext.defaultWaitTime, GuiceContext.defaultWaitUnit); - } catch (Exception e) { + es.awaitTermination(defaultWaitTime, defaultWaitUnit); + } catch (Exception e) + { log.log(Level.SEVERE, "Couldn't shut down pool" + pool + " cleanly in 60 seconds. Forcing."); es.shutdownNow(); } - if (!es.isTerminated()) { + if (!es.isTerminated()) + { es.shutdownNow(); } pollingMap.remove(pool); return es; } - + /** * Registers a new job pool with a specific service * * @param name * @param executorService */ - public ExecutorService registerJobPool(String name, ExecutorService executorService) { - if (serviceMap.containsKey(name)) { + public ExecutorService registerJobPool(String name, ExecutorService executorService) + { + if (serviceMap.containsKey(name)) + { removeJob(name); } serviceMap.put(name, executorService); - if (!maxQueueCount.containsKey(name)) { + if (!maxQueueCount.containsKey(name)) + { maxQueueCount.put(name, 20); } - if (executorService instanceof ForkJoinPool) { + if (executorService instanceof ForkJoinPool) + { ForkJoinPool pool = (ForkJoinPool) executorService; - } - else if (executorService instanceof ThreadPoolExecutor) { + } else if (executorService instanceof ThreadPoolExecutor) + { ThreadPoolExecutor executor = (ThreadPoolExecutor) executorService; executor.setMaximumPoolSize(maxQueueCount.get(name)); - executor.setKeepAliveTime(GuiceContext.defaultWaitTime, GuiceContext.defaultWaitUnit); + 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 */ - public ScheduledExecutorService registerJobPollingPool(String name, ScheduledExecutorService executorService) { - if (pollingMap.containsKey(name)) { + 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 */ - public ExecutorService addJob(String jobPoolName, Runnable thread) { - if (!serviceMap.containsKey(jobPoolName) || serviceMap.get(jobPoolName).isTerminated() || serviceMap.get(jobPoolName).isShutdown()) { + public ExecutorService addJob(String jobPoolName, Runnable thread) + { + if (!serviceMap.containsKey(jobPoolName) || serviceMap.get(jobPoolName).isTerminated() || serviceMap.get(jobPoolName).isShutdown()) + { registerJobPool(jobPoolName, Executors.newWorkStealingPool()); } - + ExecutorService service = serviceMap.get(jobPoolName); - if (getCurrentTaskCount(service) >= maxQueueCount.get(jobPoolName)) { + if (getCurrentTaskCount(service) >= maxQueueCount.get(jobPoolName)) + { log.log(Level.FINER, maxQueueCount + " Hit - Finishing before next run"); removeJob(jobPoolName); service = registerJobPool(jobPoolName, newWorkStealingPool()); @@ -166,20 +203,23 @@ public ExecutorService addJob(String jobPoolName, Runnable thread) { service.execute(thread); return service; } - + /** * Adds a static run once job to the monitored collections * * @param jobPoolName * @param thread */ - public ExecutorService addJob(String jobPoolName, Callable thread) { - if (!serviceMap.containsKey(jobPoolName) || serviceMap.get(jobPoolName).isTerminated() || serviceMap.get(jobPoolName).isShutdown()) { + public ExecutorService addJob(String jobPoolName, Callable thread) + { + if (!serviceMap.containsKey(jobPoolName) || serviceMap.get(jobPoolName).isTerminated() || serviceMap.get(jobPoolName).isShutdown()) + { registerJobPool(jobPoolName, newWorkStealingPool()); } - + ExecutorService service = serviceMap.get(jobPoolName); - if (getCurrentTaskCount(service) >= maxQueueCount.get(jobPoolName)) { + if (getCurrentTaskCount(service) >= maxQueueCount.get(jobPoolName)) + { log.log(Level.FINER, maxQueueCount + " Hit - Finishing before next run"); removeJob(jobPoolName); service = registerJobPool(jobPoolName, newWorkStealingPool()); @@ -187,69 +227,70 @@ public ExecutorService addJob(String jobPoolName, Callable thread) { service.submit(thread); return service; } - - public void waitForJob(String jobName) { - waitForJob(jobName, GuiceContext.defaultWaitTime, GuiceContext.defaultWaitUnit); + + public void waitForJob(String jobName) + { + waitForJob(jobName, defaultWaitTime, defaultWaitUnit); } - - public void waitForJob(String jobName, long timeout, TimeUnit unit) { - if (!serviceMap.containsKey(jobName)) { + + public void waitForJob(String jobName, long timeout, TimeUnit unit) + { + if (!serviceMap.containsKey(jobName)) + { return; } ExecutorService service = serviceMap.get(jobName); service.shutdown(); - try { + try + { service.awaitTermination(timeout, unit); - } catch (InterruptedException e) { + } catch (InterruptedException e) + { log.log(Level.WARNING, "Thread didn't close cleanly, make sure running times are acceptable", e); } } - + /** * Adds a static run once job to the monitored collections * * @param jobPoolName * @param thread */ - public ScheduledExecutorService addPollingJob(String jobPoolName, Runnable thread, long delay, TimeUnit unit) { - if (!pollingMap.containsKey(jobPoolName) || pollingMap.get(jobPoolName).isTerminated() || pollingMap.get(jobPoolName).isShutdown()) { + 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())); + .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 */ - 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()) { + 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())); + .availableProcessors())); } ScheduledExecutorService service = pollingMap.get(jobPoolName); service.scheduleAtFixedRate(thread, initialDelay, delay, unit); return service; } - - /** - * Static instance giver - * - * @return The running instance - */ - public static JobService getInstance() { - return GuiceContext.get(JobService.class); - } - + /** * Shutdowns */ - public void destroy() { + public void destroy() + { log.config("Destroying all running jobs..."); serviceMap.forEach((key, value) -> { @@ -263,32 +304,37 @@ public void destroy() { }); log.config("All jobs destroyed"); } - - private int getCurrentTaskCount(ExecutorService service) { - if (service instanceof ForkJoinPool) { + + private int getCurrentTaskCount(ExecutorService service) + { + if (service instanceof ForkJoinPool) + { ForkJoinPool pool = (ForkJoinPool) service; return (int) pool.getQueuedTaskCount(); - } - else if (service instanceof ThreadPoolExecutor) { + } else if (service instanceof ThreadPoolExecutor) + { ThreadPoolExecutor executor = (ThreadPoolExecutor) service; return (int) executor.getTaskCount(); } return 0; } - - public void setMaxQueueCount(String queueName, int queueCount) { + + public void setMaxQueueCount(String queueName, int queueCount) + { maxQueueCount.put(queueName, queueCount); } - + @Override - public void onDestroy() { + public void onDestroy() + { destroy(); } - + @Override - public Integer sortOrder() { + public Integer sortOrder() + { return Integer.MIN_VALUE + 8; } - - + + } diff --git a/src/main/java/com/guicedee/guicedinjection/abstractions/GuiceInjectorModule.java b/src/main/java/com/guicedee/guicedinjection/abstractions/GuiceInjectorModule.java index 178a605..0f3308f 100644 --- a/src/main/java/com/guicedee/guicedinjection/abstractions/GuiceInjectorModule.java +++ b/src/main/java/com/guicedee/guicedinjection/abstractions/GuiceInjectorModule.java @@ -32,15 +32,13 @@ 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 lombok.extern.java.Log; 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 @@ -48,15 +46,10 @@ * @author GedMarc * @since 12 Dec 2016 */ +@Log public class GuiceInjectorModule extends AbstractModule implements IGuiceModule { - - /** - * Field log - */ - private static final Logger log = LogFactory.getLog("GuiceInjectorModule"); - /** * Constructs a new instance of the module */ @@ -77,17 +70,9 @@ public void configure() { */ @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() diff --git a/src/main/java/com/guicedee/guicedinjection/injections/ContextBinderGuice.java b/src/main/java/com/guicedee/guicedinjection/injections/ContextBinderGuice.java index 37ae739..afe4f00 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.IGuiceModule; 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()) + .in(Singleton.class); + + 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(JobService.class) + .toInstance(JobService.getINSTANCE()); + } } 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 excludeModules(); - - -} diff --git a/src/main/java/com/guicedee/guicedinjection/interfaces/IGuiceScanModuleInclusions.java b/src/main/java/com/guicedee/guicedinjection/interfaces/IGuiceScanModuleInclusions.java deleted file mode 100644 index f8c0810..0000000 --- a/src/main/java/com/guicedee/guicedinjection/interfaces/IGuiceScanModuleInclusions.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 IGuiceScanModuleInclusions> - extends IDefaultService { - /** - * Excludes the given jars for scanning - * - * @return A set - */ - @NotNull Set includeModules(); - -} diff --git a/src/main/java/com/guicedee/guicedinjection/interfaces/IPackageContentsScanner.java b/src/main/java/com/guicedee/guicedinjection/interfaces/IPackageContentsScanner.java deleted file mode 100644 index 2a77f7a..0000000 --- a/src/main/java/com/guicedee/guicedinjection/interfaces/IPackageContentsScanner.java +++ /dev/null @@ -1,117 +0,0 @@ -package com.guicedee.guicedinjection.interfaces; - -import java.util.Set; - -/** - * The constructor accepts a list of whitelisted package prefixes / jar names to scan, as well as blacklisted packages/jars not to scan, where blacklisted entries are prefixed - *

- * Whitelisting/blacklisting packages (and their subpackages) - *

- * Providing one or more package names to the constructor limits scanning to the named packages and their subpackages. Packages can be blacklisted by prefixing the name with -. - *

- * new FastClasspathScanner("com.abc", "com.xyz", "-com.xyz.badpkg") - *

- * Blacklisted entries override whitelisted entries - *

- * When whitelisted packages are used together, the result is the union of classes in the whitelisted packages. When combining whitelisted packages with blacklisted packages, the - * result is the set difference between whitelisted packages and blacklisted packages. - *

- * If only one or more blacklisted packages are provided (with no accompanying whitelisted package or class), all packages except for the blacklisted packages will be scanned. - *

- * new FastClasspathScanner("-com.xyz.badpkg") - *

- * Limiting scanning to specific jars on the classpath - *

- * By default, all jarfiles on the classpath are scanned. To limit scanning to one or more specific jars, specify the jar filenames (without path) after a jar: prefix. Jar name - * specifications can include a glob (*) character. - *

- * Note that this is a separate filtering mechanism from the package and class whitelist: whitelists are used to limit scanning within jars and/or directories; adding jar: entries - * to the scan spec limits scanning to the named jar(s), rather than scanning all jars. - *

- * Specifying a jar: entry in the scan spec does not prevent the scanning of directories. Directory scanning can also be disabled by adding "-dir:" (see below). - *

- * new FastClasspathScanner("com.x", "jar:deploy.jar", "-jar:irrelevant-*.jar") - *

- * Advanced): When using jar whitelisting with multiply-defined classes - *

- * Jar whitelisting can be problematic if multiple classes of the same fully-qualified name are defined in different classpath elements. Classes are resolved for loading in - * classpath order, so all but the first definition of a class in the classpath will be ignored due to classpath masking. This can lead to classes you expect to match not showing - * up as matches, if you only whitelist classpath jars containing the second or subsequent definition of a class. - *

- * For example, if the classpath consists of a.jar and b.jar, in that order, and both jars contain a class definition pkg/Cls.class, then the class definition in b.jar is ignored, - * because it is masked by a definition occurring earlier in the classpath, in a.jar. - *

- * Even if you restrict scanning by providing "jar:b.jar" in the scan spec, the file pkg/Cls.class in b.jar will be ignored, and will not be provided to a MatchProcessor. The - * reason for this is to ensure that MatchProcessors only ever get passed references to classes that would be loaded by the current ClassLoader. This is to prevent inconsistencies, - * since otherwise the version of the class that would be loaded would depend upon whether FastClasspathScanner manually loaded a class definition first, or whether the current - * ClassLoader loaded a definition for a class of the same name first. - *

- * In general, if you run into this issue with multiply-defined classes, there are several possible alternatives to jar whitelisting: - *

- * Ensure that you only ever have one definition on the classpath for all classes you want to match before calling FastClasspathScanner (i.e. start the JRE with a more restricted - * classpath). - * Override the classpath or provide a custom URLClassLoader before scanning, so that there are no non-scanned classpath elements that can mask elements in the whitelisted - * directories/jars that you do want to scan. (However, be aware that the system classloader may still return cached references to already-loaded classfiles outside this overridden - * path (or won't call your custom ClassLoader), due to class caching.) - */ -@FunctionalInterface -public interface IPackageContentsScanner { - /** - * The constructor accepts a list of whitelisted package prefixes / jar names to scan, as well as blacklisted packages/jars not to scan, where blacklisted entries are prefixed - *

- * Whitelisting/blacklisting packages (and their subpackages) - *

- * Providing one or more package names to the constructor limits scanning to the named packages and their subpackages. Packages can be blacklisted by prefixing the name with - * -. - *

- * new FastClasspathScanner("com.abc", "com.xyz", "-com.xyz.badpkg") - *

- * Blacklisted entries override whitelisted entries - *

- * When whitelisted packages are used together, the result is the union of classes in the whitelisted packages. When combining whitelisted packages with blacklisted packages, - * the result is the set difference between whitelisted packages and blacklisted packages. - *

- * If only one or more blacklisted packages are provided (with no accompanying whitelisted package or class), all packages except for the blacklisted packages will be scanned. - *

- * new FastClasspathScanner("-com.xyz.badpkg") - *

- * Limiting scanning to specific jars on the classpath - *

- * By default, all jarfiles on the classpath are scanned. To limit scanning to one or more specific jars, specify the jar filenames (without path) after a jar: prefix. Jar name - * specifications can include a glob (*) character. - *

- * Note that this is a separate filtering mechanism from the package and class whitelist: whitelists are used to limit scanning within jars and/or directories; adding jar: - * entries to the scan spec limits scanning to the named jar(s), rather than scanning all jars. - *

- * Specifying a jar: entry in the scan spec does not prevent the scanning of directories. Directory scanning can also be disabled by adding "-dir:" (see below). - *

- * new FastClasspathScanner("com.x", "jar:deploy.jar", "-jar:irrelevant-*.jar") - *

- * Advanced): When using jar whitelisting with multiply-defined classes - *

- * Jar whitelisting can be problematic if multiple classes of the same fully-qualified name are defined in different classpath elements. Classes are resolved for loading in - * classpath order, so all but the first definition of a class in the classpath will be ignored due to classpath masking. This can lead to classes you expect to match not - * showing up as matches, if you only whitelist classpath jars containing the second or subsequent definition of a class. - *

- * For example, if the classpath consists of a.jar and b.jar, in that order, and both jars contain a class definition pkg/Cls.class, then the class definition in b.jar is - * ignored, because it is masked by a definition occurring earlier in the classpath, in a.jar. - *

- * Even if you restrict scanning by providing "jar:b.jar" in the scan spec, the file pkg/Cls.class in b.jar will be ignored, and will not be provided to a MatchProcessor. The - * reason for this is to ensure that MatchProcessors only ever get passed references to classes that would be loaded by the current ClassLoader. This is to prevent - * inconsistencies, since otherwise the version of the class that would be loaded would depend upon whether FastClasspathScanner manually loaded a class definition first, or - * whether the current ClassLoader loaded a definition for a class of the same name first. - *

- * In general, if you run into this issue with multiply-defined classes, there are several possible alternatives to jar whitelisting: - *

- * Ensure that you only ever have one definition on the classpath for all classes you want to match before calling FastClasspathScanner (i.e. start the JRE with a more - * restricted classpath). - * Override the classpath or provide a custom URLClassLoader before scanning, so that there are no non-scanned classpath elements that can mask elements in the whitelisted - * directories/jars that you do want to scan. (However, be aware that the system classloader may still return cached references to already-loaded classfiles outside this - * overridden path (or won't call your custom ClassLoader), due to class caching.) - * - * @return the set of string - */ - Set searchFor(); - - -} diff --git a/src/main/java/com/guicedee/guicedinjection/interfaces/IPackageRejectListScanner.java b/src/main/java/com/guicedee/guicedinjection/interfaces/IPackageRejectListScanner.java deleted file mode 100644 index 87a5bda..0000000 --- a/src/main/java/com/guicedee/guicedinjection/interfaces/IPackageRejectListScanner.java +++ /dev/null @@ -1,117 +0,0 @@ -package com.guicedee.guicedinjection.interfaces; - -import java.util.Set; - -/** - * The constructor accepts a list of whitelisted package prefixes / jar names to scan, as well as blacklisted packages/jars not to scan, where blacklisted entries are prefixed - *

- * Whitelisting/blacklisting packages (and their subpackages) - *

- * Providing one or more package names to the constructor limits scanning to the named packages and their subpackages. Packages can be blacklisted by prefixing the name with -. - *

- * new FastClasspathScanner("com.abc", "com.xyz", "-com.xyz.badpkg") - *

- * Blacklisted entries override whitelisted entries - *

- * When whitelisted packages are used together, the result is the union of classes in the whitelisted packages. When combining whitelisted packages with blacklisted packages, the - * result is the set difference between whitelisted packages and blacklisted packages. - *

- * If only one or more blacklisted packages are provided (with no accompanying whitelisted package or class), all packages except for the blacklisted packages will be scanned. - *

- * new FastClasspathScanner("-com.xyz.badpkg") - *

- * Limiting scanning to specific jars on the classpath - *

- * By default, all jarfiles on the classpath are scanned. To limit scanning to one or more specific jars, specify the jar filenames (without path) after a jar: prefix. Jar name - * specifications can include a glob (*) character. - *

- * Note that this is a separate filtering mechanism from the package and class whitelist: whitelists are used to limit scanning within jars and/or directories; adding jar: entries - * to the scan spec limits scanning to the named jar(s), rather than scanning all jars. - *

- * Specifying a jar: entry in the scan spec does not prevent the scanning of directories. Directory scanning can also be disabled by adding "-dir:" (see below). - *

- * new FastClasspathScanner("com.x", "jar:deploy.jar", "-jar:irrelevant-*.jar") - *

- * Advanced): When using jar whitelisting with multiply-defined classes - *

- * Jar whitelisting can be problematic if multiple classes of the same fully-qualified name are defined in different classpath elements. Classes are resolved for loading in - * classpath order, so all but the first definition of a class in the classpath will be ignored due to classpath masking. This can lead to classes you expect to match not showing - * up as matches, if you only whitelist classpath jars containing the second or subsequent definition of a class. - *

- * For example, if the classpath consists of a.jar and b.jar, in that order, and both jars contain a class definition pkg/Cls.class, then the class definition in b.jar is ignored, - * because it is masked by a definition occurring earlier in the classpath, in a.jar. - *

- * Even if you restrict scanning by providing "jar:b.jar" in the scan spec, the file pkg/Cls.class in b.jar will be ignored, and will not be provided to a MatchProcessor. The - * reason for this is to ensure that MatchProcessors only ever get passed references to classes that would be loaded by the current ClassLoader. This is to prevent inconsistencies, - * since otherwise the version of the class that would be loaded would depend upon whether FastClasspathScanner manually loaded a class definition first, or whether the current - * ClassLoader loaded a definition for a class of the same name first. - *

- * In general, if you run into this issue with multiply-defined classes, there are several possible alternatives to jar whitelisting: - *

- * Ensure that you only ever have one definition on the classpath for all classes you want to match before calling FastClasspathScanner (i.e. start the JRE with a more restricted - * classpath). - * Override the classpath or provide a custom URLClassLoader before scanning, so that there are no non-scanned classpath elements that can mask elements in the whitelisted - * directories/jars that you do want to scan. (However, be aware that the system classloader may still return cached references to already-loaded classfiles outside this overridden - * path (or won't call your custom ClassLoader), due to class caching.) - */ -@FunctionalInterface -public interface IPackageRejectListScanner { - /** - * The constructor accepts a list of whitelisted package prefixes / jar names to scan, as well as blacklisted packages/jars not to scan, where blacklisted entries are prefixed - *

- * Whitelisting/blacklisting packages (and their subpackages) - *

- * Providing one or more package names to the constructor limits scanning to the named packages and their subpackages. Packages can be blacklisted by prefixing the name with - * -. - *

- * new FastClasspathScanner("com.abc", "com.xyz", "-com.xyz.badpkg") - *

- * Blacklisted entries override whitelisted entries - *

- * When whitelisted packages are used together, the result is the union of classes in the whitelisted packages. When combining whitelisted packages with blacklisted packages, - * the result is the set difference between whitelisted packages and blacklisted packages. - *

- * If only one or more blacklisted packages are provided (with no accompanying whitelisted package or class), all packages except for the blacklisted packages will be scanned. - *

- * new FastClasspathScanner("-com.xyz.badpkg") - *

- * Limiting scanning to specific jars on the classpath - *

- * By default, all jarfiles on the classpath are scanned. To limit scanning to one or more specific jars, specify the jar filenames (without path) after a jar: prefix. Jar name - * specifications can include a glob (*) character. - *

- * Note that this is a separate filtering mechanism from the package and class whitelist: whitelists are used to limit scanning within jars and/or directories; adding jar: - * entries to the scan spec limits scanning to the named jar(s), rather than scanning all jars. - *

- * Specifying a jar: entry in the scan spec does not prevent the scanning of directories. Directory scanning can also be disabled by adding "-dir:" (see below). - *

- * new FastClasspathScanner("com.x", "jar:deploy.jar", "-jar:irrelevant-*.jar") - *

- * Advanced): When using jar whitelisting with multiply-defined classes - *

- * Jar whitelisting can be problematic if multiple classes of the same fully-qualified name are defined in different classpath elements. Classes are resolved for loading in - * classpath order, so all but the first definition of a class in the classpath will be ignored due to classpath masking. This can lead to classes you expect to match not - * showing up as matches, if you only whitelist classpath jars containing the second or subsequent definition of a class. - *

- * For example, if the classpath consists of a.jar and b.jar, in that order, and both jars contain a class definition pkg/Cls.class, then the class definition in b.jar is - * ignored, because it is masked by a definition occurring earlier in the classpath, in a.jar. - *

- * Even if you restrict scanning by providing "jar:b.jar" in the scan spec, the file pkg/Cls.class in b.jar will be ignored, and will not be provided to a MatchProcessor. The - * reason for this is to ensure that MatchProcessors only ever get passed references to classes that would be loaded by the current ClassLoader. This is to prevent - * inconsistencies, since otherwise the version of the class that would be loaded would depend upon whether FastClasspathScanner manually loaded a class definition first, or - * whether the current ClassLoader loaded a definition for a class of the same name first. - *

- * In general, if you run into this issue with multiply-defined classes, there are several possible alternatives to jar whitelisting: - *

- * Ensure that you only ever have one definition on the classpath for all classes you want to match before calling FastClasspathScanner (i.e. start the JRE with a more - * restricted classpath). - * Override the classpath or provide a custom URLClassLoader before scanning, so that there are no non-scanned classpath elements that can mask elements in the whitelisted - * directories/jars that you do want to scan. (However, be aware that the system classloader may still return cached references to already-loaded classfiles outside this - * overridden path (or won't call your custom ClassLoader), due to class caching.) - * - * @return the set of string - */ - Set exclude(); - - -} diff --git a/src/main/java/com/guicedee/guicedinjection/interfaces/IPathContentsRejectListScanner.java b/src/main/java/com/guicedee/guicedinjection/interfaces/IPathContentsRejectListScanner.java deleted file mode 100644 index ed0dbab..0000000 --- a/src/main/java/com/guicedee/guicedinjection/interfaces/IPathContentsRejectListScanner.java +++ /dev/null @@ -1,70 +0,0 @@ -package com.guicedee.guicedinjection.interfaces; - -import java.util.Set; - -/** - * The constructor accepts a list of whitelisted package prefixes / jar names to scan, as well as blacklisted packages/jars not to scan, where blacklisted entries are prefixed - *

- * Whitelisting/blacklisting packages (and their subpackages) - *

- * Providing one or more package names to the constructor limits scanning to the named packages and their subpackages. Packages can be blacklisted by prefixing the name with -. - *

- * new FastClasspathScanner("com.abc", "com.xyz", "-com.xyz.badpkg") - *

- * Blacklisted entries override whitelisted entries - *

- * When whitelisted packages are used together, the result is the union of classes in the whitelisted packages. When combining whitelisted packages with blacklisted packages, the - * result is the set difference between whitelisted packages and blacklisted packages. - *

- * If only one or more blacklisted packages are provided (with no accompanying whitelisted package or class), all packages except for the blacklisted packages will be scanned. - *

- * new FastClasspathScanner("-com.xyz.badpkg") - *

- * Limiting scanning to specific jars on the classpath - *

- * By default, all jarfiles on the classpath are scanned. To limit scanning to one or more specific jars, specify the jar filenames (without path) after a jar: prefix. Jar name - * specifications can include a glob (*) character. - *

- * Note that this is a separate filtering mechanism from the package and class whitelist: whitelists are used to limit scanning within jars and/or directories; adding jar: entries - * to the scan spec limits scanning to the named jar(s), rather than scanning all jars. - *

- * Specifying a jar: entry in the scan spec does not prevent the scanning of directories. Directory scanning can also be disabled by adding "-dir:" (see below). - *

- * new FastClasspathScanner("com.x", "jar:deploy.jar", "-jar:irrelevant-*.jar") - *

- * Advanced): When using jar whitelisting with multiply-defined classes - *

- * Jar whitelisting can be problematic if multiple classes of the same fully-qualified name are defined in different classpath elements. Classes are resolved for loading in - * classpath order, so all but the first definition of a class in the classpath will be ignored due to classpath masking. This can lead to classes you expect to match not showing - * up as matches, if you only whitelist classpath jars containing the second or subsequent definition of a class. - *

- * For example, if the classpath consists of a.jar and b.jar, in that order, and both jars contain a class definition pkg/Cls.class, then the class definition in b.jar is ignored, - * because it is masked by a definition occurring earlier in the classpath, in a.jar. - *

- * Even if you restrict scanning by providing "jar:b.jar" in the scan spec, the file pkg/Cls.class in b.jar will be ignored, and will not be provided to a MatchProcessor. The - * reason for this is to ensure that MatchProcessors only ever get passed references to classes that would be loaded by the current ClassLoader. This is to prevent inconsistencies, - * since otherwise the version of the class that would be loaded would depend upon whether FastClasspathScanner manually loaded a class definition first, or whether the current - * ClassLoader loaded a definition for a class of the same name first. - *

- * In general, if you run into this issue with multiply-defined classes, there are several possible alternatives to jar whitelisting: - *

- * Ensure that you only ever have one definition on the classpath for all classes you want to match before calling FastClasspathScanner (i.e. start the JRE with a more restricted - * classpath). - * Override the classpath or provide a custom URLClassLoader before scanning, so that there are no non-scanned classpath elements that can mask elements in the whitelisted - * directories/jars that you do want to scan. (However, be aware that the system classloader may still return cached references to already-loaded classfiles outside this overridden - * path (or won't call your custom ClassLoader), due to class caching.) - */ -@FunctionalInterface -public interface IPathContentsRejectListScanner { - /** - * If you only need to scan resources and not classes, .enableClassInfo() or .enableAllInfo() should not be called, for speed. Also, if you don't need to scan classes, you - * should specify the whitelist by calling .whitelistPaths() and using path separators (/), rather than by calling .whitelistPackages() and using package separators (.). Path - * and package whitelists work the same way internally, you can just choose one way or the other of specifying the whitelist/blacklist. However, calling .whitelistPackages() - * also implicitly calls .enableClassInfo(). - * - * @return the set of string - */ - Set searchFor(); - - -} diff --git a/src/main/java/com/guicedee/guicedinjection/interfaces/IPathContentsScanner.java b/src/main/java/com/guicedee/guicedinjection/interfaces/IPathContentsScanner.java deleted file mode 100644 index 0cb3999..0000000 --- a/src/main/java/com/guicedee/guicedinjection/interfaces/IPathContentsScanner.java +++ /dev/null @@ -1,70 +0,0 @@ -package com.guicedee.guicedinjection.interfaces; - -import java.util.Set; - -/** - * The constructor accepts a list of whitelisted package prefixes / jar names to scan, as well as blacklisted packages/jars not to scan, where blacklisted entries are prefixed - *

- * Whitelisting/blacklisting packages (and their subpackages) - *

- * Providing one or more package names to the constructor limits scanning to the named packages and their subpackages. Packages can be blacklisted by prefixing the name with -. - *

- * new FastClasspathScanner("com.abc", "com.xyz", "-com.xyz.badpkg") - *

- * Blacklisted entries override whitelisted entries - *

- * When whitelisted packages are used together, the result is the union of classes in the whitelisted packages. When combining whitelisted packages with blacklisted packages, the - * result is the set difference between whitelisted packages and blacklisted packages. - *

- * If only one or more blacklisted packages are provided (with no accompanying whitelisted package or class), all packages except for the blacklisted packages will be scanned. - *

- * new FastClasspathScanner("-com.xyz.badpkg") - *

- * Limiting scanning to specific jars on the classpath - *

- * By default, all jarfiles on the classpath are scanned. To limit scanning to one or more specific jars, specify the jar filenames (without path) after a jar: prefix. Jar name - * specifications can include a glob (*) character. - *

- * Note that this is a separate filtering mechanism from the package and class whitelist: whitelists are used to limit scanning within jars and/or directories; adding jar: entries - * to the scan spec limits scanning to the named jar(s), rather than scanning all jars. - *

- * Specifying a jar: entry in the scan spec does not prevent the scanning of directories. Directory scanning can also be disabled by adding "-dir:" (see below). - *

- * new FastClasspathScanner("com.x", "jar:deploy.jar", "-jar:irrelevant-*.jar") - *

- * Advanced): When using jar whitelisting with multiply-defined classes - *

- * Jar whitelisting can be problematic if multiple classes of the same fully-qualified name are defined in different classpath elements. Classes are resolved for loading in - * classpath order, so all but the first definition of a class in the classpath will be ignored due to classpath masking. This can lead to classes you expect to match not showing - * up as matches, if you only whitelist classpath jars containing the second or subsequent definition of a class. - *

- * For example, if the classpath consists of a.jar and b.jar, in that order, and both jars contain a class definition pkg/Cls.class, then the class definition in b.jar is ignored, - * because it is masked by a definition occurring earlier in the classpath, in a.jar. - *

- * Even if you restrict scanning by providing "jar:b.jar" in the scan spec, the file pkg/Cls.class in b.jar will be ignored, and will not be provided to a MatchProcessor. The - * reason for this is to ensure that MatchProcessors only ever get passed references to classes that would be loaded by the current ClassLoader. This is to prevent inconsistencies, - * since otherwise the version of the class that would be loaded would depend upon whether FastClasspathScanner manually loaded a class definition first, or whether the current - * ClassLoader loaded a definition for a class of the same name first. - *

- * In general, if you run into this issue with multiply-defined classes, there are several possible alternatives to jar whitelisting: - *

- * Ensure that you only ever have one definition on the classpath for all classes you want to match before calling FastClasspathScanner (i.e. start the JRE with a more restricted - * classpath). - * Override the classpath or provide a custom URLClassLoader before scanning, so that there are no non-scanned classpath elements that can mask elements in the whitelisted - * directories/jars that you do want to scan. (However, be aware that the system classloader may still return cached references to already-loaded classfiles outside this overridden - * path (or won't call your custom ClassLoader), due to class caching.) - */ -@FunctionalInterface -public interface IPathContentsScanner { - /** - * If you only need to scan resources and not classes, .enableClassInfo() or .enableAllInfo() should not be called, for speed. Also, if you don't need to scan classes, you - * should specify the whitelist by calling .whitelistPaths() and using path separators (/), rather than by calling .whitelistPackages() and using package separators (.). Path - * and package whitelists work the same way internally, you can just choose one way or the other of specifying the whitelist/blacklist. However, calling .whitelistPackages() - * also implicitly calls .enableClassInfo(). - * - * @return the set of string - */ - Set searchFor(); - - -} diff --git a/src/main/java/com/guicedee/guicedinjection/interfaces/IServiceEnablement.java b/src/main/java/com/guicedee/guicedinjection/interfaces/IServiceEnablement.java deleted file mode 100644 index 23e079b..0000000 --- a/src/main/java/com/guicedee/guicedinjection/interfaces/IServiceEnablement.java +++ /dev/null @@ -1,17 +0,0 @@ -package com.guicedee.guicedinjection.interfaces; - -/** - * Defines an instance as being able to be switched off if need be - */ -@SuppressWarnings("unused") -@FunctionalInterface -public interface IServiceEnablement> { - /** - * If this page configurator is enabled - * - * @return if the configuration must run - */ - boolean enabled(); - - -} diff --git a/src/main/java/com/guicedee/guicedinjection/interfaces/ObjectBinderKeys.java b/src/main/java/com/guicedee/guicedinjection/interfaces/ObjectBinderKeys.java deleted file mode 100644 index fe02d59..0000000 --- a/src/main/java/com/guicedee/guicedinjection/interfaces/ObjectBinderKeys.java +++ /dev/null @@ -1,44 +0,0 @@ -package com.guicedee.guicedinjection.interfaces; - -import com.fasterxml.jackson.databind.*; -import com.google.inject.*; -import com.google.inject.name.*; - -public class ObjectBinderKeys -{ - /** - * The default object mapping - */ - public static final Key DefaultObjectMapper = Key.get(ObjectMapper.class, Names.named("Default")); - /** - * The default object writer - */ - public static final Key JSONObjectWriter = Key.get(ObjectWriter.class, Names.named("JSON")); - /** - * The default object writer for tiny - */ - public static final Key JSONObjectWriterTiny = Key.get(ObjectWriter.class, Names.named("JSONTiny")); - /** - * The object reader for tiny - */ - public static final Key JSONObjectReader = Key.get(ObjectReader.class, Names.named("JSON")); - - - /** - * The default object mapping - */ - public static final Key JavascriptObjectMapper = Key.get(ObjectMapper.class, Names.named("Javascript")); - /** - * /** - * The default object writer - */ - public static final Key JavaScriptObjectWriter = Key.get(ObjectWriter.class, Names.named("Javascript")); - /** - * The default object writer for tiny - */ - public static final Key JavaScriptObjectWriterTiny = Key.get(ObjectWriter.class, Names.named("JavascriptTiny")); - /** - * The object reader for tiny - */ - public static final Key JavaScriptObjectReader = Key.get(ObjectReader.class, Names.named("Javascript")); -} diff --git a/src/main/java/com/guicedee/guicedinjection/interfaces/annotations/INotEnhanceable.java b/src/main/java/com/guicedee/guicedinjection/interfaces/annotations/INotEnhanceable.java deleted file mode 100644 index 019b01d..0000000 --- a/src/main/java/com/guicedee/guicedinjection/interfaces/annotations/INotEnhanceable.java +++ /dev/null @@ -1,19 +0,0 @@ -package com.guicedee.guicedinjection.interfaces.annotations; - -import java.lang.annotation.ElementType; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; - -/** - * Marker interface to identify if the class can/should be aop enhanced - *

- * By default entity classes are not aop (the criteria API will not read the class as a valid entity) - */ -@Target( - { - ElementType.TYPE, ElementType.TYPE_USE - }) -@Retention(RetentionPolicy.RUNTIME) -public @interface INotEnhanceable { -} diff --git a/src/main/java/com/guicedee/guicedinjection/interfaces/annotations/INotInjectable.java b/src/main/java/com/guicedee/guicedinjection/interfaces/annotations/INotInjectable.java deleted file mode 100644 index 3b6582f..0000000 --- a/src/main/java/com/guicedee/guicedinjection/interfaces/annotations/INotInjectable.java +++ /dev/null @@ -1,16 +0,0 @@ -package com.guicedee.guicedinjection.interfaces.annotations; - -import java.lang.annotation.*; - -/** - * Marker interface to identify if the class is not injectable - */ - -@Target( - { - ElementType.TYPE, ElementType.TYPE_USE - }) -@Retention(RetentionPolicy.RUNTIME) -@Inherited -public @interface INotInjectable { -} diff --git a/src/main/java/com/guicedee/guicedinjection/json/LocalDateDeserializer.java b/src/main/java/com/guicedee/guicedinjection/json/LocalDateDeserializer.java index 8cb98f9..98b940e 100644 --- a/src/main/java/com/guicedee/guicedinjection/json/LocalDateDeserializer.java +++ b/src/main/java/com/guicedee/guicedinjection/json/LocalDateDeserializer.java @@ -4,19 +4,15 @@ import com.fasterxml.jackson.databind.DeserializationContext; import com.fasterxml.jackson.databind.JsonDeserializer; import com.google.common.base.Strings; -import com.guicedee.logger.LogFactory; +import lombok.extern.java.Log; import java.io.IOException; import java.time.LocalDate; -import java.time.format.DateTimeFormatter; -import java.time.format.DateTimeFormatterBuilder; -import java.time.format.DateTimeParseException; -import java.time.temporal.ChronoField; import java.util.logging.Level; import static com.guicedee.guicedinjection.json.StaticStrings.*; - +@Log public class LocalDateDeserializer extends JsonDeserializer { @@ -46,7 +42,7 @@ public LocalDate convert(String value) LocalDate time = new LocalDateTimeDeserializer().convert(value).toLocalDate(); if (time == null) { - LogFactory.getLog(LocalDateTimeDeserializer.class).log(Level.WARNING,"Unable to determine local date from string - [" + value + "]"); + log.log(Level.WARNING,"Unable to determine local date from string - [" + value + "]"); } return time; } diff --git a/src/main/java/com/guicedee/guicedinjection/json/LocalDateTimeDeserializer.java b/src/main/java/com/guicedee/guicedinjection/json/LocalDateTimeDeserializer.java index 45a76e4..4f03f21 100644 --- a/src/main/java/com/guicedee/guicedinjection/json/LocalDateTimeDeserializer.java +++ b/src/main/java/com/guicedee/guicedinjection/json/LocalDateTimeDeserializer.java @@ -5,7 +5,7 @@ import com.fasterxml.jackson.databind.DeserializationContext; import com.fasterxml.jackson.databind.JsonDeserializer; import com.google.common.base.Strings; -import com.guicedee.logger.LogFactory; +import lombok.extern.java.Log; import java.io.IOException; import java.time.LocalDateTime; @@ -17,7 +17,7 @@ import static com.guicedee.guicedinjection.json.StaticStrings.*; - +@Log public class LocalDateTimeDeserializer extends JsonDeserializer { @@ -164,8 +164,7 @@ public LocalDateTime convert(String value) } if (time == null) { - LogFactory.getLog(LocalDateTimeDeserializer.class) - .log(Level.WARNING, "Unable to determine local date time from string - [" + value + "]"); + log.log(Level.WARNING, "Unable to determine local date time from string - [" + value + "]"); } return time; } diff --git a/src/main/java/com/guicedee/guicedinjection/json/ObjectMapperBinder.java b/src/main/java/com/guicedee/guicedinjection/json/ObjectMapperBinder.java index 9dbf5d0..555076f 100644 --- a/src/main/java/com/guicedee/guicedinjection/json/ObjectMapperBinder.java +++ b/src/main/java/com/guicedee/guicedinjection/json/ObjectMapperBinder.java @@ -3,23 +3,22 @@ import com.fasterxml.jackson.annotation.*; import com.fasterxml.jackson.core.*; import com.fasterxml.jackson.databind.*; +import com.google.inject.AbstractModule; import com.guicedee.guicedinjection.*; import com.guicedee.guicedinjection.abstractions.*; import com.guicedee.guicedinjection.interfaces.*; -import com.guicedee.logger.*; import jakarta.inject.*; import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule; +import lombok.extern.java.Log; import static com.fasterxml.jackson.core.JsonParser.Feature.*; import static com.guicedee.guicedinjection.interfaces.ObjectBinderKeys.*; +@Log public class ObjectMapperBinder - implements IGuiceDefaultBinder + extends AbstractModule + implements IGuiceModule { - /** - * Field log - */ - private static final java.util.logging.Logger log = LogFactory.getLog("ObjectMapperBinding"); /** * If the object mapper must behave as a singleton @@ -28,122 +27,121 @@ public class ObjectMapperBinder /** * Method onBind ... - * - * @param module of type GuiceInjectorModule */ @SuppressWarnings("deprecation") @Override - public void onBind(GuiceInjectorModule module) + public void configure() { - log.config("Bound ObjectMapper (DefaultObjectMapper) as singleton [" + singleton+ "]"); + log.config("Bound ObjectMapper (DefaultObjectMapper) as singleton [" + singleton + "]"); var p = (Provider) () -> new ObjectMapper() - .registerModule(new JavaTimeModule()) - //.registerModule(new LaxJsonModule()) - .configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false) - .configure(DeserializationFeature.FAIL_ON_MISSING_CREATOR_PROPERTIES, true) - .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false) - .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false) - .configure(DeserializationFeature.READ_UNKNOWN_ENUM_VALUES_AS_NULL, true) - .configure(JsonGenerator.Feature.ESCAPE_NON_ASCII, true) - .enable(ALLOW_UNQUOTED_CONTROL_CHARS) - .enable(SerializationFeature.WRITE_ENUMS_USING_TO_STRING) - .setVisibility(PropertyAccessor.FIELD, JsonAutoDetect.Visibility.ANY) - .setVisibility(PropertyAccessor.GETTER, JsonAutoDetect.Visibility.NONE) - .setVisibility(PropertyAccessor.IS_GETTER, JsonAutoDetect.Visibility.NONE) - .setVisibility(PropertyAccessor.SETTER, JsonAutoDetect.Visibility.NONE); - if(singleton) + .registerModule(new JavaTimeModule()) + //.registerModule(new LaxJsonModule()) + .configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false) + .configure(DeserializationFeature.FAIL_ON_MISSING_CREATOR_PROPERTIES, true) + .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false) + .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false) + .configure(DeserializationFeature.READ_UNKNOWN_ENUM_VALUES_AS_NULL, true) + .configure(JsonGenerator.Feature.ESCAPE_NON_ASCII, true) + .enable(ALLOW_UNQUOTED_CONTROL_CHARS) + .enable(SerializationFeature.WRITE_ENUMS_USING_TO_STRING) + .setVisibility(PropertyAccessor.FIELD, JsonAutoDetect.Visibility.ANY) + .setVisibility(PropertyAccessor.GETTER, JsonAutoDetect.Visibility.NONE) + .setVisibility(PropertyAccessor.IS_GETTER, JsonAutoDetect.Visibility.NONE) + .setVisibility(PropertyAccessor.SETTER, JsonAutoDetect.Visibility.NONE); + if (singleton) { - module - .bind(DefaultObjectMapper) - .toProvider(p) - .in(Singleton.class); - }else { - module.bind(DefaultObjectMapper) - .toProvider(p); + bind(DefaultObjectMapper) + .toProvider(p) + .in(Singleton.class); + } else + { + bind(DefaultObjectMapper) + .toProvider(p); } log.fine("Bound ObjectWriter.class @Named(JSON)"); - module.bind(ObjectBinderKeys.JSONObjectWriter) - .toProvider(() -> - GuiceContext.get(ObjectBinderKeys.DefaultObjectMapper) - .writerWithDefaultPrettyPrinter() - .with(SerializationFeature.INDENT_OUTPUT) - .with(SerializationFeature.WRITE_ENUMS_USING_TO_STRING) - .with(JsonGenerator.Feature.QUOTE_FIELD_NAMES) - .without(SerializationFeature.FAIL_ON_EMPTY_BEANS) - .withoutFeatures(SerializationFeature.FAIL_ON_UNWRAPPED_TYPE_IDENTIFIERS)); + bind(ObjectBinderKeys.JSONObjectWriter) + .toProvider(() -> + GuiceContext.get(ObjectBinderKeys.DefaultObjectMapper) + .writerWithDefaultPrettyPrinter() + .with(SerializationFeature.INDENT_OUTPUT) + .with(SerializationFeature.WRITE_ENUMS_USING_TO_STRING) + .with(JsonGenerator.Feature.QUOTE_FIELD_NAMES) + .without(SerializationFeature.FAIL_ON_EMPTY_BEANS) + .withoutFeatures(SerializationFeature.FAIL_ON_UNWRAPPED_TYPE_IDENTIFIERS)); - module.bind(ObjectBinderKeys.JSONObjectWriterTiny) - .toProvider(() -> - GuiceContext.get(ObjectBinderKeys.DefaultObjectMapper) - .writer() - .without(SerializationFeature.INDENT_OUTPUT) - .with(SerializationFeature.WRITE_ENUMS_USING_TO_STRING) - .with(JsonGenerator.Feature.QUOTE_FIELD_NAMES) - .without(SerializationFeature.FAIL_ON_EMPTY_BEANS) - .withoutFeatures(SerializationFeature.FAIL_ON_UNWRAPPED_TYPE_IDENTIFIERS)); + bind(ObjectBinderKeys.JSONObjectWriterTiny) + .toProvider(() -> + GuiceContext.get(ObjectBinderKeys.DefaultObjectMapper) + .writer() + .without(SerializationFeature.INDENT_OUTPUT) + .with(SerializationFeature.WRITE_ENUMS_USING_TO_STRING) + .with(JsonGenerator.Feature.QUOTE_FIELD_NAMES) + .without(SerializationFeature.FAIL_ON_EMPTY_BEANS) + .withoutFeatures(SerializationFeature.FAIL_ON_UNWRAPPED_TYPE_IDENTIFIERS)); - module.bind(ObjectBinderKeys.JSONObjectReader) - .toProvider(() -> - GuiceContext.get(ObjectBinderKeys.DefaultObjectMapper) - .reader() - .with(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY) - .with(DeserializationFeature.ACCEPT_EMPTY_ARRAY_AS_NULL_OBJECT) - .without(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES) - ); + bind(ObjectBinderKeys.JSONObjectReader) + .toProvider(() -> + GuiceContext.get(ObjectBinderKeys.DefaultObjectMapper) + .reader() + .with(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY) + .with(DeserializationFeature.ACCEPT_EMPTY_ARRAY_AS_NULL_OBJECT) + .without(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES) + ); log.fine("Bound ObjectWriter.class @Named(JavaScriptObjectReader)"); - module.bind(ObjectBinderKeys.JavascriptObjectMapper) - .toInstance(new ObjectMapper() - .registerModule(new LaxJsonModule()) - .configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false) - .configure(DeserializationFeature.FAIL_ON_MISSING_CREATOR_PROPERTIES, false) - .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false) - .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false) - .configure(DeserializationFeature.READ_UNKNOWN_ENUM_VALUES_AS_NULL, true) - .configure(JsonGenerator.Feature.ESCAPE_NON_ASCII, true) - .configure(JsonGenerator.Feature.QUOTE_FIELD_NAMES, false) - .enable(ALLOW_UNQUOTED_CONTROL_CHARS) - .setVisibility(PropertyAccessor.FIELD, JsonAutoDetect.Visibility.ANY) - .setVisibility(PropertyAccessor.GETTER, JsonAutoDetect.Visibility.NONE) - .setVisibility(PropertyAccessor.IS_GETTER, JsonAutoDetect.Visibility.NONE) - .setVisibility(PropertyAccessor.SETTER, JsonAutoDetect.Visibility.NONE) - ); + bind(ObjectBinderKeys.JavascriptObjectMapper) + .toInstance(new ObjectMapper() + .registerModule(new LaxJsonModule()) + .configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false) + .configure(DeserializationFeature.FAIL_ON_MISSING_CREATOR_PROPERTIES, false) + .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false) + .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false) + .configure(DeserializationFeature.READ_UNKNOWN_ENUM_VALUES_AS_NULL, true) + .configure(JsonGenerator.Feature.ESCAPE_NON_ASCII, true) + .configure(JsonGenerator.Feature.QUOTE_FIELD_NAMES, false) + .enable(ALLOW_UNQUOTED_CONTROL_CHARS) + .setVisibility(PropertyAccessor.FIELD, JsonAutoDetect.Visibility.ANY) + .setVisibility(PropertyAccessor.GETTER, JsonAutoDetect.Visibility.NONE) + .setVisibility(PropertyAccessor.IS_GETTER, JsonAutoDetect.Visibility.NONE) + .setVisibility(PropertyAccessor.SETTER, JsonAutoDetect.Visibility.NONE) + ); - module.bind(JavaScriptObjectWriter) - .toProvider(() -> - GuiceContext.get(ObjectBinderKeys.JavascriptObjectMapper) - .writerWithDefaultPrettyPrinter() - .with(SerializationFeature.INDENT_OUTPUT) - .with(SerializationFeature.WRITE_ENUMS_USING_TO_STRING) - .without(JsonGenerator.Feature.QUOTE_FIELD_NAMES) - .without(SerializationFeature.FAIL_ON_EMPTY_BEANS) - .withoutFeatures(SerializationFeature.FAIL_ON_UNWRAPPED_TYPE_IDENTIFIERS)); + bind(JavaScriptObjectWriter) + .toProvider(() -> + GuiceContext.get(ObjectBinderKeys.JavascriptObjectMapper) + .writerWithDefaultPrettyPrinter() + .with(SerializationFeature.INDENT_OUTPUT) + .with(SerializationFeature.WRITE_ENUMS_USING_TO_STRING) + .without(JsonGenerator.Feature.QUOTE_FIELD_NAMES) + .without(SerializationFeature.FAIL_ON_EMPTY_BEANS) + .withoutFeatures(SerializationFeature.FAIL_ON_UNWRAPPED_TYPE_IDENTIFIERS)); - module.bind(ObjectBinderKeys.JavaScriptObjectWriterTiny) - .toProvider(() -> - GuiceContext.get(ObjectBinderKeys.JavascriptObjectMapper) - .writer() - .without(SerializationFeature.INDENT_OUTPUT) - .with(SerializationFeature.WRITE_ENUMS_USING_TO_STRING) - .without(JsonGenerator.Feature.QUOTE_FIELD_NAMES) - .without(SerializationFeature.FAIL_ON_EMPTY_BEANS) - .withoutFeatures(SerializationFeature.FAIL_ON_UNWRAPPED_TYPE_IDENTIFIERS)); + bind(ObjectBinderKeys.JavaScriptObjectWriterTiny) + .toProvider(() -> + GuiceContext.get(ObjectBinderKeys.JavascriptObjectMapper) + .writer() + .without(SerializationFeature.INDENT_OUTPUT) + .with(SerializationFeature.WRITE_ENUMS_USING_TO_STRING) + .without(JsonGenerator.Feature.QUOTE_FIELD_NAMES) + .without(SerializationFeature.FAIL_ON_EMPTY_BEANS) + .withoutFeatures(SerializationFeature.FAIL_ON_UNWRAPPED_TYPE_IDENTIFIERS)); - module.bind(ObjectBinderKeys.JavaScriptObjectReader) - .toProvider(() -> - GuiceContext.get(ObjectBinderKeys.JavascriptObjectMapper) - .reader() - .with(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY) - .with(DeserializationFeature.ACCEPT_EMPTY_ARRAY_AS_NULL_OBJECT) - .without(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES) - ); + bind(ObjectBinderKeys.JavaScriptObjectReader) + .toProvider(() -> + GuiceContext.get(ObjectBinderKeys.JavascriptObjectMapper) + .reader() + .with(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY) + .with(DeserializationFeature.ACCEPT_EMPTY_ARRAY_AS_NULL_OBJECT) + .without(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES) + ); } /** * Returns the object mapper instance for JAVASCRIPT + * * @return */ public static ObjectMapper getObjectMapper() diff --git a/src/main/java/com/guicedee/guicedinjection/json/OffsetDateTimeDeserializer.java b/src/main/java/com/guicedee/guicedinjection/json/OffsetDateTimeDeserializer.java index dcf260a..0dda9b3 100644 --- a/src/main/java/com/guicedee/guicedinjection/json/OffsetDateTimeDeserializer.java +++ b/src/main/java/com/guicedee/guicedinjection/json/OffsetDateTimeDeserializer.java @@ -5,20 +5,21 @@ import com.fasterxml.jackson.databind.DeserializationContext; import com.fasterxml.jackson.databind.JsonDeserializer; import com.google.common.base.Strings; -import com.guicedee.logger.LogFactory; +import lombok.extern.java.Log; import java.io.IOException; -import java.time.*; +import java.time.LocalDateTime; +import java.time.OffsetDateTime; +import java.time.ZoneId; +import java.time.ZonedDateTime; import java.time.format.DateTimeFormatter; -import java.time.format.DateTimeFormatterBuilder; import java.time.format.DateTimeParseException; -import java.time.temporal.ChronoField; import java.util.logging.Level; -import static com.guicedee.guicedinjection.json.LocalDateTimeDeserializer.*; +import static com.guicedee.guicedinjection.json.LocalDateTimeDeserializer.formats; import static com.guicedee.guicedinjection.json.StaticStrings.*; - +@Log public class OffsetDateTimeDeserializer extends JsonDeserializer { @@ -62,8 +63,7 @@ public OffsetDateTime convert(String value) time = convertToUTCDateTime(convert); }else { - LogFactory.getLog(getClass()) - .log(Level.WARNING, "Unable to determine offset datetime from string - [" + value + "]"); + log.log(Level.WARNING, "Unable to determine offset datetime from string - [" + value + "]"); } } return time; diff --git a/src/main/java/com/guicedee/guicedinjection/json/OffsetTimeDeserializer.java b/src/main/java/com/guicedee/guicedinjection/json/OffsetTimeDeserializer.java index d9aa361..6c15a62 100644 --- a/src/main/java/com/guicedee/guicedinjection/json/OffsetTimeDeserializer.java +++ b/src/main/java/com/guicedee/guicedinjection/json/OffsetTimeDeserializer.java @@ -5,7 +5,7 @@ import com.fasterxml.jackson.databind.DeserializationContext; import com.fasterxml.jackson.databind.JsonDeserializer; import com.google.common.base.Strings; -import com.guicedee.logger.LogFactory; +import lombok.extern.java.Log; import java.io.IOException; import java.time.OffsetTime; @@ -17,7 +17,7 @@ import static com.guicedee.guicedinjection.json.StaticStrings.*; - +@Log public class OffsetTimeDeserializer extends JsonDeserializer { @@ -63,7 +63,7 @@ public OffsetTime convert(String value) } if (time == null) { - LogFactory.getLog(OffsetTimeSerializer.class).log(Level.WARNING,"Unable to determine offset time from string - [" + value + "]"); + log.log(Level.WARNING,"Unable to determine offset time from string - [" + value + "]"); } return time; diff --git a/src/main/java/com/guicedee/guicedinjection/json/ZonedDateTimeDeserializer.java b/src/main/java/com/guicedee/guicedinjection/json/ZonedDateTimeDeserializer.java index 6ae4982..eb5853b 100644 --- a/src/main/java/com/guicedee/guicedinjection/json/ZonedDateTimeDeserializer.java +++ b/src/main/java/com/guicedee/guicedinjection/json/ZonedDateTimeDeserializer.java @@ -5,7 +5,8 @@ import com.fasterxml.jackson.databind.DeserializationContext; import com.fasterxml.jackson.databind.JsonDeserializer; import com.google.common.base.Strings; -import com.guicedee.logger.LogFactory; +import lombok.extern.java.Log; + import java.io.IOException; import java.time.ZonedDateTime; @@ -17,29 +18,29 @@ import static com.guicedee.guicedinjection.json.StaticStrings.*; - +@Log public class ZonedDateTimeDeserializer - extends JsonDeserializer + extends JsonDeserializer { private static final DateTimeFormatter[] formats = new DateTimeFormatter[] - { - new DateTimeFormatterBuilder().append(DateTimeFormatter.ISO_ZONED_DATE_TIME) - .parseDefaulting(ChronoField.MONTH_OF_YEAR, 1L) - .parseDefaulting(ChronoField.DAY_OF_MONTH, 1L) - .parseDefaulting(ChronoField.HOUR_OF_DAY, 0L) - .parseDefaulting(ChronoField.MINUTE_OF_HOUR, 0L) - .parseDefaulting(ChronoField.SECOND_OF_MINUTE, 0L) - .parseDefaulting(ChronoField.NANO_OF_SECOND, 0L) - .toFormatter() - }; - + { + new DateTimeFormatterBuilder().append(DateTimeFormatter.ISO_ZONED_DATE_TIME) + .parseDefaulting(ChronoField.MONTH_OF_YEAR, 1L) + .parseDefaulting(ChronoField.DAY_OF_MONTH, 1L) + .parseDefaulting(ChronoField.HOUR_OF_DAY, 0L) + .parseDefaulting(ChronoField.MINUTE_OF_HOUR, 0L) + .parseDefaulting(ChronoField.SECOND_OF_MINUTE, 0L) + .parseDefaulting(ChronoField.NANO_OF_SECOND, 0L) + .toFormatter() + }; + @Override public ZonedDateTime deserialize(JsonParser p, DeserializationContext ctxt) throws IOException, JsonProcessingException { String name = p.getValueAsString(); return convert(name); } - + public ZonedDateTime convert(String value) { if (Strings.isNullOrEmpty(value) || STRING_NULL.equalsIgnoreCase(value) || STRING_0.equals(value)) @@ -49,7 +50,7 @@ public ZonedDateTime convert(String value) if (value.contains(E)) { value = value.replaceAll(STRING_DOT_ESCAPED, STRING_EMPTY) - .substring(0, value.indexOf(E) - 1); + .substring(0, value.indexOf(E) - 1); } ZonedDateTime time = null; for (DateTimeFormatter format : formats) @@ -58,16 +59,15 @@ public ZonedDateTime convert(String value) { time = ZonedDateTime.parse(value, format); break; - } - catch (DateTimeParseException dtpe) + } catch (DateTimeParseException dtpe) { //try the next one } } if (time == null) { - LogFactory.getLog(ZonedDateTimeDeserializer.class).log(Level.WARNING,"Unable to determine local date from string - [" + value + "]"); - + log.log(Level.WARNING, "Unable to determine local date from string - [" + value + "]"); + } return time; } diff --git a/src/main/java/com/guicedee/guicedinjection/properties/GlobalProperties.java b/src/main/java/com/guicedee/guicedinjection/properties/GlobalProperties.java index ecae064..34799d3 100644 --- a/src/main/java/com/guicedee/guicedinjection/properties/GlobalProperties.java +++ b/src/main/java/com/guicedee/guicedinjection/properties/GlobalProperties.java @@ -21,7 +21,7 @@ import com.fasterxml.jackson.databind.*; import com.google.inject.*; import com.guicedee.guicedinjection.*; -import com.guicedee.logger.*; +import lombok.extern.java.Log; import java.util.*; import java.util.logging.*; @@ -43,10 +43,9 @@ getterVisibility = NONE, setterVisibility = NONE) @JsonInclude(NON_NULL) +@Log public class GlobalProperties { - private static final Logger log = LogFactory.getLog("GlobalPropertyMaps"); - private final Map> globalProperties; /** diff --git a/src/main/java/com/guicedee/guicedinjection/representations/ICopyable.java b/src/main/java/com/guicedee/guicedinjection/representations/ICopyable.java index 996e969..bce8854 100644 --- a/src/main/java/com/guicedee/guicedinjection/representations/ICopyable.java +++ b/src/main/java/com/guicedee/guicedinjection/representations/ICopyable.java @@ -4,12 +4,13 @@ import com.google.inject.Key; import com.google.inject.name.Names; import com.guicedee.guicedinjection.GuiceContext; -import com.guicedee.logger.LogFactory; +import lombok.extern.java.Log; import java.io.IOException; import java.lang.reflect.*; import java.util.*; import java.util.logging.Level; +import java.util.logging.Logger; public interface ICopyable { @@ -31,8 +32,7 @@ default J updateNonNullField(J source) { fieldTarget.set(this, value); } - } - catch (IllegalAccessException e) + } catch (IllegalAccessException e) { e.printStackTrace(); } @@ -70,11 +70,9 @@ default J updateFrom(Object source) String jsonFromSource = om.writeValueAsString(source); ObjectReader objectReader = om.readerForUpdating(this); objectReader.readValue(jsonFromSource); - } - catch (IOException e) + } catch (IOException e) { - LogFactory.getLog("ICopyable") - .log(Level.SEVERE, "Cannot write or read source/destination", e); + Logger.getLogger("ICopyable").log(Level.SEVERE, "Cannot write or read source/destination", e); } return (J) this; } diff --git a/src/main/java/com/guicedee/guicedinjection/representations/excel/ExcelReader.java b/src/main/java/com/guicedee/guicedinjection/representations/excel/ExcelReader.java index 6002c48..12ce15c 100644 --- a/src/main/java/com/guicedee/guicedinjection/representations/excel/ExcelReader.java +++ b/src/main/java/com/guicedee/guicedinjection/representations/excel/ExcelReader.java @@ -3,7 +3,7 @@ import com.fasterxml.jackson.databind.ObjectMapper; import com.guicedee.guicedinjection.GuiceContext; import com.guicedee.guicedinjection.exceptions.ExcelRenderingException; -import com.guicedee.logger.LogFactory; +import lombok.extern.java.Log; import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.apache.poi.ss.usermodel.*; import org.apache.poi.xssf.usermodel.XSSFWorkbook; @@ -27,12 +27,10 @@ * @author Ernst Created:23 Oct 2013 */ @SuppressWarnings({"WeakerAccess", "unused"}) - +@Log public class ExcelReader implements AutoCloseable { - private static final Logger log = LogFactory.getLog("Excel Reader"); - private InputStream inputStream; private HSSFWorkbook oldStyle; diff --git a/src/test/java/com/guicedee/guicedinjection/FileSearchTest.java b/src/test/java/com/guicedee/guicedinjection/FileSearchTest.java index e6e368c..9d5997e 100644 --- a/src/test/java/com/guicedee/guicedinjection/FileSearchTest.java +++ b/src/test/java/com/guicedee/guicedinjection/FileSearchTest.java @@ -1,7 +1,6 @@ package com.guicedee.guicedinjection; import com.guicedee.guicedinjection.interfaces.IPathContentsRejectListScanner; -import com.guicedee.logger.LogFactory; import io.github.classgraph.ResourceList; import org.junit.jupiter.api.Test; @@ -14,7 +13,7 @@ public class FileSearchTest { @Test public void findJSFiles() { - LogFactory.configureConsoleColourOutput(Level.FINE); + // LogFactory.configureConsoleColourOutput(Level.FINE); GuiceContext.instance().getConfig() .setPathScanning(true) .setExcludeModulesAndJars(true) diff --git a/src/test/java/com/guicedee/guicedinjection/GlobalPropertiesTest.java b/src/test/java/com/guicedee/guicedinjection/GlobalPropertiesTest.java index e540204..0e67216 100644 --- a/src/test/java/com/guicedee/guicedinjection/GlobalPropertiesTest.java +++ b/src/test/java/com/guicedee/guicedinjection/GlobalPropertiesTest.java @@ -1,7 +1,7 @@ package com.guicedee.guicedinjection; import com.guicedee.guicedinjection.properties.GlobalProperties; -import com.guicedee.logger.LogFactory; + import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; @@ -15,7 +15,7 @@ public class GlobalPropertiesTest { @Test public void testSomeMethod() { - LogFactory.configureConsoleColourOutput(Level.FINE); + //LogFactory.configureConsoleColourOutput(Level.FINE); GuiceContext.instance() .getConfig() .setServiceLoadWithClassPath(true); diff --git a/src/test/java/com/guicedee/guicedinjection/GuiceContextTest.java b/src/test/java/com/guicedee/guicedinjection/GuiceContextTest.java index 7b5a0a5..da90a24 100644 --- a/src/test/java/com/guicedee/guicedinjection/GuiceContextTest.java +++ b/src/test/java/com/guicedee/guicedinjection/GuiceContextTest.java @@ -7,8 +7,8 @@ import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; -import com.guicedee.logger.LogFactory; -import com.guicedee.logger.handlers.ConsoleSTDOutputHandler; + + import java.util.logging.Handler; import java.util.logging.Level; @@ -21,7 +21,7 @@ public class GuiceContextTest { @BeforeAll public static void pre() { - LogFactory.configureConsoleColourOutput(Level.FINE); + //LogFactory.configureConsoleColourOutput(Level.FINE); GuiceContext.instance() .getConfig() .setServiceLoadWithClassPath(true); diff --git a/src/test/java/com/guicedee/guicedinjection/IGuiceConfigTest.java b/src/test/java/com/guicedee/guicedinjection/IGuiceConfigTest.java index fccb730..e9ecc92 100644 --- a/src/test/java/com/guicedee/guicedinjection/IGuiceConfigTest.java +++ b/src/test/java/com/guicedee/guicedinjection/IGuiceConfigTest.java @@ -1,20 +1,22 @@ package com.guicedee.guicedinjection; +import com.guicedee.guicedinjection.interfaces.IGuiceConfig; import com.guicedee.guicedinjection.interfaces.IGuiceConfigurator; -import com.guicedee.logger.LogFactory; +import lombok.extern.java.Log; import org.junit.jupiter.api.Test; import java.util.logging.Level; import static org.junit.jupiter.api.Assertions.*; +@Log public class IGuiceConfigTest implements IGuiceConfigurator { @Test public void testConfig() { - LogFactory.configureConsoleColourOutput(Level.FINE); + //LogFactory.configureConsoleColourOutput(Level.FINE); GuiceContext.instance() .loadIGuiceConfigs() .add(new IGuiceConfigTest()); @@ -32,7 +34,7 @@ public void testConfig() } @Override - public GuiceConfig configure(GuiceConfig config) + public IGuiceConfig configure(IGuiceConfig config) { config.setIgnoreMethodVisibility(true) .setExcludeModulesAndJars(true) diff --git a/src/test/java/com/guicedee/guicedinjection/IGuiceContextTestConfigurator.java b/src/test/java/com/guicedee/guicedinjection/IGuiceContextTestConfigurator.java index 69bd45f..ce33b99 100644 --- a/src/test/java/com/guicedee/guicedinjection/IGuiceContextTestConfigurator.java +++ b/src/test/java/com/guicedee/guicedinjection/IGuiceContextTestConfigurator.java @@ -1,12 +1,13 @@ package com.guicedee.guicedinjection; +import com.guicedee.guicedinjection.interfaces.IGuiceConfig; import com.guicedee.guicedinjection.interfaces.IGuiceConfigurator; public class IGuiceContextTestConfigurator implements IGuiceConfigurator { @Override - public GuiceConfig configure(GuiceConfig config) { + public IGuiceConfig configure(IGuiceConfig config) { config.setServiceLoadWithClassPath(true); return config; } From 8bca29f257538b92cba2c9210cc10c5e4a832708 Mon Sep 17 00:00:00 2001 From: Marc Magon Date: Thu, 28 Dec 2023 04:55:59 +0200 Subject: [PATCH 02/23] Add Github Actions Build (cherry picked from commit ad4c26b42c55598245c3d36e9730faa725e85568) --- .github/workflows/maven-publish.yml | 15 +++++++++++++++ 1 file changed, 15 insertions(+) create mode 100644 .github/workflows/maven-publish.yml diff --git a/.github/workflows/maven-publish.yml b/.github/workflows/maven-publish.yml new file mode 100644 index 0000000..7acb4dd --- /dev/null +++ b/.github/workflows/maven-publish.yml @@ -0,0 +1,15 @@ +name: Maven Package (BOM) +on: + workflow_dispatch: + push: +jobs: + GuicedInjection: + uses: GuicedEE/Workflows/.github/workflows/bom.yml@master + with: + baseDir: '/' + name: 'Guiced Injection' + secrets: + USERNAME: ${{secrets.USERNAME}} + USER_TOKEN: ${{secrets.USER_TOKEN}} + SONA_USERNAME: ${{secrets.SONA_USERNAME}} + SONA_PASSWORD: ${{secrets.SONA_PASSWORD}} \ No newline at end of file From d7af8e590a8aa286d9769becf38207fbc02c8b5a Mon Sep 17 00:00:00 2001 From: Marc Magon Date: Thu, 28 Dec 2023 04:56:50 +0200 Subject: [PATCH 03/23] Add Github Actions Build --- .gitignore | 1 + 1 file changed, 1 insertion(+) diff --git a/.gitignore b/.gitignore index ef3b017..a280132 100644 --- a/.gitignore +++ b/.gitignore @@ -20,3 +20,4 @@ Thumbs.db flatter.pom**/*.classpath /.idea/ /.flattened-pom.xml +/dependency-reduced-pom.xml From 18feb2419581262ac4838e6c23c6ac00a7084756 Mon Sep 17 00:00:00 2001 From: Marc Magon Date: Thu, 28 Dec 2023 04:57:41 +0200 Subject: [PATCH 04/23] Add Github Actions Build --- .github/workflows/maven-publish.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/maven-publish.yml b/.github/workflows/maven-publish.yml index 7acb4dd..a28f992 100644 --- a/.github/workflows/maven-publish.yml +++ b/.github/workflows/maven-publish.yml @@ -6,7 +6,7 @@ jobs: GuicedInjection: uses: GuicedEE/Workflows/.github/workflows/bom.yml@master with: - baseDir: '/' + baseDir: '' name: 'Guiced Injection' secrets: USERNAME: ${{secrets.USERNAME}} From aab136e9e1baeedcf5b4c797601b23fdbf09ddc8 Mon Sep 17 00:00:00 2001 From: Marc Magon Date: Thu, 28 Dec 2023 05:16:05 +0200 Subject: [PATCH 05/23] Add Github Actions Build --- .github/workflows/maven-publish.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/maven-publish.yml b/.github/workflows/maven-publish.yml index a28f992..30abe29 100644 --- a/.github/workflows/maven-publish.yml +++ b/.github/workflows/maven-publish.yml @@ -1,4 +1,4 @@ -name: Maven Package (BOM) +name: Maven Package on: workflow_dispatch: push: From fc60d66104c3cffd33b25e94430ad30da03ab843 Mon Sep 17 00:00:00 2001 From: Marc Magon Date: Thu, 28 Dec 2023 12:42:55 +0200 Subject: [PATCH 06/23] Base update --- .github/workflows/maven-publish.yml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/workflows/maven-publish.yml b/.github/workflows/maven-publish.yml index 30abe29..bc27034 100644 --- a/.github/workflows/maven-publish.yml +++ b/.github/workflows/maven-publish.yml @@ -4,9 +4,9 @@ on: push: jobs: GuicedInjection: - uses: GuicedEE/Workflows/.github/workflows/bom.yml@master + uses: GuicedEE/Workflows/.github/workflows/projects.yml@master with: - baseDir: '' + baseDir: 'GuiceInjection/' name: 'Guiced Injection' secrets: USERNAME: ${{secrets.USERNAME}} From 182f5f53abd7901d6acf6b11e8ad18881127eb2a Mon Sep 17 00:00:00 2001 From: Marc Magon Date: Thu, 28 Dec 2023 12:50:26 +0200 Subject: [PATCH 07/23] Base update --- .github/workflows/maven-publish.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/maven-publish.yml b/.github/workflows/maven-publish.yml index bc27034..93a4c3f 100644 --- a/.github/workflows/maven-publish.yml +++ b/.github/workflows/maven-publish.yml @@ -6,7 +6,7 @@ jobs: GuicedInjection: uses: GuicedEE/Workflows/.github/workflows/projects.yml@master with: - baseDir: 'GuiceInjection/' + baseDir: '' name: 'Guiced Injection' secrets: USERNAME: ${{secrets.USERNAME}} From e12b1a9551384f919808a2f4ae47552b057d195f Mon Sep 17 00:00:00 2001 From: Marc Magon Date: Fri, 29 Dec 2023 00:51:32 +0200 Subject: [PATCH 08/23] Guiced Injection Cleanup --- pom.xml | 27 +- .../ExecutorServiceSupplier.java | 14 + .../ExecutorServiceSupplier.java | 14 + .../guicedinjection/GuiceContext.java | 88 +++- .../guicedee/guicedinjection/JobService.java | 31 +- .../exceptions/ExcelRenderingException.java | 31 -- .../exceptions/JsonRenderException.java | 59 --- .../exceptions/XmlRenderException.java | 59 --- .../injections/ContextBinderGuice.java | 6 +- .../json/DurationToInteger.java | 39 -- .../json/DurationToString.java | 29 -- .../json/InstantDeserializer.java | 80 --- .../json/InstantSerializer.java | 24 - .../guicedinjection/json/LaxJsonModule.java | 67 --- .../json/LocalDateDeserializer.java | 49 -- .../json/LocalDateSerializer.java | 30 -- .../json/LocalDateTimeDeserializer.java | 171 ------- .../json/LocalDateTimeSerializer.java | 31 -- .../json/LocalTimeDeserializer.java | 50 -- .../json/LocalTimeSerializer.java | 40 -- .../json/ObjectMapperBinder.java | 151 ------ .../json/OffsetDateTimeDeserializer.java | 83 ---- .../json/OffsetDateTimeSerializer.java | 33 -- .../json/OffsetTimeDeserializer.java | 71 --- .../json/OffsetTimeSerializer.java | 24 - .../guicedinjection/json/StaticStrings.java | 162 ------ .../guicedinjection/json/StringToBool.java | 36 -- .../guicedinjection/json/StringToBoolean.java | 53 -- .../json/StringToCharacterSet.java | 33 -- .../json/StringToDurationTime.java | 62 --- .../json/StringToDurationTimeSeconds.java | 69 --- .../json/StringToIntRelaxed.java | 35 -- .../json/StringToIntegerRelaxed.java | 33 -- .../json/ZonedDateTimeDeserializer.java | 74 --- .../json/ZonedDateTimeSerializer.java | 23 - .../mapkeys/LocalDateDeserializerKey.java | 16 - .../mapkeys/LocalDateTimeDeserializerKey.java | 16 - .../OffsetDateTimeDeserializerKey.java | 16 - .../representations/IExcelRepresentation.java | 46 -- .../representations/IJsonRepresentation.java | 309 ------------ .../representations/IXmlRepresentation.java | 106 ---- .../representations/XmlContexts.java | 12 - .../representations/excel/ExcelReader.java | 463 ------------------ .../urls/JrtUrlConnection.java | 0 .../guicedinjection/urls/JrtUrlHandler.java | 0 src/{jre11 => main}/java/module-info.java | 24 +- ...ee.guicedinjection.interfaces.IGuiceModule | 1 + ...tion.interfaces.IGuiceScanModuleInclusions | 1 + .../guicedinjection/IGuiceConfigTest.java | 4 +- .../LocalDateTimeDeserializationTest.java | 55 --- .../ParallelPostStartupTest1.java | 18 + .../ParallelPostStartupTest2.java | 18 + ...icedinjection.interfaces.IGuicePostStartup | 2 + src/test/resources/logback.xml | 7 + 54 files changed, 169 insertions(+), 2826 deletions(-) create mode 100644 src/jre11/java/com/guicedee/guicedinjection/ExecutorServiceSupplier.java create mode 100644 src/jre21/java/com/guicedee/guicedinjection/ExecutorServiceSupplier.java delete mode 100644 src/main/java/com/guicedee/guicedinjection/exceptions/ExcelRenderingException.java delete mode 100644 src/main/java/com/guicedee/guicedinjection/exceptions/JsonRenderException.java delete mode 100644 src/main/java/com/guicedee/guicedinjection/exceptions/XmlRenderException.java delete mode 100644 src/main/java/com/guicedee/guicedinjection/json/DurationToInteger.java delete mode 100644 src/main/java/com/guicedee/guicedinjection/json/DurationToString.java delete mode 100644 src/main/java/com/guicedee/guicedinjection/json/InstantDeserializer.java delete mode 100644 src/main/java/com/guicedee/guicedinjection/json/InstantSerializer.java delete mode 100644 src/main/java/com/guicedee/guicedinjection/json/LaxJsonModule.java delete mode 100644 src/main/java/com/guicedee/guicedinjection/json/LocalDateDeserializer.java delete mode 100644 src/main/java/com/guicedee/guicedinjection/json/LocalDateSerializer.java delete mode 100644 src/main/java/com/guicedee/guicedinjection/json/LocalDateTimeDeserializer.java delete mode 100644 src/main/java/com/guicedee/guicedinjection/json/LocalDateTimeSerializer.java delete mode 100644 src/main/java/com/guicedee/guicedinjection/json/LocalTimeDeserializer.java delete mode 100644 src/main/java/com/guicedee/guicedinjection/json/LocalTimeSerializer.java delete mode 100644 src/main/java/com/guicedee/guicedinjection/json/ObjectMapperBinder.java delete mode 100644 src/main/java/com/guicedee/guicedinjection/json/OffsetDateTimeDeserializer.java delete mode 100644 src/main/java/com/guicedee/guicedinjection/json/OffsetDateTimeSerializer.java delete mode 100644 src/main/java/com/guicedee/guicedinjection/json/OffsetTimeDeserializer.java delete mode 100644 src/main/java/com/guicedee/guicedinjection/json/OffsetTimeSerializer.java delete mode 100644 src/main/java/com/guicedee/guicedinjection/json/StaticStrings.java delete mode 100644 src/main/java/com/guicedee/guicedinjection/json/StringToBool.java delete mode 100644 src/main/java/com/guicedee/guicedinjection/json/StringToBoolean.java delete mode 100644 src/main/java/com/guicedee/guicedinjection/json/StringToCharacterSet.java delete mode 100644 src/main/java/com/guicedee/guicedinjection/json/StringToDurationTime.java delete mode 100644 src/main/java/com/guicedee/guicedinjection/json/StringToDurationTimeSeconds.java delete mode 100644 src/main/java/com/guicedee/guicedinjection/json/StringToIntRelaxed.java delete mode 100644 src/main/java/com/guicedee/guicedinjection/json/StringToIntegerRelaxed.java delete mode 100644 src/main/java/com/guicedee/guicedinjection/json/ZonedDateTimeDeserializer.java delete mode 100644 src/main/java/com/guicedee/guicedinjection/json/ZonedDateTimeSerializer.java delete mode 100644 src/main/java/com/guicedee/guicedinjection/json/mapkeys/LocalDateDeserializerKey.java delete mode 100644 src/main/java/com/guicedee/guicedinjection/json/mapkeys/LocalDateTimeDeserializerKey.java delete mode 100644 src/main/java/com/guicedee/guicedinjection/json/mapkeys/OffsetDateTimeDeserializerKey.java delete mode 100644 src/main/java/com/guicedee/guicedinjection/representations/IExcelRepresentation.java delete mode 100644 src/main/java/com/guicedee/guicedinjection/representations/IJsonRepresentation.java delete mode 100644 src/main/java/com/guicedee/guicedinjection/representations/IXmlRepresentation.java delete mode 100644 src/main/java/com/guicedee/guicedinjection/representations/XmlContexts.java delete mode 100644 src/main/java/com/guicedee/guicedinjection/representations/excel/ExcelReader.java rename src/{jre11 => main}/java/com/guicedee/guicedinjection/urls/JrtUrlConnection.java (100%) rename src/{jre11 => main}/java/com/guicedee/guicedinjection/urls/JrtUrlHandler.java (100%) rename src/{jre11 => main}/java/module-info.java (78%) delete mode 100644 src/test/java/com/guicedee/guicedinjection/LocalDateTimeDeserializationTest.java create mode 100644 src/test/java/com/guicedee/guicedinjection/ParallelPostStartupTest1.java create mode 100644 src/test/java/com/guicedee/guicedinjection/ParallelPostStartupTest2.java create mode 100644 src/test/resources/META-INF/services/com.guicedee.guicedinjection.interfaces.IGuicePostStartup create mode 100644 src/test/resources/logback.xml diff --git a/pom.xml b/pom.xml index bd80779..f705276 100644 --- a/pom.xml +++ b/pom.xml @@ -24,9 +24,9 @@ true false + /GuicedEE/GuicedInjection - @@ -108,10 +108,6 @@ commons-lang3 - - jakarta.xml.bind - jakarta.xml.bind-api - com.fasterxml.jackson.core @@ -133,18 +129,6 @@ jackson-datatype-jsr310 - - com.guicedee.services - json - true - - - - com.guicedee.services - apache-poi-ooxml - true - - jakarta.inject jakarta.inject-api @@ -175,15 +159,14 @@ - - org.moditect - moditect-maven-plugin + org.codehaus.mojo + flatten-maven-plugin - org.codehaus.mojo - flatten-maven-plugin + com.coderplus.maven.plugins + copy-rename-maven-plugin diff --git a/src/jre11/java/com/guicedee/guicedinjection/ExecutorServiceSupplier.java b/src/jre11/java/com/guicedee/guicedinjection/ExecutorServiceSupplier.java new file mode 100644 index 0000000..cde995d --- /dev/null +++ b/src/jre11/java/com/guicedee/guicedinjection/ExecutorServiceSupplier.java @@ -0,0 +1,14 @@ +package com.guicedee.guicedinjection; + +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.function.Supplier; + +public class ExecutorServiceSupplier implements Supplier +{ + @Override + public ExecutorService get() + { + return Executors.newCachedThreadPool(); + } +} diff --git a/src/jre21/java/com/guicedee/guicedinjection/ExecutorServiceSupplier.java b/src/jre21/java/com/guicedee/guicedinjection/ExecutorServiceSupplier.java new file mode 100644 index 0000000..8070445 --- /dev/null +++ b/src/jre21/java/com/guicedee/guicedinjection/ExecutorServiceSupplier.java @@ -0,0 +1,14 @@ +package com.guicedee.guicedinjection; + +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.function.Supplier; + +public class ExecutorServiceSupplier implements Supplier +{ + @Override + public ExecutorService get() + { + return Executors.newVirtualThreadPerTaskExecutor(); + } +} diff --git a/src/main/java/com/guicedee/guicedinjection/GuiceContext.java b/src/main/java/com/guicedee/guicedinjection/GuiceContext.java index fb43d7f..ff623ed 100644 --- a/src/main/java/com/guicedee/guicedinjection/GuiceContext.java +++ b/src/main/java/com/guicedee/guicedinjection/GuiceContext.java @@ -25,6 +25,7 @@ import jakarta.validation.constraints.*; import lombok.extern.java.Log; +import java.lang.Module; import java.lang.annotation.*; import java.util.*; import java.util.concurrent.*; @@ -50,10 +51,11 @@ public class 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<>()); + private static final Map allLoadedServices = new LinkedHashMap<>(); /** * The building injector */ @@ -69,7 +71,7 @@ public class GuiceContext> /** * The configuration object */ - private static GuiceConfig config; + private static final GuiceConfig config = new GuiceConfig<>(); /** * The physical injector for the JVM container */ @@ -86,6 +88,10 @@ public class GuiceContext> * If the scan should run async */ private boolean async; + /** + * If this context is configured + */ + private static boolean configured; /** * Creates a new Guice context. Not necessary @@ -95,6 +101,8 @@ private GuiceContext() //No config required } + private Set registerModules = new LinkedHashSet<>(); + /** * Reference the Injector Directly * @@ -110,6 +118,7 @@ public static synchronized Injector inject() } if (GuiceContext.instance().injector == null) { + SysStreamsLogger.bindSystemStreams(); try { GuiceContext.buildingInjector = true; @@ -299,11 +308,22 @@ public static T get(@NotNull Key type) public static void destroy() { Set destroyers = GuiceContext.instance() - .getLoader(IGuicePreDestroy.class, true, ServiceLoader.load(IGuicePreDestroy.class)); - for (IGuicePreDestroy destroyer : destroyers) + .getLoader(IGuicePreDestroy.class, false, ServiceLoader.load(IGuicePreDestroy.class)); + 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) { - IGuicePreDestroy instance = GuiceContext.get(destroyer.getClass()); - instance.onDestroy(); + log.log(Level.SEVERE, "Could not run destroyers", T); } if (GuiceContext.instance().scanResult != null) { @@ -378,8 +398,6 @@ public static GuiceContext instance() return GuiceContext.instance; } - private static boolean configured; - /** * Loads the IGuiceConfigurator */ @@ -387,24 +405,19 @@ 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 = (GuiceConfig) guiceConfigurator.configure(GuiceContext.config); + guiceConfigurator.configure(GuiceContext.config); } GuiceContext.log.config("IGuiceConfigurator : " + GuiceContext.config.toString()); configured = true; } } - /** * Returns a complete list of generic exclusions * @@ -745,6 +758,18 @@ private String[] getModulesExclusionList() return strings.toArray(new String[0]); } + /** + * Registers a module for scanning when filtering is enabled + * + * @param javaModuleName The name in the module-info.java file + * @return This instance + */ + @SuppressWarnings("unchecked") + public J registerModule(String javaModuleName) + { + this.registerModules.add(javaModuleName); + return (J) this; + } /** * Returns a complete list of generic exclusions @@ -755,6 +780,7 @@ private String[] getModulesExclusionList() private String[] getModulesInclusionsList() { Set strings = new TreeSet<>(); + strings.addAll(registerModules); Set exclusions = getLoader(IGuiceScanModuleInclusions.class, true, ServiceLoader.load(IGuiceScanModuleInclusions.class)); if (exclusions.iterator() .hasNext()) @@ -882,14 +908,39 @@ private void loadPostStartups() } } else { + log.info("Starting Post Startup Group [" + key + "] in Parallel"); + ExecutorService postStartup = null; + for (IGuicePostStartup iGuicePostStartup : value) + { + postStartup = JobService.getInstance().addJob("PostStartup", () -> { + try + { + iGuicePostStartup.postLoad(); + } catch (Throwable T) + { + log.log(Level.SEVERE, "Cannot execute post startup - ", T); + } + }); + } try + { + if (postStartup != null) + { + log.config("Waiting for post startup group to finish...."); + JobService.getInstance().removeJob("PostStartup"); + } + } catch (Throwable e) + { + log.log(Level.SEVERE, "Cannot execute post startup - ", e); + } + /*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 + "]"); } @@ -902,10 +953,6 @@ private void loadPostStartups() */ public GuiceConfig getConfig() { - if (GuiceContext.config == null) - { - GuiceContext.config = new GuiceConfig<>(); - } return GuiceContext.config; } @@ -1173,7 +1220,8 @@ public Set loaderToSetNoInjection(ServiceLoader loader) String type = loader.toString(); type = type.replace("java.util.ServiceLoader[", ""); type = type.substring(0, type.length() - 1); - if (config.isServiceLoadWithClassPath() && !buildingInjector) + if (config.isServiceLoadWithClassPath() && !buildingInjector && instance() + .getScanResult() != null) { for (ClassInfo classInfo : instance() .getScanResult() diff --git a/src/main/java/com/guicedee/guicedinjection/JobService.java b/src/main/java/com/guicedee/guicedinjection/JobService.java index daf572e..249edfd 100644 --- a/src/main/java/com/guicedee/guicedinjection/JobService.java +++ b/src/main/java/com/guicedee/guicedinjection/JobService.java @@ -6,22 +6,11 @@ import lombok.Setter; import lombok.extern.java.Log; -import java.sql.Time; -import java.time.temporal.ChronoUnit; import java.util.Map; import java.util.Set; -import java.util.concurrent.Callable; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; -import java.util.concurrent.ForkJoinPool; -import java.util.concurrent.ScheduledExecutorService; -import java.util.concurrent.ThreadPoolExecutor; -import java.util.concurrent.TimeUnit; +import java.util.concurrent.*; import java.util.logging.Level; -import java.util.logging.Logger; -import static java.util.concurrent.Executors.newWorkStealingPool; /** * Manages All Concurrent Threaded Jobs that execute asynchronously outside of the EE Context @@ -36,6 +25,8 @@ public class JobService 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; @@ -43,10 +34,13 @@ public class JobService @Setter private static TimeUnit defaultWaitUnit = TimeUnit.SECONDS; - @Getter private static final JobService INSTANCE = new JobService(); - JobService() + public static JobService getInstance(){ + return INSTANCE; + } + + public JobService() { //No config required } @@ -98,6 +92,7 @@ public ExecutorService removeJob(String pool) { es.shutdownNow(); } + es.close(); serviceMap.remove(pool); return es; } @@ -190,7 +185,7 @@ public ExecutorService addJob(String jobPoolName, Runnable thread) { if (!serviceMap.containsKey(jobPoolName) || serviceMap.get(jobPoolName).isTerminated() || serviceMap.get(jobPoolName).isShutdown()) { - registerJobPool(jobPoolName, Executors.newWorkStealingPool()); + registerJobPool(jobPoolName, executorServiceSupplier.get()); } ExecutorService service = serviceMap.get(jobPoolName); @@ -198,7 +193,7 @@ public ExecutorService addJob(String jobPoolName, Runnable thread) { log.log(Level.FINER, maxQueueCount + " Hit - Finishing before next run"); removeJob(jobPoolName); - service = registerJobPool(jobPoolName, newWorkStealingPool()); + service = registerJobPool(jobPoolName,executorServiceSupplier.get()); } service.execute(thread); return service; @@ -214,7 +209,7 @@ public ExecutorService addJob(String jobPoolName, Callable thread) { if (!serviceMap.containsKey(jobPoolName) || serviceMap.get(jobPoolName).isTerminated() || serviceMap.get(jobPoolName).isShutdown()) { - registerJobPool(jobPoolName, newWorkStealingPool()); + registerJobPool(jobPoolName, executorServiceSupplier.get()); } ExecutorService service = serviceMap.get(jobPoolName); @@ -222,7 +217,7 @@ public ExecutorService addJob(String jobPoolName, Callable thread) { log.log(Level.FINER, maxQueueCount + " Hit - Finishing before next run"); removeJob(jobPoolName); - service = registerJobPool(jobPoolName, newWorkStealingPool()); + service = registerJobPool(jobPoolName, executorServiceSupplier.get()); } service.submit(thread); return service; 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/injections/ContextBinderGuice.java b/src/main/java/com/guicedee/guicedinjection/injections/ContextBinderGuice.java index afe4f00..13ef1d9 100644 --- a/src/main/java/com/guicedee/guicedinjection/injections/ContextBinderGuice.java +++ b/src/main/java/com/guicedee/guicedinjection/injections/ContextBinderGuice.java @@ -30,9 +30,7 @@ public ContextBinderGuice() { public void configure() { ContextBinderGuice.log.fine("Bound GuiceConfig.class"); bind(GuiceConfig.class) - .toProvider(() -> GuiceContext.instance() - .getConfig()) - .in(Singleton.class); + .toProvider(() -> GuiceContext.instance().getConfig()); ContextBinderGuice.log.fine("Bound GlobalProperties.class"); bind(GlobalProperties.class) @@ -46,6 +44,6 @@ public void configure() { ContextBinderGuice.log.fine("Bound JobService.class"); bind(JobService.class) - .toInstance(JobService.getINSTANCE()); + .toInstance(JobService.getInstance()); } } diff --git a/src/main/java/com/guicedee/guicedinjection/json/DurationToInteger.java b/src/main/java/com/guicedee/guicedinjection/json/DurationToInteger.java deleted file mode 100644 index 119abbf..0000000 --- a/src/main/java/com/guicedee/guicedinjection/json/DurationToInteger.java +++ /dev/null @@ -1,39 +0,0 @@ -package com.guicedee.guicedinjection.json; -import com.fasterxml.jackson.core.JsonGenerator; -import com.fasterxml.jackson.databind.JsonSerializer; -import com.fasterxml.jackson.databind.SerializerProvider; - -import java.io.IOException; -import java.text.NumberFormat; -import java.time.Duration; - -import static com.guicedee.guicedinjection.json.StaticStrings.*; -import static java.time.temporal.ChronoUnit.*; - -/** - * Converts duration to an integer with each portion forced as a single digit - */ -public class DurationToInteger - extends JsonSerializer -{ - private static final NumberFormat numberFormat = NumberFormat.getNumberInstance(); - static { - numberFormat.setMaximumFractionDigits(0); - numberFormat.setMinimumIntegerDigits(1); - } - @Override - public void serialize(Duration value, JsonGenerator gen, SerializerProvider serializers) throws IOException - { - if(value == null) - return ; - gen.writeNumber(convert(value)); - } - - public Integer convert(Duration value) - { - String intNumber = numberFormat.format(value.get(HOURS)) + STRING_EMPTY + - numberFormat.format(value.get(MINUTES)) + STRING_EMPTY + - numberFormat.format(value.get(SECONDS)); - return Integer.parseInt(intNumber); - } -} diff --git a/src/main/java/com/guicedee/guicedinjection/json/DurationToString.java b/src/main/java/com/guicedee/guicedinjection/json/DurationToString.java deleted file mode 100644 index e40ca2c..0000000 --- a/src/main/java/com/guicedee/guicedinjection/json/DurationToString.java +++ /dev/null @@ -1,29 +0,0 @@ -package com.guicedee.guicedinjection.json; - -import com.fasterxml.jackson.core.JsonGenerator; -import com.fasterxml.jackson.databind.JsonSerializer; -import com.fasterxml.jackson.databind.SerializerProvider; - -import jakarta.validation.constraints.NotNull; -import java.io.IOException; -import java.time.Duration; - -/** - * Converts most of the string knowns to boolean - */ -public class DurationToString - extends JsonSerializer -{ - @Override - public void serialize(Duration value, JsonGenerator gen, SerializerProvider serializers) throws IOException - { - if(value == null) - return ; - gen.writeString(convert(value)); - } - - public String convert(@NotNull Duration value) - { - return value.toString(); - } -} diff --git a/src/main/java/com/guicedee/guicedinjection/json/InstantDeserializer.java b/src/main/java/com/guicedee/guicedinjection/json/InstantDeserializer.java deleted file mode 100644 index b3986f7..0000000 --- a/src/main/java/com/guicedee/guicedinjection/json/InstantDeserializer.java +++ /dev/null @@ -1,80 +0,0 @@ -package com.guicedee.guicedinjection.json; - -import com.fasterxml.jackson.core.JsonParser; -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.databind.DeserializationContext; -import com.fasterxml.jackson.databind.JsonDeserializer; -import com.google.common.base.Strings; - -import java.io.IOException; -import java.time.Instant; -import java.time.LocalDateTime; -import java.time.OffsetDateTime; -import java.time.ZoneId; -import java.time.format.DateTimeFormatter; -import java.time.format.DateTimeFormatterBuilder; -import java.time.format.DateTimeParseException; -import java.time.format.FormatStyle; -import java.time.temporal.ChronoField; -import java.util.Locale; - -import static com.guicedee.guicedinjection.json.StaticStrings.*; - - -public class InstantDeserializer - extends JsonDeserializer -{ - private static final DateTimeFormatter[] formats = new DateTimeFormatter[] - { - new DateTimeFormatterBuilder().append(DateTimeFormatter.ofLocalizedDateTime(FormatStyle.SHORT) - .withLocale(Locale.UK) - .withZone(ZoneId.systemDefault())) - .parseDefaulting(ChronoField.MONTH_OF_YEAR, 1L) - .parseDefaulting(ChronoField.DAY_OF_MONTH, 1L) - .parseDefaulting(ChronoField.HOUR_OF_DAY, 0L) - .parseDefaulting(ChronoField.MINUTE_OF_HOUR, 0L) - .parseDefaulting(ChronoField.SECOND_OF_MINUTE, 0L) - .parseDefaulting(ChronoField.NANO_OF_SECOND, 0L) - .toFormatter() - }; - - @Override - public Instant deserialize(JsonParser p, DeserializationContext ctxt) throws IOException, JsonProcessingException - { - String name = p.getValueAsString(); - return convert(name); - } - - public Instant convert(String value) throws IOException - { - if (Strings.isNullOrEmpty(value) || STRING_NULL.equals(value) || STRING_0.equals(value)) - { - return null; - } - if (value.contains(E)) - { - value = value.replaceAll(STRING_DOT_ESCAPED, STRING_EMPTY) - .substring(0, value.indexOf(E) - 1); - } - LocalDateTime time = null; - for (DateTimeFormatter format : formats) - { - try - { - time = LocalDateTime.parse(value, format); - break; - } - catch (DateTimeParseException dtpe) - { - //try the next one - } - } - if (time == null) - { - throw new IOException("Unable to determine local date time from string - [" + value + "]"); - - } - return time.atZone(ZoneId.systemDefault()) - .toInstant(); - } -} diff --git a/src/main/java/com/guicedee/guicedinjection/json/InstantSerializer.java b/src/main/java/com/guicedee/guicedinjection/json/InstantSerializer.java deleted file mode 100644 index 7b7c1fa..0000000 --- a/src/main/java/com/guicedee/guicedinjection/json/InstantSerializer.java +++ /dev/null @@ -1,24 +0,0 @@ -package com.guicedee.guicedinjection.json; - -import com.fasterxml.jackson.core.JsonGenerator; -import com.fasterxml.jackson.databind.JsonSerializer; -import com.fasterxml.jackson.databind.SerializerProvider; - -import java.io.IOException; -import java.time.Instant; -import java.time.LocalDateTime; -import java.time.format.DateTimeFormatter; - -public class InstantSerializer - extends JsonSerializer -{ - public InstantSerializer() - { - } - - @Override - public void serialize(Instant value, JsonGenerator generator, SerializerProvider provider) throws IOException - { - generator.writeString(DateTimeFormatter.ISO_INSTANT.format(value)); - } -} diff --git a/src/main/java/com/guicedee/guicedinjection/json/LaxJsonModule.java b/src/main/java/com/guicedee/guicedinjection/json/LaxJsonModule.java deleted file mode 100644 index ec7518d..0000000 --- a/src/main/java/com/guicedee/guicedinjection/json/LaxJsonModule.java +++ /dev/null @@ -1,67 +0,0 @@ -package com.guicedee.guicedinjection.json; - -import com.fasterxml.jackson.core.*; -import com.fasterxml.jackson.databind.DeserializationContext; -import com.fasterxml.jackson.databind.JsonDeserializer; -import com.fasterxml.jackson.databind.module.SimpleModule; -import com.guicedee.guicedinjection.json.mapkeys.*; - -import java.io.IOException; -import java.time.*; - -public class LaxJsonModule extends SimpleModule -{ - public LaxJsonModule() - { - super("GuicedTimeHandler", Version.unknownVersion()); - - addDeserializer(Boolean.class, new StringToBoolean()) - .addDeserializer(boolean.class, new JsonDeserializer() - { - @Override - public Object deserialize(JsonParser p, DeserializationContext ctxt) throws IOException, JsonProcessingException - { - return new StringToBool().deserialize(p, ctxt); - } - }) - .addDeserializer(int.class, new JsonDeserializer() - { - @Override - public Object deserialize(JsonParser p, DeserializationContext ctxt) throws IOException, JsonProcessingException - { - return new StringToIntRelaxed().deserialize(p, ctxt); - } - }) - .addDeserializer(Integer.class, new JsonDeserializer() - { - @Override - public Object deserialize(JsonParser p, DeserializationContext ctxt) throws IOException, JsonProcessingException - { - return new StringToIntegerRelaxed().deserialize(p, ctxt); - } - }) - .addDeserializer(Duration.class, new StringToDurationTimeSeconds()) - .addDeserializer(LocalDate.class, new LocalDateDeserializer()) - .addDeserializer(LocalTime.class, new LocalTimeDeserializer()) - .addSerializer(LocalTime.class, new LocalTimeSerializer()) - .addDeserializer(LocalDateTime.class, new LocalDateTimeDeserializer()) - .addDeserializer(Integer.class, new StringToIntegerRelaxed()) - .addSerializer(LocalDate.class, new LocalDateSerializer()) - .addSerializer(LocalDateTime.class, new LocalDateTimeSerializer()) - .addSerializer(Duration.class, new DurationToString()) - .addDeserializer(Instant.class, new InstantDeserializer()) - .addSerializer(Instant.class, new InstantSerializer()) - .addDeserializer(OffsetDateTime.class, new OffsetDateTimeDeserializer()) - .addSerializer(OffsetDateTime.class, new OffsetDateTimeSerializer()) - .addDeserializer(OffsetTime.class, new OffsetTimeDeserializer()) - .addSerializer(OffsetTime.class, new OffsetTimeSerializer()) - .addDeserializer(ZonedDateTime.class, new ZonedDateTimeDeserializer()) - - .addKeyDeserializer(OffsetDateTime.class, new OffsetDateTimeDeserializerKey()) - .addKeyDeserializer(LocalDateTime.class, new LocalDateTimeDeserializerKey()) - .addKeyDeserializer(LocalDate.class, new LocalDateDeserializerKey()) - - ; - } - -} diff --git a/src/main/java/com/guicedee/guicedinjection/json/LocalDateDeserializer.java b/src/main/java/com/guicedee/guicedinjection/json/LocalDateDeserializer.java deleted file mode 100644 index 98b940e..0000000 --- a/src/main/java/com/guicedee/guicedinjection/json/LocalDateDeserializer.java +++ /dev/null @@ -1,49 +0,0 @@ -package com.guicedee.guicedinjection.json; - -import com.fasterxml.jackson.core.JsonParser; -import com.fasterxml.jackson.databind.DeserializationContext; -import com.fasterxml.jackson.databind.JsonDeserializer; -import com.google.common.base.Strings; -import lombok.extern.java.Log; - -import java.io.IOException; -import java.time.LocalDate; -import java.util.logging.Level; - -import static com.guicedee.guicedinjection.json.StaticStrings.*; - -@Log -public class LocalDateDeserializer - extends JsonDeserializer -{ - @Override - public LocalDate deserialize(JsonParser p, DeserializationContext ctxt) throws IOException - { - String name = p.getValueAsString(); - return convert(name); - } - - public LocalDate convert(String value) - { - if (Strings.isNullOrEmpty(value) || STRING_NULL.equalsIgnoreCase(value) || STRING_0.equals(value)) - { - return null; - } - if (value.contains(E)) - { - value = value.replaceAll(STRING_DOT_ESCAPED, STRING_EMPTY) - .substring(0, value.indexOf(E) - 1); - } - if (value.length() == 7) - { - value = new StringBuilder(value).insert(value.length() - 1, 0) - .toString(); - } - LocalDate time = new LocalDateTimeDeserializer().convert(value).toLocalDate(); - if (time == null) - { - log.log(Level.WARNING,"Unable to determine local date from string - [" + value + "]"); - } - return time; - } -} diff --git a/src/main/java/com/guicedee/guicedinjection/json/LocalDateSerializer.java b/src/main/java/com/guicedee/guicedinjection/json/LocalDateSerializer.java deleted file mode 100644 index 1bfe6c8..0000000 --- a/src/main/java/com/guicedee/guicedinjection/json/LocalDateSerializer.java +++ /dev/null @@ -1,30 +0,0 @@ -package com.guicedee.guicedinjection.json; -import com.fasterxml.jackson.core.JsonGenerator; -import com.fasterxml.jackson.databind.JsonSerializer; -import com.fasterxml.jackson.databind.SerializerProvider; - -import java.io.IOException; -import java.time.LocalDate; -import java.time.format.DateTimeFormatter; - -public class LocalDateSerializer - extends JsonSerializer { - public static String LocalDateFormat = "yyyy-MM-dd"; - - public LocalDateSerializer() { - } - - @Override - public void serialize(LocalDate value, JsonGenerator generator, SerializerProvider provider) throws IOException { - generator.writeString(convert(value)); - } - - public String convert(LocalDate value) - { - if (value == null) - { - return null; - } - return value.format(DateTimeFormatter.ofPattern(LocalDateFormat)); - } -} diff --git a/src/main/java/com/guicedee/guicedinjection/json/LocalDateTimeDeserializer.java b/src/main/java/com/guicedee/guicedinjection/json/LocalDateTimeDeserializer.java deleted file mode 100644 index 4f03f21..0000000 --- a/src/main/java/com/guicedee/guicedinjection/json/LocalDateTimeDeserializer.java +++ /dev/null @@ -1,171 +0,0 @@ -package com.guicedee.guicedinjection.json; - -import com.fasterxml.jackson.core.JsonParser; -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.databind.DeserializationContext; -import com.fasterxml.jackson.databind.JsonDeserializer; -import com.google.common.base.Strings; -import lombok.extern.java.Log; - -import java.io.IOException; -import java.time.LocalDateTime; -import java.time.format.DateTimeFormatter; -import java.time.format.DateTimeFormatterBuilder; -import java.time.format.DateTimeParseException; -import java.time.temporal.ChronoField; -import java.util.logging.Level; - -import static com.guicedee.guicedinjection.json.StaticStrings.*; - -@Log -public class LocalDateTimeDeserializer - extends JsonDeserializer -{ - public static final DateTimeFormatter[] formats = new DateTimeFormatter[] - { - DateTimeFormatter.ISO_DATE_TIME, - DateTimeFormatter.ISO_ZONED_DATE_TIME, - DateTimeFormatter.RFC_1123_DATE_TIME, - DateTimeFormatter.ISO_OFFSET_DATE_TIME, - new DateTimeFormatterBuilder().appendOptional(DateTimeFormatter.ISO_OFFSET_DATE_TIME) - .appendOptional(DateTimeFormatter.ISO_ZONED_DATE_TIME) - .appendOptional(DateTimeFormatter.ISO_LOCAL_DATE_TIME) - .appendOptional(DateTimeFormatter.ISO_LOCAL_DATE) - .appendOptional( - new DateTimeFormatterBuilder().appendOptional( - DateTimeFormatter.ISO_LOCAL_DATE) - .optionalStart() - .appendLiteral('T') - .optionalEnd() - .optionalStart() - .appendLiteral(' ') - .optionalEnd() - .appendPattern("HH:mm:ss") - .appendFraction( - ChronoField.NANO_OF_SECOND, 0, 9, - true) - .toFormatter() - ) - .appendOptional( - new DateTimeFormatterBuilder() - .appendPattern("yyyy") - .optionalStart() - .appendLiteral("/") - .optionalEnd() - - .optionalStart() - .appendLiteral("-") - .optionalEnd() - - .optionalStart() - .appendPattern("MM") - .optionalStart() - .appendLiteral("/") - .optionalEnd() - .optionalStart() - .appendLiteral("-") - .optionalEnd() - .optionalEnd() - - .optionalStart() - .appendPattern("dd") - .optionalEnd() - .optionalStart() - .appendPattern("d") - .optionalEnd() - - .optionalStart() - .appendLiteral('T') - .optionalEnd() - .optionalStart() - .appendLiteral(' ') - .optionalEnd() - - .optionalStart() - - .optionalStart() - .appendPattern("HH") - - - .optionalStart() - .appendLiteral(':') - .optionalEnd() - .optionalEnd() - - .optionalStart() - .appendPattern("mm") - .optionalEnd() - - .optionalStart() - .appendLiteral(':') - .optionalEnd() - - .optionalStart() - .appendPattern("ss") - .optionalEnd() - - .optionalEnd() - - .optionalStart() - .appendFraction(ChronoField.NANO_OF_SECOND, 0, 9, true) - .optionalEnd() - .optionalStart() - .appendLiteral('Z') - .optionalEnd() - - .optionalStart() - .appendZoneOrOffsetId() - .optionalEnd() - .toFormatter() - ) - .parseDefaulting(ChronoField.MONTH_OF_YEAR, 1L) - .parseDefaulting(ChronoField.DAY_OF_MONTH, 1L) - .parseDefaulting(ChronoField.HOUR_OF_DAY, 0L) - .parseDefaulting(ChronoField.MINUTE_OF_HOUR, 0L) - .parseDefaulting(ChronoField.SECOND_OF_MINUTE, 0L) - .parseDefaulting(ChronoField.NANO_OF_SECOND, 0L) - .toFormatter() - }; - - @Override - public LocalDateTime deserialize(JsonParser p, DeserializationContext ctxt) throws IOException, JsonProcessingException - { - String name = p.getValueAsString(); - return convert(name); - } - - public LocalDateTime convert(String value) - { - if (Strings.isNullOrEmpty(value) || STRING_NULL.equalsIgnoreCase(value) || STRING_0.equals(value)) - { - return null; - } - if (value.contains(E)) - { - value = value.replaceAll(STRING_DOT_ESCAPED, STRING_EMPTY) - .substring(0, value.indexOf(E) - 1); - } - LocalDateTime time = null; - for (DateTimeFormatter format : formats) - { - try - { - time = LocalDateTime.parse(value, format); - break; - } - catch (DateTimeParseException dtpe) - { - //try the next one - } - catch (Exception dtpe) - { - dtpe.printStackTrace(); - } - } - if (time == null) - { - log.log(Level.WARNING, "Unable to determine local date time from string - [" + value + "]"); - } - return time; - } -} diff --git a/src/main/java/com/guicedee/guicedinjection/json/LocalDateTimeSerializer.java b/src/main/java/com/guicedee/guicedinjection/json/LocalDateTimeSerializer.java deleted file mode 100644 index 46afa90..0000000 --- a/src/main/java/com/guicedee/guicedinjection/json/LocalDateTimeSerializer.java +++ /dev/null @@ -1,31 +0,0 @@ -package com.guicedee.guicedinjection.json; -import com.fasterxml.jackson.core.JsonGenerator; -import com.fasterxml.jackson.databind.JsonSerializer; -import com.fasterxml.jackson.databind.SerializerProvider; - -import java.io.IOException; -import java.time.LocalDate; -import java.time.LocalDateTime; -import java.time.format.DateTimeFormatter; - -public class LocalDateTimeSerializer - extends JsonSerializer { - public static String LocalDateTimeFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSSSSSS"; - - public LocalDateTimeSerializer() { - } - - @Override - public void serialize(LocalDateTime value, JsonGenerator generator, SerializerProvider provider) throws IOException { - generator.writeString(convert(value)); - } - - public String convert(LocalDateTime value) - { - if (value == null) - { - return null; - } - return value.format(DateTimeFormatter.ofPattern(LocalDateTimeFormat)); - } -} diff --git a/src/main/java/com/guicedee/guicedinjection/json/LocalTimeDeserializer.java b/src/main/java/com/guicedee/guicedinjection/json/LocalTimeDeserializer.java deleted file mode 100644 index edf4956..0000000 --- a/src/main/java/com/guicedee/guicedinjection/json/LocalTimeDeserializer.java +++ /dev/null @@ -1,50 +0,0 @@ -package com.guicedee.guicedinjection.json; - -import com.fasterxml.jackson.core.*; -import com.fasterxml.jackson.databind.*; -import com.google.common.base.*; - -import java.io.*; -import java.time.*; -import java.time.format.*; - -import static com.guicedee.guicedinjection.json.LocalTimeSerializer.*; -import static com.guicedee.guicedinjection.json.StaticStrings.*; - - -public class LocalTimeDeserializer - extends JsonDeserializer -{ - @Override - public LocalTime deserialize(JsonParser p, DeserializationContext ctxt) throws IOException - { - String name = p.getValueAsString(); - return convert(name); - } - - public LocalTime convert(String value) - { - if (Strings.isNullOrEmpty(value) || STRING_NULL.equalsIgnoreCase(value) || STRING_0.equals(value)) - { - return null; - } - LocalTime time = null; - for (DateTimeFormatter format : formats) - { - try - { - time = LocalTime.parse(value, format); - if (time != null) - { - break; - } - } - catch (DateTimeParseException p) - { - - } - } - - return time; - } -} diff --git a/src/main/java/com/guicedee/guicedinjection/json/LocalTimeSerializer.java b/src/main/java/com/guicedee/guicedinjection/json/LocalTimeSerializer.java deleted file mode 100644 index a13ac32..0000000 --- a/src/main/java/com/guicedee/guicedinjection/json/LocalTimeSerializer.java +++ /dev/null @@ -1,40 +0,0 @@ -package com.guicedee.guicedinjection.json; - -import com.fasterxml.jackson.core.*; -import com.fasterxml.jackson.databind.*; - -import java.io.*; -import java.time.*; -import java.time.format.*; - -public class LocalTimeSerializer - extends JsonSerializer -{ - public static final DateTimeFormatter[] formats = new DateTimeFormatter[]{ - DateTimeFormatter.ofPattern("HHmmss"), - DateTimeFormatter.ofPattern("HH:mm:ss"), - DateTimeFormatter.ofPattern("HH:mm:ss.SSS"), - DateTimeFormatter.ofPattern("HH:mm:ss.SSSSSS"), - DateTimeFormatter.ofPattern("HH:mm:ss.SSSSSSSSS"), - DateTimeFormatter.ofPattern("HHmm"), - }; - - public LocalTimeSerializer() - { - } - - @Override - public void serialize(LocalTime value, JsonGenerator generator, SerializerProvider provider) throws IOException - { - generator.writeString(convert(value)); - } - - public String convert(LocalTime value) - { - if (value == null) - { - return null; - } - return value.format(DateTimeFormatter.ofPattern("HHmmss")); - } -} diff --git a/src/main/java/com/guicedee/guicedinjection/json/ObjectMapperBinder.java b/src/main/java/com/guicedee/guicedinjection/json/ObjectMapperBinder.java deleted file mode 100644 index 555076f..0000000 --- a/src/main/java/com/guicedee/guicedinjection/json/ObjectMapperBinder.java +++ /dev/null @@ -1,151 +0,0 @@ -package com.guicedee.guicedinjection.json; - -import com.fasterxml.jackson.annotation.*; -import com.fasterxml.jackson.core.*; -import com.fasterxml.jackson.databind.*; -import com.google.inject.AbstractModule; -import com.guicedee.guicedinjection.*; -import com.guicedee.guicedinjection.abstractions.*; -import com.guicedee.guicedinjection.interfaces.*; -import jakarta.inject.*; -import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule; -import lombok.extern.java.Log; - -import static com.fasterxml.jackson.core.JsonParser.Feature.*; -import static com.guicedee.guicedinjection.interfaces.ObjectBinderKeys.*; - -@Log -public class ObjectMapperBinder - extends AbstractModule - implements IGuiceModule -{ - - /** - * If the object mapper must behave as a singleton - */ - public static boolean singleton = true; - - /** - * Method onBind ... - */ - @SuppressWarnings("deprecation") - @Override - public void configure() - { - log.config("Bound ObjectMapper (DefaultObjectMapper) as singleton [" + singleton + "]"); - var p = (Provider) () -> new ObjectMapper() - .registerModule(new JavaTimeModule()) - //.registerModule(new LaxJsonModule()) - .configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false) - .configure(DeserializationFeature.FAIL_ON_MISSING_CREATOR_PROPERTIES, true) - .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false) - .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false) - .configure(DeserializationFeature.READ_UNKNOWN_ENUM_VALUES_AS_NULL, true) - .configure(JsonGenerator.Feature.ESCAPE_NON_ASCII, true) - .enable(ALLOW_UNQUOTED_CONTROL_CHARS) - .enable(SerializationFeature.WRITE_ENUMS_USING_TO_STRING) - .setVisibility(PropertyAccessor.FIELD, JsonAutoDetect.Visibility.ANY) - .setVisibility(PropertyAccessor.GETTER, JsonAutoDetect.Visibility.NONE) - .setVisibility(PropertyAccessor.IS_GETTER, JsonAutoDetect.Visibility.NONE) - .setVisibility(PropertyAccessor.SETTER, JsonAutoDetect.Visibility.NONE); - if (singleton) - { - bind(DefaultObjectMapper) - .toProvider(p) - .in(Singleton.class); - } else - { - bind(DefaultObjectMapper) - .toProvider(p); - } - - log.fine("Bound ObjectWriter.class @Named(JSON)"); - - bind(ObjectBinderKeys.JSONObjectWriter) - .toProvider(() -> - GuiceContext.get(ObjectBinderKeys.DefaultObjectMapper) - .writerWithDefaultPrettyPrinter() - .with(SerializationFeature.INDENT_OUTPUT) - .with(SerializationFeature.WRITE_ENUMS_USING_TO_STRING) - .with(JsonGenerator.Feature.QUOTE_FIELD_NAMES) - .without(SerializationFeature.FAIL_ON_EMPTY_BEANS) - .withoutFeatures(SerializationFeature.FAIL_ON_UNWRAPPED_TYPE_IDENTIFIERS)); - - bind(ObjectBinderKeys.JSONObjectWriterTiny) - .toProvider(() -> - GuiceContext.get(ObjectBinderKeys.DefaultObjectMapper) - .writer() - .without(SerializationFeature.INDENT_OUTPUT) - .with(SerializationFeature.WRITE_ENUMS_USING_TO_STRING) - .with(JsonGenerator.Feature.QUOTE_FIELD_NAMES) - .without(SerializationFeature.FAIL_ON_EMPTY_BEANS) - .withoutFeatures(SerializationFeature.FAIL_ON_UNWRAPPED_TYPE_IDENTIFIERS)); - - bind(ObjectBinderKeys.JSONObjectReader) - .toProvider(() -> - GuiceContext.get(ObjectBinderKeys.DefaultObjectMapper) - .reader() - .with(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY) - .with(DeserializationFeature.ACCEPT_EMPTY_ARRAY_AS_NULL_OBJECT) - .without(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES) - ); - - log.fine("Bound ObjectWriter.class @Named(JavaScriptObjectReader)"); - bind(ObjectBinderKeys.JavascriptObjectMapper) - .toInstance(new ObjectMapper() - .registerModule(new LaxJsonModule()) - .configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false) - .configure(DeserializationFeature.FAIL_ON_MISSING_CREATOR_PROPERTIES, false) - .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false) - .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false) - .configure(DeserializationFeature.READ_UNKNOWN_ENUM_VALUES_AS_NULL, true) - .configure(JsonGenerator.Feature.ESCAPE_NON_ASCII, true) - .configure(JsonGenerator.Feature.QUOTE_FIELD_NAMES, false) - .enable(ALLOW_UNQUOTED_CONTROL_CHARS) - .setVisibility(PropertyAccessor.FIELD, JsonAutoDetect.Visibility.ANY) - .setVisibility(PropertyAccessor.GETTER, JsonAutoDetect.Visibility.NONE) - .setVisibility(PropertyAccessor.IS_GETTER, JsonAutoDetect.Visibility.NONE) - .setVisibility(PropertyAccessor.SETTER, JsonAutoDetect.Visibility.NONE) - ); - - - bind(JavaScriptObjectWriter) - .toProvider(() -> - GuiceContext.get(ObjectBinderKeys.JavascriptObjectMapper) - .writerWithDefaultPrettyPrinter() - .with(SerializationFeature.INDENT_OUTPUT) - .with(SerializationFeature.WRITE_ENUMS_USING_TO_STRING) - .without(JsonGenerator.Feature.QUOTE_FIELD_NAMES) - .without(SerializationFeature.FAIL_ON_EMPTY_BEANS) - .withoutFeatures(SerializationFeature.FAIL_ON_UNWRAPPED_TYPE_IDENTIFIERS)); - - bind(ObjectBinderKeys.JavaScriptObjectWriterTiny) - .toProvider(() -> - GuiceContext.get(ObjectBinderKeys.JavascriptObjectMapper) - .writer() - .without(SerializationFeature.INDENT_OUTPUT) - .with(SerializationFeature.WRITE_ENUMS_USING_TO_STRING) - .without(JsonGenerator.Feature.QUOTE_FIELD_NAMES) - .without(SerializationFeature.FAIL_ON_EMPTY_BEANS) - .withoutFeatures(SerializationFeature.FAIL_ON_UNWRAPPED_TYPE_IDENTIFIERS)); - - bind(ObjectBinderKeys.JavaScriptObjectReader) - .toProvider(() -> - GuiceContext.get(ObjectBinderKeys.JavascriptObjectMapper) - .reader() - .with(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY) - .with(DeserializationFeature.ACCEPT_EMPTY_ARRAY_AS_NULL_OBJECT) - .without(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES) - ); - } - - /** - * Returns the object mapper instance for JAVASCRIPT - * - * @return - */ - public static ObjectMapper getObjectMapper() - { - return GuiceContext.get(DefaultObjectMapper); - } -} diff --git a/src/main/java/com/guicedee/guicedinjection/json/OffsetDateTimeDeserializer.java b/src/main/java/com/guicedee/guicedinjection/json/OffsetDateTimeDeserializer.java deleted file mode 100644 index 0dda9b3..0000000 --- a/src/main/java/com/guicedee/guicedinjection/json/OffsetDateTimeDeserializer.java +++ /dev/null @@ -1,83 +0,0 @@ -package com.guicedee.guicedinjection.json; - -import com.fasterxml.jackson.core.JsonParser; -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.databind.DeserializationContext; -import com.fasterxml.jackson.databind.JsonDeserializer; -import com.google.common.base.Strings; -import lombok.extern.java.Log; - -import java.io.IOException; -import java.time.LocalDateTime; -import java.time.OffsetDateTime; -import java.time.ZoneId; -import java.time.ZonedDateTime; -import java.time.format.DateTimeFormatter; -import java.time.format.DateTimeParseException; -import java.util.logging.Level; - -import static com.guicedee.guicedinjection.json.LocalDateTimeDeserializer.formats; -import static com.guicedee.guicedinjection.json.StaticStrings.*; - -@Log -public class OffsetDateTimeDeserializer - extends JsonDeserializer -{ - @Override - public OffsetDateTime deserialize(JsonParser p, DeserializationContext ctxt) throws IOException, JsonProcessingException - { - String name = p.getValueAsString(); - return convert(name); - } - - public OffsetDateTime convert(String value) - { - if (Strings.isNullOrEmpty(value) || STRING_NULL.equalsIgnoreCase(value) || STRING_0.equals(value)) - { - return null; - } - if (value.contains(E)) - { - value = value.replaceAll(STRING_DOT_ESCAPED, STRING_EMPTY) - .substring(0, value.indexOf(E) - 1); - } - OffsetDateTime time = null; - for (DateTimeFormatter format : formats) - { - try - { - time = OffsetDateTime.parse(value, format); - break; - } - catch (DateTimeParseException dtpe) - { - //try the next one - } - } - if (time == null) - { - - LocalDateTime convert = new LocalDateTimeDeserializer().convert(value); - if (convert != null) - { - time = convertToUTCDateTime(convert); - }else - { - log.log(Level.WARNING, "Unable to determine offset datetime from string - [" + value + "]"); - } - } - return time; - } - private OffsetDateTime convertToUTCDateTime(LocalDateTime ldt) - { - if (ldt == null) - { - return null; - } - ZonedDateTime zonedDateTime = ldt.atZone(ZoneId.systemDefault()); - ZonedDateTime utcZonedDateTime = zonedDateTime.withZoneSameLocal(ZoneId.of("UTC")); - OffsetDateTime offsetDateTime = utcZonedDateTime.toOffsetDateTime(); - return offsetDateTime; - } - -} diff --git a/src/main/java/com/guicedee/guicedinjection/json/OffsetDateTimeSerializer.java b/src/main/java/com/guicedee/guicedinjection/json/OffsetDateTimeSerializer.java deleted file mode 100644 index 653e256..0000000 --- a/src/main/java/com/guicedee/guicedinjection/json/OffsetDateTimeSerializer.java +++ /dev/null @@ -1,33 +0,0 @@ -package com.guicedee.guicedinjection.json; - -import com.fasterxml.jackson.core.JsonGenerator; -import com.fasterxml.jackson.databind.JsonSerializer; -import com.fasterxml.jackson.databind.SerializerProvider; - -import java.io.IOException; -import java.time.LocalDateTime; -import java.time.OffsetDateTime; -import java.time.format.DateTimeFormatter; - -public class OffsetDateTimeSerializer - extends JsonSerializer -{ - public OffsetDateTimeSerializer() - { - } - - @Override - public void serialize(OffsetDateTime value, JsonGenerator generator, SerializerProvider provider) throws IOException - { - generator.writeString(convert(value)); - } - - public String convert(OffsetDateTime value) - { - if (value == null) - { - return null; - } - return value.format(DateTimeFormatter.ISO_OFFSET_DATE_TIME); - } -} diff --git a/src/main/java/com/guicedee/guicedinjection/json/OffsetTimeDeserializer.java b/src/main/java/com/guicedee/guicedinjection/json/OffsetTimeDeserializer.java deleted file mode 100644 index 6c15a62..0000000 --- a/src/main/java/com/guicedee/guicedinjection/json/OffsetTimeDeserializer.java +++ /dev/null @@ -1,71 +0,0 @@ -package com.guicedee.guicedinjection.json; - -import com.fasterxml.jackson.core.JsonParser; -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.databind.DeserializationContext; -import com.fasterxml.jackson.databind.JsonDeserializer; -import com.google.common.base.Strings; -import lombok.extern.java.Log; - -import java.io.IOException; -import java.time.OffsetTime; -import java.time.format.DateTimeFormatter; -import java.time.format.DateTimeFormatterBuilder; -import java.time.format.DateTimeParseException; -import java.time.temporal.ChronoField; -import java.util.logging.Level; - -import static com.guicedee.guicedinjection.json.StaticStrings.*; - -@Log -public class OffsetTimeDeserializer - extends JsonDeserializer -{ - private static final DateTimeFormatter[] formats = new DateTimeFormatter[] - { - new DateTimeFormatterBuilder().append(DateTimeFormatter.ISO_OFFSET_TIME) - .parseDefaulting(ChronoField.MINUTE_OF_HOUR, 0L) - .parseDefaulting(ChronoField.SECOND_OF_MINUTE, 0L) - .parseDefaulting(ChronoField.NANO_OF_SECOND, 0L) - .toFormatter() - }; - - @Override - public OffsetTime deserialize(JsonParser p, DeserializationContext ctxt) throws IOException, JsonProcessingException - { - String name = p.getValueAsString(); - return convert(name); - } - - public OffsetTime convert(String value) - { - if (Strings.isNullOrEmpty(value) || STRING_NULL.equalsIgnoreCase(value) || STRING_0.equals(value)) - { - return null; - } - if (value.contains(E)) - { - value = value.replaceAll(STRING_DOT_ESCAPED, STRING_EMPTY) - .substring(0, value.indexOf(E) - 1); - } - OffsetTime time = null; - for (DateTimeFormatter format : formats) - { - try - { - time = OffsetTime.parse(value, format); - break; - } - catch (DateTimeParseException dtpe) - { - //try the next one - } - } - if (time == null) - { - log.log(Level.WARNING,"Unable to determine offset time from string - [" + value + "]"); - - } - return time; - } -} diff --git a/src/main/java/com/guicedee/guicedinjection/json/OffsetTimeSerializer.java b/src/main/java/com/guicedee/guicedinjection/json/OffsetTimeSerializer.java deleted file mode 100644 index 994b538..0000000 --- a/src/main/java/com/guicedee/guicedinjection/json/OffsetTimeSerializer.java +++ /dev/null @@ -1,24 +0,0 @@ -package com.guicedee.guicedinjection.json; - -import com.fasterxml.jackson.core.JsonGenerator; -import com.fasterxml.jackson.databind.JsonSerializer; -import com.fasterxml.jackson.databind.SerializerProvider; - -import java.io.IOException; -import java.time.LocalDateTime; -import java.time.OffsetTime; -import java.time.format.DateTimeFormatter; - -public class OffsetTimeSerializer - extends JsonSerializer -{ - public OffsetTimeSerializer() - { - } - - @Override - public void serialize(OffsetTime value, JsonGenerator generator, SerializerProvider provider) throws IOException - { - generator.writeString(DateTimeFormatter.ISO_OFFSET_TIME.format(value)); - } -} diff --git a/src/main/java/com/guicedee/guicedinjection/json/StaticStrings.java b/src/main/java/com/guicedee/guicedinjection/json/StaticStrings.java deleted file mode 100644 index fcffe1d..0000000 --- a/src/main/java/com/guicedee/guicedinjection/json/StaticStrings.java +++ /dev/null @@ -1,162 +0,0 @@ -package com.guicedee.guicedinjection.json; - -import java.nio.charset.Charset; -import java.nio.charset.StandardCharsets; - -@SuppressWarnings("unused") -public class StaticStrings -{ - public static final String HTML_HEADER_JSON = "application/json"; - public static final String HTML_HEADER_JAVASCRIPT = "application/javascript"; - public static final String HTML_HEADER_CSS = "text/css"; - public static final String HTML_HEADER_ZIP = "application/zip"; - public static final String HTML_HEADER_PDF = "application/pdf"; - public static final String HTML_HEADER_JPG = "img/jpg"; - public static final String HTML_HEADER_MOV = "video/mov"; - public static final String HTML_HEADER_DEFAULT_CONTENT_TYPE = "text/html"; - - public static final String UTF8 = "UTF-8"; - - public static final String STRING_EMPTY = ""; - public static final String STRING_SPACE = " "; - public static final String STRING_FORWARD_SLASH = "/"; - public static final String STRING_BACK_SLASH = "\\"; - public static final String STRING_TAB = "\t"; - public static final String STRING_DOLLAR = "$"; - public static final String STRING_DOLLAR_ESCAPED = "\\$"; - public static final String STRING_EQUALS = "="; - public static final String STRING_NEWLINE_TEXT = "\n"; - public static final String STRING_DOUBLE_COLON = ":"; - public static final String STRING_ASTERISK = "*"; - public static final String STRING_QUESTIONMARK = "?"; - public static final String STRING_SPACE_DOUBLE_COLON_SPACE = " : "; - public static final String STRING_SINGLE_QUOTES = "'"; - public static final String STRING_DOUBLE_QUOTES = "\""; - public static final String STRING_SINGLE_QUOTES_SPACE = "' "; - public static final String STRING_DOUBLE_QUOTES_SPACE = "\" "; - public static final String STRING_EQUALS_SINGLE_QUOTES = "='"; - public static final String STRING_EQUALS_DOUBLE_QUOTES = "=\""; - public static final String STRING_SHARP_BRACE_OPEN = "<"; - public static final String STRING_SHARP_BRACE_SLASH_OPEN = ""; - public static final String STRING_HASH = "#"; - public static final String STRING_DASH = "-"; - public static final String STRING_SPACE_DASH_SPACE = " - "; - public static final String STRING_COMMNA = ","; - public static final String STRING_COMMNA_SPACE = ", "; - public static final String STRING_COMMNA_SEMICOLON = ",'"; - public static final String STRING_DOT = "."; - public static final String STRING_EQUALS_SPACE_EQUALS = " = "; - public static final String STRING_SEMICOLON = ";"; - public static final String STRING_BRACES_OPEN = "{"; - public static final String STRING_BRACES_CLOSE = "}"; - public static final String STRING_CLOSING_BRACKET_SEMICOLON = ");"; - public static final String STRING_SPACE_OPEN_BRACKET = " ("; - public static final String STRING_AMPERSAND = "&"; - - - public static final String FAKE_KEY = "fake"; - - public static final String STRING_INSERT_INTO_SQL = "INSERT INTO "; - public static final String STRING_DELETE_FROM_SQL = "DELETE FROM "; - public static final String STRING_UPDATE_SQL = "UPDATE "; - public static final String STRING_UPDATE_SET_SQL = " SET "; - public static final String STRING_WHERE_SQL = "WHERE "; - public static final String STRING_VALUES_SQL_INSERT = ") VALUES ("; - public static final String STRING_HEX_SQL_START = "0x"; - - public static final String STRING_NULL = "NULL"; - public static final String STRING_DOT_ESCAPED = "\\."; - public static final String STRING_0 = "0"; - public static final String STRING_1 = "1"; - - public static final String STRING_AUTHORIZATION = "Authorization: "; - public static final String STRING_AUTHORIZATION_HEADER = "Authorization"; - public static final String STRING_AUTHORIZATION_BASIC = "Basic"; - public static final String STRING_AUTHORIZATION_BASIC_SPACE = "Basic "; - public static final String STRING_AUTHORIZATION_BEARER = "Bearer"; - public static final String STRING_AUTHORIZATION_BEARER_SPACE = "Bearer "; - - public static final String STRING_DURATION_TIME = "PT"; - - - public static final String STRING_HMAC_256 = "HMAC256"; - public static final String STRING_HMAC_512 = "HMAC512"; - - /** - * A default regex to identify query parameters - */ - public static final String QUERY_PARAMETERS_REGEX = "(\\?.*)?"; - public static final String NOT_WEB_SOCKETS = "(?!wssocket)"; - public static final String ACCESS_CONTROL_ALLOW_ORIGIN_HEADER_NAME = "Access-Control-Allow-Origin"; - public static final String ACCESS_CONTROL_ALLOW_CREDENTIALS_HEADER_NAME = "Access-Control-Allow-Credentials"; - public static final String ACCESS_CONTROL_ALLOW_METHODS_HEADER_NAME = "Access-Control-Allow-Methods"; - public static final String ACCESS_CONTROL_ALLOW_HEADERS_HEADER_NAME = "Access-Control-Allow-Headers"; - public static final String DEFAULT_DATE_TIME_PATTERN = "yyyy-MM-dd HH:mm:ss"; - public static final String DEFAULT_XML_DATE_TIME_PATTERN = "yyyy-MM-dd'T'HH:mm:ss"; - public static final String STRING_SELECTED = "selected"; - /** - * The × string - */ - public static final String HTML_TIMES = "×"; - /** - * The   string - */ - public static final String HTML_TAB = " "; - public static final String HTML_AMPERSAND = "&"; - /** - * Default text for Latin - */ - public static final String ShortLatin = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Pellentesque eleifend..."; - /** - * Default Medium text for Latin - */ - public static final String MediumLatin = "Lorem ipsum dolor sit amet, consectetur adipisicing elit. Libero laboriosam dolor perspiciatis omnis\n " + - "exercitationem. Beatae, officia pariatur? Est cum veniam excepturi. Maiores praesentium, porro voluptas\n" + - " dicta, \n" + - "debitis...\n"; - public static final char CHAR_SPACE = ' '; - public static final char CHAR_DOT = '.'; - public static final char CHAR_EQUALS = '='; - public static final char CHAR_COMMA = ','; - public static final char CHAR_SEMI_COLON = ';'; - public static final char CHAR_DOUBLE_COLON = ':'; - public static final char CHAR_UNDERSCORE = '_'; - public static final char CHAR_PERCENT = '%'; - public static final char CHAR_DOLLAR = '$'; - public static final char CHAR_DASH = '-'; - public static final char CHAR_QUESTIONMARK = '?'; - public static final char CHAR_SLASH = '/'; - public static final char CHAR_BACKSLASH = '\\'; - public static final char CHAR_HASH = '#'; - public static final char CHAR_PLUS = '+'; - public static final char CHAR_BRACES_OPEN = '{'; - public static final char CHAR_BRACES_CLOSE = '}'; - public static final char CHAR_AMPERSAND = '&'; - - public static final String P = "P"; - public static final String H = "H"; - public static final String M = "M"; - public static final String S = "S"; - public static final String E = "E"; - - public static Charset UTF_CHARSET = StandardCharsets.UTF_8; - - private StaticStrings() - { - //No config required - } - - /** - * Sets the default charset used across the baord - * - * @param charset - * The charset to use, default StandardCharset.UTF_8 - */ - public static void setDefaultChartset(Charset charset) - { - UTF_CHARSET = charset; - } -} diff --git a/src/main/java/com/guicedee/guicedinjection/json/StringToBool.java b/src/main/java/com/guicedee/guicedinjection/json/StringToBool.java deleted file mode 100644 index 33e7bee..0000000 --- a/src/main/java/com/guicedee/guicedinjection/json/StringToBool.java +++ /dev/null @@ -1,36 +0,0 @@ -package com.guicedee.guicedinjection.json; - -import com.fasterxml.jackson.core.JsonParser; -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.databind.DeserializationContext; -import com.fasterxml.jackson.databind.JsonDeserializer; -import com.google.common.base.Strings; - -import java.io.IOException; - -/** - * Converts most of the string knowns to boolean - */ -public class StringToBool - extends JsonDeserializer -{ - @Override - public Object deserialize(JsonParser p, DeserializationContext ctxt) throws IOException - { - String value = p.getValueAsString(); - return convert(value); - } - - public boolean convert(String value) - { - Boolean bValue = new StringToBoolean().convert(value); - if (bValue == null) - { - return false; - } - else - { - return bValue; - } - } -} diff --git a/src/main/java/com/guicedee/guicedinjection/json/StringToBoolean.java b/src/main/java/com/guicedee/guicedinjection/json/StringToBoolean.java deleted file mode 100644 index f367af4..0000000 --- a/src/main/java/com/guicedee/guicedinjection/json/StringToBoolean.java +++ /dev/null @@ -1,53 +0,0 @@ -package com.guicedee.guicedinjection.json; - -import com.fasterxml.jackson.core.JsonParser; -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.databind.DeserializationContext; -import com.fasterxml.jackson.databind.JsonDeserializer; -import com.google.common.base.Strings; - -import java.io.IOException; - -/** - * Converts most of the string knowns to boolean - */ -public class StringToBoolean - extends JsonDeserializer -{ - public static boolean nullable = true; - - @Override - public Boolean deserialize(JsonParser p, DeserializationContext ctxt) throws IOException - { - return convert(p.getValueAsString()); - } - - public Boolean convert(String value) - { - if (Strings.isNullOrEmpty(value)) - { - return null; - } - value = value.trim().toLowerCase(); - switch (value) - { - case "1": - case "1.0": - case "y": - case "yes": - case "on": - case "true": - return true; - case "0": - case "0.0": - case "no": - case "off": - case "n": - case "false": - return false; - } - if(nullable) - return null; - else return false; - } -} diff --git a/src/main/java/com/guicedee/guicedinjection/json/StringToCharacterSet.java b/src/main/java/com/guicedee/guicedinjection/json/StringToCharacterSet.java deleted file mode 100644 index 6ed749a..0000000 --- a/src/main/java/com/guicedee/guicedinjection/json/StringToCharacterSet.java +++ /dev/null @@ -1,33 +0,0 @@ -package com.guicedee.guicedinjection.json; - -import com.fasterxml.jackson.core.JsonParser; -import com.fasterxml.jackson.databind.DeserializationContext; -import com.fasterxml.jackson.databind.JsonDeserializer; -import com.google.common.base.Strings; -import org.apache.commons.lang3.StringEscapeUtils; - -import java.io.IOException; -import java.util.LinkedHashSet; -import java.util.Set; - -/** - * Converts most of the string knowns to boolean - */ -public class StringToCharacterSet - extends JsonDeserializer> -{ - @Override - public Set deserialize(JsonParser p, DeserializationContext ctxt) throws IOException - { - Set chars = new LinkedHashSet<>(); - String value = p.getValueAsString(); - if (Strings.isNullOrEmpty(value)) - { - return chars; - } - value = StringEscapeUtils.unescapeJava(value); - value.chars().forEach(a->chars.add((char)a)); - - return chars; - } -} diff --git a/src/main/java/com/guicedee/guicedinjection/json/StringToDurationTime.java b/src/main/java/com/guicedee/guicedinjection/json/StringToDurationTime.java deleted file mode 100644 index 776a3e2..0000000 --- a/src/main/java/com/guicedee/guicedinjection/json/StringToDurationTime.java +++ /dev/null @@ -1,62 +0,0 @@ -package com.guicedee.guicedinjection.json; -import com.fasterxml.jackson.core.JsonParser; -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.databind.DeserializationContext; -import com.fasterxml.jackson.databind.JsonDeserializer; -import com.google.common.base.Strings; -import org.apache.commons.lang3.StringUtils; - -import jakarta.validation.constraints.NotNull; -import java.io.IOException; -import java.text.NumberFormat; -import java.time.Duration; - -import static com.guicedee.guicedinjection.json.StaticStrings.*; - -/** - * Converts most of the string knowns to boolean - */ -public class StringToDurationTime extends JsonDeserializer { - private static final NumberFormat nf = NumberFormat.getInstance(); - - static { - nf.setMinimumIntegerDigits(2); - } - - @Override - public Duration deserialize(JsonParser p, DeserializationContext ctxt) throws IOException { - String name = p.getValueAsString(); - return convert(name); - } - - public Duration convert(@NotNull String value) - { - if (Strings.isNullOrEmpty(value) || STRING_NULL.equals(value) || STRING_0.equals(value)) { - return null; - } - if (value.contains(E)) { - value = value.replaceAll(STRING_DOT_ESCAPED, STRING_EMPTY).substring(0, value.indexOf(E) - 1); - } - - if (value.contains(STRING_DOT)) { - double d = Double.parseDouble(value); - value = String.valueOf((int) d); - } - - if(value.length() > 4) - return new StringToDurationTimeSeconds().convert(value); - - value = value.trim(); - if (!value.contains(P)) { - //Numeric - if (value.length() < 4) { - value = StringUtils.leftPad(value, 4, STRING_0); - } - int hours = Integer.parseInt(value.substring(0, 2)); - int minutes = Integer.parseInt(value.substring(2)); - return Duration.parse(P + nf.format(hours) + H + nf.format(minutes) + M); - } else { - return Duration.parse(value); - } - } -} diff --git a/src/main/java/com/guicedee/guicedinjection/json/StringToDurationTimeSeconds.java b/src/main/java/com/guicedee/guicedinjection/json/StringToDurationTimeSeconds.java deleted file mode 100644 index 12ea8b7..0000000 --- a/src/main/java/com/guicedee/guicedinjection/json/StringToDurationTimeSeconds.java +++ /dev/null @@ -1,69 +0,0 @@ -package com.guicedee.guicedinjection.json; - -import com.fasterxml.jackson.core.JsonParser; -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.databind.DeserializationContext; -import com.fasterxml.jackson.databind.JsonDeserializer; -import com.google.common.base.Strings; -import org.apache.commons.lang3.StringUtils; - -import java.io.IOException; -import java.text.NumberFormat; -import java.time.Duration; - -import static com.guicedee.guicedinjection.json.StaticStrings.*; - -/** - * Converts most of the string knowns to boolean - */ -public class StringToDurationTimeSeconds extends JsonDeserializer { - private static final NumberFormat nf = NumberFormat.getInstance(); - - static { - nf.setMinimumIntegerDigits(2); - } - - @Override - public Duration deserialize(JsonParser p, DeserializationContext ctxt) throws IOException { - String name = p.getValueAsString(); - return convert(name); - } - - public Duration convert(String value) - { - if (Strings.isNullOrEmpty(value) || STRING_NULL.equals(value) || STRING_0.equals(value)) { - return null; - } - if (value.contains(E)) { - value = value.replaceAll(STRING_DOT_ESCAPED, STRING_EMPTY).substring(0, value.indexOf(E) - 1); - } - - if (value.contains(STRING_DOT)) { - double d = Double.parseDouble(value); - value = String.valueOf((int) d); - } - - value = value.trim(); - if (value.length() == 4) { - return new StringToDurationTime().convert(value); - } - - if (value.length() < 6) { - value = StringUtils.leftPad(value, value.length() + 1, STRING_0); - } - if (!value.contains(P)) { - //Numeric - int hours = Integer.parseInt(value.substring(0, 2)); - int minutes = Integer.parseInt(value.substring(2, 4)); - int seconds = Integer.parseInt(value.substring(4, 6)); - return Duration.parse(STRING_DURATION_TIME + nf.format(hours) + H + nf.format(minutes) + M + nf.format(seconds) + S); - } else { - if(value.indexOf(P) != 0) - { - value = value.substring(value.indexOf(P)); - } - return Duration.parse(value); - } - } - -} diff --git a/src/main/java/com/guicedee/guicedinjection/json/StringToIntRelaxed.java b/src/main/java/com/guicedee/guicedinjection/json/StringToIntRelaxed.java deleted file mode 100644 index 875f1d8..0000000 --- a/src/main/java/com/guicedee/guicedinjection/json/StringToIntRelaxed.java +++ /dev/null @@ -1,35 +0,0 @@ -package com.guicedee.guicedinjection.json; - -import com.fasterxml.jackson.core.JsonParser; -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.databind.DeserializationContext; -import com.fasterxml.jackson.databind.JsonDeserializer; -import com.google.common.base.Strings; - -import jakarta.validation.constraints.NotNull; -import java.io.IOException; - -/** - * Converts most of the string knowns to boolean - */ -public class StringToIntRelaxed - extends JsonDeserializer -{ - @Override - public Object deserialize(JsonParser p, DeserializationContext ctxt) throws IOException - { - String value = p.getValueAsString(); - return convert(value); - } - - public int convert(@NotNull String value) - { - if (Strings.isNullOrEmpty(value)) - { - return 0; - } - value = value.trim(); - double d = Double.parseDouble(value); - return (int) d; - } -} diff --git a/src/main/java/com/guicedee/guicedinjection/json/StringToIntegerRelaxed.java b/src/main/java/com/guicedee/guicedinjection/json/StringToIntegerRelaxed.java deleted file mode 100644 index c8d2abf..0000000 --- a/src/main/java/com/guicedee/guicedinjection/json/StringToIntegerRelaxed.java +++ /dev/null @@ -1,33 +0,0 @@ -package com.guicedee.guicedinjection.json; -import com.fasterxml.jackson.core.JsonParser; -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.databind.DeserializationContext; -import com.fasterxml.jackson.databind.JsonDeserializer; -import com.google.common.base.Strings; - -import jakarta.validation.constraints.NotNull; -import java.io.IOException; - -/** - * Converts most of the string knowns to boolean - */ -public class StringToIntegerRelaxed extends JsonDeserializer { - @Override - public Integer deserialize(JsonParser p, DeserializationContext ctxt) throws IOException { - String value = p.getValueAsString(); - if (Strings.isNullOrEmpty(value)) { - return null; - } - return convert(value); - } - - public Integer convert(@NotNull String value) - { - if (Strings.isNullOrEmpty(value)) { - return null; - } - value = value.trim(); - double d = Double.parseDouble(value); - return (int) d; - } -} diff --git a/src/main/java/com/guicedee/guicedinjection/json/ZonedDateTimeDeserializer.java b/src/main/java/com/guicedee/guicedinjection/json/ZonedDateTimeDeserializer.java deleted file mode 100644 index eb5853b..0000000 --- a/src/main/java/com/guicedee/guicedinjection/json/ZonedDateTimeDeserializer.java +++ /dev/null @@ -1,74 +0,0 @@ -package com.guicedee.guicedinjection.json; - -import com.fasterxml.jackson.core.JsonParser; -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.databind.DeserializationContext; -import com.fasterxml.jackson.databind.JsonDeserializer; -import com.google.common.base.Strings; -import lombok.extern.java.Log; - - -import java.io.IOException; -import java.time.ZonedDateTime; -import java.time.format.DateTimeFormatter; -import java.time.format.DateTimeFormatterBuilder; -import java.time.format.DateTimeParseException; -import java.time.temporal.ChronoField; -import java.util.logging.Level; - -import static com.guicedee.guicedinjection.json.StaticStrings.*; - -@Log -public class ZonedDateTimeDeserializer - extends JsonDeserializer -{ - private static final DateTimeFormatter[] formats = new DateTimeFormatter[] - { - new DateTimeFormatterBuilder().append(DateTimeFormatter.ISO_ZONED_DATE_TIME) - .parseDefaulting(ChronoField.MONTH_OF_YEAR, 1L) - .parseDefaulting(ChronoField.DAY_OF_MONTH, 1L) - .parseDefaulting(ChronoField.HOUR_OF_DAY, 0L) - .parseDefaulting(ChronoField.MINUTE_OF_HOUR, 0L) - .parseDefaulting(ChronoField.SECOND_OF_MINUTE, 0L) - .parseDefaulting(ChronoField.NANO_OF_SECOND, 0L) - .toFormatter() - }; - - @Override - public ZonedDateTime deserialize(JsonParser p, DeserializationContext ctxt) throws IOException, JsonProcessingException - { - String name = p.getValueAsString(); - return convert(name); - } - - public ZonedDateTime convert(String value) - { - if (Strings.isNullOrEmpty(value) || STRING_NULL.equalsIgnoreCase(value) || STRING_0.equals(value)) - { - return null; - } - if (value.contains(E)) - { - value = value.replaceAll(STRING_DOT_ESCAPED, STRING_EMPTY) - .substring(0, value.indexOf(E) - 1); - } - ZonedDateTime time = null; - for (DateTimeFormatter format : formats) - { - try - { - time = ZonedDateTime.parse(value, format); - break; - } catch (DateTimeParseException dtpe) - { - //try the next one - } - } - if (time == null) - { - log.log(Level.WARNING, "Unable to determine local date from string - [" + value + "]"); - - } - return time; - } -} diff --git a/src/main/java/com/guicedee/guicedinjection/json/ZonedDateTimeSerializer.java b/src/main/java/com/guicedee/guicedinjection/json/ZonedDateTimeSerializer.java deleted file mode 100644 index 2c9eeec..0000000 --- a/src/main/java/com/guicedee/guicedinjection/json/ZonedDateTimeSerializer.java +++ /dev/null @@ -1,23 +0,0 @@ -package com.guicedee.guicedinjection.json; - -import com.fasterxml.jackson.core.JsonGenerator; -import com.fasterxml.jackson.databind.JsonSerializer; -import com.fasterxml.jackson.databind.SerializerProvider; - -import java.io.IOException; -import java.time.LocalDateTime; -import java.time.format.DateTimeFormatter; - -public class ZonedDateTimeSerializer - extends JsonSerializer -{ - public ZonedDateTimeSerializer() - { - } - - @Override - public void serialize(LocalDateTime value, JsonGenerator generator, SerializerProvider provider) throws IOException - { - generator.writeString(value.format(DateTimeFormatter.ISO_ZONED_DATE_TIME)); - } -} diff --git a/src/main/java/com/guicedee/guicedinjection/json/mapkeys/LocalDateDeserializerKey.java b/src/main/java/com/guicedee/guicedinjection/json/mapkeys/LocalDateDeserializerKey.java deleted file mode 100644 index fdcea3e..0000000 --- a/src/main/java/com/guicedee/guicedinjection/json/mapkeys/LocalDateDeserializerKey.java +++ /dev/null @@ -1,16 +0,0 @@ -package com.guicedee.guicedinjection.json.mapkeys; - -import com.fasterxml.jackson.databind.*; -import com.guicedee.guicedinjection.json.*; - -import java.io.*; - -public class LocalDateDeserializerKey - extends KeyDeserializer -{ - @Override - public Object deserializeKey(String key, DeserializationContext ctxt) throws IOException - { - return new LocalDateDeserializer().convert(key); - } -} diff --git a/src/main/java/com/guicedee/guicedinjection/json/mapkeys/LocalDateTimeDeserializerKey.java b/src/main/java/com/guicedee/guicedinjection/json/mapkeys/LocalDateTimeDeserializerKey.java deleted file mode 100644 index 0b2b484..0000000 --- a/src/main/java/com/guicedee/guicedinjection/json/mapkeys/LocalDateTimeDeserializerKey.java +++ /dev/null @@ -1,16 +0,0 @@ -package com.guicedee.guicedinjection.json.mapkeys; - -import com.fasterxml.jackson.databind.*; -import com.guicedee.guicedinjection.json.*; - -import java.io.*; - -public class LocalDateTimeDeserializerKey - extends KeyDeserializer -{ - @Override - public Object deserializeKey(String key, DeserializationContext ctxt) throws IOException - { - return new LocalDateTimeDeserializer().convert(key); - } -} diff --git a/src/main/java/com/guicedee/guicedinjection/json/mapkeys/OffsetDateTimeDeserializerKey.java b/src/main/java/com/guicedee/guicedinjection/json/mapkeys/OffsetDateTimeDeserializerKey.java deleted file mode 100644 index 16f9fa8..0000000 --- a/src/main/java/com/guicedee/guicedinjection/json/mapkeys/OffsetDateTimeDeserializerKey.java +++ /dev/null @@ -1,16 +0,0 @@ -package com.guicedee.guicedinjection.json.mapkeys; - -import com.fasterxml.jackson.databind.*; -import com.guicedee.guicedinjection.json.*; - -import java.io.*; - -public class OffsetDateTimeDeserializerKey - extends KeyDeserializer -{ - @Override - public Object deserializeKey(String key, DeserializationContext ctxt) throws IOException - { - return new OffsetDateTimeDeserializer().convert(key); - } -} diff --git a/src/main/java/com/guicedee/guicedinjection/representations/IExcelRepresentation.java b/src/main/java/com/guicedee/guicedinjection/representations/IExcelRepresentation.java deleted file mode 100644 index 5ad7d20..0000000 --- a/src/main/java/com/guicedee/guicedinjection/representations/IExcelRepresentation.java +++ /dev/null @@ -1,46 +0,0 @@ -package com.guicedee.guicedinjection.representations; - -import com.guicedee.guicedinjection.representations.excel.ExcelReader; -import com.guicedee.guicedinjection.exceptions.ExcelRenderingException; - -import java.io.IOException; -import java.io.InputStream; -import java.util.List; - -public interface IExcelRepresentation -{ - - /** - * Reads an excel file into it's objects representation - *

- * - * @param stream - * @param objectType - * @param sheetName - * @param - * @return - * @throws ExcelRenderingException - */ - default List fromExcel(InputStream stream, Class objectType, String sheetName) throws ExcelRenderingException - { - try (ExcelReader excelReader = new ExcelReader(stream, "xlsx")) - { - return excelReader.getRecords(sheetName, objectType); - } - catch (IOException e) - { - throw new ExcelRenderingException("Cannot read the excel file"); - } - catch (Exception e) - { - throw new ExcelRenderingException("General error with the excel file", e); - } - } - - default String toExcel() - { - return null; - } - - -} diff --git a/src/main/java/com/guicedee/guicedinjection/representations/IJsonRepresentation.java b/src/main/java/com/guicedee/guicedinjection/representations/IJsonRepresentation.java deleted file mode 100644 index 946eb6a..0000000 --- a/src/main/java/com/guicedee/guicedinjection/representations/IJsonRepresentation.java +++ /dev/null @@ -1,309 +0,0 @@ -package com.guicedee.guicedinjection.representations; - -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.core.type.TypeReference; -import com.fasterxml.jackson.databind.*; -import com.guicedee.guicedinjection.GuiceContext; -import com.guicedee.guicedinjection.exceptions.JsonRenderException; -import com.guicedee.guicedinjection.interfaces.ObjectBinderKeys; - -import java.io.*; -import java.net.URL; -import java.util.*; - -import static com.guicedee.guicedinjection.interfaces.ObjectBinderKeys.*; - -@SuppressWarnings("unused") -public interface IJsonRepresentation extends ICopyable -{ - /** - * Serializes this object as JSON - * - * @return The rendered JSON or an empty string - */ - default String toJson() - { - return toJson(false); - } - - /** - * Serializes this object as JSON - * - * @return The rendered JSON or an empty string - */ - default String toJson(boolean tiny) - { - ObjectMapper objectMapper = GuiceContext.get(DefaultObjectMapper); - try - { - if (tiny) - { - return objectMapper.disable(SerializationFeature.INDENT_OUTPUT) - .writeValueAsString(this); - } - else - { - return objectMapper.writerWithDefaultPrettyPrinter() - .writeValueAsString(this); - } - } - catch (JsonProcessingException e) - { - throw new JsonRenderException("Unable to serialize as JSON", e); - } - } - - /** - * Deserializes this object from a JSON String (updates the current object) - * - * @param json The JSON String - * @return This object updated - */ - default J fromJson(String json) - { - ObjectMapper objectMapper = GuiceContext.get(DefaultObjectMapper); - try - { - return objectMapper.readerForUpdating(this) - .readValue(json); - } - catch (IOException e) - { - throw new JsonRenderException("Unable to serialize as JSON", e); - } - } - - /** - * Deserializes this object from a JSON String (updates the current object) - * - * @param json The JSON String - * @return This object updated - */ - @SuppressWarnings({"UnusedReturnValue"}) - default List fromJsonArray(String json) - { - ObjectMapper objectMapper = GuiceContext.get(DefaultObjectMapper); - try - { - return objectMapper.readerFor(new TypeReference>() {}) - .readValue(json); - } - catch (IOException e) - { - throw new JsonRenderException("Unable to serialize as JSON", e); - } - } - - /** - * Deserializes this object from a JSON String (updates the current object) - * - * @param json The JSON String - * @return This object updated - */ - @SuppressWarnings({"UnusedReturnValue"}) - default Set fromJsonArrayUnique(String json, @SuppressWarnings("unused") - Class type) - { - ObjectMapper objectMapper = GuiceContext.get(DefaultObjectMapper); - try - { - return objectMapper.readerFor(new TypeReference>() {}) - .readValue(json); - } - catch (IOException e) - { - throw new JsonRenderException("Unable to serialize as JSON", e); - } - } - - /** - * Read direct from the stream - * - * @param - * @param file the stream - * @param clazz - * @return - * @throws IOException - */ - static T From(InputStream file, Class clazz) throws IOException - { - return getJsonObjectReader().forType(clazz) - .readValue(file); - } - - - /** - * Read from a file - * - * @param - * @param file - * @param clazz - * @return - * @throws IOException - */ - static T From(File file, Class clazz) throws IOException - { - return getJsonObjectReader().forType(clazz) - .readValue(file); - } - - /** - * Read from a reader - * - * @param - * @param file - * @param clazz - * @return - * @throws IOException - */ - static T From(Reader file, Class clazz) throws IOException - { - return getJsonObjectReader().forType(clazz) - .readValue(file); - } - - static ObjectReader getJsonObjectReader() - { - return GuiceContext.get(ObjectBinderKeys.JSONObjectReader); - } - - /** - * Read from a content string - * - * @param - * @param content - * @param clazz - * @return - * @throws IOException - */ - static T From(String content, Class clazz) throws IOException - { - return getJsonObjectReader().forType(clazz) - .readValue(content); - } - - /** - * Read from a URL - * - * @param - * @param content - * @param clazz - * @return - * @throws IOException - */ - static T From(URL content, Class clazz) throws IOException - { - return getJsonObjectReader().forType(clazz) - .readValue(content); - } - - - /** - * Read direct from the stream - * - * @param - * @param file the stream - * @param clazz - * @return - * @throws IOException - */ - static List fromToList(InputStream file, Class clazz) - { - T list = null; - try - { - list = GuiceContext.get(DefaultObjectMapper) - .reader() - .forType(clazz) - .readValue(file); - } - catch (IOException e) - { - throw new JsonRenderException("Unable to read the input stream ", e); - } - ArrayList lists = new ArrayList<>(); - lists.addAll(Arrays.asList((T[]) list)); - return lists; - } - - /** - * Read from a URL - * - * @param - * @param content - * @param clazz - * @return - * @throws IOException - */ - static List fromToList(URL content, Class clazz) throws IOException - { - T list = GuiceContext.get(DefaultObjectMapper) - .reader() - .forType(clazz) - .readValue(content); - ArrayList lists = new ArrayList<>(); - lists.addAll(Arrays.asList((T[]) list)); - return lists; - } - - /** - * Read from a file - * - * @param - * @param file - * @param clazz - * @return - * @throws IOException - */ - static List fromToList(File file, Class clazz) throws IOException - { - T list = GuiceContext.get(DefaultObjectMapper) - .reader() - .forType(clazz) - .readValue(file); - ArrayList lists = new ArrayList<>(); - lists.addAll(Arrays.asList((T[]) list)); - return lists; - } - - /** - * Read from a reader - * - * @param - * @param file - * @param clazz - * @return - * @throws IOException - */ - static List fromToList(Reader file, Class clazz) throws IOException - { - T list = GuiceContext.get(DefaultObjectMapper) - .reader() - .forType(clazz) - .readValue(file); - ArrayList lists = new ArrayList<>(); - lists.addAll(Arrays.asList((T[]) list)); - return lists; - } - - /** - * Read from a content string - * - * @param - * @param content - * @param clazz - * @return - * @throws IOException - */ - static List fromToList(String content, Class clazz) throws IOException - { - T list = GuiceContext.get(DefaultObjectMapper) - .reader() - .forType(clazz) - .readValue(content); - ArrayList lists = new ArrayList<>(); - lists.addAll(Arrays.asList((T[]) list)); - return lists; - } - -} diff --git a/src/main/java/com/guicedee/guicedinjection/representations/IXmlRepresentation.java b/src/main/java/com/guicedee/guicedinjection/representations/IXmlRepresentation.java deleted file mode 100644 index 9c430ea..0000000 --- a/src/main/java/com/guicedee/guicedinjection/representations/IXmlRepresentation.java +++ /dev/null @@ -1,106 +0,0 @@ -package com.guicedee.guicedinjection.representations; - -import com.guicedee.guicedinjection.exceptions.XmlRenderException; -import com.guicedee.guicedinjection.pairing.Pair; -import jakarta.xml.bind.*; - -import javax.xml.namespace.QName; -import javax.xml.stream.XMLInputFactory; -import javax.xml.stream.XMLStreamException; -import javax.xml.stream.XMLStreamReader; -import java.io.StringReader; -import java.io.StringWriter; -import java.lang.reflect.InvocationTargetException; -/** - * Makes any object representable as XML - * - * @param - */ -public interface IXmlRepresentation { - - @SuppressWarnings("unchecked") - default J fromXml(String xml, Class type) { - try { - J instance = type.getDeclaredConstructor() - .newInstance(); - JAXBContext context = null; - if (XmlContexts.JAXB.containsKey(type)) { - context = XmlContexts.JAXB.get(type); - } else { - context = JAXBContext.newInstance(type); - XmlContexts.JAXB.put(type, context); - } - JAXBIntrospector introspector = context.createJAXBIntrospector(); - Unmarshaller unmarshaller = context.createUnmarshaller(); - if (null == introspector.getElementName(instance)) { - XMLInputFactory factory = XMLInputFactory.newFactory(); - factory.setProperty(XMLInputFactory.IS_SUPPORTING_EXTERNAL_ENTITIES, Boolean.FALSE); - factory.setProperty(XMLInputFactory.SUPPORT_DTD, Boolean.FALSE); - - XMLStreamReader streamReader = factory.createXMLStreamReader( - new StringReader(xml)); - JAXBElement customer = unmarshaller.unmarshal(streamReader, type); - instance = customer.getValue(); - } else { - instance = (J) unmarshaller.unmarshal(new StringReader(xml)); - } - return instance; - } catch (IllegalAccessException T) { - throw new XmlRenderException("Unable to IllegalAccessException ", T); - } catch (IllegalArgumentException T) { - throw new XmlRenderException("Unable to IllegalArgumentException ", T); - } catch (InstantiationException T) { - throw new XmlRenderException("Unable to InstantiationException ", T); - } catch (NoSuchMethodException T) { - throw new XmlRenderException("Unable to NoSuchMethodException ", T); - } catch (SecurityException T) { - throw new XmlRenderException("Unable to SecurityException ", T); - } catch (InvocationTargetException T) { - throw new XmlRenderException("Unable to InvocationTargetException ", T); - } catch (JAXBException T) { - throw new XmlRenderException("Unable to JAXBException ", T); - } catch (XMLStreamException T) { - throw new XmlRenderException("Unable to XMLStreamException ", T); - } - } - - @SuppressWarnings("unchecked") - default String toXml() { - Object requestObject = this; - try (StringWriter stringWriter = new StringWriter()) { - JAXBContext context = null; - if (XmlContexts.JAXB.containsKey(requestObject.getClass())) { - context = XmlContexts.JAXB.get(requestObject.getClass()); - } else { - context = JAXBContext.newInstance(requestObject.getClass()); - XmlContexts.JAXB.put(requestObject.getClass(), context); - } - if (requestObject instanceof Pair) { - Pair p = (Pair) requestObject; - Class keyType = p.getKey() - .getClass(); - Class valueType = p.getValue() - .getClass(); - context = JAXBContext.newInstance(requestObject.getClass(), keyType, valueType); - } - JAXBIntrospector introspector = context.createJAXBIntrospector(); - Marshaller marshaller = context.createMarshaller(); - if (null == introspector.getElementName(requestObject)) { - - @SuppressWarnings("rawtypes") - JAXBElement jaxbElement = new JAXBElement(new QName(requestObject.getClass() - .getSimpleName()), - requestObject.getClass(), requestObject); - marshaller.setProperty("com.sun.xml.bind.xmlDeclaration", Boolean.FALSE); - marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE); - marshaller.setProperty(Marshaller.JAXB_FRAGMENT, true); - marshaller.marshal(jaxbElement, stringWriter); - } else { - marshaller.marshal(requestObject, stringWriter); - } - return stringWriter.toString(); - } catch (Exception e) { - throw new XmlRenderException("Unable to marshal string writer from log intercepter", e); - } - } -} diff --git a/src/main/java/com/guicedee/guicedinjection/representations/XmlContexts.java b/src/main/java/com/guicedee/guicedinjection/representations/XmlContexts.java deleted file mode 100644 index 87e0c45..0000000 --- a/src/main/java/com/guicedee/guicedinjection/representations/XmlContexts.java +++ /dev/null @@ -1,12 +0,0 @@ -package com.guicedee.guicedinjection.representations; - -import jakarta.xml.bind.JAXBContext; - -import java.util.Map; -import java.util.concurrent.ConcurrentHashMap; - -class XmlContexts { - public static final Map, JAXBContext> JAXB = new ConcurrentHashMap<>(); - - private XmlContexts(){} -} diff --git a/src/main/java/com/guicedee/guicedinjection/representations/excel/ExcelReader.java b/src/main/java/com/guicedee/guicedinjection/representations/excel/ExcelReader.java deleted file mode 100644 index 12ce15c..0000000 --- a/src/main/java/com/guicedee/guicedinjection/representations/excel/ExcelReader.java +++ /dev/null @@ -1,463 +0,0 @@ -package com.guicedee.guicedinjection.representations.excel; - -import com.fasterxml.jackson.databind.ObjectMapper; -import com.guicedee.guicedinjection.GuiceContext; -import com.guicedee.guicedinjection.exceptions.ExcelRenderingException; -import lombok.extern.java.Log; -import org.apache.poi.hssf.usermodel.HSSFWorkbook; -import org.apache.poi.ss.usermodel.*; -import org.apache.poi.xssf.usermodel.XSSFWorkbook; -import org.json.JSONObject; - -import java.io.ByteArrayOutputStream; -import java.io.InputStream; -import java.math.BigDecimal; -import java.sql.Timestamp; -import java.util.*; -import java.util.logging.Level; -import java.util.logging.Logger; - -import static com.guicedee.guicedinjection.interfaces.ObjectBinderKeys.*; -import static com.guicedee.guicedinjection.json.StaticStrings.*; -import static java.math.BigDecimal.*; - -/** - * This class is used when a spreadsheet needs to be generated dynamically - * - * @author Ernst Created:23 Oct 2013 - */ -@SuppressWarnings({"WeakerAccess", "unused"}) -@Log -public class ExcelReader - implements AutoCloseable -{ - private InputStream inputStream; - - private HSSFWorkbook oldStyle; - private XSSFWorkbook xwb; - private boolean isH; - private Sheet currentSheet; - - /** - * Constructs with a file to read - */ - public ExcelReader(InputStream inputStream, String extension) throws ExcelRenderingException - { - this(inputStream, extension, 0); - } - - /** - * Constructs with a file to create - */ - public ExcelReader(InputStream inputStream, String extension, int sheet) throws ExcelRenderingException - { - if (inputStream == null) - { - throw new ExcelRenderingException("Inputstream for document is null"); - } - this.inputStream = inputStream; - if (extension.equalsIgnoreCase("xls")) - { - try - { - oldStyle = new HSSFWorkbook(inputStream); - } - catch (Throwable e) - { - log.log(Level.SEVERE,"Unable to excel ",e); - throw new ExcelRenderingException("Cannot open xls workbook",e); - } - this.currentSheet = oldStyle.getSheetAt(sheet); - isH = true; - } - else - { - try - { - xwb = new XSSFWorkbook(inputStream); - } - catch (Throwable e) - { - log.log(Level.SEVERE,"Unable to excel ",e); - throw new ExcelRenderingException("Cannot open xlsx workbook", e); - } - this.currentSheet = xwb.getSheetAt(sheet); - isH = false; - } - } - - public Workbook getWorkbook() - { - if (isH) - { - return oldStyle; - } - else - { - return xwb; - } - } - - /** - * Creates the cell headers - */ - public void writeHeader(List headers) - { - Row row = currentSheet.createRow(0); - int counter = 0; - for (String item : headers) - { - Cell cell = row.createCell(counter); - cell.setCellValue(item); - counter++; - } - } - - /** - * Fetches a sheets complete data for the given number of records - * - * @param sheetNumber - * The sheet number starts at 0 - * @param start - * How many rows to skip - * @param records - * The number of rows to return - * - * @return - */ - public Object[][] fetchRows(int sheetNumber, int start, int records) - { - int totalSheetRows = getRowCount(sheetNumber) + 1; - int totalRowColumns = getColCount(sheetNumber); - if (records > totalSheetRows) - { - records = totalSheetRows; - } - int arraySize = records - start; - if (arraySize == 0) - { - arraySize = 1; - } - else if (arraySize < 0) - { - arraySize = arraySize * -1; - } - Object[][] tableOut = new Object[arraySize][getColCount(sheetNumber)]; - Sheet sheet; - if (isH) - { - sheet = oldStyle.getSheetAt(sheetNumber); - } - else - { - sheet = xwb.getSheetAt(sheetNumber); - } - int rowN = 0; - int cellN = 0; - int skip = 0; - try - { - for (Row row : sheet) - { - if (skip < start) - { - skip++; - continue; - } - cellN = 0; - int tCs = getColCount(sheetNumber); - for (int cn = 0; cn < tCs; cn++) - { - Cell cell = row.getCell(cn, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK); - CellType cellType = cell.getCellType(); - switch (cellType) - { - case BLANK: - { - tableOut[rowN][cellN] = STRING_EMPTY; - break; - } - case NUMERIC: - { - tableOut[rowN][cellN] = cell.getNumericCellValue(); - if (tableOut[rowN][cellN] instanceof Double) - { - Double d = (Double) tableOut[rowN][cellN]; - if (new BigDecimal(d).equals(ZERO)) - { - tableOut[rowN][cellN] = 0; - } - } - break; - } - case STRING: - { - tableOut[rowN][cellN] = cell.getStringCellValue(); - break; - } - case FORMULA: - { - FormulaEvaluator evaluator; - if (isH) - { - evaluator = oldStyle.getCreationHelper() - .createFormulaEvaluator(); - } - else - { - evaluator = xwb.getCreationHelper() - .createFormulaEvaluator(); - } - CellValue cellValue = evaluator.evaluate(cell); - Double valueD = cellValue.getNumberValue(); - tableOut[rowN][cellN] = valueD; - break; - } - case BOOLEAN: - { - tableOut[rowN][cellN] = cell.getBooleanCellValue(); - break; - } - default: - { - break; - } - } - cellN++; - if (totalRowColumns == cellN) - { - break; - } - } - rowN++; - if (records == rowN) - { - break; - } - } - } - catch (ArrayIndexOutOfBoundsException e) - { - log.log(Level.WARNING, "Reached the end of the file before hitting the max results. logic error.", e); - } - catch (Exception e) - { - log.log(Level.WARNING, "Couldn't go through the whole excel file - ", e); - } - return tableOut; - } - - /** - * Returns the number of columns - * - * @param sheetNo - * - * @return - */ - public int getColCount(int sheetNo) - { - Sheet sheet; - if (isH) - { - sheet = oldStyle.getSheetAt(sheetNo); - } - else - { - sheet = xwb.getSheetAt(sheetNo); - } - - Row row = sheet.getRow(sheetNo); - return row.getLastCellNum(); - } - - public int getRowCount(int sheetNo) - { - if (isH) - { - return oldStyle.getSheetAt(sheetNo) - .getLastRowNum() + 1; - } - else - { - return xwb.getSheetAt(sheetNo) - .getLastRowNum() + 1; - } - } - - /** - * Writes a row of strings to the given row number (created) - */ - public void writeRow(int rowNumber, List headers) - { - Row row = currentSheet.createRow(rowNumber); - int counter = 0; - for (String item : headers) - { - Cell cell = row.createCell(counter); - cell.setCellValue(item); - counter++; - } - } - - /** - * Writes data to a spreadsheet row - */ - @SuppressWarnings("ConstantConditions") - public void writeRow(int rowNumber, Object[] rowData) - { - Row row = currentSheet.createRow(rowNumber); - int counter = 0; - for (Object item : rowData) - { - Cell cell = row.createCell(counter); - if (item == null) - { - item = ""; - } - String ftype = item.getClass() - .getName(); - if (ftype.equals("java.lang.String")) - { - cell.setCellValue((String) item); - } - else if (ftype.equals("java.lang.Boolean") || ftype.equals("boolean")) - { - cell.setCellValue((Boolean) item); - } - else if (ftype.equals("java.util.Date")) - { - cell.setCellValue((Date) item); - } - else if (ftype.equals("java.sql.Timestamp")) - { - Timestamp obj = (Timestamp) item; - Date temp = new Date(obj.getTime()); - cell.setCellValue(temp); - } - else if (ftype.equals("int") || ftype.equals("java.lang.Integer")) - { - cell.setCellValue((Integer) item); - } - else if (ftype.equals("long") || ftype.equals("java.lang.Long") || ftype.equals("java.math.BigInteger")) - { - cell.setCellValue((Long) item); - } - else if (ftype.equals("java.math.BigDecimal")) - { - cell.setCellValue(((BigDecimal) item).doubleValue()); - } - else - { - cell.setCellValue((Double) item); - } - counter++; - } - } - - public Row getRow(int rowNumber) - { - return currentSheet.getRow(rowNumber); - } - - public Cell getCell(int rowNumber, int cellNumber) - { - return currentSheet.getRow(rowNumber) - .getCell(cellNumber); - } - - public byte[] get() - { - byte[] output = null; - try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) - { - if (isH) - { - oldStyle.write(baos); - } - else - { - xwb.write(baos); - } - output = baos.toByteArray(); - } - catch (Exception e) - { - log.log(Level.SEVERE, "Unable to get the byte array for the excel file", e); - } - return output; - } - - @SuppressWarnings("unchecked") - public List getRecords(String sheetName, Class type) - { - int sheetLocation = getWorkbook().getSheetIndex(sheetName); - Object[][] rows = this.fetchRows(sheetLocation, 0, getRowCount(sheetLocation)); - Object[] headerRow = rows[0]; - List output = new ArrayList<>(); - Map> cells = new TreeMap<>(); - for (int i = 1; i < rows.length; i++) - { - //Cell - cells.put(i, new LinkedHashMap<>()); - JSONObject rowData = new JSONObject(); - for (int j = 0; j < getColCount(sheetLocation); j++) - { - if (rows[i][j] instanceof BigDecimal) - { - rowData.put(headerRow[j].toString(), ((BigDecimal) rows[i][j]).toPlainString()); - } - else - { - rowData.put(headerRow[j].toString(), rows[i][j]) - .toString(); - } - if(rows[i][j] != null) - { - cells.get(i) - .put(headerRow[j].toString(), rows[i][j].toString()); - } - else - { - //end of row? - } - //cells.put(i, rows[i][j].toString().trim()); - } - String outcome = rowData.toString(); - try - { - ObjectMapper om = GuiceContext.get(DefaultObjectMapper); - T typed = om.readValue(outcome, type); - output.add(typed); - } - catch (Exception e) - { - log.log(Level.SEVERE, "Unable to build an object from the references - " + outcome, e); - } - } - return output; - } - - @Override - public void close() throws Exception - { - try - { - if (isH) - { - oldStyle.close(); - } - else - { - xwb.close(); - } - - } - catch (Exception e) - { - log.log(Level.SEVERE, "Unable to write the excel file out", e); - } - inputStream.close(); - } - - -} diff --git a/src/jre11/java/com/guicedee/guicedinjection/urls/JrtUrlConnection.java b/src/main/java/com/guicedee/guicedinjection/urls/JrtUrlConnection.java similarity index 100% rename from src/jre11/java/com/guicedee/guicedinjection/urls/JrtUrlConnection.java rename to src/main/java/com/guicedee/guicedinjection/urls/JrtUrlConnection.java diff --git a/src/jre11/java/com/guicedee/guicedinjection/urls/JrtUrlHandler.java b/src/main/java/com/guicedee/guicedinjection/urls/JrtUrlHandler.java similarity index 100% rename from src/jre11/java/com/guicedee/guicedinjection/urls/JrtUrlHandler.java rename to src/main/java/com/guicedee/guicedinjection/urls/JrtUrlHandler.java diff --git a/src/jre11/java/module-info.java b/src/main/java/module-info.java similarity index 78% rename from src/jre11/java/module-info.java rename to src/main/java/module-info.java index 7131fbb..f7de039 100644 --- a/src/jre11/java/module-info.java +++ b/src/main/java/module-info.java @@ -1,36 +1,21 @@ -import com.guicedee.guicedinjection.json.*; - module com.guicedee.guicedinjection { - requires transitive com.guicedee.client; requires transitive com.google.guice; requires transitive io.github.classgraph; - requires transitive com.fasterxml.jackson.databind; - requires transitive com.fasterxml.jackson.annotation; - requires transitive com.fasterxml.jackson.datatype.jsr310; //requires transitive com.guicedee.logmaster; requires transitive org.apache.commons.lang3; - requires transitive jakarta.xml.bind; - - requires static java.sql; - requires static org.json; - requires static org.apache.poi.ooxml; - requires static org.apache.poi.poi; - - requires static java.xml; requires static org.slf4j; requires static lombok; - exports com.guicedee.guicedinjection; - exports com.guicedee.guicedinjection.exceptions; + //exports com.guicedee.guicedinjection.exceptions; exports com.guicedee.guicedinjection.abstractions; exports com.guicedee.guicedinjection.pairing; - exports com.guicedee.guicedinjection.json; + //exports com.guicedee.services.jsonrepresentation.json; exports com.guicedee.guicedinjection.properties; exports com.guicedee.guicedinjection.representations; @@ -54,14 +39,13 @@ provides com.guicedee.guicedinjection.interfaces.IGuiceScanModuleExclusions with com.guicedee.guicedinjection.implementations.GuiceDefaultModuleExclusions; provides com.guicedee.guicedinjection.interfaces.IGuiceScanJarExclusions with com.guicedee.guicedinjection.implementations.GuiceDefaultModuleExclusions; - provides com.guicedee.guicedinjection.interfaces.IGuiceModule with com.guicedee.guicedinjection.injections.ContextBinderGuice, ObjectMapperBinder; + provides com.guicedee.guicedinjection.interfaces.IGuiceModule with com.guicedee.guicedinjection.injections.ContextBinderGuice; //provides com.guicedee.guicedinjection.interfaces.IGuiceModule with com.guicedee.guicedinjection.abstractions.GuiceInjectorModule; provides java.net.spi.URLStreamHandlerProvider with com.guicedee.guicedinjection.urls.JrtUrlHandler; opens com.guicedee.guicedinjection to com.fasterxml.jackson.databind; opens com.guicedee.guicedinjection.properties to com.fasterxml.jackson.databind; - opens com.guicedee.guicedinjection.json to com.fasterxml.jackson.databind; - + opens com.guicedee.guicedinjection.pairing; } diff --git a/src/main/resources/META-INF/services/com.guicedee.guicedinjection.interfaces.IGuiceModule b/src/main/resources/META-INF/services/com.guicedee.guicedinjection.interfaces.IGuiceModule index e69de29..fd77f94 100644 --- a/src/main/resources/META-INF/services/com.guicedee.guicedinjection.interfaces.IGuiceModule +++ b/src/main/resources/META-INF/services/com.guicedee.guicedinjection.interfaces.IGuiceModule @@ -0,0 +1 @@ +com.guicedee.guicedinjection.injections.ContextBinderGuice \ No newline at end of file diff --git a/src/main/resources/META-INF/services/com.guicedee.guicedinjection.interfaces.IGuiceScanModuleInclusions b/src/main/resources/META-INF/services/com.guicedee.guicedinjection.interfaces.IGuiceScanModuleInclusions index e69de29..b4ebcda 100644 --- a/src/main/resources/META-INF/services/com.guicedee.guicedinjection.interfaces.IGuiceScanModuleInclusions +++ b/src/main/resources/META-INF/services/com.guicedee.guicedinjection.interfaces.IGuiceScanModuleInclusions @@ -0,0 +1 @@ +com.guicedee.guicedinjection.implementations.GuiceDefaultModuleInclusions \ No newline at end of file diff --git a/src/test/java/com/guicedee/guicedinjection/IGuiceConfigTest.java b/src/test/java/com/guicedee/guicedinjection/IGuiceConfigTest.java index e9ecc92..aa03d6a 100644 --- a/src/test/java/com/guicedee/guicedinjection/IGuiceConfigTest.java +++ b/src/test/java/com/guicedee/guicedinjection/IGuiceConfigTest.java @@ -22,7 +22,8 @@ public void testConfig() .add(new IGuiceConfigTest()); GuiceContext.inject(); GuiceConfig config = GuiceContext.get(GuiceConfig.class); - + config = GuiceContext.instance().getConfig(); + assertTrue(config.isServiceLoadWithClassPath()); assertTrue(config.isAnnotationScanning()); assertTrue(config.isFieldInfo()); @@ -38,7 +39,6 @@ public IGuiceConfig configure(IGuiceConfig config) { config.setIgnoreMethodVisibility(true) .setExcludeModulesAndJars(true) - .setServiceLoadWithClassPath(true) .setExcludePaths(true) .setAllowPaths(true) .setIncludePackages(true) diff --git a/src/test/java/com/guicedee/guicedinjection/LocalDateTimeDeserializationTest.java b/src/test/java/com/guicedee/guicedinjection/LocalDateTimeDeserializationTest.java deleted file mode 100644 index 604dc3d..0000000 --- a/src/test/java/com/guicedee/guicedinjection/LocalDateTimeDeserializationTest.java +++ /dev/null @@ -1,55 +0,0 @@ -package com.guicedee.guicedinjection; - -import com.guicedee.guicedinjection.json.LocalDateTimeDeserializer; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.Test; - -import java.io.IOException; -import java.time.LocalDateTime; -import java.time.format.DateTimeFormatter; -import java.time.format.DateTimeFormatterBuilder; -import java.time.format.DateTimeParseException; -import java.time.format.FormatStyle; -import java.time.temporal.ChronoField; - -import static com.guicedee.guicedinjection.json.LocalDateTimeDeserializer.formats; - -public class LocalDateTimeDeserializationTest -{ - @Test - public void testLdt() throws IOException - { - - LocalDateTime ldt = LocalDateTime.parse("2020-05-11T04:59:20.052125", formats[4]); - LocalDateTime ldt4 = LocalDateTime.parse("2020-05-11 04:59:20.052125", formats[4]); - LocalDateTime ldt5 = LocalDateTime.parse("2020-05-11T07:53:52.467080", formats[4]); - LocalDateTime ldt2 = LocalDateTime.parse("2020-05-11T04:59:20.052", formats[4]); - LocalDateTime ldt3 = LocalDateTime.parse("2020-05-11T04:59:20.052123456", formats[4]); - LocalDateTime ldt33 = LocalDateTime.parse("2020/05/11T04", formats[4]); - LocalDateTime ldt43 = LocalDateTime.parse("2020/05/11T04:30", formats[4]); - LocalDateTime ldt53 = LocalDateTime.parse("2020/05/11T04:30:00", formats[4]); - LocalDateTime ldt73 = LocalDateTime.parse("2020/05/11 04:30", formats[4]); - LocalDateTime ldt83 = LocalDateTime.parse("2020/05/11 04:30:00", formats[4]); - - LocalDateTime.parse("2020-05-11", formats[4]); - LocalDateTime.parse("2020/05/11 04", formats[4]); - LocalDateTime.parse("2020/05/11", formats[4]); - - //this must be local time -> it must fail - Assertions.assertThrows(DateTimeParseException.class, () -> LocalDateTime.parse("04:14", formats[4])); - Assertions.assertThrows(DateTimeParseException.class, () -> LocalDateTime.parse("04:14:20", formats[4])); - Assertions.assertThrows(DateTimeParseException.class, () -> LocalDateTime.parse("04", formats[4])); - - //direct access conversion - new LocalDateTimeDeserializer().convert("2020-05-11T04:59:20.052125"); - new LocalDateTimeDeserializer().convert("2020-05-11T07:53:52.467080"); - new LocalDateTimeDeserializer().convert("2020-05-11T04:59:20.052"); - new LocalDateTimeDeserializer().convert("2016-10-02T20:15:30-06:00"); - new LocalDateTimeDeserializer().convert("2020-05-11T04:59:20.052+01:00"); - new LocalDateTimeDeserializer().convert("2016-12-02T11:15:30-05:00"); - new LocalDateTimeDeserializer().convert("2016-12-02T11:15:30Z"); - new LocalDateTimeDeserializer().convert("2020-05-11T04:59:20.052123456"); - - System.out.println("all parsed"); - } -} diff --git a/src/test/java/com/guicedee/guicedinjection/ParallelPostStartupTest1.java b/src/test/java/com/guicedee/guicedinjection/ParallelPostStartupTest1.java new file mode 100644 index 0000000..4fc1271 --- /dev/null +++ b/src/test/java/com/guicedee/guicedinjection/ParallelPostStartupTest1.java @@ -0,0 +1,18 @@ +package com.guicedee.guicedinjection; + +import com.guicedee.guicedinjection.interfaces.IGuicePostStartup; + +public class ParallelPostStartupTest1 implements IGuicePostStartup +{ + @Override + public void postLoad() + { + System.out.println("Starting 1"); + } + + @Override + public Integer sortOrder() + { + return 200; + } +} diff --git a/src/test/java/com/guicedee/guicedinjection/ParallelPostStartupTest2.java b/src/test/java/com/guicedee/guicedinjection/ParallelPostStartupTest2.java new file mode 100644 index 0000000..a900b44 --- /dev/null +++ b/src/test/java/com/guicedee/guicedinjection/ParallelPostStartupTest2.java @@ -0,0 +1,18 @@ +package com.guicedee.guicedinjection; + +import com.guicedee.guicedinjection.interfaces.IGuicePostStartup; + +public class ParallelPostStartupTest2 implements IGuicePostStartup +{ + @Override + public void postLoad() + { + System.out.println("Starting 2"); + } + + @Override + public Integer sortOrder() + { + return 200; + } +} diff --git a/src/test/resources/META-INF/services/com.guicedee.guicedinjection.interfaces.IGuicePostStartup b/src/test/resources/META-INF/services/com.guicedee.guicedinjection.interfaces.IGuicePostStartup new file mode 100644 index 0000000..f480432 --- /dev/null +++ b/src/test/resources/META-INF/services/com.guicedee.guicedinjection.interfaces.IGuicePostStartup @@ -0,0 +1,2 @@ +com.guicedee.guicedinjection.ParallelPostStartupTest1 +com.guicedee.guicedinjection.ParallelPostStartupTest2 \ No newline at end of file diff --git a/src/test/resources/logback.xml b/src/test/resources/logback.xml new file mode 100644 index 0000000..d59ef06 --- /dev/null +++ b/src/test/resources/logback.xml @@ -0,0 +1,7 @@ + + + + %d %highlight(%-5level) [%thread] %cyan(%logger{15}): %msg%n + + \ No newline at end of file From 2a56104cf405a7298688a3d84861727202945ca3 Mon Sep 17 00:00:00 2001 From: Marc Magon Date: Sun, 31 Dec 2023 01:48:25 +0200 Subject: [PATCH 09/23] Guiced Persistence, Test Modules configuration, Add dynamic register modules to Guice Context --- pom.xml | 8 +- .../guicedinjection/GuiceContext.java | 41 ++-- .../guicedinjection/SysStreamsLogger.java | 188 ------------------ .../CustomClassScannerI.java | 2 +- .../FileSearchTest.java | 3 +- .../GlobalPropertiesTest.java | 3 +- .../GuiceContextTest.java | 3 +- .../IGuiceConfigTest.java | 6 +- .../IGuiceContextTestConfigurator.java | 2 +- .../OptionalPairTest.java | 3 +- .../{guicedinjection => tests}/PairTest.java | 3 +- .../ParallelPostStartupTest1.java | 2 +- .../ParallelPostStartupTest2.java | 2 +- .../{guicedinjection => tests}/PsvmTest.java | 4 +- src/test/java/module-info.java | 9 + ...dinjection.interfaces.IFileContentsScanner | 2 +- ...cedinjection.interfaces.IGuiceConfigurator | 4 +- ...icedinjection.interfaces.IGuicePostStartup | 4 +- 18 files changed, 61 insertions(+), 228 deletions(-) delete mode 100644 src/main/java/com/guicedee/guicedinjection/SysStreamsLogger.java rename src/test/java/com/guicedee/{guicedinjection => tests}/CustomClassScannerI.java (93%) rename src/test/java/com/guicedee/{guicedinjection => tests}/FileSearchTest.java (96%) rename src/test/java/com/guicedee/{guicedinjection => tests}/GlobalPropertiesTest.java (92%) rename src/test/java/com/guicedee/{guicedinjection => tests}/GuiceContextTest.java (89%) rename src/test/java/com/guicedee/{guicedinjection => tests}/IGuiceConfigTest.java (92%) rename src/test/java/com/guicedee/{guicedinjection => tests}/IGuiceContextTestConfigurator.java (89%) rename src/test/java/com/guicedee/{guicedinjection => tests}/OptionalPairTest.java (89%) rename src/test/java/com/guicedee/{guicedinjection => tests}/PairTest.java (85%) rename src/test/java/com/guicedee/{guicedinjection => tests}/ParallelPostStartupTest1.java (88%) rename src/test/java/com/guicedee/{guicedinjection => tests}/ParallelPostStartupTest2.java (88%) rename src/test/java/com/guicedee/{guicedinjection => tests}/PsvmTest.java (71%) create mode 100644 src/test/java/module-info.java diff --git a/pom.xml b/pom.xml index f705276..7ac77dc 100644 --- a/pom.xml +++ b/pom.xml @@ -108,7 +108,6 @@ commons-lang3 - com.fasterxml.jackson.core jackson-core @@ -149,6 +148,12 @@ jcl-over-slf4j + + org.slf4j + slf4j-simple + test + + org.junit.jupiter junit-jupiter-api @@ -177,7 +182,6 @@ org.apache.maven.plugins maven-compiler-plugin - ${maven.compiler.version} true diff --git a/src/main/java/com/guicedee/guicedinjection/GuiceContext.java b/src/main/java/com/guicedee/guicedinjection/GuiceContext.java index ff623ed..2ffe661 100644 --- a/src/main/java/com/guicedee/guicedinjection/GuiceContext.java +++ b/src/main/java/com/guicedee/guicedinjection/GuiceContext.java @@ -25,7 +25,6 @@ import jakarta.validation.constraints.*; import lombok.extern.java.Log; -import java.lang.Module; import java.lang.annotation.*; import java.util.*; import java.util.concurrent.*; @@ -60,14 +59,6 @@ public class GuiceContext> * 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 */ @@ -101,7 +92,8 @@ private GuiceContext() //No config required } - private Set registerModules = new LinkedHashSet<>(); + private static Set registerModuleForScanning = new LinkedHashSet<>(); + private static List modules = new ArrayList<>(); /** * Reference the Injector Directly @@ -118,7 +110,6 @@ public static synchronized Injector inject() } if (GuiceContext.instance().injector == null) { - SysStreamsLogger.bindSystemStreams(); try { GuiceContext.buildingInjector = true; @@ -138,8 +129,11 @@ public static synchronized Injector inject() GuiceContext.instance() .loadPreStartups(); - List cModules = new ArrayList<>(); - cModules.add(new GuiceInjectorModule()); + List cModules = new ArrayList<>(modules); + Set iGuiceModules = GuiceContext.instance().loadIGuiceModules(); + cModules.addAll(iGuiceModules); + + //cModules.add(new GuiceInjectorModule()); GuiceContext.instance().injector = Guice.createInjector(cModules); GuiceContext.buildingInjector = false; GuiceContext.instance() @@ -765,10 +759,15 @@ private String[] getModulesExclusionList() * @return This instance */ @SuppressWarnings("unchecked") - public J registerModule(String javaModuleName) + public static void registerModule(String javaModuleName) { - this.registerModules.add(javaModuleName); - return (J) this; + instance().registerModuleForScanning.add(javaModuleName); + instance().getConfig().setIncludeModuleAndJars(true); + } + + public static void registerModule(com.google.inject.Module module) + { + instance().modules.add(module); } /** @@ -780,7 +779,7 @@ public J registerModule(String javaModuleName) private String[] getModulesInclusionsList() { Set strings = new TreeSet<>(); - strings.addAll(registerModules); + strings.addAll(registerModuleForScanning); Set exclusions = getLoader(IGuiceScanModuleInclusions.class, true, ServiceLoader.load(IGuiceScanModuleInclusions.class)); if (exclusions.iterator() .hasNext()) @@ -1240,7 +1239,10 @@ public Set loaderToSetNoInjection(ServiceLoader loader) output.add(newInstance); completed.add((Class) newInstance.getClass()); } - } catch (Throwable T) + } catch (java.util.ServiceConfigurationError T) + { + log.log(Level.WARNING, "Cannot load services - ", T); + }catch (Throwable T) { log.log(Level.SEVERE, "Cannot load services - ", T); } @@ -1255,8 +1257,7 @@ public Set loaderToSetNoInjection(ServiceLoader loader) output.add((T) newInstance.getDeclaredConstructor()); } catch (NoSuchMethodException e) { - log - .log(Level.SEVERE, "Cannot load a service through default constructor", e); + log.log(Level.SEVERE, "Cannot load a service through default constructor", e); } } return output; 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/test/java/com/guicedee/guicedinjection/CustomClassScannerI.java b/src/test/java/com/guicedee/tests/CustomClassScannerI.java similarity index 93% rename from src/test/java/com/guicedee/guicedinjection/CustomClassScannerI.java rename to src/test/java/com/guicedee/tests/CustomClassScannerI.java index 8580981..df1af29 100644 --- a/src/test/java/com/guicedee/guicedinjection/CustomClassScannerI.java +++ b/src/test/java/com/guicedee/tests/CustomClassScannerI.java @@ -1,4 +1,4 @@ -package com.guicedee.guicedinjection; +package com.guicedee.tests; import com.guicedee.guicedinjection.interfaces.IFileContentsScanner; import io.github.classgraph.ResourceList; diff --git a/src/test/java/com/guicedee/guicedinjection/FileSearchTest.java b/src/test/java/com/guicedee/tests/FileSearchTest.java similarity index 96% rename from src/test/java/com/guicedee/guicedinjection/FileSearchTest.java rename to src/test/java/com/guicedee/tests/FileSearchTest.java index 9d5997e..9b4de66 100644 --- a/src/test/java/com/guicedee/guicedinjection/FileSearchTest.java +++ b/src/test/java/com/guicedee/tests/FileSearchTest.java @@ -1,5 +1,6 @@ -package com.guicedee.guicedinjection; +package com.guicedee.tests; +import com.guicedee.guicedinjection.GuiceContext; import com.guicedee.guicedinjection.interfaces.IPathContentsRejectListScanner; import io.github.classgraph.ResourceList; import org.junit.jupiter.api.Test; diff --git a/src/test/java/com/guicedee/guicedinjection/GlobalPropertiesTest.java b/src/test/java/com/guicedee/tests/GlobalPropertiesTest.java similarity index 92% rename from src/test/java/com/guicedee/guicedinjection/GlobalPropertiesTest.java rename to src/test/java/com/guicedee/tests/GlobalPropertiesTest.java index 0e67216..94b22c1 100644 --- a/src/test/java/com/guicedee/guicedinjection/GlobalPropertiesTest.java +++ b/src/test/java/com/guicedee/tests/GlobalPropertiesTest.java @@ -1,5 +1,6 @@ -package com.guicedee.guicedinjection; +package com.guicedee.tests; +import com.guicedee.guicedinjection.GuiceContext; import com.guicedee.guicedinjection.properties.GlobalProperties; import org.junit.jupiter.api.Assertions; diff --git a/src/test/java/com/guicedee/guicedinjection/GuiceContextTest.java b/src/test/java/com/guicedee/tests/GuiceContextTest.java similarity index 89% rename from src/test/java/com/guicedee/guicedinjection/GuiceContextTest.java rename to src/test/java/com/guicedee/tests/GuiceContextTest.java index da90a24..89d7957 100644 --- a/src/test/java/com/guicedee/guicedinjection/GuiceContextTest.java +++ b/src/test/java/com/guicedee/tests/GuiceContextTest.java @@ -3,8 +3,9 @@ * To change this template file, choose Tools | Templates * and open the template in the editor. */ -package com.guicedee.guicedinjection; +package com.guicedee.tests; +import com.guicedee.guicedinjection.GuiceContext; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; diff --git a/src/test/java/com/guicedee/guicedinjection/IGuiceConfigTest.java b/src/test/java/com/guicedee/tests/IGuiceConfigTest.java similarity index 92% rename from src/test/java/com/guicedee/guicedinjection/IGuiceConfigTest.java rename to src/test/java/com/guicedee/tests/IGuiceConfigTest.java index aa03d6a..35cec54 100644 --- a/src/test/java/com/guicedee/guicedinjection/IGuiceConfigTest.java +++ b/src/test/java/com/guicedee/tests/IGuiceConfigTest.java @@ -1,12 +1,12 @@ -package com.guicedee.guicedinjection; +package com.guicedee.tests; +import com.guicedee.guicedinjection.GuiceConfig; +import com.guicedee.guicedinjection.GuiceContext; import com.guicedee.guicedinjection.interfaces.IGuiceConfig; import com.guicedee.guicedinjection.interfaces.IGuiceConfigurator; import lombok.extern.java.Log; import org.junit.jupiter.api.Test; -import java.util.logging.Level; - import static org.junit.jupiter.api.Assertions.*; @Log diff --git a/src/test/java/com/guicedee/guicedinjection/IGuiceContextTestConfigurator.java b/src/test/java/com/guicedee/tests/IGuiceContextTestConfigurator.java similarity index 89% rename from src/test/java/com/guicedee/guicedinjection/IGuiceContextTestConfigurator.java rename to src/test/java/com/guicedee/tests/IGuiceContextTestConfigurator.java index ce33b99..7048fd2 100644 --- a/src/test/java/com/guicedee/guicedinjection/IGuiceContextTestConfigurator.java +++ b/src/test/java/com/guicedee/tests/IGuiceContextTestConfigurator.java @@ -1,4 +1,4 @@ -package com.guicedee.guicedinjection; +package com.guicedee.tests; import com.guicedee.guicedinjection.interfaces.IGuiceConfig; import com.guicedee.guicedinjection.interfaces.IGuiceConfigurator; diff --git a/src/test/java/com/guicedee/guicedinjection/OptionalPairTest.java b/src/test/java/com/guicedee/tests/OptionalPairTest.java similarity index 89% rename from src/test/java/com/guicedee/guicedinjection/OptionalPairTest.java rename to src/test/java/com/guicedee/tests/OptionalPairTest.java index a5f70e3..038d7f7 100644 --- a/src/test/java/com/guicedee/guicedinjection/OptionalPairTest.java +++ b/src/test/java/com/guicedee/tests/OptionalPairTest.java @@ -1,5 +1,6 @@ -package com.guicedee.guicedinjection; +package com.guicedee.tests; +import com.guicedee.guicedinjection.GuiceContext; import com.guicedee.guicedinjection.pairing.OptionalPair; import com.guicedee.guicedinjection.properties.GlobalProperties; import org.junit.jupiter.api.Assertions; diff --git a/src/test/java/com/guicedee/guicedinjection/PairTest.java b/src/test/java/com/guicedee/tests/PairTest.java similarity index 85% rename from src/test/java/com/guicedee/guicedinjection/PairTest.java rename to src/test/java/com/guicedee/tests/PairTest.java index 81007de..1718315 100644 --- a/src/test/java/com/guicedee/guicedinjection/PairTest.java +++ b/src/test/java/com/guicedee/tests/PairTest.java @@ -1,5 +1,6 @@ -package com.guicedee.guicedinjection; +package com.guicedee.tests; +import com.guicedee.guicedinjection.GuiceContext; import com.guicedee.guicedinjection.pairing.Pair; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; diff --git a/src/test/java/com/guicedee/guicedinjection/ParallelPostStartupTest1.java b/src/test/java/com/guicedee/tests/ParallelPostStartupTest1.java similarity index 88% rename from src/test/java/com/guicedee/guicedinjection/ParallelPostStartupTest1.java rename to src/test/java/com/guicedee/tests/ParallelPostStartupTest1.java index 4fc1271..1db134c 100644 --- a/src/test/java/com/guicedee/guicedinjection/ParallelPostStartupTest1.java +++ b/src/test/java/com/guicedee/tests/ParallelPostStartupTest1.java @@ -1,4 +1,4 @@ -package com.guicedee.guicedinjection; +package com.guicedee.tests; import com.guicedee.guicedinjection.interfaces.IGuicePostStartup; diff --git a/src/test/java/com/guicedee/guicedinjection/ParallelPostStartupTest2.java b/src/test/java/com/guicedee/tests/ParallelPostStartupTest2.java similarity index 88% rename from src/test/java/com/guicedee/guicedinjection/ParallelPostStartupTest2.java rename to src/test/java/com/guicedee/tests/ParallelPostStartupTest2.java index a900b44..028767c 100644 --- a/src/test/java/com/guicedee/guicedinjection/ParallelPostStartupTest2.java +++ b/src/test/java/com/guicedee/tests/ParallelPostStartupTest2.java @@ -1,4 +1,4 @@ -package com.guicedee.guicedinjection; +package com.guicedee.tests; import com.guicedee.guicedinjection.interfaces.IGuicePostStartup; diff --git a/src/test/java/com/guicedee/guicedinjection/PsvmTest.java b/src/test/java/com/guicedee/tests/PsvmTest.java similarity index 71% rename from src/test/java/com/guicedee/guicedinjection/PsvmTest.java rename to src/test/java/com/guicedee/tests/PsvmTest.java index 753fb5f..61f0c45 100644 --- a/src/test/java/com/guicedee/guicedinjection/PsvmTest.java +++ b/src/test/java/com/guicedee/tests/PsvmTest.java @@ -1,4 +1,6 @@ -package com.guicedee.guicedinjection; +package com.guicedee.tests; + +import com.guicedee.guicedinjection.GuiceContext; public class PsvmTest { diff --git a/src/test/java/module-info.java b/src/test/java/module-info.java new file mode 100644 index 0000000..b58f263 --- /dev/null +++ b/src/test/java/module-info.java @@ -0,0 +1,9 @@ +module guice.injection.tests { + requires com.guicedee.guicedinjection; + + requires static lombok; + + requires org.junit.jupiter.api; + requires org.slf4j; + requires org.slf4j.simple; +} \ No newline at end of file diff --git a/src/test/resources/META-INF/services/com.guicedee.guicedinjection.interfaces.IFileContentsScanner b/src/test/resources/META-INF/services/com.guicedee.guicedinjection.interfaces.IFileContentsScanner index fd6f9d8..29d96e2 100644 --- a/src/test/resources/META-INF/services/com.guicedee.guicedinjection.interfaces.IFileContentsScanner +++ b/src/test/resources/META-INF/services/com.guicedee.guicedinjection.interfaces.IFileContentsScanner @@ -1 +1 @@ -com.guicedee.guicedinjection.CustomClassScannerI +com.guicedee.tests.CustomClassScannerI diff --git a/src/test/resources/META-INF/services/com.guicedee.guicedinjection.interfaces.IGuiceConfigurator b/src/test/resources/META-INF/services/com.guicedee.guicedinjection.interfaces.IGuiceConfigurator index 87bcf4a..ed7c8dc 100644 --- a/src/test/resources/META-INF/services/com.guicedee.guicedinjection.interfaces.IGuiceConfigurator +++ b/src/test/resources/META-INF/services/com.guicedee.guicedinjection.interfaces.IGuiceConfigurator @@ -1,2 +1,2 @@ -com.guicedee.guicedinjection.IGuiceConfigTest -com.guicedee.guicedinjection.IGuiceContextTestConfigurator \ No newline at end of file +com.guicedee.tests.IGuiceConfigTest +com.guicedee.tests.IGuiceContextTestConfigurator \ No newline at end of file diff --git a/src/test/resources/META-INF/services/com.guicedee.guicedinjection.interfaces.IGuicePostStartup b/src/test/resources/META-INF/services/com.guicedee.guicedinjection.interfaces.IGuicePostStartup index f480432..525220c 100644 --- a/src/test/resources/META-INF/services/com.guicedee.guicedinjection.interfaces.IGuicePostStartup +++ b/src/test/resources/META-INF/services/com.guicedee.guicedinjection.interfaces.IGuicePostStartup @@ -1,2 +1,2 @@ -com.guicedee.guicedinjection.ParallelPostStartupTest1 -com.guicedee.guicedinjection.ParallelPostStartupTest2 \ No newline at end of file +com.guicedee.tests.ParallelPostStartupTest1 +com.guicedee.tests.ParallelPostStartupTest2 \ No newline at end of file From 317680847f4ea8a8694da16f2102c4884dabe07a Mon Sep 17 00:00:00 2001 From: Marc Magon Date: Tue, 2 Jan 2024 03:31:14 +0200 Subject: [PATCH 10/23] Open API and Rest Updates --- src/main/java/com/guicedee/guicedinjection/GuiceContext.java | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/src/main/java/com/guicedee/guicedinjection/GuiceContext.java b/src/main/java/com/guicedee/guicedinjection/GuiceContext.java index 2ffe661..615866d 100644 --- a/src/main/java/com/guicedee/guicedinjection/GuiceContext.java +++ b/src/main/java/com/guicedee/guicedinjection/GuiceContext.java @@ -407,6 +407,10 @@ private void loadConfiguration() .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; } From 4a6a10da038ad32712b2a88d461f84736642f975 Mon Sep 17 00:00:00 2001 From: Marc Magon Date: Tue, 2 Jan 2024 05:55:33 +0200 Subject: [PATCH 11/23] JLink Minor Updates --- .../java/com/guicedee/guicedinjection/GuiceContext.java | 4 ++-- src/main/java/module-info.java | 7 +++++++ ...om.guicedee.guicedinjection.interfaces.IGuicePreDestroy | 2 +- 3 files changed, 10 insertions(+), 3 deletions(-) diff --git a/src/main/java/com/guicedee/guicedinjection/GuiceContext.java b/src/main/java/com/guicedee/guicedinjection/GuiceContext.java index 615866d..f8c2a66 100644 --- a/src/main/java/com/guicedee/guicedinjection/GuiceContext.java +++ b/src/main/java/com/guicedee/guicedinjection/GuiceContext.java @@ -295,14 +295,14 @@ public static T get(@NotNull Key type) return instance; } + private static Set destroyers = GuiceContext.instance() + .getLoader(IGuicePreDestroy.class, false, ServiceLoader.load(IGuicePreDestroy.class)); /** * Execute on Destroy */ @SuppressWarnings("unused") public static void destroy() { - Set destroyers = GuiceContext.instance() - .getLoader(IGuicePreDestroy.class, false, ServiceLoader.load(IGuicePreDestroy.class)); try { for (IGuicePreDestroy destroyer : destroyers) diff --git a/src/main/java/module-info.java b/src/main/java/module-info.java index f7de039..6b88e06 100644 --- a/src/main/java/module-info.java +++ b/src/main/java/module-info.java @@ -1,3 +1,6 @@ +import com.guicedee.guicedinjection.JobService; +import com.guicedee.guicedinjection.interfaces.IGuicePreDestroy; + module com.guicedee.guicedinjection { requires transitive com.guicedee.client; @@ -26,6 +29,8 @@ //uses com.guicedee.guicedinjection.interfaces.IGuiceDefaultBinder; uses com.guicedee.guicedinjection.interfaces.IGuicePreStartup; uses com.guicedee.guicedinjection.interfaces.IGuicePreDestroy; + + uses com.guicedee.guicedinjection.interfaces.IGuiceModule; uses com.guicedee.guicedinjection.interfaces.IGuicePostStartup; uses com.guicedee.guicedinjection.interfaces.IPathContentsScanner; @@ -42,6 +47,8 @@ provides com.guicedee.guicedinjection.interfaces.IGuiceModule with com.guicedee.guicedinjection.injections.ContextBinderGuice; //provides com.guicedee.guicedinjection.interfaces.IGuiceModule with com.guicedee.guicedinjection.abstractions.GuiceInjectorModule; + provides IGuicePreDestroy with JobService; + provides java.net.spi.URLStreamHandlerProvider with com.guicedee.guicedinjection.urls.JrtUrlHandler; opens com.guicedee.guicedinjection to com.fasterxml.jackson.databind; diff --git a/src/main/resources/META-INF/services/com.guicedee.guicedinjection.interfaces.IGuicePreDestroy b/src/main/resources/META-INF/services/com.guicedee.guicedinjection.interfaces.IGuicePreDestroy index 37239e4..8cbebf5 100644 --- a/src/main/resources/META-INF/services/com.guicedee.guicedinjection.interfaces.IGuicePreDestroy +++ b/src/main/resources/META-INF/services/com.guicedee.guicedinjection.interfaces.IGuicePreDestroy @@ -1 +1 @@ -com.guicedee.guicedinjection.interfaces.JobService \ No newline at end of file +com.guicedee.guicedinjection.JobService \ No newline at end of file From b63046d0eb8a1ee4af71a02b57ddf1bd0ff01a8d Mon Sep 17 00:00:00 2001 From: Marc Magon Date: Mon, 5 Feb 2024 00:59:40 +0200 Subject: [PATCH 12/23] Version 2 Updates --- .../guicedee/guicedinjection/JobService.java | 42 +++++-------------- 1 file changed, 10 insertions(+), 32 deletions(-) diff --git a/src/main/java/com/guicedee/guicedinjection/JobService.java b/src/main/java/com/guicedee/guicedinjection/JobService.java index 249edfd..89f8681 100644 --- a/src/main/java/com/guicedee/guicedinjection/JobService.java +++ b/src/main/java/com/guicedee/guicedinjection/JobService.java @@ -78,21 +78,7 @@ public ExecutorService removeJob(String pool) log.warning("Pool " + pool + " was not registered"); return null; } - - es.shutdown(); - try - { - log.finer("Waiting for pool " + pool + " to shutdown cleanly."); - es.awaitTermination(defaultWaitTime, defaultWaitUnit); - } catch (Exception e) - { - log.log(Level.SEVERE, "Couldn't shut down pool" + pool + " cleanly in 60 seconds. Forcing."); - } - if (!es.isShutdown()) - { - es.shutdownNow(); - } - es.close(); + waitForJob(pool); serviceMap.remove(pool); return es; } @@ -110,20 +96,7 @@ public ScheduledExecutorService removePollingJob(String pool) log.warning("Repeating Pool " + pool + " was not registered"); return null; } - es.shutdown(); - try - { - log.finer("Waiting for repeating pool " + pool + " to shutdown cleanly."); - es.awaitTermination(defaultWaitTime, defaultWaitUnit); - } catch (Exception e) - { - log.log(Level.SEVERE, "Couldn't shut down pool" + pool + " cleanly in 60 seconds. Forcing."); - es.shutdownNow(); - } - if (!es.isTerminated()) - { - es.shutdownNow(); - } + waitForJob(pool); pollingMap.remove(pool); return es; } @@ -205,7 +178,7 @@ public ExecutorService addJob(String jobPoolName, Runnable thread) * @param jobPoolName * @param thread */ - public ExecutorService addJob(String jobPoolName, Callable thread) + public Future addTask(String jobPoolName, Callable thread) { if (!serviceMap.containsKey(jobPoolName) || serviceMap.get(jobPoolName).isTerminated() || serviceMap.get(jobPoolName).isShutdown()) { @@ -219,8 +192,7 @@ public ExecutorService addJob(String jobPoolName, Callable thread) removeJob(jobPoolName); service = registerJobPool(jobPoolName, executorServiceSupplier.get()); } - service.submit(thread); - return service; + return service.submit(thread); } public void waitForJob(String jobName) @@ -242,7 +214,13 @@ public void waitForJob(String jobName, long timeout, TimeUnit 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(); } /** From 6e5a6fe3519a33c7f32401afa295acc379b26038 Mon Sep 17 00:00:00 2001 From: GedMarc Date: Sun, 25 Feb 2024 01:20:06 +0200 Subject: [PATCH 13/23] Updates for Builds and Versions --- pom.xml | 1 + .../guicedee/guicedinjection/JobService.java | 28 +++++++++++++++++++ 2 files changed, 29 insertions(+) diff --git a/pom.xml b/pom.xml index 7ac77dc..3d5db6d 100644 --- a/pom.xml +++ b/pom.xml @@ -146,6 +146,7 @@ org.slf4j jcl-over-slf4j + test diff --git a/src/main/java/com/guicedee/guicedinjection/JobService.java b/src/main/java/com/guicedee/guicedinjection/JobService.java index 89f8681..8c09c52 100644 --- a/src/main/java/com/guicedee/guicedinjection/JobService.java +++ b/src/main/java/com/guicedee/guicedinjection/JobService.java @@ -35,8 +35,13 @@ public class JobService private static TimeUnit defaultWaitUnit = TimeUnit.SECONDS; private static final JobService INSTANCE = new JobService(); + private static ExecutorService jobCleanup = null; public static JobService getInstance(){ + if (jobCleanup == null) + { + jobCleanup = INSTANCE.jobCleanup(); + } return INSTANCE; } @@ -223,6 +228,29 @@ public void waitForJob(String jobName, long timeout, TimeUnit unit) service.close(); } + private ExecutorService jobCleanup() + { + ScheduledExecutorService jobsShutdownNotClosed = addPollingJob("JobsShutdownNotClosed", () -> { + for (String jobPool : getInstance().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 * From 6ddcfac8e2f96bd2c56839d6543fb0e4f116fef6 Mon Sep 17 00:00:00 2001 From: GedMarc Date: Sun, 25 Feb 2024 23:52:55 +0200 Subject: [PATCH 14/23] Add MicroProfile Config --- src/jre8/java/.gitignore | 20 -------------------- src/jre8/resources/.gitignore | 20 -------------------- 2 files changed, 40 deletions(-) delete mode 100644 src/jre8/java/.gitignore delete mode 100644 src/jre8/resources/.gitignore diff --git a/src/jre8/java/.gitignore b/src/jre8/java/.gitignore deleted file mode 100644 index a727ce1..0000000 --- a/src/jre8/java/.gitignore +++ /dev/null @@ -1,20 +0,0 @@ -/build/ -/dist/ -Thumbs.db -/javadoc/ -/.jacocoverage/ -/build -/target/ -/out/ -/**/.sonar/ -**.jacocoverage/ -**/*.iml -*.iml -**/*.tloh -**/*.tlog -**/*.db - -**/*.factorypath -**/*.flattened-pom.xml -**/flatter.pom -flatter.pom \ No newline at end of file diff --git a/src/jre8/resources/.gitignore b/src/jre8/resources/.gitignore deleted file mode 100644 index a727ce1..0000000 --- a/src/jre8/resources/.gitignore +++ /dev/null @@ -1,20 +0,0 @@ -/build/ -/dist/ -Thumbs.db -/javadoc/ -/.jacocoverage/ -/build -/target/ -/out/ -/**/.sonar/ -**.jacocoverage/ -**/*.iml -*.iml -**/*.tloh -**/*.tlog -**/*.db - -**/*.factorypath -**/*.flattened-pom.xml -**/flatter.pom -flatter.pom \ No newline at end of file From c2d44ce19716f6933beb2afc0ac3dfacaf4969fe Mon Sep 17 00:00:00 2001 From: GedMarc Date: Thu, 29 Feb 2024 01:13:39 +0200 Subject: [PATCH 15/23] Client update for more decentralized functionality --- .../guicedinjection/GuiceContext.java | 524 ++++++++---------- .../guicedee/guicedinjection/JobService.java | 87 +-- .../GuiceContextProvision.java | 15 + .../implementations/JobServiceProvision.java | 14 + .../injections/ContextBinderGuice.java | 6 +- .../guicedinjection/pairing/OptionalPair.java | 75 --- .../guicedinjection/pairing/Pair.java | 145 ----- .../properties/GlobalProperties.java | 218 -------- .../representations/ICopyable.java | 3 +- src/main/java/module-info.java | 11 +- ....guicedinjection.interfaces.IGuiceProvider | 1 + ...edinjection.interfaces.IJobServiceProvider | 1 + .../com/guicedee/tests/FileSearchTest.java | 6 +- .../com/guicedee/tests/GuiceContextTest.java | 4 +- .../com/guicedee/tests/IGuiceConfigTest.java | 5 +- .../com/guicedee/tests/OptionalPairTest.java | 3 +- .../java/com/guicedee/tests/PsvmTest.java | 4 +- 17 files changed, 340 insertions(+), 782 deletions(-) create mode 100644 src/main/java/com/guicedee/guicedinjection/implementations/GuiceContextProvision.java create mode 100644 src/main/java/com/guicedee/guicedinjection/implementations/JobServiceProvision.java delete mode 100644 src/main/java/com/guicedee/guicedinjection/pairing/OptionalPair.java delete mode 100644 src/main/java/com/guicedee/guicedinjection/pairing/Pair.java delete mode 100644 src/main/java/com/guicedee/guicedinjection/properties/GlobalProperties.java create mode 100644 src/main/resources/META-INF/services/com.guicedee.guicedinjection.interfaces.IGuiceProvider create mode 100644 src/main/resources/META-INF/services/com.guicedee.guicedinjection.interfaces.IJobServiceProvider diff --git a/src/main/java/com/guicedee/guicedinjection/GuiceContext.java b/src/main/java/com/guicedee/guicedinjection/GuiceContext.java index f8c2a66..bb23574 100644 --- a/src/main/java/com/guicedee/guicedinjection/GuiceContext.java +++ b/src/main/java/com/guicedee/guicedinjection/GuiceContext.java @@ -18,6 +18,7 @@ import com.google.common.base.*; import com.google.inject.*; +import com.guicedee.client.*; import com.guicedee.guicedinjection.abstractions.*; import com.guicedee.guicedinjection.interfaces.*; import com.guicedee.guicedinjection.interfaces.annotations.*; @@ -44,7 +45,7 @@ */ @Log @SuppressWarnings("MissingClassJavaDoc") -public class GuiceContext> +public class GuiceContext> implements IGuiceContext { /** * This particular instance of the class @@ -54,7 +55,7 @@ public class GuiceContext> /** * A list of all the loaded singleton sets */ - private static final Map allLoadedServices = new LinkedHashMap<>(); + //private static final Map allLoadedServices = new LinkedHashMap<>(); /** * The building injector */ @@ -92,8 +93,6 @@ private GuiceContext() //No config required } - private static Set registerModuleForScanning = new LinkedHashSet<>(); - private static List modules = new ArrayList<>(); /** * Reference the Injector Directly @@ -101,7 +100,7 @@ private GuiceContext() * @return The global Guice Injector Object, Never Null, Instantiates the Injector if not configured */ @NotNull - public static synchronized Injector inject() + public synchronized Injector inject() { if (GuiceContext.buildingInjector) { @@ -114,36 +113,53 @@ public static synchronized Injector inject() { GuiceContext.buildingInjector = true; GuiceContext.log.info("Starting up Guice Context"); - GuiceContext.instance() - .loadConfiguration(); - if (GuiceContext.instance() - .getConfig() - .isPathScanning() || - GuiceContext.instance() - .getConfig() - .isClasspathScanning()) + GuiceContext + .instance() + .loadConfiguration(); + if (GuiceContext + .instance() + .getConfig() + .isPathScanning() || GuiceContext + .instance() + .getConfig() + .isClasspathScanning()) { - GuiceContext.instance() - .loadScanner(); + GuiceContext + .instance() + .loadScanner(); } - GuiceContext.instance() - .loadPreStartups(); + GuiceContext + .instance() + .loadPreStartups(); List cModules = new ArrayList<>(modules); - Set iGuiceModules = GuiceContext.instance().loadIGuiceModules(); + Set iGuiceModules = GuiceContext + .instance() + .loadIGuiceModules(); cModules.addAll(iGuiceModules); //cModules.add(new GuiceInjectorModule()); GuiceContext.instance().injector = Guice.createInjector(cModules); GuiceContext.buildingInjector = false; - GuiceContext.instance() - .loadPostStartups(); + GuiceContext + .instance() + .loadPostStartups(); - Runtime.getRuntime() - .addShutdownHook(new Thread(GuiceContext::destroy)); + Runtime + .getRuntime() + .addShutdownHook(new Thread() + { + public void run() + { + IGuiceContext + .getContext() + .destroy(); + } + }); GuiceContext.log.config("Injection System Ready"); - } catch (Throwable e) + } + catch (Throwable e) { GuiceContext.log.log(Level.SEVERE, "Exception creating Injector : " + e.getMessage(), e); throw new RuntimeException("Unable to boot Guice Injector", e); @@ -153,155 +169,15 @@ public static synchronized Injector inject() 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 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 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; - } + private static Set destroyers = GuiceContext + .instance() + .getLoader(IGuicePreDestroy.class, false, ServiceLoader.load(IGuicePreDestroy.class)); - private static Set destroyers = GuiceContext.instance() - .getLoader(IGuicePreDestroy.class, false, ServiceLoader.load(IGuicePreDestroy.class)); /** * Execute on Destroy */ @SuppressWarnings("unused") - public static void destroy() + public void destroy() { try { @@ -310,12 +186,17 @@ public static void destroy() try { destroyer.onDestroy(); - } catch (Throwable T) + } + catch (Throwable T) { - log.log(Level.SEVERE, "Could not run destroyer [" + destroyer.getClass().getCanonicalName() + "]"); + log.log(Level.SEVERE, + "Could not run destroyer [" + destroyer + .getClass() + .getCanonicalName() + "]"); } } - } catch (Throwable T) + } + catch (Throwable T) { log.log(Level.SEVERE, "Could not run destroyers", T); } @@ -336,6 +217,7 @@ public static void destroy() * 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() @@ -402,12 +284,12 @@ private void loadConfiguration() Set guiceConfigurators = loadIGuiceConfigs(); for (IGuiceConfigurator guiceConfigurator : guiceConfigurators) { - GuiceContext.log.config("Loading IGuiceConfigurator - " + - guiceConfigurator.getClass() - .getCanonicalName()); + GuiceContext.log.config("Loading IGuiceConfigurator - " + guiceConfigurator + .getClass() + .getCanonicalName()); guiceConfigurator.configure(GuiceContext.config); } - if(!GuiceContext.config.isIncludeModuleAndJars()) + 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"); } @@ -426,8 +308,9 @@ private String[] getJarsExclusionList() { Set strings = new TreeSet<>(); Set exclusions = loadJarRejectScanners(); - if (exclusions.iterator() - .hasNext()) + if (exclusions + .iterator() + .hasNext()) { for (IGuiceScanJarExclusions exclusion : exclusions) { @@ -449,8 +332,9 @@ private String[] getJarsInclusionList() { Set strings = new TreeSet<>(); Set exclusions = loadJarInclusionScanners(); - if (exclusions.iterator() - .hasNext()) + if (exclusions + .iterator() + .hasNext()) { for (IGuiceScanJarInclusions exclusion : exclusions) { @@ -479,23 +363,25 @@ private synchronized void loadScanner() { if (async) { - scanResult = scanner.scan(Runtime.getRuntime() - .availableProcessors()); - } else + 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)); + fileScans.forEach((key, value) -> scanResult + .getResourcesWithLeafName(key) + .forEachByteArrayIgnoringIOException(value)); + quickScanFilesPattern().forEach((key, value) -> scanResult + .getResourcesMatchingPattern(key) + .forEachByteArrayIgnoringIOException(value)); - } catch (Exception mpe) + } + catch (Exception mpe) { GuiceContext.log.log(Level.SEVERE, "Unable to run scanner", mpe); } @@ -536,13 +422,15 @@ private ClassGraph configureScanner(ClassGraph graph) { graph = graph.rejectJars(jarRejections); } - } else + } + else { String[] modulesRejection = getModulesExclusionList(); if (modulesRejection.length != 0) { graph = graph.rejectModules(modulesRejection); - } else + } + else { graph = graph.ignoreParentModuleLayers(); } @@ -559,14 +447,16 @@ private ClassGraph configureScanner(ClassGraph graph) { graph = graph.acceptJars(jarRejections); } - } else + } + else { String[] modulesRejection = getModulesInclusionsList(); log.config("Accepted Modules for Scanning : " + Arrays.toString(modulesRejection)); if (modulesRejection.length != 0) { graph = graph.acceptModules(modulesRejection); - } else + } + else { graph = graph.ignoreParentModuleLayers(); } @@ -642,14 +532,16 @@ private String[] getPackagesList() { Set strings = new LinkedHashSet<>(); Set exclusions = getLoader(IPackageContentsScanner.class, true, ServiceLoader.load(IPackageContentsScanner.class)); - if (exclusions.iterator() - .hasNext()) + if (exclusions + .iterator() + .hasNext()) { for (IPackageContentsScanner exclusion : exclusions) { - GuiceContext.log.log(Level.CONFIG, "Loading IPackageContentsScanner - " + - exclusion.getClass() - .getCanonicalName()); + GuiceContext.log.log(Level.CONFIG, + "Loading IPackageContentsScanner - " + exclusion + .getClass() + .getCanonicalName()); Set searches = exclusion.searchFor(); strings.addAll(searches); } @@ -667,14 +559,16 @@ private String[] getBlacklistPackages() { Set strings = new LinkedHashSet<>(); Set exclusions = getLoader(IPackageRejectListScanner.class, true, ServiceLoader.load(IPackageRejectListScanner.class)); - if (exclusions.iterator() - .hasNext()) + if (exclusions + .iterator() + .hasNext()) { for (IPackageRejectListScanner exclusion : exclusions) { - GuiceContext.log.log(Level.CONFIG, "Loading IPackageContentsScanner - " + - exclusion.getClass() - .getCanonicalName()); + GuiceContext.log.log(Level.CONFIG, + "Loading IPackageContentsScanner - " + exclusion + .getClass() + .getCanonicalName()); Set searches = exclusion.exclude(); strings.addAll(searches); } @@ -692,14 +586,16 @@ private String[] getPathsList() { Set strings = new TreeSet<>(); Set exclusions = getLoader(IPathContentsScanner.class, true, ServiceLoader.load(IPathContentsScanner.class)); - if (exclusions.iterator() - .hasNext()) + if (exclusions + .iterator() + .hasNext()) { for (IPathContentsScanner exclusion : exclusions) { - GuiceContext.log.log(Level.CONFIG, "Loading IPathScanningContentsScanner - " + - exclusion.getClass() - .getCanonicalName()); + GuiceContext.log.log(Level.CONFIG, + "Loading IPathScanningContentsScanner - " + exclusion + .getClass() + .getCanonicalName()); Set searches = exclusion.searchFor(); strings.addAll(searches); } @@ -717,14 +613,16 @@ private String[] getPathsBlacklistList() { Set strings = new TreeSet<>(); Set exclusions = loadPathRejectScanners(); - if (exclusions.iterator() - .hasNext()) + if (exclusions + .iterator() + .hasNext()) { for (IPathContentsRejectListScanner exclusion : exclusions) { - GuiceContext.log.log(Level.CONFIG, "Loading IPathContentsRejectListScanner - " + - exclusion.getClass() - .getCanonicalName()); + GuiceContext.log.log(Level.CONFIG, + "Loading IPathContentsRejectListScanner - " + exclusion + .getClass() + .getCanonicalName()); Set searches = exclusion.searchFor(); strings.addAll(searches); } @@ -743,8 +641,9 @@ private String[] getModulesExclusionList() { Set strings = new TreeSet<>(); Set exclusions = getLoader(IGuiceScanModuleExclusions.class, true, ServiceLoader.load(IGuiceScanModuleExclusions.class)); - if (exclusions.iterator() - .hasNext()) + if (exclusions + .iterator() + .hasNext()) { for (IGuiceScanModuleExclusions exclusion : exclusions) { @@ -755,24 +654,27 @@ private String[] getModulesExclusionList() } return strings.toArray(new String[0]); } - - /** + /* + *//** * Registers a module for scanning when filtering is enabled * * @param javaModuleName The name in the module-info.java file + * * @return This instance - */ + *//* @SuppressWarnings("unchecked") public static void registerModule(String javaModuleName) { instance().registerModuleForScanning.add(javaModuleName); - instance().getConfig().setIncludeModuleAndJars(true); + instance() + .getConfig() + .setIncludeModuleAndJars(true); } public static void registerModule(com.google.inject.Module module) { instance().modules.add(module); - } + }*/ /** * Returns a complete list of generic exclusions @@ -785,8 +687,9 @@ private String[] getModulesInclusionsList() Set strings = new TreeSet<>(); strings.addAll(registerModuleForScanning); Set exclusions = getLoader(IGuiceScanModuleInclusions.class, true, ServiceLoader.load(IGuiceScanModuleInclusions.class)); - if (exclusions.iterator() - .hasNext()) + if (exclusions + .iterator() + .hasNext()) { for (IGuiceScanModuleInclusions exclusion : exclusions) { @@ -807,9 +710,10 @@ private Map quickScanFiles() Set fileScanners = getLoader(IFileContentsScanner.class, true, ServiceLoader.load(IFileContentsScanner.class)); for (IFileContentsScanner fileScanner : fileScanners) { - GuiceContext.log.log(Level.CONFIG, "Loading IFileContentsScanner - " + - fileScanner.getClass() - .getCanonicalName()); + GuiceContext.log.log(Level.CONFIG, + "Loading IFileContentsScanner - " + fileScanner + .getClass() + .getCanonicalName()); fileScans.putAll(fileScanner.onMatch()); } return fileScans; @@ -824,9 +728,10 @@ private Map quickScanFilesPattern() Set fileScanners = getLoader(IFileContentsPatternScanner.class, true, ServiceLoader.load(IFileContentsPatternScanner.class)); for (IFileContentsPatternScanner fileScanner : fileScanners) { - GuiceContext.log.log(Level.CONFIG, "Loading IFileContentsPatternScanner - " + - fileScanner.getClass() - .getCanonicalName()); + GuiceContext.log.log(Level.CONFIG, + "Loading IFileContentsPatternScanner - " + fileScanner + .getClass() + .getCanonicalName()); fileScans.putAll(fileScanner.onMatch()); } return fileScans; @@ -838,20 +743,25 @@ private Map quickScanFilesPattern() * @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) + public Set getLoader(Class loaderType, @SuppressWarnings("unused") boolean dontInject, ServiceLoader serviceLoader) { - if (!getAllLoadedServices().containsKey(loaderType)) + if (!IGuiceContext + .getAllLoadedServices() + .containsKey(loaderType)) { - Set loader = loaderToSetNoInjection(serviceLoader); - getAllLoadedServices().put(loaderType, loader); + Set loader = IGuiceContext.loaderToSetNoInjection(serviceLoader); + IGuiceContext + .getAllLoadedServices() + .put(loaderType, loader); } - return getAllLoadedServices().get(loaderType); + return IGuiceContext + .getAllLoadedServices() + .get(loaderType); } /** @@ -887,8 +797,9 @@ private void loadPostStartups() for (IGuicePostStartup postStartup : startupSet) { Integer sortOrder = postStartup.sortOrder(); - postStartupGroups.computeIfAbsent(sortOrder, k -> new TreeSet<>()) - .add(postStartup); + postStartupGroups + .computeIfAbsent(sortOrder, k -> new TreeSet<>()) + .add(postStartup); } for (Map.Entry> entry : postStartupGroups.entrySet()) @@ -903,23 +814,29 @@ private void loadPostStartups() try { iGuicePostStartup.postLoad(); - } catch (Throwable T) + } + catch (Throwable T) { - log.log(Level.SEVERE, "Cannot execute post startup - " + iGuicePostStartup.getClass() - .getCanonicalName(), T); + log.log(Level.SEVERE, + "Cannot execute post startup - " + iGuicePostStartup + .getClass() + .getCanonicalName(), + T); } } - } else + } + else { log.info("Starting Post Startup Group [" + key + "] in Parallel"); ExecutorService postStartup = null; for (IGuicePostStartup iGuicePostStartup : value) { - postStartup = JobService.getInstance().addJob("PostStartup", () -> { + postStartup = JobService.INSTANCE.addJob("PostStartup", () -> { try { iGuicePostStartup.postLoad(); - } catch (Throwable T) + } + catch (Throwable T) { log.log(Level.SEVERE, "Cannot execute post startup - ", T); } @@ -930,9 +847,10 @@ private void loadPostStartups() if (postStartup != null) { log.config("Waiting for post startup group to finish...."); - JobService.getInstance().removeJob("PostStartup"); + JobService.INSTANCE.removeJob("PostStartup"); } - } catch (Throwable e) + } + catch (Throwable e) { log.log(Level.SEVERE, "Cannot execute post startup - ", e); } @@ -964,8 +882,7 @@ public GuiceConfig getConfig() * * @return The list of guice post startups */ - public @NotNull - Set loadPostStartupServices() + public @NotNull Set loadPostStartupServices() { return getLoader(IGuicePostStartup.class, ServiceLoader.load(IGuicePostStartup.class)); } @@ -975,8 +892,7 @@ Set loadPostStartupServices() * * @return The list of guice post startups */ - public @NotNull - Set loadPathRejectScanners() + public @NotNull Set loadPathRejectScanners() { return getLoader(IPathContentsRejectListScanner.class, true, ServiceLoader.load(IPathContentsRejectListScanner.class)); } @@ -987,8 +903,7 @@ Set loadPathRejectScanners() * * @return The list of guice post startups */ - public @NotNull - Set loadJarRejectScanners() + public @NotNull Set loadJarRejectScanners() { return getLoader(IGuiceScanJarExclusions.class, true, ServiceLoader.load(IGuiceScanJarExclusions.class)); } @@ -999,8 +914,7 @@ Set loadJarRejectScanners() * * @return The list of guice post startups */ - public @NotNull - Set loadJarInclusionScanners() + public @NotNull Set loadJarInclusionScanners() { return getLoader(IGuiceScanJarInclusions.class, true, ServiceLoader.load(IGuiceScanJarInclusions.class)); } @@ -1011,8 +925,7 @@ Set loadJarInclusionScanners() * * @return The list of guice post startups */ - public @NotNull - Set loadPreStartupServices() + public @NotNull Set loadPreStartupServices() { return getLoader(IGuicePreStartup.class, true, ServiceLoader.load(IGuicePreStartup.class)); } @@ -1022,8 +935,7 @@ Set loadPreStartupServices() * * @return The list of guice post startups */ - public @NotNull - Set loadIGuiceModules() + public @NotNull Set loadIGuiceModules() { return getLoader(IGuiceModule.class, true, ServiceLoader.load(IGuiceModule.class)); } @@ -1033,8 +945,7 @@ Set loadIGuiceModules() * * @return The list of guice configs */ - public @NotNull - Set loadIGuiceConfigs() + public @NotNull Set loadIGuiceConfigs() { return getLoader(IGuiceConfigurator.class, true, ServiceLoader.load(IGuiceConfigurator.class)); } @@ -1049,9 +960,9 @@ private void loadPreStartups() startups.sort(Comparator.comparing(IGuicePreStartup::sortOrder)); for (IGuicePreStartup startup : startups) { - GuiceContext.log.config("Loading IGuicePreStartup - " + - startup.getClass() - .getCanonicalName()); + GuiceContext.log.config("Loading IGuicePreStartup - " + startup + .getClass() + .getCanonicalName()); startup.onStartup(); } } @@ -1062,25 +973,33 @@ private void loadPreStartups() * * @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)) + if (!IGuiceContext + .getAllLoadedServices() + .containsKey(loaderType)) { Set loader; if (GuiceContext.buildingInjector || injector == null) { - loader = loaderToSetNoInjection(serviceLoader); - } else + loader = IGuiceContext.loaderToSetNoInjection(serviceLoader); + } + else { - loader = loaderToSet(serviceLoader); + loader = IGuiceContext.loaderToSet(serviceLoader); } - getAllLoadedServices().put(loaderType, loader); + IGuiceContext + .getAllLoadedServices() + .put(loaderType, loader); } - return getAllLoadedServices().get(loaderType); + return IGuiceContext + .getAllLoadedServices() + .get(loaderType); } /** @@ -1091,18 +1010,17 @@ public > Set getLoader(Class loaderType, ServiceLo * @return the allLoadedServices (type Map Class, Set ) of this GuiceContext object. */ @SuppressWarnings("WeakerAccess") - @NotNull + /*@NotNull public static Map getAllLoadedServices() { return allLoadedServices; - } + }*/ /** * If this scanner is registered to run asynchronously * * @return - */ - public boolean isAsync() + */ public boolean isAsync() { return async; } @@ -1117,16 +1035,17 @@ public void setAsync(boolean async) this.async = async; } - Map> loaderClasses = new ConcurrentHashMap<>(); + //Map> loaderClasses = new ConcurrentHashMap<>(); /** * Method loaderToSet, converts a ServiceLoader into a TreeSet * * @param loader of type ServiceLoader + * * @return Set */ - @SuppressWarnings("unchecked") - @NotNull + //@SuppressWarnings("unchecked") + /*@NotNull public > Set loaderToSet(ServiceLoader loader) { @SuppressWarnings("rawtypes") @@ -1138,12 +1057,14 @@ public > Set loaderToSet(ServiceLoader loader) if (!loaderClasses.containsKey(type)) { - GuiceConfig config = GuiceContext.instance().getConfig(); + GuiceConfig config = GuiceContext + .instance() + .getConfig(); if (config.isServiceLoadWithClassPath()) { for (ClassInfo classInfo : instance() - .getScanResult() - .getClassesImplementing(type)) + .getScanResult() + .getClassesImplementing(type)) { Class load = (Class) classInfo.loadClass(); loadeds.add(load); @@ -1155,7 +1076,8 @@ public > Set loaderToSet(ServiceLoader loader) { loadeds.add(newInstance.getClass()); } - } catch (Throwable T) + } + catch (Throwable T) { log.log(Level.SEVERE, "Unable to provide instance of " + type + " to TreeSet", T); } @@ -1165,12 +1087,12 @@ public > Set loaderToSet(ServiceLoader loader) Set outcomes = new TreeSet<>(); for (Class aClass : loaderClasses.get(type)) { - outcomes.add((T) GuiceContext.get(aClass)); + outcomes.add((T) IGuiceContext.get(aClass)); } return outcomes; - } + }*/ - public > Set> loadClassSet(ServiceLoader loader) + /*public > Set> loadClassSet(ServiceLoader loader) { String type = loader.toString(); type = type.replace("java.util.ServiceLoader[", ""); @@ -1179,12 +1101,14 @@ public > Set> loadClassSet(ServiceLoader loa if (!loaderClasses.containsKey(type)) { Set loadeds = new HashSet<>(); - GuiceConfig config = GuiceContext.instance().getConfig(); + GuiceConfig config = GuiceContext + .instance() + .getConfig(); if (config.isServiceLoadWithClassPath()) { for (ClassInfo classInfo : instance() - .getScanResult() - .getClassesImplementing(type)) + .getScanResult() + .getClassesImplementing(type)) { @SuppressWarnings("unchecked") Class load = (Class) classInfo.loadClass(); @@ -1198,7 +1122,8 @@ public > Set> loadClassSet(ServiceLoader loa //noinspection unchecked loadeds.add((Class) newInstance.getClass()); } - } catch (Throwable T) + } + catch (Throwable T) { log.log(Level.SEVERE, "Unable to provide instance of " + type + " to TreeSet", T); } @@ -1206,29 +1131,31 @@ public > Set> loadClassSet(ServiceLoader loa } //noinspection unchecked return (Set) loaderClasses.get(type); - } + }*/ /** * Method loaderToSet, converts a ServiceLoader into a TreeSet * * @param loader of type ServiceLoader + * * @return Set */ - @SuppressWarnings("unchecked") + /*@SuppressWarnings("unchecked") @NotNull public Set loaderToSetNoInjection(ServiceLoader loader) { Set> loadeds = new HashSet<>(); - GuiceConfig config = GuiceContext.instance().getConfig(); + 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 && instance() - .getScanResult() != null) + if (config.isServiceLoadWithClassPath() && !buildingInjector && instance().getScanResult() != null) { for (ClassInfo classInfo : instance() - .getScanResult() - .getClassesImplementing(type)) + .getScanResult() + .getClassesImplementing(type)) { Class load = (Class) classInfo.loadClass(); loadeds.add(load); @@ -1243,10 +1170,12 @@ public Set loaderToSetNoInjection(ServiceLoader loader) output.add(newInstance); completed.add((Class) newInstance.getClass()); } - } catch (java.util.ServiceConfigurationError T) + } + catch (java.util.ServiceConfigurationError T) { log.log(Level.WARNING, "Cannot load services - ", T); - }catch (Throwable T) + } + catch (Throwable T) { log.log(Level.SEVERE, "Cannot load services - ", T); } @@ -1259,11 +1188,12 @@ public Set loaderToSetNoInjection(ServiceLoader loader) try { output.add((T) newInstance.getDeclaredConstructor()); - } catch (NoSuchMethodException e) + } + catch (NoSuchMethodException e) { log.log(Level.SEVERE, "Cannot load a service through default constructor", e); } } return output; - } + }*/ } diff --git a/src/main/java/com/guicedee/guicedinjection/JobService.java b/src/main/java/com/guicedee/guicedinjection/JobService.java index 8c09c52..5cc584a 100644 --- a/src/main/java/com/guicedee/guicedinjection/JobService.java +++ b/src/main/java/com/guicedee/guicedinjection/JobService.java @@ -1,7 +1,7 @@ package com.guicedee.guicedinjection; import com.google.inject.Singleton; -import com.guicedee.guicedinjection.interfaces.IGuicePreDestroy; +import com.guicedee.guicedinjection.interfaces.*; import lombok.Getter; import lombok.Setter; import lombok.extern.java.Log; @@ -18,8 +18,7 @@ @Singleton @Log -public class JobService - implements IGuicePreDestroy +public class JobService implements IGuicePreDestroy, IJobService { private final Map serviceMap = new ConcurrentHashMap<>(); private final Map pollingMap = new ConcurrentHashMap<>(); @@ -34,17 +33,9 @@ public class JobService @Setter private static TimeUnit defaultWaitUnit = TimeUnit.SECONDS; - private static final JobService INSTANCE = new JobService(); + public static final JobService INSTANCE = new JobService(); private static ExecutorService jobCleanup = null; - public static JobService getInstance(){ - if (jobCleanup == null) - { - jobCleanup = INSTANCE.jobCleanup(); - } - return INSTANCE; - } - public JobService() { //No config required @@ -55,6 +46,7 @@ public JobService() * * @return */ + @Override public Set getJobPools() { return serviceMap.keySet(); @@ -65,6 +57,7 @@ public Set getJobPools() * * @return */ + @Override public Set getPollingPools() { return pollingMap.keySet(); @@ -75,6 +68,7 @@ public Set getPollingPools() * * @param pool The pool to remove */ + @Override public ExecutorService removeJob(String pool) { ExecutorService es = serviceMap.get(pool); @@ -93,6 +87,7 @@ public ExecutorService removeJob(String pool) * * @param pool The pool name to remove */ + @Override public ScheduledExecutorService removePollingJob(String pool) { ScheduledExecutorService es = pollingMap.get(pool); @@ -112,6 +107,7 @@ public ScheduledExecutorService removePollingJob(String pool) * @param name * @param executorService */ + @Override public ExecutorService registerJobPool(String name, ExecutorService executorService) { if (serviceMap.containsKey(name)) @@ -126,7 +122,8 @@ public ExecutorService registerJobPool(String name, ExecutorService executorServ if (executorService instanceof ForkJoinPool) { ForkJoinPool pool = (ForkJoinPool) executorService; - } else if (executorService instanceof ThreadPoolExecutor) + } + else if (executorService instanceof ThreadPoolExecutor) { ThreadPoolExecutor executor = (ThreadPoolExecutor) executorService; executor.setMaximumPoolSize(maxQueueCount.get(name)); @@ -143,6 +140,7 @@ public ExecutorService registerJobPool(String name, ExecutorService executorServ * @param name The name of the pool * @param executorService The service executor */ + @Override public ScheduledExecutorService registerJobPollingPool(String name, ScheduledExecutorService executorService) { if (pollingMap.containsKey(name)) @@ -159,9 +157,14 @@ public ScheduledExecutorService registerJobPollingPool(String name, ScheduledExe * @param jobPoolName * @param thread */ + @Override public ExecutorService addJob(String jobPoolName, Runnable thread) { - if (!serviceMap.containsKey(jobPoolName) || serviceMap.get(jobPoolName).isTerminated() || serviceMap.get(jobPoolName).isShutdown()) + if (!serviceMap.containsKey(jobPoolName) || serviceMap + .get(jobPoolName) + .isTerminated() || serviceMap + .get(jobPoolName) + .isShutdown()) { registerJobPool(jobPoolName, executorServiceSupplier.get()); } @@ -171,7 +174,7 @@ public ExecutorService addJob(String jobPoolName, Runnable thread) { log.log(Level.FINER, maxQueueCount + " Hit - Finishing before next run"); removeJob(jobPoolName); - service = registerJobPool(jobPoolName,executorServiceSupplier.get()); + service = registerJobPool(jobPoolName, executorServiceSupplier.get()); } service.execute(thread); return service; @@ -183,9 +186,14 @@ public ExecutorService addJob(String jobPoolName, Runnable thread) * @param jobPoolName * @param thread */ + @Override public Future addTask(String jobPoolName, Callable thread) { - if (!serviceMap.containsKey(jobPoolName) || serviceMap.get(jobPoolName).isTerminated() || serviceMap.get(jobPoolName).isShutdown()) + if (!serviceMap.containsKey(jobPoolName) || serviceMap + .get(jobPoolName) + .isTerminated() || serviceMap + .get(jobPoolName) + .isShutdown()) { registerJobPool(jobPoolName, executorServiceSupplier.get()); } @@ -200,11 +208,13 @@ public Future addTask(String jobPoolName, Callable thread) 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)) @@ -216,7 +226,8 @@ public void waitForJob(String jobName, long timeout, TimeUnit unit) try { service.awaitTermination(timeout, unit); - } catch (InterruptedException e) + } + catch (InterruptedException e) { log.log(Level.WARNING, "Thread didn't close cleanly, make sure running times are acceptable", e); service.shutdownNow(); @@ -231,15 +242,15 @@ public void waitForJob(String jobName, long timeout, TimeUnit unit) private ExecutorService jobCleanup() { ScheduledExecutorService jobsShutdownNotClosed = addPollingJob("JobsShutdownNotClosed", () -> { - for (String jobPool : getInstance().getJobPools()) + for (String jobPool : getJobPools()) { ExecutorService executorService = serviceMap.get(jobPool); - if(executorService.isShutdown() && !executorService.isTerminated()) + if (executorService.isShutdown() && !executorService.isTerminated()) { log.fine("Closing unfinished job - " + jobPool); removeJob(jobPool); } - if(executorService.isShutdown() && executorService.isTerminated()) + if (executorService.isShutdown() && executorService.isTerminated()) { log.fine("Cleaning terminated job - " + jobPool); executorService.close(); @@ -257,12 +268,19 @@ private ExecutorService jobCleanup() * @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()) + if (!pollingMap.containsKey(jobPoolName) || pollingMap + .get(jobPoolName) + .isTerminated() || pollingMap + .get(jobPoolName) + .isShutdown()) { - registerJobPollingPool(jobPoolName, Executors.newScheduledThreadPool(Runtime.getRuntime() - .availableProcessors())); + registerJobPollingPool(jobPoolName, + Executors.newScheduledThreadPool(Runtime + .getRuntime() + .availableProcessors())); } ScheduledExecutorService service = pollingMap.get(jobPoolName); service.scheduleAtFixedRate(thread, 1L, delay, unit); @@ -275,12 +293,19 @@ public ScheduledExecutorService addPollingJob(String jobPoolName, Runnable threa * @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()) + if (!pollingMap.containsKey(jobPoolName) || pollingMap + .get(jobPoolName) + .isTerminated() || pollingMap + .get(jobPoolName) + .isShutdown()) { - registerJobPollingPool(jobPoolName, Executors.newScheduledThreadPool(Runtime.getRuntime() - .availableProcessors())); + registerJobPollingPool(jobPoolName, + Executors.newScheduledThreadPool(Runtime + .getRuntime() + .availableProcessors())); } ScheduledExecutorService service = pollingMap.get(jobPoolName); service.scheduleAtFixedRate(thread, initialDelay, delay, unit); @@ -290,16 +315,15 @@ public ScheduledExecutorService addPollingJob(String jobPoolName, Runnable threa /** * Shutdowns */ + @Override public void destroy() { log.config("Destroying all running jobs..."); - serviceMap.forEach((key, value) -> - { + serviceMap.forEach((key, value) -> { log.config("Shutting Down [" + key + "]"); removeJob(key); }); - pollingMap.forEach((key, value) -> - { + pollingMap.forEach((key, value) -> { log.config("Shutting Down Poll Job [" + key + "]"); removePollingJob(key); }); @@ -312,7 +336,8 @@ private int getCurrentTaskCount(ExecutorService service) { ForkJoinPool pool = (ForkJoinPool) service; return (int) pool.getQueuedTaskCount(); - } else if (service instanceof ThreadPoolExecutor) + } + else if (service instanceof ThreadPoolExecutor) { ThreadPoolExecutor executor = (ThreadPoolExecutor) service; return (int) executor.getTaskCount(); 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/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 13ef1d9..c628429 100644 --- a/src/main/java/com/guicedee/guicedinjection/injections/ContextBinderGuice.java +++ b/src/main/java/com/guicedee/guicedinjection/injections/ContextBinderGuice.java @@ -6,7 +6,7 @@ import com.guicedee.guicedinjection.GuiceContext; import com.guicedee.guicedinjection.JobService; -import com.guicedee.guicedinjection.interfaces.IGuiceModule; +import com.guicedee.guicedinjection.interfaces.*; import com.guicedee.guicedinjection.properties.GlobalProperties; import io.github.classgraph.ScanResult; import lombok.extern.java.Log; @@ -43,7 +43,9 @@ public void configure() { .in(Singleton.class); ContextBinderGuice.log.fine("Bound JobService.class"); + bind(IJobService.class) + .toInstance(JobService.INSTANCE); bind(JobService.class) - .toInstance(JobService.getInstance()); + .toInstance(JobService.INSTANCE); } } diff --git a/src/main/java/com/guicedee/guicedinjection/pairing/OptionalPair.java b/src/main/java/com/guicedee/guicedinjection/pairing/OptionalPair.java deleted file mode 100644 index 0750857..0000000 --- a/src/main/java/com/guicedee/guicedinjection/pairing/OptionalPair.java +++ /dev/null @@ -1,75 +0,0 @@ -package com.guicedee.guicedinjection.pairing; - -import jakarta.validation.constraints.NotNull; -import java.util.Optional; - -/** - * Specifies a generic pair - * - * @param Key - * @param Value - */ -public class OptionalPair - extends Pair { - - /** - * Constructs a new blank pair - */ - public OptionalPair() { - //No config required - } - - /** - * Constructs a new key value pair - * - * @param key The key to use - * @param value the value to use - */ - public OptionalPair(K key, V value) { - super(key, value); - } - - @Override - public String toString() { - return "Key[" + getKey() + "];Value[" + getValue() + "]"; - } - - /** - * Sets the value for the given pair - * - * @param value The value to set - * @return Optional nullable of the value - */ - @Override - public OptionalPair setValue(V value) { - super.setValue(value); - return this; - } - - /** - * Sets the key for the given pair - * - * @param key The key to return - * @return The optional pair - */ - @Override - public OptionalPair setKey(@NotNull K key) { - super.setKey(key); - return this; - } - - public Optional getKeyOptional() { - return Optional.ofNullable(getKey()); - } - - /** - * Returns the optional object of the value - * - * @return Optional nullable of the value - */ - public Optional getValueOptional() { - return Optional.ofNullable(getValue()); - } - - -} diff --git a/src/main/java/com/guicedee/guicedinjection/pairing/Pair.java b/src/main/java/com/guicedee/guicedinjection/pairing/Pair.java deleted file mode 100644 index 765f7f0..0000000 --- a/src/main/java/com/guicedee/guicedinjection/pairing/Pair.java +++ /dev/null @@ -1,145 +0,0 @@ -package com.guicedee.guicedinjection.pairing; - -import jakarta.validation.constraints.NotNull; -import java.util.Objects; - -/** - * Specifies a generic pair - * - * @param Key - * @param Value - */ -public class Pair - implements Comparable> { - private static final Pair emptyPair = new Pair<>(null, null); - - /** - * The specified key - */ - private K key; - /** - * The specified value - */ - private V value; - - /** - * Constructs a new blank pair - */ - public Pair() { - //Nothing Needed - } - - /** - * Constructs a new key value pair - * - * @param key The key for the pair - * @param value The value for the pair - */ - public Pair(@NotNull K key, V value) { - this.key = key; - this.value = value; - } - - @Override - public String toString() { - return "Key[" + getKey() + "]-[" + getValue() + "}"; - } - - /** - * Gets the key for the given pair - * - * @return The key given - */ - public K getKey() { - return key; - } - - /** - * Returns the value for the given pair - * - * @return Sets this Pairs value - */ - public V getValue() { - return value; - } - - /** - * Sets the value for the given pair - * - * @param value Sets this pairs values - * @return this Pair - */ - public Pair setValue(V value) { - this.value = value; - return this; - } - - /** - * Sets the key for the given pair - * - * @param key Sets this pairs key - * @return The pair - */ - public Pair setKey(@NotNull K key) { - this.key = key; - return this; - } - - @Override - public int compareTo(@NotNull Pair o) { - return getKey().toString() - .compareTo(o.getKey() - .toString()); - } - - /** - * Returns an empty pair - * - * @return An empty pair - */ - @SuppressWarnings("unchecked") - public static Pair empty() { - return (Pair) emptyPair; - } - - /** - * If the pair is empty - * - * @return if the key is null - */ - public boolean isEmpty() { - return key == null; - } - - /** - * Returns a new instance of a pair - * - * @param key The key - * @param value The value - * @param The key type - * @param The value type - * @return The new instance of Pair - */ - public static Pair of(K key, V value) { - return new Pair<>(key, value); - } - - @Override - public boolean equals(Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - Pair pair = (Pair) o; - return Objects.equals(getKey(), pair.getKey()); - } - - @Override - public int hashCode() { - return Objects.hash(getKey()); - } - - -} diff --git a/src/main/java/com/guicedee/guicedinjection/properties/GlobalProperties.java b/src/main/java/com/guicedee/guicedinjection/properties/GlobalProperties.java deleted file mode 100644 index 34799d3..0000000 --- a/src/main/java/com/guicedee/guicedinjection/properties/GlobalProperties.java +++ /dev/null @@ -1,218 +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.properties; - -import com.fasterxml.jackson.annotation.*; -import com.fasterxml.jackson.core.*; -import com.fasterxml.jackson.databind.*; -import com.google.inject.*; -import com.guicedee.guicedinjection.*; -import lombok.extern.java.Log; - -import java.util.*; -import java.util.logging.*; - -import static com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility.*; -import static com.fasterxml.jackson.annotation.JsonInclude.Include.*; - -/** - * A pretty class for containing EAR or Container level global properties. - *

- * Key to Map ID to Property - * - * @author GedMarc - * @since 08 Jul 2017 - */ -@SuppressWarnings("MissingClassJavaDoc") -@Singleton -@JsonAutoDetect(fieldVisibility = ANY, - getterVisibility = NONE, - setterVisibility = NONE) -@JsonInclude(NON_NULL) -@Log -public class GlobalProperties -{ - private final Map> globalProperties; - - /** - * Constructs a new GlobalProperties - */ - public GlobalProperties() - { - globalProperties = new HashMap<>(); - } - - /** - * Adds a key to the global application library - * - * @param key Adds a key into the global library - * @param properties Puts the property map into the global settings - */ - public void addKey(String key, Map properties) - { - globalProperties.put(key, properties); - } - - /** - * Adds a normal string string property to the library - * - * @param key Takes the key for the property - * @param property The property to apply - * @param value The value to apply - */ - public void addProperty(String key, String property, String value) - { - if (!globalProperties.containsKey(key)) - { - globalProperties.put(key, new HashMap<>()); - } - globalProperties.get(key) - .put(property, value); - } - - /** - * Adds a normal string string property to the library - * - * @param key The key and property to add - * @param property The property to add - * @param value The value to add - */ - public void addProperty(String key, String property, Object value) - { - if (!globalProperties.containsKey(key)) - { - globalProperties.put(key, new HashMap<>()); - } - globalProperties.get(key) - .put(property, value); - } - - /** - * Gets the key with the given map return type - * - * @param The key type - * @param The value map type - * @param key The key - * @return A map to return - */ - @SuppressWarnings({"unchecked", "UnusedReturnValue"}) - public Map getKey(String key) - { - return (Map) globalProperties.get(key); - } - - /** - * Gets a default string key and property mapping - * - * @param The value type - * @param key The key - * @param property And properties map to retrieve from - * @return The value of the mapped key and map ID - */ - @SuppressWarnings("unchecked") - public V getProperty(String key, String property) - { - return (V) globalProperties.get(key) - .get(property); - } - - /** - * Removes a property from any list - * - * @param key The key to remove - * @param property The property to remove from the assigned map - */ - public void removeProperty(String key, String property) - { - if (globalProperties.containsKey(key)) - { - globalProperties.get(key) - .remove(property); - } - } - - /** - * Sets the property - * - * @param key The key to remove - * @param property The property to return - */ - public void emptyProperty(String key, String property) - { - if (globalProperties.containsKey(key)) - { - globalProperties.get(key) - .put(property, ""); - } - } - - /** - * Returns a JSON implementation of the toString() - * - * @return A JSON Representation - */ - @Override - public String toString() - { - try - { - return GuiceContext.get(ObjectMapper.class) - .writeValueAsString(this); - } - catch (JsonProcessingException e) - { - log.log(Level.SEVERE, "Non-Mappable character in GlobalProperties Map, Can't toString()", e); - return super.toString(); - } - } - - public static String getSystemPropertyOrEnvironment(String name, String defaultValue) - { - if (System.getProperty(name) != null) - { - return System.getProperty(name); - } - if (System.getenv(name) != null) - { - try - { - System.setProperty(name, System.getenv(name)); - return System.getProperty(name); - }catch (Throwable T) - { - log.log(Level.WARNING,"Couldn't set system property value [" + name + "] - [" + defaultValue + "]"); - return System.getenv(name); - } - } - else { - if (defaultValue == null) - { - return null; - } - log.log(Level.WARNING,"Return default value for property [" + name + "] - [" + defaultValue + "]"); - try - { - System.setProperty(name, defaultValue); - return System.getProperty(name); - }catch (Throwable T) - { - log.log(Level.WARNING,"Couldn't set system property value [" + name + "] - [" + defaultValue + "]"); - return defaultValue; - } - } - } -} diff --git a/src/main/java/com/guicedee/guicedinjection/representations/ICopyable.java b/src/main/java/com/guicedee/guicedinjection/representations/ICopyable.java index bce8854..4e65e85 100644 --- a/src/main/java/com/guicedee/guicedinjection/representations/ICopyable.java +++ b/src/main/java/com/guicedee/guicedinjection/representations/ICopyable.java @@ -3,6 +3,7 @@ import com.fasterxml.jackson.databind.*; import com.google.inject.Key; import com.google.inject.name.Names; +import com.guicedee.client.*; import com.guicedee.guicedinjection.GuiceContext; import lombok.extern.java.Log; @@ -64,7 +65,7 @@ default Map asMap(Field[] fields) */ default J updateFrom(Object source) { - ObjectMapper om = GuiceContext.get(Key.get(ObjectMapper.class, Names.named("Default"))); + ObjectMapper om = IGuiceContext.get(Key.get(ObjectMapper.class, Names.named("Default"))); try { String jsonFromSource = om.writeValueAsString(source); diff --git a/src/main/java/module-info.java b/src/main/java/module-info.java index 6b88e06..d5d892c 100644 --- a/src/main/java/module-info.java +++ b/src/main/java/module-info.java @@ -1,5 +1,6 @@ import com.guicedee.guicedinjection.JobService; -import com.guicedee.guicedinjection.interfaces.IGuicePreDestroy; +import com.guicedee.guicedinjection.implementations.*; +import com.guicedee.guicedinjection.interfaces.*; module com.guicedee.guicedinjection { requires transitive com.guicedee.client; @@ -17,9 +18,8 @@ exports com.guicedee.guicedinjection; //exports com.guicedee.guicedinjection.exceptions; exports com.guicedee.guicedinjection.abstractions; - exports com.guicedee.guicedinjection.pairing; + //exports com.guicedee.guicedinjection.pairing; //exports com.guicedee.services.jsonrepresentation.json; - exports com.guicedee.guicedinjection.properties; exports com.guicedee.guicedinjection.representations; uses com.guicedee.guicedinjection.interfaces.IPackageContentsScanner; @@ -46,13 +46,12 @@ provides com.guicedee.guicedinjection.interfaces.IGuiceModule with com.guicedee.guicedinjection.injections.ContextBinderGuice; //provides com.guicedee.guicedinjection.interfaces.IGuiceModule with com.guicedee.guicedinjection.abstractions.GuiceInjectorModule; + provides IGuiceProvider with GuiceContextProvision; + provides IJobServiceProvider with JobServiceProvision; provides IGuicePreDestroy with JobService; provides java.net.spi.URLStreamHandlerProvider with com.guicedee.guicedinjection.urls.JrtUrlHandler; opens com.guicedee.guicedinjection to com.fasterxml.jackson.databind; - opens com.guicedee.guicedinjection.properties to com.fasterxml.jackson.databind; - - opens com.guicedee.guicedinjection.pairing; } diff --git a/src/main/resources/META-INF/services/com.guicedee.guicedinjection.interfaces.IGuiceProvider b/src/main/resources/META-INF/services/com.guicedee.guicedinjection.interfaces.IGuiceProvider new file mode 100644 index 0000000..cf6b8cd --- /dev/null +++ b/src/main/resources/META-INF/services/com.guicedee.guicedinjection.interfaces.IGuiceProvider @@ -0,0 +1 @@ +com.guicedee.guicedinjection.implementations.GuiceContextProvision \ No newline at end of file diff --git a/src/main/resources/META-INF/services/com.guicedee.guicedinjection.interfaces.IJobServiceProvider b/src/main/resources/META-INF/services/com.guicedee.guicedinjection.interfaces.IJobServiceProvider new file mode 100644 index 0000000..1ff1c61 --- /dev/null +++ b/src/main/resources/META-INF/services/com.guicedee.guicedinjection.interfaces.IJobServiceProvider @@ -0,0 +1 @@ +com.guicedee.guicedinjection.implementations.JobServiceProvision \ No newline at end of file diff --git a/src/test/java/com/guicedee/tests/FileSearchTest.java b/src/test/java/com/guicedee/tests/FileSearchTest.java index 9b4de66..75c2100 100644 --- a/src/test/java/com/guicedee/tests/FileSearchTest.java +++ b/src/test/java/com/guicedee/tests/FileSearchTest.java @@ -1,5 +1,6 @@ package com.guicedee.tests; +import com.guicedee.client.*; import com.guicedee.guicedinjection.GuiceContext; import com.guicedee.guicedinjection.interfaces.IPathContentsRejectListScanner; import io.github.classgraph.ResourceList; @@ -28,8 +29,9 @@ public void findJSFiles() return output; } ); - - GuiceContext.inject(); + + IGuiceContext + .getContext().inject(); ResourceList resourceswithPattern = GuiceContext.instance().getScanResult() .getResourcesMatchingPattern(Pattern.compile("(.*)\\/resources\\/testResourceFind\\.js")); System.out.println("Resource List found : " + resourceswithPattern); diff --git a/src/test/java/com/guicedee/tests/GuiceContextTest.java b/src/test/java/com/guicedee/tests/GuiceContextTest.java index 89d7957..ef42082 100644 --- a/src/test/java/com/guicedee/tests/GuiceContextTest.java +++ b/src/test/java/com/guicedee/tests/GuiceContextTest.java @@ -5,6 +5,7 @@ */ package com.guicedee.tests; +import com.guicedee.client.*; import com.guicedee.guicedinjection.GuiceContext; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; @@ -30,7 +31,8 @@ public static void pre() { @Test public void testInjection() { - GuiceContext.inject(); + IGuiceContext + .getContext().inject(); } } diff --git a/src/test/java/com/guicedee/tests/IGuiceConfigTest.java b/src/test/java/com/guicedee/tests/IGuiceConfigTest.java index 35cec54..9b13002 100644 --- a/src/test/java/com/guicedee/tests/IGuiceConfigTest.java +++ b/src/test/java/com/guicedee/tests/IGuiceConfigTest.java @@ -1,5 +1,6 @@ package com.guicedee.tests; +import com.guicedee.client.*; import com.guicedee.guicedinjection.GuiceConfig; import com.guicedee.guicedinjection.GuiceContext; import com.guicedee.guicedinjection.interfaces.IGuiceConfig; @@ -20,8 +21,8 @@ public void testConfig() GuiceContext.instance() .loadIGuiceConfigs() .add(new IGuiceConfigTest()); - GuiceContext.inject(); - GuiceConfig config = GuiceContext.get(GuiceConfig.class); + IGuiceContext.getContext().inject(); + GuiceConfig config = IGuiceContext.get(GuiceConfig.class); config = GuiceContext.instance().getConfig(); assertTrue(config.isServiceLoadWithClassPath()); diff --git a/src/test/java/com/guicedee/tests/OptionalPairTest.java b/src/test/java/com/guicedee/tests/OptionalPairTest.java index 038d7f7..9c8aa03 100644 --- a/src/test/java/com/guicedee/tests/OptionalPairTest.java +++ b/src/test/java/com/guicedee/tests/OptionalPairTest.java @@ -1,5 +1,6 @@ package com.guicedee.tests; +import com.guicedee.client.*; import com.guicedee.guicedinjection.GuiceContext; import com.guicedee.guicedinjection.pairing.OptionalPair; import com.guicedee.guicedinjection.properties.GlobalProperties; @@ -9,7 +10,7 @@ public class OptionalPairTest { @Test public void toStringTest() { - GlobalProperties global = GuiceContext.get(GlobalProperties.class); + GlobalProperties global = IGuiceContext.get(GlobalProperties.class); } @Test diff --git a/src/test/java/com/guicedee/tests/PsvmTest.java b/src/test/java/com/guicedee/tests/PsvmTest.java index 61f0c45..ba2a121 100644 --- a/src/test/java/com/guicedee/tests/PsvmTest.java +++ b/src/test/java/com/guicedee/tests/PsvmTest.java @@ -1,5 +1,6 @@ package com.guicedee.tests; +import com.guicedee.client.*; import com.guicedee.guicedinjection.GuiceContext; public class PsvmTest @@ -10,6 +11,7 @@ public static void main(String[] args) GuiceContext.instance() .getConfig() .setServiceLoadWithClassPath(true); - GuiceContext.inject(); + IGuiceContext + .getContext().inject(); } } From d1417d1831fc7d9274c5ffb73200a141bc724fe0 Mon Sep 17 00:00:00 2001 From: GedMarc Date: Thu, 29 Feb 2024 01:30:18 +0200 Subject: [PATCH 16/23] Client update for more decentralized functionality --- src/test/java/module-info.java | 3 +++ 1 file changed, 3 insertions(+) diff --git a/src/test/java/module-info.java b/src/test/java/module-info.java index b58f263..fa2e43f 100644 --- a/src/test/java/module-info.java +++ b/src/test/java/module-info.java @@ -6,4 +6,7 @@ requires org.junit.jupiter.api; requires org.slf4j; requires org.slf4j.simple; + + opens com.guicedee.tests to org.junit.platform.commons; + } \ No newline at end of file From 42317493ed920501c4cda2b8a1bf6c9bfec4198c Mon Sep 17 00:00:00 2001 From: GedMarc Date: Thu, 29 Feb 2024 02:40:06 +0200 Subject: [PATCH 17/23] Clean up modules listing on context --- .../guicedinjection/GuiceContext.java | 8 +- .../abstractions/GuiceInjectorModule.java | 229 ------------------ src/main/java/module-info.java | 2 +- ...edinjection.interfaces.IGuiceDefaultBinder | 2 - 4 files changed, 4 insertions(+), 237 deletions(-) delete mode 100644 src/main/java/com/guicedee/guicedinjection/abstractions/GuiceInjectorModule.java delete mode 100644 src/main/resources/META-INF/services/com.guicedee.guicedinjection.interfaces.IGuiceDefaultBinder diff --git a/src/main/java/com/guicedee/guicedinjection/GuiceContext.java b/src/main/java/com/guicedee/guicedinjection/GuiceContext.java index bb23574..812f230 100644 --- a/src/main/java/com/guicedee/guicedinjection/GuiceContext.java +++ b/src/main/java/com/guicedee/guicedinjection/GuiceContext.java @@ -19,20 +19,17 @@ import com.google.common.base.*; import com.google.inject.*; import com.guicedee.client.*; -import com.guicedee.guicedinjection.abstractions.*; import com.guicedee.guicedinjection.interfaces.*; -import com.guicedee.guicedinjection.interfaces.annotations.*; import io.github.classgraph.*; import jakarta.validation.constraints.*; -import lombok.extern.java.Log; +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; /** * Provides an interface for reflection and injection in one. @@ -139,6 +136,7 @@ public synchronized Injector inject() cModules.addAll(iGuiceModules); //cModules.add(new GuiceInjectorModule()); + log.config("Modules - " + Arrays.toString(cModules.toArray())); GuiceContext.instance().injector = Guice.createInjector(cModules); GuiceContext.buildingInjector = false; GuiceContext 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 0f3308f..0000000 --- a/src/main/java/com/guicedee/guicedinjection/abstractions/GuiceInjectorModule.java +++ /dev/null @@ -1,229 +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.IGuiceModule; -import lombok.extern.java.Log; - -import java.lang.annotation.Annotation; -import java.lang.reflect.Method; -import java.util.*; -import java.util.logging.Level; - -/** - * Exposes the abstract module methods as public - * - * @author GedMarc - * @since 12 Dec 2016 - */ -@Log -public class GuiceInjectorModule - extends AbstractModule - implements IGuiceModule { - /** - * 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 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 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> classMatcher, Matcher 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> 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> bindingMatcher, ProvisionListener... listener) { - super.bindListener(bindingMatcher, listener); - } - - -} diff --git a/src/main/java/module-info.java b/src/main/java/module-info.java index d5d892c..b9fa788 100644 --- a/src/main/java/module-info.java +++ b/src/main/java/module-info.java @@ -17,7 +17,7 @@ exports com.guicedee.guicedinjection; //exports com.guicedee.guicedinjection.exceptions; - exports com.guicedee.guicedinjection.abstractions; + //exports com.guicedee.guicedinjection.abstractions; //exports com.guicedee.guicedinjection.pairing; //exports com.guicedee.services.jsonrepresentation.json; exports com.guicedee.guicedinjection.representations; diff --git a/src/main/resources/META-INF/services/com.guicedee.guicedinjection.interfaces.IGuiceDefaultBinder b/src/main/resources/META-INF/services/com.guicedee.guicedinjection.interfaces.IGuiceDefaultBinder deleted file mode 100644 index 7bd6858..0000000 --- a/src/main/resources/META-INF/services/com.guicedee.guicedinjection.interfaces.IGuiceDefaultBinder +++ /dev/null @@ -1,2 +0,0 @@ -com.guicedee.guicedinjection.injections.ContextBinderGuice -com.guicedee.guicedinjection.json.ObjectMapperBinder \ No newline at end of file From 669f71c8df2b896b5d3e1ee65d5b16630081aaca Mon Sep 17 00:00:00 2001 From: GedMarc Date: Thu, 29 Feb 2024 04:28:01 +0200 Subject: [PATCH 18/23] Modular updates --- .../guicedinjection/GuiceContext.java | 211 +----------------- 1 file changed, 6 insertions(+), 205 deletions(-) diff --git a/src/main/java/com/guicedee/guicedinjection/GuiceContext.java b/src/main/java/com/guicedee/guicedinjection/GuiceContext.java index 812f230..0c48e0d 100644 --- a/src/main/java/com/guicedee/guicedinjection/GuiceContext.java +++ b/src/main/java/com/guicedee/guicedinjection/GuiceContext.java @@ -652,27 +652,6 @@ private String[] getModulesExclusionList() } return strings.toArray(new String[0]); } - /* - *//** - * Registers a module for scanning when filtering is enabled - * - * @param javaModuleName The name in the module-info.java file - * - * @return This instance - *//* - @SuppressWarnings("unchecked") - public static void registerModule(String javaModuleName) - { - instance().registerModuleForScanning.add(javaModuleName); - instance() - .getConfig() - .setIncludeModuleAndJars(true); - } - - public static void registerModule(com.google.inject.Module module) - { - instance().modules.add(module); - }*/ /** * Returns a complete list of generic exclusions @@ -762,6 +741,12 @@ public Set getLoader(Class loaderType, @SuppressWarnings("unused") boo .get(loaderType); } + @Override + public boolean isBuildingInjector() + { + return buildingInjector; + } + /** * Returns the current classpath scanner * @@ -852,14 +837,6 @@ private void loadPostStartups() { log.log(Level.SEVERE, "Cannot execute post startup - ", e); } - /*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 + "]"); } @@ -1000,20 +977,6 @@ public > Set getLoader(Class loaderType, ServiceLo .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 * @@ -1032,166 +995,4 @@ public void setAsync(boolean async) { this.async = async; } - - //Map> loaderClasses = new ConcurrentHashMap<>(); - - /** - * Method loaderToSet, converts a ServiceLoader into a TreeSet - * - * @param loader of type ServiceLoader - * - * @return Set - */ - //@SuppressWarnings("unchecked") - /*@NotNull - public > 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) - { - log.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) IGuiceContext.get(aClass)); - } - return outcomes; - }*/ - - /*public > 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) - { - log.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 - public 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 && instance().getScanResult() != null) - { - 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 (java.util.ServiceConfigurationError T) - { - log.log(Level.WARNING, "Cannot load services - ", T); - } - catch (Throwable T) - { - log.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) - { - log.log(Level.SEVERE, "Cannot load a service through default constructor", e); - } - } - return output; - }*/ } From 40b7c32e9c32f92dd2ed4001a2a5ebf1ea4339ea Mon Sep 17 00:00:00 2001 From: GedMarc Date: Thu, 29 Feb 2024 17:13:04 +0200 Subject: [PATCH 19/23] Modular updates --- src/main/java/com/guicedee/guicedinjection/JobService.java | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/src/main/java/com/guicedee/guicedinjection/JobService.java b/src/main/java/com/guicedee/guicedinjection/JobService.java index 5cc584a..8259d46 100644 --- a/src/main/java/com/guicedee/guicedinjection/JobService.java +++ b/src/main/java/com/guicedee/guicedinjection/JobService.java @@ -36,6 +36,11 @@ public class JobService implements IGuicePreDestroy, IJobService public static final JobService INSTANCE = new JobService(); private static ExecutorService jobCleanup = null; + static + { + jobCleanup = INSTANCE.jobCleanup(); + } + public JobService() { //No config required From 03aaf2ddab464ac0a57696a7bc2230e881158a67 Mon Sep 17 00:00:00 2001 From: GedMarc Date: Mon, 4 Mar 2024 00:05:41 +0200 Subject: [PATCH 20/23] Parallel Startups --- .../guicedee/guicedinjection/GuiceContext.java | 14 ++++++++++++-- .../guicedee/guicedinjection/JobService.java | 18 ++++++++++++++++++ 2 files changed, 30 insertions(+), 2 deletions(-) diff --git a/src/main/java/com/guicedee/guicedinjection/GuiceContext.java b/src/main/java/com/guicedee/guicedinjection/GuiceContext.java index 0c48e0d..5fe5371 100644 --- a/src/main/java/com/guicedee/guicedinjection/GuiceContext.java +++ b/src/main/java/com/guicedee/guicedinjection/GuiceContext.java @@ -812,7 +812,17 @@ private void loadPostStartups() { log.info("Starting Post Startup Group [" + key + "] in Parallel"); ExecutorService postStartup = null; - for (IGuicePostStartup iGuicePostStartup : value) + value.stream().forEach(a->{ + try + { + a.postLoad(); + } + catch (Throwable T) + { + log.log(Level.SEVERE, "Cannot execute post startup - ", T); + } + }); + /*for (IGuicePostStartup iGuicePostStartup : value) { postStartup = JobService.INSTANCE.addJob("PostStartup", () -> { try @@ -836,7 +846,7 @@ private void loadPostStartups() catch (Throwable e) { log.log(Level.SEVERE, "Cannot execute post startup - ", e); - } + }*/ } GuiceContext.log.fine("Completed with Post Startups Key [" + key + "]"); } diff --git a/src/main/java/com/guicedee/guicedinjection/JobService.java b/src/main/java/com/guicedee/guicedinjection/JobService.java index 8259d46..f03ecb0 100644 --- a/src/main/java/com/guicedee/guicedinjection/JobService.java +++ b/src/main/java/com/guicedee/guicedinjection/JobService.java @@ -86,6 +86,24 @@ public ExecutorService removeJob(String 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 From 7380b2a99bc6b0e134149d688e7db0d1a9738dfb Mon Sep 17 00:00:00 2001 From: GedMarc Date: Sat, 13 Apr 2024 15:33:06 +0200 Subject: [PATCH 21/23] Add Vert.x, MP Config use raw injection, JTA Updates, Remove annotation and use persistence unit name. --- pom.xml | 2 +- .../guicedinjection/GuiceContext.java | 1897 ++++++++--------- 2 files changed, 937 insertions(+), 962 deletions(-) diff --git a/pom.xml b/pom.xml index 3d5db6d..a2748ea 100644 --- a/pom.xml +++ b/pom.xml @@ -10,8 +10,8 @@ 4.0.0 com.guicedee - guice-injection + jar 2.0.0-SNAPSHOT Guiced Injector diff --git a/src/main/java/com/guicedee/guicedinjection/GuiceContext.java b/src/main/java/com/guicedee/guicedinjection/GuiceContext.java index 5fe5371..dbbc63b 100644 --- a/src/main/java/com/guicedee/guicedinjection/GuiceContext.java +++ b/src/main/java/com/guicedee/guicedinjection/GuiceContext.java @@ -44,965 +44,940 @@ @SuppressWarnings("MissingClassJavaDoc") public class GuiceContext> implements IGuiceContext { - /** - * 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; - /** - * 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 - */ - @NotNull - 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 - */ - @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; - } - - /** - * 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") - @NotNull - 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> 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 - { - log.info("Starting Post Startup Group [" + key + "] in Parallel"); - ExecutorService postStartup = null; - value.stream().forEach(a->{ - try - { - a.postLoad(); - } - catch (Throwable T) - { - log.log(Level.SEVERE, "Cannot execute post startup - ", T); - } - }); - /*for (IGuicePostStartup iGuicePostStartup : value) - { - postStartup = JobService.INSTANCE.addJob("PostStartup", () -> { - try - { - iGuicePostStartup.postLoad(); - } - catch (Throwable T) - { - log.log(Level.SEVERE, "Cannot execute post startup - ", T); - } - }); - } - try - { - if (postStartup != null) - { - log.config("Waiting for post startup group to finish...."); - JobService.INSTANCE.removeJob("PostStartup"); - } - } - catch (Throwable e) - { - log.log(Level.SEVERE, "Cannot execute post startup - ", 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 @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 (!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; - } + /** + * 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 + */ + @NotNull + 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 + */ + @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; + } + + /** + * 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") + @NotNull + 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>> 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 + { + 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 @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 (!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; + } } From 4b3d28443c00a5445fff9db8dfdd90be88142cec Mon Sep 17 00:00:00 2001 From: GedMarc Date: Sun, 14 Apr 2024 05:32:00 +0200 Subject: [PATCH 22/23] Vert.x Configurators and build updates --- .../guicedee/guicedinjection/GuiceConfig.java | 26 ++++++++----------- .../guicedinjection/GuiceContext.java | 23 ++++++++-------- .../GuiceDefaultModuleExclusions.java | 5 ++-- .../GuiceDefaultModuleInclusions.java | 4 +-- 4 files changed, 25 insertions(+), 33 deletions(-) diff --git a/src/main/java/com/guicedee/guicedinjection/GuiceConfig.java b/src/main/java/com/guicedee/guicedinjection/GuiceConfig.java index 68dd78c..d3c046a 100644 --- a/src/main/java/com/guicedee/guicedinjection/GuiceConfig.java +++ b/src/main/java/com/guicedee/guicedinjection/GuiceConfig.java @@ -2,10 +2,6 @@ import com.google.inject.Singleton; -import jakarta.validation.constraints.NotNull; -import lombok.Getter; -import lombok.Setter; - /** * The configuration class for Guice Context and the Classpath Scanner */ @@ -127,7 +123,7 @@ public boolean isFieldScanning() @Override @SuppressWarnings("unchecked") - @NotNull + public J setFieldScanning(boolean fieldScanning) { this.fieldScanning = fieldScanning; @@ -142,7 +138,7 @@ public boolean isAnnotationScanning() @Override @SuppressWarnings("unchecked") - @NotNull + public J setAnnotationScanning(boolean annotationScanning) { this.annotationScanning = annotationScanning; @@ -157,7 +153,7 @@ public boolean isMethodInfo() @Override @SuppressWarnings("unchecked") - @NotNull + public J setMethodInfo(boolean methodInfo) { this.methodInfo = methodInfo; @@ -172,7 +168,7 @@ public boolean isIgnoreFieldVisibility() @Override @SuppressWarnings("unchecked") - @NotNull + public J setIgnoreFieldVisibility(boolean ignoreFieldVisibility) { this.ignoreFieldVisibility = ignoreFieldVisibility; @@ -187,7 +183,7 @@ public boolean isIgnoreMethodVisibility() @Override @SuppressWarnings("unchecked") - @NotNull + public J setIgnoreMethodVisibility(boolean ignoreMethodVisibility) { this.ignoreMethodVisibility = ignoreMethodVisibility; @@ -202,7 +198,7 @@ public boolean isIncludePackages() @Override @SuppressWarnings("unchecked") - @NotNull + public J setIncludePackages(boolean includePackages) { this.includePackages = includePackages; @@ -217,7 +213,7 @@ public boolean isFieldInfo() @Override @SuppressWarnings("unchecked") - @NotNull + public J setFieldInfo(boolean fieldInfo) { this.fieldInfo = fieldInfo; @@ -232,7 +228,7 @@ public boolean isVerbose() @Override @SuppressWarnings("unchecked") - @NotNull + public J setVerbose(boolean verbose) { this.verbose = verbose; @@ -248,7 +244,7 @@ public boolean isClasspathScanning() @Override @SuppressWarnings("unchecked") - @NotNull + public J setClasspathScanning(boolean classpathScanning) { this.classpathScanning = classpathScanning; @@ -263,7 +259,7 @@ public boolean isExcludeModulesAndJars() @Override @SuppressWarnings("unchecked") - @NotNull + public J setExcludeModulesAndJars(boolean excludeModulesAndJars) { this.excludeModulesAndJars = excludeModulesAndJars; @@ -278,7 +274,7 @@ public boolean isExcludePaths() @Override @SuppressWarnings("unchecked") - @NotNull + public J setExcludePaths(boolean excludePaths) { this.excludePaths = excludePaths; diff --git a/src/main/java/com/guicedee/guicedinjection/GuiceContext.java b/src/main/java/com/guicedee/guicedinjection/GuiceContext.java index dbbc63b..24cf021 100644 --- a/src/main/java/com/guicedee/guicedinjection/GuiceContext.java +++ b/src/main/java/com/guicedee/guicedinjection/GuiceContext.java @@ -21,7 +21,6 @@ import com.guicedee.client.*; import com.guicedee.guicedinjection.interfaces.*; import io.github.classgraph.*; -import jakarta.validation.constraints.*; import lombok.extern.java.*; import java.util.*; @@ -96,7 +95,7 @@ private GuiceContext() * * @return The global Guice Injector Object, Never Null, Instantiates the Injector if not configured */ - @NotNull + public synchronized Injector inject() { if (GuiceContext.buildingInjector) @@ -240,7 +239,7 @@ private static int getJavaVersion() * * @return The physical Scan Result from the complete class scanner */ - @NotNull + public ScanResult getScanResult() { if (scanResult == null) @@ -722,7 +721,7 @@ private Map quickScanFilesPattern() * @return A set of them */ @SuppressWarnings("unchecked") - @NotNull + public Set getLoader(Class loaderType, @SuppressWarnings("unused") boolean dontInject, ServiceLoader serviceLoader) { if (!IGuiceContext @@ -842,7 +841,7 @@ public GuiceConfig getConfig() * * @return The list of guice post startups */ - public @NotNull Set loadPostStartupServices() + public Set loadPostStartupServices() { return getLoader(IGuicePostStartup.class, ServiceLoader.load(IGuicePostStartup.class)); } @@ -852,7 +851,7 @@ public GuiceConfig getConfig() * * @return The list of guice post startups */ - public @NotNull Set loadPathRejectScanners() + public Set loadPathRejectScanners() { return getLoader(IPathContentsRejectListScanner.class, true, ServiceLoader.load(IPathContentsRejectListScanner.class)); } @@ -863,7 +862,7 @@ public GuiceConfig getConfig() * * @return The list of guice post startups */ - public @NotNull Set loadJarRejectScanners() + public Set loadJarRejectScanners() { return getLoader(IGuiceScanJarExclusions.class, true, ServiceLoader.load(IGuiceScanJarExclusions.class)); } @@ -874,7 +873,7 @@ public GuiceConfig getConfig() * * @return The list of guice post startups */ - public @NotNull Set loadJarInclusionScanners() + public Set loadJarInclusionScanners() { return getLoader(IGuiceScanJarInclusions.class, true, ServiceLoader.load(IGuiceScanJarInclusions.class)); } @@ -885,7 +884,7 @@ public GuiceConfig getConfig() * * @return The list of guice post startups */ - public @NotNull Set loadPreStartupServices() + public Set loadPreStartupServices() { return getLoader(IGuicePreStartup.class, true, ServiceLoader.load(IGuicePreStartup.class)); } @@ -895,7 +894,7 @@ public GuiceConfig getConfig() * * @return The list of guice post startups */ - public @NotNull Set loadIGuiceModules() + public Set loadIGuiceModules() { return getLoader(IGuiceModule.class, true, ServiceLoader.load(IGuiceModule.class)); } @@ -905,7 +904,7 @@ public GuiceConfig getConfig() * * @return The list of guice configs */ - public @NotNull Set loadIGuiceConfigs() + public Set loadIGuiceConfigs() { return getLoader(IGuiceConfigurator.class, true, ServiceLoader.load(IGuiceConfigurator.class)); } @@ -936,7 +935,7 @@ private void loadPreStartups() * @return A set of them */ @SuppressWarnings("unchecked") - @NotNull + public > Set getLoader(Class loaderType, ServiceLoader serviceLoader) { if (!IGuiceContext 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; From 1df4e181cfa43f0f8f23e2bd35320c88f39848e7 Mon Sep 17 00:00:00 2001 From: GedMarc Date: Sun, 14 Apr 2024 07:40:33 +0200 Subject: [PATCH 23/23] Cleanup rest service dependencies for Vert.x --- .../guicedinjection/GuiceContext.java | 22 ++++++++++--------- 1 file changed, 12 insertions(+), 10 deletions(-) diff --git a/src/main/java/com/guicedee/guicedinjection/GuiceContext.java b/src/main/java/com/guicedee/guicedinjection/GuiceContext.java index 24cf021..41fe3a0 100644 --- a/src/main/java/com/guicedee/guicedinjection/GuiceContext.java +++ b/src/main/java/com/guicedee/guicedinjection/GuiceContext.java @@ -29,6 +29,8 @@ import java.util.regex.Pattern; 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. @@ -772,8 +774,10 @@ public static void setScanner(ClassGraph scanner) private void loadPostStartups() { Set startupSet = loadPostStartupServices(); + Map> groupedPostStartup = startupSet.stream() + .collect(groupingBy(IGuicePostStartup::sortOrder, toSet())); + /* Map>> postStartupGroups = new TreeMap<>(); - Map>> postStartupGroups = new TreeMap<>(); for (IGuicePostStartup postStartup : startupSet) { Integer sortOrder = postStartup.sortOrder(); @@ -781,11 +785,11 @@ private void loadPostStartups() .computeIfAbsent(sortOrder, k -> new TreeSet<>()) .add(postStartup); } - - for (Map.Entry>> entry : postStartupGroups.entrySet()) +*/ + for (Map.Entry> entry : groupedPostStartup.entrySet()) { Integer key = entry.getKey(); - Set> value = entry.getValue(); + Set value = entry.getValue(); if (value.size() == 1) { //run in order @@ -843,7 +847,7 @@ public GuiceConfig getConfig() */ public Set loadPostStartupServices() { - return getLoader(IGuicePostStartup.class, ServiceLoader.load(IGuicePostStartup.class)); + return new TreeSet<>(getLoader(IGuicePostStartup.class, ServiceLoader.load(IGuicePostStartup.class))); } /** @@ -886,7 +890,7 @@ public Set loadJarInclusionScanners() */ public Set loadPreStartupServices() { - return getLoader(IGuicePreStartup.class, true, ServiceLoader.load(IGuicePreStartup.class)); + return new TreeSet<>(getLoader(IGuicePreStartup.class, true, ServiceLoader.load(IGuicePreStartup.class))); } /** @@ -896,7 +900,7 @@ public Set loadPreStartupServices() */ public Set loadIGuiceModules() { - return getLoader(IGuiceModule.class, true, ServiceLoader.load(IGuiceModule.class)); + return new TreeSet<>(getLoader(IGuiceModule.class, true, ServiceLoader.load(IGuiceModule.class))); } /** @@ -915,9 +919,7 @@ public Set loadIGuiceConfigs() private void loadPreStartups() { Set preStartups = loadPreStartupServices(); - List startups = new ArrayList<>(preStartups); - startups.sort(Comparator.comparing(IGuicePreStartup::sortOrder)); - for (IGuicePreStartup startup : startups) + for (IGuicePreStartup startup : preStartups) { GuiceContext.log.config("Loading IGuicePreStartup - " + startup .getClass()