diff --git a/.github/workflows/maven-publish.yml b/.github/workflows/maven-publish.yml index 7acb4dd..93a4c3f 100644 --- a/.github/workflows/maven-publish.yml +++ b/.github/workflows/maven-publish.yml @@ -1,12 +1,12 @@ -name: Maven Package (BOM) +name: Maven Package on: workflow_dispatch: push: jobs: GuicedInjection: - uses: GuicedEE/Workflows/.github/workflows/bom.yml@master + uses: GuicedEE/Workflows/.github/workflows/projects.yml@master with: - baseDir: '/' + baseDir: '' name: 'Guiced Injection' secrets: USERNAME: ${{secrets.USERNAME}} 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 diff --git a/pom.xml b/pom.xml index 7f8b6f2..a2748ea 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 + guice-injection - guiced-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 @@ -25,9 +24,9 @@ true false + /GuicedEE/GuicedInjection - @@ -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,23 +104,18 @@ - com.guicedee.services + org.apache.commons commons-lang3 - - com.guicedee.services - jakarta.xml.bind-api - - com.fasterxml.jackson.core jackson-core - com.guicedee.services - slf4j + org.slf4j + slf4j-api @@ -93,101 +128,79 @@ jackson-datatype-jsr310 + + jakarta.inject + jakarta.inject-api + com.guicedee.services - json - true + aopalliance-core com.guicedee.services - apache-poi-ooxml - true + guava - com.guicedee.services - javax.inject + org.slf4j + jcl-over-slf4j + test - com.guicedee.services - aopalliance-core + org.slf4j + slf4j-simple + test - com.guicedee.services - guava + org.junit.jupiter + junit-jupiter-api + test - - https://github.com/GedMarc?tab=repositories - - - - Github - https://github.com/GedMarc/GuiceInjection/issues - - - - TeamCity - http://jwebmp.com/teamcity - - org.codehaus.mojo flatten-maven-plugin - - - ossrh - direct - true - true - flatter.pom - - - - - flatten - verify - - flatten - - - - - flatten.clean - clean - - clean - - - 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-javadoc-plugin + + + + org.apache.maven.plugins + maven-compiler-plugin + true + + + + org.projectlombok + lombok + ${lombok.version} + + + + lombok.launch.AnnotationProcessorHider$AnnotationProcessor + + + true + + + + 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/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 diff --git a/src/main/java/com/guicedee/guicedinjection/GuiceConfig.java b/src/main/java/com/guicedee/guicedinjection/GuiceConfig.java index 856cd2c..d3c046a 100644 --- a/src/main/java/com/guicedee/guicedinjection/GuiceConfig.java +++ b/src/main/java/com/guicedee/guicedinjection/GuiceConfig.java @@ -2,15 +2,12 @@ import com.google.inject.Singleton; -import jakarta.validation.constraints.NotNull; - /** * 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 +76,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 +93,13 @@ public GuiceConfig() //No Config } - /** - * Enable classpath scanning for service sets loaded via GuiceContext.getLoader() - * It's a great way to enable testing in jdk 12 where test classes using service loading and jdk no longer reads service loaders from meta-inf/services - *

- * Try to only use in test to load test modules. otherwise it may be a bad design - * - */ + @Override public boolean isServiceLoadWithClassPath() { return serviceLoadWithClassPath; } - /** - * Enable classpath scanning for service sets loaded via GuiceContext.getLoader() - * It's a great way to enable testing in jdk 12 where test classes using service loading and jdk no longer reads service loaders from meta-inf/services - *

- * Try to only use in test to load test modules. otherwise it may be a bad design - * - * @param serviceLoadWithClassPath Should scanning with classpath instead of SPI be used? - * - * @return this - */ + @Override @SuppressWarnings("unchecked") public J setServiceLoadWithClassPath(boolean serviceLoadWithClassPath) { @@ -124,224 +114,121 @@ public J setServiceLoadWithClassPath(boolean serviceLoadWithClassPath) return (J) this; } - /** - * Enable classpath scanning for service sets loaded via GuiceContext.getLoader() - * It's a great way to enable testing in jdk 12 where test classes using service loading and jdk no longer reads service loaders from meta-inf/services - *

- * Try to only use in test to load test modules. otherwise it may be a bad design - */ - private boolean serviceLoadWithClassPath; - /** - * If field scanning should be enabled - * - * @return mandatory result - */ + @Override public boolean isFieldScanning() { return fieldScanning; } - /** - * Enables scanning of fields - * - * @param fieldScanning - * If field scanning should happen - * - * @return Mandatory field scanning - */ + @Override @SuppressWarnings("unchecked") - @NotNull + public J setFieldScanning(boolean fieldScanning) { this.fieldScanning = fieldScanning; return (J) this; } - /** - * Enables scanning of field annotations - * - * @return not null - */ + @Override public boolean isAnnotationScanning() { return annotationScanning; } - /** - * Enables scanning of field annotations - * - * @param annotationScanning - * if the field annotation scanning - * - * @return the field annotation scanning - */ + @Override @SuppressWarnings("unchecked") - @NotNull + public J setAnnotationScanning(boolean annotationScanning) { this.annotationScanning = annotationScanning; return (J) this; } - /** - * If method info should be kept - * - * @return always this - */ + @Override public boolean isMethodInfo() { return methodInfo; } - /** - * Sets if method info should be kept - * - * @param methodInfo - * if method information should be collected - * - * @return always this - */ + @Override @SuppressWarnings("unchecked") - @NotNull + public J setMethodInfo(boolean methodInfo) { this.methodInfo = methodInfo; return (J) this; } - /** - * Sets to ignore field visibility - * - * @return if field visibility is being used - */ + @Override public boolean isIgnoreFieldVisibility() { return ignoreFieldVisibility; } - /** - * Sets to ignore field visibility - * - * @param ignoreFieldVisibility - * if the field should be visible - * - * @return always this - */ + @Override @SuppressWarnings("unchecked") - @NotNull + public J setIgnoreFieldVisibility(boolean ignoreFieldVisibility) { this.ignoreFieldVisibility = ignoreFieldVisibility; return (J) this; } - /** - * Sets to ignore method visibility - * - * @return if method is visibility ignored - */ + @Override public boolean isIgnoreMethodVisibility() { return ignoreMethodVisibility; } - /** - * Sets to ignore method visibility - * - * @param ignoreMethodVisibility - * the ignore method - * - * @return always This - */ + @Override @SuppressWarnings("unchecked") - @NotNull + public J setIgnoreMethodVisibility(boolean ignoreMethodVisibility) { this.ignoreMethodVisibility = ignoreMethodVisibility; return (J) this; } - /** - * Sets if packages must be white listed. - *

- * Use META-INF/services/com.guicedee.guiceinjection.scanners.IPackageContentsScanner to register your packages - * - * @return if whitelisting is enabled - */ + @Override public boolean isIncludePackages() { return includePackages; } - /** - * Sets if packages must be white listed. - * *

- * * Use META-INF/services/com.guicedee.guiceinjection.scanners.IPackageContentsScanner to register your packages - * - * @param includePackages - * if packages should be white listed - * - * @return Always this - */ + @Override @SuppressWarnings("unchecked") - @NotNull + public J setIncludePackages(boolean includePackages) { this.includePackages = includePackages; return (J) this; } - /** - * Returns the field information included in the scan result - * - * @return if field info is included - */ + @Override public boolean isFieldInfo() { return fieldInfo; } - /** - * Sets if the field info should be in the field result - * - * @param fieldInfo - * if field info should be scanned - * - * @return always this object - */ + @Override @SuppressWarnings("unchecked") - @NotNull + public J setFieldInfo(boolean fieldInfo) { this.fieldInfo = fieldInfo; return (J) this; } - /** - * Method isVerbose returns the verbose of this GuiceConfig object. - *

- * Whether or not to log very verbose - * - * @return the verbose (type boolean) of this GuiceConfig object. - */ + @Override public boolean isVerbose() { return verbose; } - /** - * Method setVerbose sets the verbose of this GuiceConfig object. - *

- * Whether or not to log very verbose - * - * @param verbose - * the verbose of this GuiceConfig object. - * - * @return J - */ + @Override @SuppressWarnings("unchecked") - @NotNull + public J setVerbose(boolean verbose) { this.verbose = verbose; @@ -349,82 +236,45 @@ public J setVerbose(boolean verbose) return (J) this; } - /** - * Method isClasspathScanning returns the classpathScanning of this GuiceConfig object. - *

- * If classpath scanning is enabled. - * - * @return the classpathScanning (type boolean) of this GuiceConfig object. - */ + @Override public boolean isClasspathScanning() { return classpathScanning; } - /** - * Method setClasspathScanning sets the classpathScanning of this GuiceConfig object. - *

- * If classpath scanning is enabled. - * - * @param classpathScanning - * the classpathScanning of this GuiceConfig object. - * - * @return J - */ + @Override @SuppressWarnings("unchecked") - @NotNull + public J setClasspathScanning(boolean classpathScanning) { this.classpathScanning = classpathScanning; return (J) this; } - /** - * Excludes modules and jars from scanning - may and may not make it faster depending on your pc - * - * @return is modules/jars are excluded from scans - */ + @Override public boolean isExcludeModulesAndJars() { return excludeModulesAndJars; } - /** - * Excludes modules and jars from scanning - may and may not make it faster depending on your pc - * - * @param excludeModulesAndJars - * to exclude them - * - * @return J - */ + @Override @SuppressWarnings("unchecked") - @NotNull + public J setExcludeModulesAndJars(boolean excludeModulesAndJars) { this.excludeModulesAndJars = excludeModulesAndJars; return (J) this; } - /** - * Excludes paths from scanning - excellent for minizing path scanning on web application - * - * @return boolean - */ + @Override public boolean isExcludePaths() { return excludePaths; } - /** - * Excludes paths from scanning - excellent for minizing path scanning on web application - * - * @param excludePaths - * If the default paths must be automatically excluded - * - * @return J - */ + @Override @SuppressWarnings("unchecked") - @NotNull + public J setExcludePaths(boolean excludePaths) { this.excludePaths = excludePaths; @@ -457,39 +307,26 @@ public String toString() '}'; } - /** - * Method isAllowPaths returns the allowed Paths of this GuiceConfig object. - *

- * Excludes paths from scanning - excellent for minizing path scanning on web application - * - * @return the whitelistPaths (type boolean) of this GuiceConfig object. - */ + @Override public boolean isAllowPaths() { return allowedPaths; } - /** - * Method setAllowPaths sets the allowed Paths of this GuiceConfig object. - *

- * Excludes paths from scanning - excellent for minizing path scanning on web application - * - * @param allowedPaths - * the allowedPaths of this GuiceConfig object. - * - * @return GuiceConfig J - */ - public GuiceConfig setAllowPaths(boolean allowedPaths) + @Override + public J setAllowPaths(boolean allowedPaths) { this.allowedPaths = allowedPaths; - return this; + return (J)this; } + @Override public boolean isIgnoreClassVisibility() { return ignoreClassVisibility; } + @Override @SuppressWarnings("unchecked") public J setIgnoreClassVisibility(boolean ignoreClassVisibility) { @@ -497,110 +334,56 @@ public J setIgnoreClassVisibility(boolean ignoreClassVisibility) return (J) this; } - /** - * Include module/jars from being loaded - uses ModuleInclusions for jdk9 and JarInclusions for jdk8 - * - * @return - */ + @Override public boolean isIncludeModuleAndJars() { return includeModuleAndJars; } - /** - * Include module/jars from being loaded - uses ModuleInclusions for jdk9 and JarInclusions for jdk8 - * - * @param includeModuleAndJars - * @return - */ - public GuiceConfig setIncludeModuleAndJars(boolean includeModuleAndJars) { + @Override + public J setIncludeModuleAndJars(boolean includeModuleAndJars) { this.includeModuleAndJars = includeModuleAndJars; - return this; + return (J)this; } - /** - * Method isPathScanning returns the pathScanning of this GuiceConfig object. - *

- * If the path should be scanned - * - * @return the pathScanning (type boolean) of this GuiceConfig object. - */ + @Override public boolean isPathScanning() { return pathScanning; } - /** - * Method setPathScanning sets the pathScanning of this GuiceConfig object. - *

- * If the path should be scanned - * - * @param pathScanning - * the pathScanning of this GuiceConfig object. - * - * @return GuiceConfig J - */ - public GuiceConfig setPathScanning(boolean pathScanning) + @Override + public J setPathScanning(boolean pathScanning) { this.pathScanning = pathScanning; - return this; + return (J)this; } - /** - * Method isExcludeParentModules returns the excludeParentModules of this GuiceConfig object. - *

- * Property to use when everything is found in the boot module - * - * @return the excludeParentModules (type boolean) of this GuiceConfig object. - */ + @Override @SuppressWarnings("unused") public boolean isExcludeParentModules() { return excludeParentModules; } - /** - * Method setExcludeParentModules sets the excludeParentModules of this GuiceConfig object. - *

- * Property to use when everything is found in the boot module - * - * @param excludeParentModules - * the excludeParentModules of this GuiceConfig object. - * - * @return GuiceConfig J - */ + @Override @SuppressWarnings("unused") - public GuiceConfig setExcludeParentModules(boolean excludeParentModules) + public J setExcludeParentModules(boolean excludeParentModules) { this.excludeParentModules = excludeParentModules; - return this; + return (J)this; } - /** - * Method isRejectPackages returns the excludePackages of this GuiceConfig object. - *

- * Excludes packages from scanning - excellent for minimizing path scanning on web application - * - * @return the excludePackages (type boolean) of this GuiceConfig object. - */ + @Override public boolean isRejectPackages() { return excludePackages; } - /** - * Method setExcludePackages sets the excludePackages of this GuiceConfig object. - *

- * Excludes packages from scanning - excellent for minimizing path scanning on web application - * - * @param excludePackages - * the excludePackages of this GuiceConfig object. - * - * @return GuiceConfig J - */ - public GuiceConfig setExcludePackages(boolean excludePackages) + @Override + public J setExcludePackages(boolean excludePackages) { this.excludePackages = excludePackages; - return this; + return (J)this; } diff --git a/src/main/java/com/guicedee/guicedinjection/GuiceContext.java b/src/main/java/com/guicedee/guicedinjection/GuiceContext.java index b6731cb..41fe3a0 100644 --- a/src/main/java/com/guicedee/guicedinjection/GuiceContext.java +++ b/src/main/java/com/guicedee/guicedinjection/GuiceContext.java @@ -18,20 +18,19 @@ import com.google.common.base.*; import com.google.inject.*; -import com.guicedee.guicedinjection.abstractions.*; +import com.guicedee.client.*; import com.guicedee.guicedinjection.interfaces.*; -import com.guicedee.guicedinjection.interfaces.annotations.*; -import com.guicedee.logger.*; import io.github.classgraph.*; -import jakarta.validation.constraints.*; +import lombok.extern.java.*; -import java.lang.annotation.*; import java.util.*; import java.util.concurrent.*; import java.util.logging.*; import java.util.regex.Pattern; -import static com.guicedee.guicedinjection.properties.GlobalProperties.*; +import static com.guicedee.guicedinjection.properties.GlobalProperties.getSystemPropertyOrEnvironment; +import static java.util.stream.Collectors.groupingBy; +import static java.util.stream.Collectors.toSet; /** * Provides an interface for reflection and injection in one. @@ -42,1044 +41,944 @@ * @version 1.0 * @since Nov 14, 2016 */ +@Log @SuppressWarnings("MissingClassJavaDoc") -public class GuiceContext> +public class GuiceContext> implements IGuiceContext { - /** - * Field log - */ - private static final Logger log = LogFactory.getLog("GuiceContext"); - /** - * This particular instance of the class - */ - private static final GuiceContext instance = new GuiceContext<>(); - /** - * A list of all the loaded singleton sets - */ - private static final Map allLoadedServices = Collections.synchronizedMap(new LinkedHashMap<>()); - /** - * The building injector - */ - public static boolean buildingInjector = false; - /** - * A standard default waiting time for threads - */ - public static long defaultWaitTime = 2; - /** - * The default wait unit for the thread time - */ - public static TimeUnit defaultWaitUnit = TimeUnit.SECONDS; - /** - * The configuration object - */ - private static GuiceConfig config; - /** - * The physical injector for the JVM container - */ - private Injector injector; - /** - * The actual scanner - */ - private ClassGraph scanner; - /** - * The scan result built from everything - the core scanner. - */ - private ScanResult scanResult; - /** - * If the scan should run async - */ - private boolean async; - - /** - * Creates a new Guice context. Not necessary - */ - private GuiceContext() - { - //No config required - } - - /** - * Reference the Injector Directly - * - * @return The global Guice Injector Object, Never Null, Instantiates the Injector if not configured - */ - @NotNull - public static synchronized Injector inject() - { - if (GuiceContext.buildingInjector) - { - log.log(Level.SEVERE, "The injector is being called recursively during build. Place such actions in a IGuicePostStartup or use the IGuicePreStartup Service Loader."); - System.exit(1); - } - if (GuiceContext.instance().injector == null) - { - try - { - GuiceContext.buildingInjector = true; - GuiceContext.log.info("Starting up Guice Context"); - GuiceContext.instance() - .loadConfiguration(); - if (GuiceContext.instance() - .getConfig() - .isPathScanning() || - GuiceContext.instance() - .getConfig() - .isClasspathScanning()) - { - GuiceContext.instance() - .loadScanner(); - } - GuiceContext.instance() - .loadPreStartups(); - - List cModules = new ArrayList<>(); - cModules.add(new GuiceInjectorModule()); - GuiceContext.instance().injector = Guice.createInjector(cModules); - GuiceContext.buildingInjector = false; - GuiceContext.instance() - .loadPostStartups(); - - Runtime.getRuntime() - .addShutdownHook(new Thread(GuiceContext::destroy)); - - GuiceContext.log.config("Injection System Ready"); - } - catch (Throwable e) - { - GuiceContext.log.log(Level.SEVERE, "Exception creating Injector : " + e.getMessage(), e); - throw new RuntimeException("Unable to boot Guice Injector", e); - } - } - GuiceContext.buildingInjector = false; - return GuiceContext.instance().injector; - } - - /** - * Gets a new injected instance of a class - * - * @param The type to retrieve - * @param type The physical class object - * @return The scoped object - */ - @NotNull - public static T get(@NotNull Class type) - { - return get(type, null); - } - - /** - * Gets a new injected instance of a class - * - * @param The type to retrieve - * @param type The physical class object - * @return The scoped object - * @deprecated For get() - */ - @NotNull - @Deprecated() - public static T getInstance(@NotNull Class type) - { - return get(type, null); - } - - /** - * Gets a new injected instance of a class - * - * @param The type to retrieve - * @param type The physical class object - * @return The scoped object - * @deprecated For get() - */ - @NotNull - @Deprecated() - public static T getInstance(@NotNull Key type) - { - return get(type); - } - - /** - * Gets a new injected instance of a class - * - * @param The type to retrieve - * @param type The physical class object - * @return The scoped object - * @deprecated For get() - */ - @NotNull - @Deprecated() - public static T getInstance(@NotNull Class type, Class 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; - } - - /** - * Execute on Destroy - */ - @SuppressWarnings("unused") - public static void destroy() - { - Set destroyers = GuiceContext.instance() - .getLoader(IGuicePreDestroy.class, true, ServiceLoader.load(IGuicePreDestroy.class)); - for (IGuicePreDestroy destroyer : destroyers) - { - IGuicePreDestroy instance = GuiceContext.get(destroyer.getClass()); - instance.onDestroy(); - } - if (GuiceContext.instance().scanResult != null) - { - GuiceContext.instance().scanResult.close(); - } - if (GuiceContext.instance().scanResult != null) - { - GuiceContext.instance().scanResult.close(); - } - GuiceContext.instance().scanResult = null; - GuiceContext.instance().scanner = null; - GuiceContext.instance().injector = null; - } - - /** - * Returns the Java version as an int value. - * - * @return the Java version as an int value (8, 9, etc.) - * @since 12130 - */ - private static int getJavaVersion() - { - String version = getSystemPropertyOrEnvironment("java.version","11"); - if (version.startsWith("1.")) - { - version = version.substring(2); - } - // Allow these formats: - // 1.8.0_72-ea - // 9-ea - // 9 - // 9.0.1 - int dotPos = version.indexOf('.'); - int dashPos = version.indexOf('-'); - String value = version.substring(0, dotPos > -1 ? dotPos : dashPos > -1 ? dashPos : version.length()); - return Integer.parseInt(value); - } - - /** - * Returns the current scan result - * - * @return The physical Scan Result from the complete class scanner - */ - @NotNull - public ScanResult getScanResult() - { - if (scanResult == null) - { - loadScanner(); - } - return scanResult; - } - - /** - * Sets the current scan result - * - * @param scanResult The physical Scan Result from the complete class scanner - */ - @SuppressWarnings("unused") - public void setScanResult(ScanResult scanResult) - { - GuiceContext.instance().scanResult = scanResult; - } - - /** - * Returns the actual context instance, provides access to methods existing a bit deeper - * - * @return The singleton instance of this - */ - public static GuiceContext instance() - { - return GuiceContext.instance; - } - - private static boolean configured; - - /** - * Loads the IGuiceConfigurator - */ - private void loadConfiguration() - { - if (!configured) - { - if (GuiceContext.config == null) - { - GuiceContext.config = new GuiceConfig<>(); - } - Set guiceConfigurators = loadIGuiceConfigs(); - for (IGuiceConfigurator guiceConfigurator : guiceConfigurators) - { - GuiceContext.log.config("Loading IGuiceConfigurator - " + - guiceConfigurator.getClass() - .getCanonicalName()); - GuiceContext.config = guiceConfigurator.configure(GuiceContext.config); - } - GuiceContext.log.config("IGuiceConfigurator : " + GuiceContext.config.toString()); - configured = true; - } - } - - - /** - * Returns a complete list of generic exclusions - * - * @return A string list of packages to be scanned - */ - @SuppressWarnings("unchecked") - private String[] getJarsExclusionList() - { - Set strings = new TreeSet<>(); - Set exclusions = loadJarRejectScanners(); - if (exclusions.iterator() - .hasNext()) - { - for (IGuiceScanJarExclusions exclusion : exclusions) - { - Set searches = exclusion.excludeJars(); - strings.addAll(searches); - } - GuiceContext.log.log(Level.FINE, "IGuiceScanJarExclusions - " + strings.toString()); - } - return strings.toArray(new String[0]); - } - - /** - * Returns a complete list of generic exclusions - * - * @return A string list of packages to be scanned - */ - @SuppressWarnings("unchecked") - private String[] getJarsInclusionList() - { - Set strings = new TreeSet<>(); - Set exclusions = loadJarInclusionScanners(); - if (exclusions.iterator() - .hasNext()) - { - for (IGuiceScanJarInclusions exclusion : exclusions) - { - Set searches = exclusion.includeJars(); - strings.addAll(searches); - } - GuiceContext.log.log(Level.FINE, "IGuiceScanJarExclusions - " + strings.toString()); - } - return strings.toArray(new String[0]); - } - - - /** - * Starts up Guice and the scanner - */ - private synchronized void loadScanner() - { - if (scanner == null) - { - scanner = new ClassGraph(); - Stopwatch stopwatch = Stopwatch.createStarted(); - GuiceContext.log.info("Loading Classpath Scanner"); - loadConfiguration(); - scanner = configureScanner(scanner); - try - { - if (async) - { - scanResult = scanner.scan(Runtime.getRuntime() - .availableProcessors()); - } - else - { - scanResult = scanner.scan(); - } - stopwatch.stop(); - Map fileScans = quickScanFiles(); - fileScans.forEach((key, value) -> - scanResult.getResourcesWithLeafName(key) - .forEachByteArrayIgnoringIOException(value)); - quickScanFilesPattern().forEach( - (key, value) -> - scanResult.getResourcesMatchingPattern(key) - .forEachByteArrayIgnoringIOException(value)); - - } - catch (Exception mpe) - { - GuiceContext.log.log(Level.SEVERE, "Unable to run scanner", mpe); - } - GuiceContext.log.fine("Loaded Classpath Scanner - Took [" + stopwatch.elapsed(TimeUnit.MILLISECONDS) + "] millis."); - } - } - - /** - * Configures the scanner from its setup - * - * @param graph The ClassGraph to apply the configuration to - */ - private ClassGraph configureScanner(ClassGraph graph) - { - if (config.isAllowPaths()) - { - String[] paths = getPathsList(); - if (paths.length != 0) - { - graph = graph.acceptPaths(paths); - } - } - if (GuiceContext.config.isExcludePaths()) - { - String[] blacklistList = getPathsBlacklistList(); - if (blacklistList.length != 0) - { - graph = graph.rejectPaths(blacklistList); - } - } - - if (GuiceContext.config.isExcludeModulesAndJars()) - { - if (getJavaVersion() < 9) - { - String[] jarRejections = getJarsExclusionList(); - if (jarRejections.length != 0) - { - graph = graph.rejectJars(jarRejections); - } - } - else - { - String[] modulesRejection = getModulesExclusionList(); - if (modulesRejection.length != 0) - { - graph = graph.rejectModules(modulesRejection); - } - else - { - graph = graph.ignoreParentModuleLayers(); - } - } - } - - if (GuiceContext.config.isIncludeModuleAndJars()) - { - if (getJavaVersion() < 9) - { - String[] jarRejections = getJarsInclusionList(); - log.config("Accepted Jars for Scanning : " + Arrays.toString(jarRejections)); - if (jarRejections.length != 0) - { - graph = graph.acceptJars(jarRejections); - } - } - else - { - String[] modulesRejection = getModulesInclusionsList(); - log.config("Accepted Modules for Scanning : " + Arrays.toString(modulesRejection)); - if (modulesRejection.length != 0) - { - graph = graph.acceptModules(modulesRejection); - } - else - { - graph = graph.ignoreParentModuleLayers(); - } - } - } - - if (GuiceContext.config.isIncludePackages()) - { - String[] packages = getPackagesList(); - if (packages.length != 0) - { - graph = graph.acceptPackages(packages); - } - } - if (GuiceContext.config.isRejectPackages()) - { - String[] packages = getBlacklistPackages(); - if (packages.length != 0) - { - graph = graph.rejectPackages(packages); - } - } - if (GuiceContext.config.isExcludeParentModules()) - { - graph = graph.ignoreParentModuleLayers(); - } - if (GuiceContext.config.isFieldInfo()) - { - graph = graph.enableClassInfo(); - graph = graph.enableFieldInfo(); - } - if (GuiceContext.config.isAnnotationScanning()) - { - graph = graph.enableClassInfo(); - graph = graph.enableAnnotationInfo(); - } - if (GuiceContext.config.isMethodInfo()) - { - graph = graph.enableClassInfo(); - graph = graph.enableMethodInfo(); - } - if (GuiceContext.config.isIgnoreFieldVisibility()) - { - graph = graph.enableClassInfo(); - graph = graph.ignoreFieldVisibility(); - } - if (GuiceContext.config.isIgnoreMethodVisibility()) - { - graph = graph.enableClassInfo(); - graph = graph.ignoreMethodVisibility(); - } - if (GuiceContext.config.isClasspathScanning()) - { - graph = graph.enableClassInfo(); - } - if (GuiceContext.config.isVerbose()) - { - graph = graph.verbose(); - } - if (GuiceContext.config.isIgnoreClassVisibility()) - { - graph = graph.ignoreClassVisibility(); - } - return graph; - } - - /** - * Returns a complete list of generic exclusions - * - * @return A string list of packages to be scanned - */ - private String[] getPackagesList() - { - Set strings = new LinkedHashSet<>(); - Set exclusions = getLoader(IPackageContentsScanner.class, true, ServiceLoader.load(IPackageContentsScanner.class)); - if (exclusions.iterator() - .hasNext()) - { - for (IPackageContentsScanner exclusion : exclusions) - { - GuiceContext.log.log(Level.CONFIG, "Loading IPackageContentsScanner - " + - exclusion.getClass() - .getCanonicalName()); - Set searches = exclusion.searchFor(); - strings.addAll(searches); - } - GuiceContext.log.log(Level.FINE, "IPackageScanningContentsScanner - " + strings.toString()); - } - return strings.toArray(new String[0]); - } - - /** - * Returns a complete list of generic exclusions - * - * @return A string list of packages to be scanned - */ - private String[] getBlacklistPackages() - { - Set strings = new LinkedHashSet<>(); - Set exclusions = getLoader(IPackageRejectListScanner.class, true, ServiceLoader.load(IPackageRejectListScanner.class)); - if (exclusions.iterator() - .hasNext()) - { - for (IPackageRejectListScanner exclusion : exclusions) - { - GuiceContext.log.log(Level.CONFIG, "Loading IPackageContentsScanner - " + - exclusion.getClass() - .getCanonicalName()); - Set searches = exclusion.exclude(); - strings.addAll(searches); - } - GuiceContext.log.log(Level.FINE, "IPackageScanningContentsScanner - " + strings.toString()); - } - return strings.toArray(new String[0]); - } - - /* - * Returns a complete list of generic exclusions - * - * @return A string list of packages to be scanned - */ - private String[] getPathsList() - { - Set strings = new TreeSet<>(); - Set exclusions = getLoader(IPathContentsScanner.class, true, ServiceLoader.load(IPathContentsScanner.class)); - if (exclusions.iterator() - .hasNext()) - { - for (IPathContentsScanner exclusion : exclusions) - { - GuiceContext.log.log(Level.CONFIG, "Loading IPathScanningContentsScanner - " + - exclusion.getClass() - .getCanonicalName()); - Set searches = exclusion.searchFor(); - strings.addAll(searches); - } - GuiceContext.log.log(Level.FINE, "IPathScanningContentsScanner - " + strings.toString()); - } - return strings.toArray(new String[0]); - } - - /** - * Returns a complete list of generic exclusions - * - * @return A string list of packages to be scanned - */ - private String[] getPathsBlacklistList() - { - Set strings = new TreeSet<>(); - Set exclusions = loadPathRejectScanners(); - if (exclusions.iterator() - .hasNext()) - { - for (IPathContentsRejectListScanner exclusion : exclusions) - { - GuiceContext.log.log(Level.CONFIG, "Loading IPathContentsRejectListScanner - " + - exclusion.getClass() - .getCanonicalName()); - Set searches = exclusion.searchFor(); - strings.addAll(searches); - } - GuiceContext.log.log(Level.FINE, "IPathContentsRejectListScanner - " + strings.toString()); - } - return strings.toArray(new String[0]); - } - - /** - * Returns a complete list of generic exclusions - * - * @return A string list of packages to be scanned - */ - @SuppressWarnings("unchecked") - private String[] getModulesExclusionList() - { - Set strings = new TreeSet<>(); - Set exclusions = getLoader(IGuiceScanModuleExclusions.class, true, ServiceLoader.load(IGuiceScanModuleExclusions.class)); - if (exclusions.iterator() - .hasNext()) - { - for (IGuiceScanModuleExclusions exclusion : exclusions) - { - Set searches = exclusion.excludeModules(); - strings.addAll(searches); - } - GuiceContext.log.log(Level.FINE, "IGuiceScanModuleExclusions - " + strings.toString()); - } - return strings.toArray(new String[0]); - } - - - /** - * Returns a complete list of generic exclusions - * - * @return A string list of packages to be scanned - */ - @SuppressWarnings("unchecked") - private String[] getModulesInclusionsList() - { - Set strings = new TreeSet<>(); - Set exclusions = getLoader(IGuiceScanModuleInclusions.class, true, ServiceLoader.load(IGuiceScanModuleInclusions.class)); - if (exclusions.iterator() - .hasNext()) - { - for (IGuiceScanModuleInclusions exclusion : exclusions) - { - Set searches = exclusion.includeModules(); - strings.addAll(searches); - } - GuiceContext.log.log(Level.FINE, "IGuiceScanModuleInclusions - " + strings.toString()); - } - return strings.toArray(new String[0]); - } - - /** - * Registers the quick scan files - */ - private Map quickScanFiles() - { - Map fileScans = new HashMap<>(); - Set fileScanners = getLoader(IFileContentsScanner.class, true, ServiceLoader.load(IFileContentsScanner.class)); - for (IFileContentsScanner fileScanner : fileScanners) - { - GuiceContext.log.log(Level.CONFIG, "Loading IFileContentsScanner - " + - fileScanner.getClass() - .getCanonicalName()); - fileScans.putAll(fileScanner.onMatch()); - } - return fileScans; - } - - /** - * Registers the quick scan files - */ - private Map quickScanFilesPattern() - { - Map fileScans = new HashMap<>(); - Set fileScanners = getLoader(IFileContentsPatternScanner.class, true, ServiceLoader.load(IFileContentsPatternScanner.class)); - for (IFileContentsPatternScanner fileScanner : fileScanners) - { - GuiceContext.log.log(Level.CONFIG, "Loading IFileContentsPatternScanner - " + - fileScanner.getClass() - .getCanonicalName()); - fileScans.putAll(fileScanner.onMatch()); - } - return fileScans; - } - - /** - * A set - * - * @param loaderType The service type - * @param The type - * @param dontInject Don't inject - * @return A set of them - */ - @SuppressWarnings("unchecked") - @NotNull - public Set getLoader(Class loaderType, - @SuppressWarnings("unused") - boolean dontInject, ServiceLoader serviceLoader) - { - if (!getAllLoadedServices().containsKey(loaderType)) - { - Set loader = IDefaultService.loaderToSetNoInjection(serviceLoader); - getAllLoadedServices().put(loaderType, loader); - } - return getAllLoadedServices().get(loaderType); - } - - /** - * Returns the current classpath scanner - * - * @return Default processors count - */ - @SuppressWarnings("unused") - public ClassGraph getScanner() - { - return scanner; - } - - /** - * Sets the classpath scanner - * - * @param scanner Sets the scanner to a specific instance - */ - @SuppressWarnings("unused") - public static void setScanner(ClassGraph scanner) - { - GuiceContext.instance().scanner = scanner; - } - - /** - * Method loadPostStartups ... - */ - private void loadPostStartups() - { - Set startupSet = loadPostStartupServices(); - - Map> postStartupGroups = new TreeMap<>(); - for (IGuicePostStartup postStartup : startupSet) - { - Integer sortOrder = postStartup.sortOrder(); - postStartupGroups.computeIfAbsent(sortOrder, k -> new TreeSet<>()) - .add(postStartup); - } - - for (Map.Entry> entry : postStartupGroups.entrySet()) - { - Integer key = entry.getKey(); - Set value = entry.getValue(); - if (value.size() == 1) - { - //run in order - for (IGuicePostStartup iGuicePostStartup : value) - { - try - { - iGuicePostStartup.postLoad(); - } - catch (Throwable T) - { - log.log(Level.SEVERE, "Cannot execute post startup - " + iGuicePostStartup.getClass() - .getCanonicalName(), T); - } - } - } - else - { - try - { - value.parallelStream() - .forEach(IGuicePostStartup::postLoad); - } - catch (Throwable T) - { - log.log(Level.SEVERE, "Cannot execute post startup - ", T); - } - } - GuiceContext.log.fine("Completed with Post Startups Key [" + key + "]"); - } - } - - /** - * Returns the Guice Config Instance - * - * @return The singleton Guice Config instance. Also available with @Inject - */ - public GuiceConfig getConfig() - { - if (GuiceContext.config == null) - { - GuiceContext.config = new GuiceConfig<>(); - } - return GuiceContext.config; - } - - /** - * Loads the service lists of post startup's for manual additions - * - * @return The list of guice post startups - */ - public @NotNull - Set loadPostStartupServices() - { - return getLoader(IGuicePostStartup.class, ServiceLoader.load(IGuicePostStartup.class)); - } - - /** - * Loads the service lists of post startup's for manual additions - * - * @return The list of guice post startups - */ - public @NotNull - Set loadPathRejectScanners() - { - return getLoader(IPathContentsRejectListScanner.class, true, ServiceLoader.load(IPathContentsRejectListScanner.class)); - } - - - /** - * Loads the service lists of post startup's for manual additions - * - * @return The list of guice post startups - */ - public @NotNull - Set loadJarRejectScanners() - { - return getLoader(IGuiceScanJarExclusions.class, true, ServiceLoader.load(IGuiceScanJarExclusions.class)); - } - - - /** - * Loads the service lists of post startup's for manual additions - * - * @return The list of guice post startups - */ - public @NotNull - Set loadJarInclusionScanners() - { - return getLoader(IGuiceScanJarInclusions.class, true, ServiceLoader.load(IGuiceScanJarInclusions.class)); - } - - - /** - * Returns the set of service lists of pre startup's for manual additions - * - * @return The list of guice post startups - */ - public @NotNull - Set loadPreStartupServices() - { - return getLoader(IGuicePreStartup.class, true, ServiceLoader.load(IGuicePreStartup.class)); - } - - /** - * Loads the service lists of post startup's for manual additions - * - * @return The list of guice post startups - */ - public @NotNull - Set loadIGuiceModules() - { - return getLoader(IGuiceModule.class, true, ServiceLoader.load(IGuiceModule.class)); - } - - /** - * Loads the service lists of guice configurators (before pre-startup) for manual additions - * - * @return The list of guice configs - */ - public @NotNull - Set loadIGuiceConfigs() - { - return getLoader(IGuiceConfigurator.class, true, ServiceLoader.load(IGuiceConfigurator.class)); - } - - /** - * Method loadPreStartups gets the pre startups and loads them up - */ - private void loadPreStartups() - { - Set preStartups = loadPreStartupServices(); - List startups = new ArrayList<>(preStartups); - startups.sort(Comparator.comparing(IGuicePreStartup::sortOrder)); - for (IGuicePreStartup startup : startups) - { - GuiceContext.log.config("Loading IGuicePreStartup - " + - startup.getClass() - .getCanonicalName()); - startup.onStartup(); - } - } - - /** - * Returns the loader for anything that is located locally in guice context - * replacing with set load methods instead for each type - * - * @param loaderType The service type - * @param The type - * @return A set of them - */ - @SuppressWarnings("unchecked") - @NotNull - public > Set getLoader(Class loaderType, ServiceLoader serviceLoader) - { - if (!getAllLoadedServices().containsKey(loaderType)) - { - Set loader; - if (GuiceContext.buildingInjector || injector == null) - { - loader = IDefaultService.loaderToSetNoInjection(serviceLoader); - } - else - { - loader = IDefaultService.loaderToSet(serviceLoader); - } - getAllLoadedServices().put(loaderType, loader); - } - return getAllLoadedServices().get(loaderType); - } - - /** - * Method getAllLoadedServices returns the allLoadedServices of this GuiceContext object. - *

- * A list of all the loaded singleton sets - * - * @return the allLoadedServices (type Map Class, Set ) of this GuiceContext object. - */ - @SuppressWarnings("WeakerAccess") - @NotNull - public static Map getAllLoadedServices() - { - return allLoadedServices; - } - - /** - * If this scanner is registered to run asynchronously - * - * @return - */ - public boolean isAsync() - { - return async; - } - - /** - * Sets if the scanner must run asynchronously - * - * @param async - */ - public void setAsync(boolean async) - { - this.async = async; - } + /** + * This particular instance of the class + */ + private static final GuiceContext instance = new GuiceContext<>(); + + /** + * A list of all the loaded singleton sets + */ + //private static final Map allLoadedServices = new LinkedHashMap<>(); + /** + * The building injector + */ + public static boolean buildingInjector = false; + /** + * The configuration object + */ + private static final GuiceConfig config = new GuiceConfig<>(); + /** + * The physical injector for the JVM container + */ + private Injector injector; + /** + * The actual scanner + */ + private ClassGraph scanner; + /** + * The scan result built from everything - the core scanner. + */ + private ScanResult scanResult; + /** + * If the scan should run async + */ + private boolean async = true; + /** + * If this context is configured + */ + private static boolean configured; + + /** + * Creates a new Guice context. Not necessary + */ + private GuiceContext() + { + //No config required + } + + + /** + * Reference the Injector Directly + * + * @return The global Guice Injector Object, Never Null, Instantiates the Injector if not configured + */ + + public synchronized Injector inject() + { + if (GuiceContext.buildingInjector) + { + log.log(Level.SEVERE, "The injector is being called recursively during build. Place such actions in a IGuicePostStartup or use the IGuicePreStartup Service Loader."); + System.exit(1); + } + if (GuiceContext.instance().injector == null) + { + try + { + GuiceContext.buildingInjector = true; + GuiceContext.log.info("Starting up Guice Context"); + GuiceContext + .instance() + .loadConfiguration(); + if (GuiceContext + .instance() + .getConfig() + .isPathScanning() || GuiceContext + .instance() + .getConfig() + .isClasspathScanning()) + { + GuiceContext + .instance() + .loadScanner(); + } + GuiceContext + .instance() + .loadPreStartups(); + + List cModules = new ArrayList<>(modules); + Set iGuiceModules = GuiceContext + .instance() + .loadIGuiceModules(); + cModules.addAll(iGuiceModules); + + //cModules.add(new GuiceInjectorModule()); + log.config("Modules - " + Arrays.toString(cModules.toArray())); + GuiceContext.instance().injector = Guice.createInjector(cModules); + GuiceContext.buildingInjector = false; + GuiceContext + .instance() + .loadPostStartups(); + + Runtime + .getRuntime() + .addShutdownHook(new Thread() + { + public void run() + { + IGuiceContext + .getContext() + .destroy(); + } + }); + + GuiceContext.log.config("Injection System Ready"); + } + catch (Throwable e) + { + GuiceContext.log.log(Level.SEVERE, "Exception creating Injector : " + e.getMessage(), e); + throw new RuntimeException("Unable to boot Guice Injector", e); + } + } + GuiceContext.buildingInjector = false; + return GuiceContext.instance().injector; + } + + private static Set destroyers = GuiceContext + .instance() + .getLoader(IGuicePreDestroy.class, false, ServiceLoader.load(IGuicePreDestroy.class)); + + /** + * Execute on Destroy + */ + @SuppressWarnings("unused") + public void destroy() + { + try + { + for (IGuicePreDestroy destroyer : destroyers) + { + try + { + destroyer.onDestroy(); + } + catch (Throwable T) + { + log.log(Level.SEVERE, + "Could not run destroyer [" + destroyer + .getClass() + .getCanonicalName() + "]"); + } + } + } + catch (Throwable T) + { + log.log(Level.SEVERE, "Could not run destroyers", T); + } + if (GuiceContext.instance().scanResult != null) + { + GuiceContext.instance().scanResult.close(); + } + if (GuiceContext.instance().scanResult != null) + { + GuiceContext.instance().scanResult.close(); + } + GuiceContext.instance().scanResult = null; + GuiceContext.instance().scanner = null; + GuiceContext.instance().injector = null; + } + + /** + * Returns the Java version as an int value. + * + * @return the Java version as an int value (8, 9, etc.) + * @since 12130 + */ + private static int getJavaVersion() + { + String version = getSystemPropertyOrEnvironment("java.version", "11"); + if (version.startsWith("1.")) + { + version = version.substring(2); + } + // Allow these formats: + // 1.8.0_72-ea + // 9-ea + // 9 + // 9.0.1 + int dotPos = version.indexOf('.'); + int dashPos = version.indexOf('-'); + String value = version.substring(0, dotPos > -1 ? dotPos : dashPos > -1 ? dashPos : version.length()); + return Integer.parseInt(value); + } + + /** + * Returns the current scan result + * + * @return The physical Scan Result from the complete class scanner + */ + + public ScanResult getScanResult() + { + if (scanResult == null) + { + loadScanner(); + } + return scanResult; + } + + /** + * Sets the current scan result + * + * @param scanResult The physical Scan Result from the complete class scanner + */ + @SuppressWarnings("unused") + public void setScanResult(ScanResult scanResult) + { + GuiceContext.instance().scanResult = scanResult; + } + + /** + * Returns the actual context instance, provides access to methods existing a bit deeper + * + * @return The singleton instance of this + */ + public static GuiceContext instance() + { + return GuiceContext.instance; + } + + /** + * Loads the IGuiceConfigurator + */ + private void loadConfiguration() + { + if (!configured) + { + Set guiceConfigurators = loadIGuiceConfigs(); + for (IGuiceConfigurator guiceConfigurator : guiceConfigurators) + { + GuiceContext.log.config("Loading IGuiceConfigurator - " + guiceConfigurator + .getClass() + .getCanonicalName()); + guiceConfigurator.configure(GuiceContext.config); + } + if (!GuiceContext.config.isIncludeModuleAndJars()) + { + log.warning("Scanning is not restricted to modules and may incur a performance impact. Consider registering your module with GuiceContext.registerModule() to auto enable, or SPI IGuiceConfiguration"); + } + GuiceContext.log.config("IGuiceConfigurator : " + GuiceContext.config.toString()); + configured = true; + } + } + + /** + * Returns a complete list of generic exclusions + * + * @return A string list of packages to be scanned + */ + @SuppressWarnings("unchecked") + private String[] getJarsExclusionList() + { + Set strings = new TreeSet<>(); + Set exclusions = loadJarRejectScanners(); + if (exclusions + .iterator() + .hasNext()) + { + for (IGuiceScanJarExclusions exclusion : exclusions) + { + Set searches = exclusion.excludeJars(); + strings.addAll(searches); + } + GuiceContext.log.log(Level.FINE, "IGuiceScanJarExclusions - " + strings.toString()); + } + return strings.toArray(new String[0]); + } + + /** + * Returns a complete list of generic exclusions + * + * @return A string list of packages to be scanned + */ + @SuppressWarnings("unchecked") + private String[] getJarsInclusionList() + { + Set strings = new TreeSet<>(); + Set exclusions = loadJarInclusionScanners(); + if (exclusions + .iterator() + .hasNext()) + { + for (IGuiceScanJarInclusions exclusion : exclusions) + { + Set searches = exclusion.includeJars(); + strings.addAll(searches); + } + GuiceContext.log.log(Level.FINE, "IGuiceScanJarExclusions - " + strings.toString()); + } + return strings.toArray(new String[0]); + } + + + /** + * Starts up Guice and the scanner + */ + private synchronized void loadScanner() + { + if (scanner == null) + { + scanner = new ClassGraph(); + Stopwatch stopwatch = Stopwatch.createStarted(); + GuiceContext.log.info("Loading Classpath Scanner"); + loadConfiguration(); + scanner = configureScanner(scanner); + try + { + if (async) + { + scanResult = scanner.scan(Runtime + .getRuntime() + .availableProcessors()); + } + else + { + scanResult = scanner.scan(); + } + stopwatch.stop(); + Map fileScans = quickScanFiles(); + fileScans.forEach((key, value) -> scanResult + .getResourcesWithLeafName(key) + .forEachByteArrayIgnoringIOException(value)); + quickScanFilesPattern().forEach((key, value) -> scanResult + .getResourcesMatchingPattern(key) + .forEachByteArrayIgnoringIOException(value)); + + } + catch (Exception mpe) + { + GuiceContext.log.log(Level.SEVERE, "Unable to run scanner", mpe); + } + GuiceContext.log.fine("Loaded Classpath Scanner - Took [" + stopwatch.elapsed(TimeUnit.MILLISECONDS) + "] millis."); + } + } + + /** + * Configures the scanner from its setup + * + * @param graph The ClassGraph to apply the configuration to + */ + private ClassGraph configureScanner(ClassGraph graph) + { + if (config.isAllowPaths()) + { + String[] paths = getPathsList(); + if (paths.length != 0) + { + graph = graph.acceptPaths(paths); + } + } + if (GuiceContext.config.isExcludePaths()) + { + String[] blacklistList = getPathsBlacklistList(); + if (blacklistList.length != 0) + { + graph = graph.rejectPaths(blacklistList); + } + } + + if (GuiceContext.config.isExcludeModulesAndJars()) + { + if (getJavaVersion() < 9) + { + String[] jarRejections = getJarsExclusionList(); + if (jarRejections.length != 0) + { + graph = graph.rejectJars(jarRejections); + } + } + else + { + String[] modulesRejection = getModulesExclusionList(); + if (modulesRejection.length != 0) + { + graph = graph.rejectModules(modulesRejection); + } + else + { + graph = graph.ignoreParentModuleLayers(); + } + } + } + + if (GuiceContext.config.isIncludeModuleAndJars()) + { + if (getJavaVersion() < 9) + { + String[] jarRejections = getJarsInclusionList(); + log.config("Accepted Jars for Scanning : " + Arrays.toString(jarRejections)); + if (jarRejections.length != 0) + { + graph = graph.acceptJars(jarRejections); + } + } + else + { + String[] modulesRejection = getModulesInclusionsList(); + log.config("Accepted Modules for Scanning : " + Arrays.toString(modulesRejection)); + if (modulesRejection.length != 0) + { + graph = graph.acceptModules(modulesRejection); + } + else + { + graph = graph.ignoreParentModuleLayers(); + } + } + } + + if (GuiceContext.config.isIncludePackages()) + { + String[] packages = getPackagesList(); + if (packages.length != 0) + { + graph = graph.acceptPackages(packages); + } + } + if (GuiceContext.config.isRejectPackages()) + { + String[] packages = getBlacklistPackages(); + if (packages.length != 0) + { + graph = graph.rejectPackages(packages); + } + } + if (GuiceContext.config.isExcludeParentModules()) + { + graph = graph.ignoreParentModuleLayers(); + } + if (GuiceContext.config.isFieldInfo()) + { + graph = graph.enableClassInfo(); + graph = graph.enableFieldInfo(); + } + if (GuiceContext.config.isAnnotationScanning()) + { + graph = graph.enableClassInfo(); + graph = graph.enableAnnotationInfo(); + } + if (GuiceContext.config.isMethodInfo()) + { + graph = graph.enableClassInfo(); + graph = graph.enableMethodInfo(); + } + if (GuiceContext.config.isIgnoreFieldVisibility()) + { + graph = graph.enableClassInfo(); + graph = graph.ignoreFieldVisibility(); + } + if (GuiceContext.config.isIgnoreMethodVisibility()) + { + graph = graph.enableClassInfo(); + graph = graph.ignoreMethodVisibility(); + } + if (GuiceContext.config.isClasspathScanning()) + { + graph = graph.enableClassInfo(); + } + if (GuiceContext.config.isVerbose()) + { + graph = graph.verbose(); + } + if (GuiceContext.config.isIgnoreClassVisibility()) + { + graph = graph.ignoreClassVisibility(); + } + return graph; + } + + /** + * Returns a complete list of generic exclusions + * + * @return A string list of packages to be scanned + */ + private String[] getPackagesList() + { + Set strings = new LinkedHashSet<>(); + Set exclusions = getLoader(IPackageContentsScanner.class, true, ServiceLoader.load(IPackageContentsScanner.class)); + if (exclusions + .iterator() + .hasNext()) + { + for (IPackageContentsScanner exclusion : exclusions) + { + GuiceContext.log.log(Level.CONFIG, + "Loading IPackageContentsScanner - " + exclusion + .getClass() + .getCanonicalName()); + Set searches = exclusion.searchFor(); + strings.addAll(searches); + } + GuiceContext.log.log(Level.FINE, "IPackageScanningContentsScanner - " + strings.toString()); + } + return strings.toArray(new String[0]); + } + + /** + * Returns a complete list of generic exclusions + * + * @return A string list of packages to be scanned + */ + private String[] getBlacklistPackages() + { + Set strings = new LinkedHashSet<>(); + Set exclusions = getLoader(IPackageRejectListScanner.class, true, ServiceLoader.load(IPackageRejectListScanner.class)); + if (exclusions + .iterator() + .hasNext()) + { + for (IPackageRejectListScanner exclusion : exclusions) + { + GuiceContext.log.log(Level.CONFIG, + "Loading IPackageContentsScanner - " + exclusion + .getClass() + .getCanonicalName()); + Set searches = exclusion.exclude(); + strings.addAll(searches); + } + GuiceContext.log.log(Level.FINE, "IPackageScanningContentsScanner - " + strings.toString()); + } + return strings.toArray(new String[0]); + } + + /* + * Returns a complete list of generic exclusions + * + * @return A string list of packages to be scanned + */ + private String[] getPathsList() + { + Set strings = new TreeSet<>(); + Set exclusions = getLoader(IPathContentsScanner.class, true, ServiceLoader.load(IPathContentsScanner.class)); + if (exclusions + .iterator() + .hasNext()) + { + for (IPathContentsScanner exclusion : exclusions) + { + GuiceContext.log.log(Level.CONFIG, + "Loading IPathScanningContentsScanner - " + exclusion + .getClass() + .getCanonicalName()); + Set searches = exclusion.searchFor(); + strings.addAll(searches); + } + GuiceContext.log.log(Level.FINE, "IPathScanningContentsScanner - " + strings.toString()); + } + return strings.toArray(new String[0]); + } + + /** + * Returns a complete list of generic exclusions + * + * @return A string list of packages to be scanned + */ + private String[] getPathsBlacklistList() + { + Set strings = new TreeSet<>(); + Set exclusions = loadPathRejectScanners(); + if (exclusions + .iterator() + .hasNext()) + { + for (IPathContentsRejectListScanner exclusion : exclusions) + { + GuiceContext.log.log(Level.CONFIG, + "Loading IPathContentsRejectListScanner - " + exclusion + .getClass() + .getCanonicalName()); + Set searches = exclusion.searchFor(); + strings.addAll(searches); + } + GuiceContext.log.log(Level.FINE, "IPathContentsRejectListScanner - " + strings.toString()); + } + return strings.toArray(new String[0]); + } + + /** + * Returns a complete list of generic exclusions + * + * @return A string list of packages to be scanned + */ + @SuppressWarnings("unchecked") + private String[] getModulesExclusionList() + { + Set strings = new TreeSet<>(); + Set exclusions = getLoader(IGuiceScanModuleExclusions.class, true, ServiceLoader.load(IGuiceScanModuleExclusions.class)); + if (exclusions + .iterator() + .hasNext()) + { + for (IGuiceScanModuleExclusions exclusion : exclusions) + { + Set searches = exclusion.excludeModules(); + strings.addAll(searches); + } + GuiceContext.log.log(Level.FINE, "IGuiceScanModuleExclusions - " + strings.toString()); + } + return strings.toArray(new String[0]); + } + + /** + * Returns a complete list of generic exclusions + * + * @return A string list of packages to be scanned + */ + @SuppressWarnings("unchecked") + private String[] getModulesInclusionsList() + { + Set strings = new TreeSet<>(); + strings.addAll(registerModuleForScanning); + Set exclusions = getLoader(IGuiceScanModuleInclusions.class, true, ServiceLoader.load(IGuiceScanModuleInclusions.class)); + if (exclusions + .iterator() + .hasNext()) + { + for (IGuiceScanModuleInclusions exclusion : exclusions) + { + Set searches = exclusion.includeModules(); + strings.addAll(searches); + } + GuiceContext.log.log(Level.FINE, "IGuiceScanModuleInclusions - " + strings.toString()); + } + return strings.toArray(new String[0]); + } + + /** + * Registers the quick scan files + */ + private Map quickScanFiles() + { + Map fileScans = new HashMap<>(); + Set fileScanners = getLoader(IFileContentsScanner.class, true, ServiceLoader.load(IFileContentsScanner.class)); + for (IFileContentsScanner fileScanner : fileScanners) + { + GuiceContext.log.log(Level.CONFIG, + "Loading IFileContentsScanner - " + fileScanner + .getClass() + .getCanonicalName()); + fileScans.putAll(fileScanner.onMatch()); + } + return fileScans; + } + + /** + * Registers the quick scan files + */ + private Map quickScanFilesPattern() + { + Map fileScans = new HashMap<>(); + Set fileScanners = getLoader(IFileContentsPatternScanner.class, true, ServiceLoader.load(IFileContentsPatternScanner.class)); + for (IFileContentsPatternScanner fileScanner : fileScanners) + { + GuiceContext.log.log(Level.CONFIG, + "Loading IFileContentsPatternScanner - " + fileScanner + .getClass() + .getCanonicalName()); + fileScans.putAll(fileScanner.onMatch()); + } + return fileScans; + } + + /** + * A set + * + * @param loaderType The service type + * @param The type + * @param dontInject Don't inject + * @return A set of them + */ + @SuppressWarnings("unchecked") + + public Set getLoader(Class loaderType, @SuppressWarnings("unused") boolean dontInject, ServiceLoader serviceLoader) + { + if (!IGuiceContext + .getAllLoadedServices() + .containsKey(loaderType)) + { + Set loader = IGuiceContext.loaderToSetNoInjection(serviceLoader); + IGuiceContext + .getAllLoadedServices() + .put(loaderType, loader); + } + return IGuiceContext + .getAllLoadedServices() + .get(loaderType); + } + + @Override + public boolean isBuildingInjector() + { + return buildingInjector; + } + + /** + * Returns the current classpath scanner + * + * @return Default processors count + */ + @SuppressWarnings("unused") + public ClassGraph getScanner() + { + return scanner; + } + + /** + * Sets the classpath scanner + * + * @param scanner Sets the scanner to a specific instance + */ + @SuppressWarnings("unused") + public static void setScanner(ClassGraph scanner) + { + GuiceContext.instance().scanner = scanner; + } + + /** + * Method loadPostStartups ... + */ + private void loadPostStartups() + { + Set startupSet = loadPostStartupServices(); + Map> groupedPostStartup = startupSet.stream() + .collect(groupingBy(IGuicePostStartup::sortOrder, toSet())); + /* Map>> postStartupGroups = new TreeMap<>(); + + for (IGuicePostStartup postStartup : startupSet) + { + Integer sortOrder = postStartup.sortOrder(); + postStartupGroups + .computeIfAbsent(sortOrder, k -> new TreeSet<>()) + .add(postStartup); + } +*/ + for (Map.Entry> entry : groupedPostStartup.entrySet()) + { + Integer key = entry.getKey(); + Set value = entry.getValue(); + if (value.size() == 1) + { + //run in order + for (IGuicePostStartup iGuicePostStartup : value) + { + try + { + iGuicePostStartup.postLoad(); + } + catch (Throwable T) + { + log.log(Level.SEVERE, + "Cannot execute post startup - " + iGuicePostStartup + .getClass() + .getCanonicalName(), + T); + } + } + } + else + { + log.info("Starting Post Startup Group [" + key + "] in Parallel"); + List> futures = new ArrayList<>(); + for (IGuicePostStartup iGuicePostStartup : value) + { + futures.add(CompletableFuture.runAsync(iGuicePostStartup::postLoad)); + } + try + { + CompletableFuture.allOf(futures.toArray(new CompletableFuture[]{})).join(); + } + catch (Exception e) + { + log.log(Level.SEVERE, "Exception in completing post startups", e); + } + } + GuiceContext.log.fine("Completed with Post Startups Key [" + key + "]"); + } + } + + /** + * Returns the Guice Config Instance + * + * @return The singleton Guice Config instance. Also available with @Inject + */ + public GuiceConfig getConfig() + { + return GuiceContext.config; + } + + /** + * Loads the service lists of post startup's for manual additions + * + * @return The list of guice post startups + */ + public Set loadPostStartupServices() + { + return new TreeSet<>(getLoader(IGuicePostStartup.class, ServiceLoader.load(IGuicePostStartup.class))); + } + + /** + * Loads the service lists of post startup's for manual additions + * + * @return The list of guice post startups + */ + public Set loadPathRejectScanners() + { + return getLoader(IPathContentsRejectListScanner.class, true, ServiceLoader.load(IPathContentsRejectListScanner.class)); + } + + + /** + * Loads the service lists of post startup's for manual additions + * + * @return The list of guice post startups + */ + public Set loadJarRejectScanners() + { + return getLoader(IGuiceScanJarExclusions.class, true, ServiceLoader.load(IGuiceScanJarExclusions.class)); + } + + + /** + * Loads the service lists of post startup's for manual additions + * + * @return The list of guice post startups + */ + public Set loadJarInclusionScanners() + { + return getLoader(IGuiceScanJarInclusions.class, true, ServiceLoader.load(IGuiceScanJarInclusions.class)); + } + + + /** + * Returns the set of service lists of pre startup's for manual additions + * + * @return The list of guice post startups + */ + public Set loadPreStartupServices() + { + return new TreeSet<>(getLoader(IGuicePreStartup.class, true, ServiceLoader.load(IGuicePreStartup.class))); + } + + /** + * Loads the service lists of post startup's for manual additions + * + * @return The list of guice post startups + */ + public Set loadIGuiceModules() + { + return new TreeSet<>(getLoader(IGuiceModule.class, true, ServiceLoader.load(IGuiceModule.class))); + } + + /** + * Loads the service lists of guice configurators (before pre-startup) for manual additions + * + * @return The list of guice configs + */ + public Set loadIGuiceConfigs() + { + return getLoader(IGuiceConfigurator.class, true, ServiceLoader.load(IGuiceConfigurator.class)); + } + + /** + * Method loadPreStartups gets the pre startups and loads them up + */ + private void loadPreStartups() + { + Set preStartups = loadPreStartupServices(); + for (IGuicePreStartup startup : preStartups) + { + GuiceContext.log.config("Loading IGuicePreStartup - " + startup + .getClass() + .getCanonicalName()); + startup.onStartup(); + } + } + + /** + * Returns the loader for anything that is located locally in guice context + * replacing with set load methods instead for each type + * + * @param loaderType The service type + * @param The type + * @return A set of them + */ + @SuppressWarnings("unchecked") + + public > Set getLoader(Class loaderType, ServiceLoader serviceLoader) + { + if (!IGuiceContext + .getAllLoadedServices() + .containsKey(loaderType)) + { + Set loader; + if (GuiceContext.buildingInjector || injector == null) + { + loader = IGuiceContext.loaderToSetNoInjection(serviceLoader); + } + else + { + loader = IGuiceContext.loaderToSet(serviceLoader); + } + IGuiceContext + .getAllLoadedServices() + .put(loaderType, loader); + } + return IGuiceContext + .getAllLoadedServices() + .get(loaderType); + } + + /** + * If this scanner is registered to run asynchronously + * + * @return + */ + public boolean isAsync() + { + return async; + } + + /** + * Sets if the scanner must run asynchronously + * + * @param async + */ + public void setAsync(boolean async) + { + this.async = async; + } } diff --git a/src/main/java/com/guicedee/guicedinjection/JobService.java b/src/main/java/com/guicedee/guicedinjection/JobService.java new file mode 100644 index 0000000..f03ecb0 --- /dev/null +++ b/src/main/java/com/guicedee/guicedinjection/JobService.java @@ -0,0 +1,389 @@ +package com.guicedee.guicedinjection; + +import com.google.inject.Singleton; +import com.guicedee.guicedinjection.interfaces.*; +import lombok.Getter; +import lombok.Setter; +import lombok.extern.java.Log; + +import java.util.Map; +import java.util.Set; +import java.util.concurrent.*; +import java.util.logging.Level; + + +/** + * Manages All Concurrent Threaded Jobs that execute asynchronously outside of the EE Context + */ + +@Singleton +@Log +public class JobService implements IGuicePreDestroy, IJobService +{ + private final Map serviceMap = new ConcurrentHashMap<>(); + private final Map pollingMap = new ConcurrentHashMap<>(); + private final Map maxQueueCount = new ConcurrentHashMap<>(); + + private final ExecutorServiceSupplier executorServiceSupplier = new ExecutorServiceSupplier(); + + @Getter + @Setter + private static long defaultWaitTime = 120; + @Getter + @Setter + private static TimeUnit defaultWaitUnit = TimeUnit.SECONDS; + + public static final JobService INSTANCE = new JobService(); + private static ExecutorService jobCleanup = null; + + static + { + jobCleanup = INSTANCE.jobCleanup(); + } + + public JobService() + { + //No config required + } + + /** + * Gets a list of all job pools currently registered + * + * @return + */ + @Override + public Set getJobPools() + { + return serviceMap.keySet(); + } + + /** + * Returns the list of repeating task pools registered + * + * @return + */ + @Override + public Set getPollingPools() + { + return pollingMap.keySet(); + } + + /** + * Completes and Removes all jobs running from the given pool + * + * @param pool The pool to remove + */ + @Override + public ExecutorService removeJob(String pool) + { + ExecutorService es = serviceMap.get(pool); + if (es == null) + { + log.warning("Pool " + pool + " was not registered"); + return null; + } + waitForJob(pool); + serviceMap.remove(pool); + return es; + } + + /** + * Completes and Removes all jobs running from the given pool + * + * @param pool The pool to remove + */ + public ExecutorService removeJobNoWait(String pool) + { + ExecutorService es = serviceMap.get(pool); + if (es == null) + { + log.warning("Pool " + pool + " was not registered"); + return null; + } + waitForJob(pool,1L,TimeUnit.MILLISECONDS); + serviceMap.remove(pool); + return es; + } + + /** + * Completes and Removes all jobs running from the given pool + * + * @param pool The pool name to remove + */ + @Override + public ScheduledExecutorService removePollingJob(String pool) + { + ScheduledExecutorService es = pollingMap.get(pool); + if (es == null) + { + log.warning("Repeating Pool " + pool + " was not registered"); + return null; + } + waitForJob(pool); + pollingMap.remove(pool); + return es; + } + + /** + * Registers a new job pool with a specific service + * + * @param name + * @param executorService + */ + @Override + public ExecutorService registerJobPool(String name, ExecutorService executorService) + { + if (serviceMap.containsKey(name)) + { + removeJob(name); + } + serviceMap.put(name, executorService); + if (!maxQueueCount.containsKey(name)) + { + maxQueueCount.put(name, 20); + } + if (executorService instanceof ForkJoinPool) + { + ForkJoinPool pool = (ForkJoinPool) executorService; + } + else if (executorService instanceof ThreadPoolExecutor) + { + ThreadPoolExecutor executor = (ThreadPoolExecutor) executorService; + executor.setMaximumPoolSize(maxQueueCount.get(name)); + executor.setKeepAliveTime(defaultWaitTime, defaultWaitUnit); + executor.setRejectedExecutionHandler(new ThreadPoolExecutor.DiscardPolicy()); + } + + return executorService; + } + + /** + * Registers a repeating task to be registered and monitored + * + * @param name The name of the pool + * @param executorService The service executor + */ + @Override + public ScheduledExecutorService registerJobPollingPool(String name, ScheduledExecutorService executorService) + { + if (pollingMap.containsKey(name)) + { + removeJob(name); + } + pollingMap.put(name, executorService); + return executorService; + } + + /** + * Adds a static run once job to the monitored collections + * + * @param jobPoolName + * @param thread + */ + @Override + public ExecutorService addJob(String jobPoolName, Runnable thread) + { + if (!serviceMap.containsKey(jobPoolName) || serviceMap + .get(jobPoolName) + .isTerminated() || serviceMap + .get(jobPoolName) + .isShutdown()) + { + registerJobPool(jobPoolName, executorServiceSupplier.get()); + } + + ExecutorService service = serviceMap.get(jobPoolName); + if (getCurrentTaskCount(service) >= maxQueueCount.get(jobPoolName)) + { + log.log(Level.FINER, maxQueueCount + " Hit - Finishing before next run"); + removeJob(jobPoolName); + service = registerJobPool(jobPoolName, executorServiceSupplier.get()); + } + service.execute(thread); + return service; + } + + /** + * Adds a static run once job to the monitored collections + * + * @param jobPoolName + * @param thread + */ + @Override + public Future addTask(String jobPoolName, Callable thread) + { + if (!serviceMap.containsKey(jobPoolName) || serviceMap + .get(jobPoolName) + .isTerminated() || serviceMap + .get(jobPoolName) + .isShutdown()) + { + registerJobPool(jobPoolName, executorServiceSupplier.get()); + } + + ExecutorService service = serviceMap.get(jobPoolName); + if (getCurrentTaskCount(service) >= maxQueueCount.get(jobPoolName)) + { + log.log(Level.FINER, maxQueueCount + " Hit - Finishing before next run"); + removeJob(jobPoolName); + service = registerJobPool(jobPoolName, executorServiceSupplier.get()); + } + return service.submit(thread); + } + + @Override + public void waitForJob(String jobName) + { + waitForJob(jobName, defaultWaitTime, defaultWaitUnit); + } + + @Override + public void waitForJob(String jobName, long timeout, TimeUnit unit) + { + if (!serviceMap.containsKey(jobName)) + { + return; + } + ExecutorService service = serviceMap.get(jobName); + service.shutdown(); + try + { + service.awaitTermination(timeout, unit); + } + catch (InterruptedException e) + { + log.log(Level.WARNING, "Thread didn't close cleanly, make sure running times are acceptable", e); + service.shutdownNow(); + } + if (!service.isTerminated()) + { + service.shutdownNow(); + } + service.close(); + } + + private ExecutorService jobCleanup() + { + ScheduledExecutorService jobsShutdownNotClosed = addPollingJob("JobsShutdownNotClosed", () -> { + for (String jobPool : getJobPools()) + { + ExecutorService executorService = serviceMap.get(jobPool); + if (executorService.isShutdown() && !executorService.isTerminated()) + { + log.fine("Closing unfinished job - " + jobPool); + removeJob(jobPool); + } + if (executorService.isShutdown() && executorService.isTerminated()) + { + log.fine("Cleaning terminated job - " + jobPool); + executorService.close(); + serviceMap.remove(jobPool); + } + } + }, 2, TimeUnit.MINUTES); + + return jobsShutdownNotClosed; + } + + /** + * Adds a static run once job to the monitored collections + * + * @param jobPoolName + * @param thread + */ + @Override + public ScheduledExecutorService addPollingJob(String jobPoolName, Runnable thread, long delay, TimeUnit unit) + { + if (!pollingMap.containsKey(jobPoolName) || pollingMap + .get(jobPoolName) + .isTerminated() || pollingMap + .get(jobPoolName) + .isShutdown()) + { + registerJobPollingPool(jobPoolName, + Executors.newScheduledThreadPool(Runtime + .getRuntime() + .availableProcessors())); + } + ScheduledExecutorService service = pollingMap.get(jobPoolName); + service.scheduleAtFixedRate(thread, 1L, delay, unit); + return service; + } + + /** + * Adds a static run once job to the monitored collections + * + * @param jobPoolName + * @param thread + */ + @Override + public ScheduledExecutorService addPollingJob(String jobPoolName, Runnable thread, long initialDelay, long delay, TimeUnit unit) + { + if (!pollingMap.containsKey(jobPoolName) || pollingMap + .get(jobPoolName) + .isTerminated() || pollingMap + .get(jobPoolName) + .isShutdown()) + { + registerJobPollingPool(jobPoolName, + Executors.newScheduledThreadPool(Runtime + .getRuntime() + .availableProcessors())); + } + ScheduledExecutorService service = pollingMap.get(jobPoolName); + service.scheduleAtFixedRate(thread, initialDelay, delay, unit); + return service; + } + + /** + * Shutdowns + */ + @Override + public void destroy() + { + log.config("Destroying all running jobs..."); + serviceMap.forEach((key, value) -> { + log.config("Shutting Down [" + key + "]"); + removeJob(key); + }); + pollingMap.forEach((key, value) -> { + log.config("Shutting Down Poll Job [" + key + "]"); + removePollingJob(key); + }); + log.config("All jobs destroyed"); + } + + private int getCurrentTaskCount(ExecutorService service) + { + if (service instanceof ForkJoinPool) + { + ForkJoinPool pool = (ForkJoinPool) service; + return (int) pool.getQueuedTaskCount(); + } + else if (service instanceof ThreadPoolExecutor) + { + ThreadPoolExecutor executor = (ThreadPoolExecutor) service; + return (int) executor.getTaskCount(); + } + return 0; + } + + public void setMaxQueueCount(String queueName, int queueCount) + { + maxQueueCount.put(queueName, queueCount); + } + + @Override + public void onDestroy() + { + destroy(); + } + + @Override + public Integer sortOrder() + { + return Integer.MIN_VALUE + 8; + } + + +} diff --git a/src/main/java/com/guicedee/guicedinjection/SysStreamsLogger.java b/src/main/java/com/guicedee/guicedinjection/SysStreamsLogger.java deleted file mode 100644 index 174601a..0000000 --- a/src/main/java/com/guicedee/guicedinjection/SysStreamsLogger.java +++ /dev/null @@ -1,188 +0,0 @@ -package com.guicedee.guicedinjection; -import java.io.IOException; -import java.io.PrintStream; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import static com.guicedee.guicedinjection.properties.GlobalProperties.*; - -public class SysStreamsLogger { - private static Logger sysOutLogger = LoggerFactory.getLogger("SYSOUT"); - private static Logger sysErrLogger = LoggerFactory.getLogger("SYSERR"); - - public static final PrintStream sysout = System.out; - public static final PrintStream syserr = System.err; - - protected static final String LINE_SEPERATOR = getSystemPropertyOrEnvironment("line.separator","\n"); - - public static void bindSystemStreams() { - // Enable autoflush - System.setOut(new PrintStream(new LoggingOutputStream(sysOutLogger, false), true)); - System.setErr(new PrintStream(new LoggingOutputStream(sysErrLogger, true), true)); - } - - public static void unbindSystemStreams() { - System.setOut(sysout); - System.setErr(syserr); - } - - private static class LoggingOutputStream extends java.io.OutputStream { - - protected Logger log; - protected boolean isError; - - /** - * Used to maintain the contract of {@link #close()}. - */ - protected boolean hasBeenClosed = false; - - /** - * The internal buffer where data is stored. - */ - protected byte[] buf; - - /** - * The number of valid bytes in the buffer. This value is always in the - * range 0 through buf.length; elements - * buf[0] through buf[count-1] contain valid byte - * data. - */ - protected int count; - - /** - * Remembers the size of the buffer for speed. - */ - private int bufLength; - - /** - * The default number of bytes in the buffer. =2048 - */ - public static final int DEFAULT_BUFFER_LENGTH = 2048; - - private LoggingOutputStream() { - // illegal - } - - /** - * Creates the LoggingOutputStream to flush to the given Category. - * - * @param log - * the Logger to write to - * - * @param isError - * the if true write to error, else info - * - * @exception IllegalArgumentException - * if cat == null or priority == null - */ - public LoggingOutputStream(Logger log, boolean isError) throws IllegalArgumentException { - if (log == null) { - throw new IllegalArgumentException("log == null"); - } - - this.isError = isError; - this.log = log; - bufLength = DEFAULT_BUFFER_LENGTH; - buf = new byte[DEFAULT_BUFFER_LENGTH]; - count = 0; - } - - /** - * Closes this output stream and releases any system resources - * associated with this stream. The general contract of - * close is that it closes the output stream. A closed - * stream cannot perform output operations and cannot be reopened. - */ - @Override - public void close() { - flush(); - hasBeenClosed = true; - } - - /** - * Writes the specified byte to this output stream. The general contract - * for write is that one byte is written to the output - * stream. The byte to be written is the eight low-order bits of the - * argument b. The 24 high-order bits of b are - * ignored. - * - * @param b - * the byte to write - */ - @Override - public void write(final int b) throws IOException { - if (hasBeenClosed) { - throw new IOException("The stream has been closed."); - } - - // don't log nulls - if (b == 0) { - return; - } - - // would this be writing past the buffer? - if (count == bufLength) { - // grow the buffer - final int newBufLength = bufLength + DEFAULT_BUFFER_LENGTH; - final byte[] newBuf = new byte[newBufLength]; - - System.arraycopy(buf, 0, newBuf, 0, bufLength); - - buf = newBuf; - bufLength = newBufLength; - } - - buf[count] = (byte) b; - count++; - } - - /** - * Flushes this output stream and forces any buffered output bytes to be - * written out. The general contract of flush is that - * calling it is an indication that, if any bytes previously written - * have been buffered by the implementation of the output stream, such - * bytes should immediately be written to their intended destination. - */ - @Override - public void flush() { - - if (count == 0) { - return; - } - - // don't print out blank lines; flushing from PrintStream puts out - // these - if (count == LINE_SEPERATOR.length()) { - if (((char) buf[0]) == LINE_SEPERATOR.charAt(0) && ((count == 1) || // <- - // Unix - // & - // Mac, - // -> - // Windows - ((count == 2) && ((char) buf[1]) == LINE_SEPERATOR.charAt(1)))) { - reset(); - return; - } - } - - final byte[] theBytes = new byte[count]; - - System.arraycopy(buf, 0, theBytes, 0, count); - - if (isError) { - log.error(new String(theBytes)); - } else { - log.info(new String(theBytes)); - } - - reset(); - } - - private void reset() { - // not resetting the buffer -- assuming that if it grew that it - // will likely grow similarly again - count = 0; - } - } -} \ No newline at end of file diff --git a/src/main/java/com/guicedee/guicedinjection/abstractions/GuiceInjectorModule.java b/src/main/java/com/guicedee/guicedinjection/abstractions/GuiceInjectorModule.java deleted file mode 100644 index 178a605..0000000 --- a/src/main/java/com/guicedee/guicedinjection/abstractions/GuiceInjectorModule.java +++ /dev/null @@ -1,244 +0,0 @@ -/* - * Copyright (C) 2017 GedMarc - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ -package com.guicedee.guicedinjection.abstractions; - -import com.google.inject.AbstractModule; -import com.google.inject.Binder; -import com.google.inject.Binding; -import com.google.inject.Key; -import com.google.inject.Module; -import com.google.inject.Provider; -import com.google.inject.Scope; -import com.google.inject.TypeLiteral; -import com.google.inject.binder.AnnotatedBindingBuilder; -import com.google.inject.binder.AnnotatedConstantBindingBuilder; -import com.google.inject.binder.LinkedBindingBuilder; -import com.google.inject.matcher.Matcher; -import com.google.inject.spi.Message; -import com.google.inject.spi.ProvisionListener; -import com.google.inject.spi.TypeListener; -import com.guicedee.guicedinjection.GuiceContext; -import com.guicedee.guicedinjection.interfaces.IGuiceDefaultBinder; -import com.guicedee.guicedinjection.interfaces.IGuiceModule; -import com.guicedee.logger.LogFactory; - -import java.lang.annotation.Annotation; -import java.lang.reflect.Method; -import java.util.*; -import java.util.logging.Level; -import java.util.logging.Logger; - -/** - * Exposes the abstract module methods as public - * - * @author GedMarc - * @since 12 Dec 2016 - */ -public class GuiceInjectorModule - extends AbstractModule - implements IGuiceModule { - - /** - * Field log - */ - private static final Logger log = LogFactory.getLog("GuiceInjectorModule"); - - /** - * Constructs a new instance of the module - */ - public GuiceInjectorModule() { - //Nothing Needed - } - - /** - * Executes the runBinders method - */ - @Override - public void configure() { - runBinders(); - } - - /** - * Executes the linked binders to perform any custom binding - */ - @SuppressWarnings("unchecked") - private void runBinders() { - Set loader = GuiceContext.instance() - .getLoader(IGuiceDefaultBinder.class, true, ServiceLoader.load(IGuiceDefaultBinder.class)); - for (IGuiceDefaultBinder binder : loader) { - log.log(Level.CONFIG, "Loading IGuiceDefaultBinder - " + binder.getClass()); - binder.onBind(this); - } - - Set iGuiceModules = GuiceContext.instance().loadIGuiceModules(); - Set guicy = new TreeSet<>(); - guicy.addAll(iGuiceModules); - - for (IGuiceModule iGuiceModule : guicy) - { - log.log(Level.CONFIG, "Loading IGuice Module - " + iGuiceModule.getClass() - .getSimpleName()); - Module mod = (Module) iGuiceModule; - install(mod); - } - } - - /** - * Gets direct access to the underlying {@code Binder}. - */ - @Override - public Binder binder() { - return super.binder(); - } - - /** - * @see Binder#bindScope(Class, Scope) - */ - @Override - public void bindScope(Class 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/com/guicedee/guicedinjection/exceptions/ExcelRenderingException.java b/src/main/java/com/guicedee/guicedinjection/exceptions/ExcelRenderingException.java deleted file mode 100644 index 0ed3df8..0000000 --- a/src/main/java/com/guicedee/guicedinjection/exceptions/ExcelRenderingException.java +++ /dev/null @@ -1,31 +0,0 @@ -package com.guicedee.guicedinjection.exceptions; - - -public class ExcelRenderingException extends RuntimeException { - - private static final long serialVersionUID = 1L; - - public ExcelRenderingException() - { - } - - public ExcelRenderingException(String message) - { - super(message); - } - - public ExcelRenderingException(String message, Throwable cause) - { - super(message, cause); - } - - public ExcelRenderingException(Throwable cause) - { - super(cause); - } - - public ExcelRenderingException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) - { - super(message, cause, enableSuppression, writableStackTrace); - } -} diff --git a/src/main/java/com/guicedee/guicedinjection/exceptions/JsonRenderException.java b/src/main/java/com/guicedee/guicedinjection/exceptions/JsonRenderException.java deleted file mode 100644 index b948d18..0000000 --- a/src/main/java/com/guicedee/guicedinjection/exceptions/JsonRenderException.java +++ /dev/null @@ -1,59 +0,0 @@ -package com.guicedee.guicedinjection.exceptions; - -public class JsonRenderException extends RuntimeException -{ - private static final long serialVersionUID = 1L; - - /** - * Instantiates a new Module exception. - */ - public JsonRenderException() - { - //No config required - } - - /** - * Instantiates a new Module exception. - * - * @param message the message - */ - public JsonRenderException(String message) - { - super(message); - } - - /** - * Instantiates a new Module exception. - * - * @param message the message - * @param cause the cause - */ - public JsonRenderException(String message, Throwable cause) - { - super(message, cause); - } - - /** - * Instantiates a new Module exception. - * - * @param cause the cause - */ - public JsonRenderException(Throwable cause) - { - super(cause); - } - - /** - * Instantiates a new Module exception. - * - * @param message the message - * @param cause the cause - * @param enableSuppression the enable suppression - * @param writableStackTrace the writable stack trace - */ - public JsonRenderException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) - { - super(message, cause, enableSuppression, writableStackTrace); - } - -} diff --git a/src/main/java/com/guicedee/guicedinjection/exceptions/XmlRenderException.java b/src/main/java/com/guicedee/guicedinjection/exceptions/XmlRenderException.java deleted file mode 100644 index b9444db..0000000 --- a/src/main/java/com/guicedee/guicedinjection/exceptions/XmlRenderException.java +++ /dev/null @@ -1,59 +0,0 @@ -package com.guicedee.guicedinjection.exceptions; - -public class XmlRenderException extends RuntimeException -{ - private static final long serialVersionUID = 1L; - - /** - * Instantiates a new Module exception. - */ - public XmlRenderException() - { - //No config required - } - - /** - * Instantiates a new Module exception. - * - * @param message the message - */ - public XmlRenderException(String message) - { - super(message); - } - - /** - * Instantiates a new Module exception. - * - * @param message the message - * @param cause the cause - */ - public XmlRenderException(String message, Throwable cause) - { - super(message, cause); - } - - /** - * Instantiates a new Module exception. - * - * @param cause the cause - */ - public XmlRenderException(Throwable cause) - { - super(cause); - } - - /** - * Instantiates a new Module exception. - * - * @param message the message - * @param cause the cause - * @param enableSuppression the enable suppression - * @param writableStackTrace the writable stack trace - */ - public XmlRenderException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) - { - super(message, cause, enableSuppression, writableStackTrace); - } - -} diff --git a/src/main/java/com/guicedee/guicedinjection/implementations/GuiceContextProvision.java b/src/main/java/com/guicedee/guicedinjection/implementations/GuiceContextProvision.java new file mode 100644 index 0000000..55f37f4 --- /dev/null +++ b/src/main/java/com/guicedee/guicedinjection/implementations/GuiceContextProvision.java @@ -0,0 +1,15 @@ +package com.guicedee.guicedinjection.implementations; + +import com.guicedee.client.*; +import com.guicedee.guicedinjection.*; +import com.guicedee.guicedinjection.interfaces.*; + +public class GuiceContextProvision implements IGuiceProvider +{ + @Override + public IGuiceContext get() + { + return GuiceContext.instance(); + } + +} diff --git a/src/main/java/com/guicedee/guicedinjection/implementations/GuiceDefaultModuleExclusions.java b/src/main/java/com/guicedee/guicedinjection/implementations/GuiceDefaultModuleExclusions.java index 6341e12..b629aed 100644 --- a/src/main/java/com/guicedee/guicedinjection/implementations/GuiceDefaultModuleExclusions.java +++ b/src/main/java/com/guicedee/guicedinjection/implementations/GuiceDefaultModuleExclusions.java @@ -3,7 +3,6 @@ import com.guicedee.guicedinjection.interfaces.IGuiceScanJarExclusions; import com.guicedee.guicedinjection.interfaces.IGuiceScanModuleExclusions; -import jakarta.validation.constraints.NotNull; import java.util.HashSet; import java.util.Set; @@ -11,7 +10,7 @@ public class GuiceDefaultModuleExclusions implements IGuiceScanModuleExclusions, IGuiceScanJarExclusions { @Override - public @NotNull + public Set excludeModules() { Set strings = new HashSet<>(); @@ -101,7 +100,7 @@ Set excludeModules() } @Override - public @NotNull Set excludeJars() { + public Set excludeJars() { Set strings = new HashSet<>(); strings.add("activation-*"); strings.add("adal4j-*"); diff --git a/src/main/java/com/guicedee/guicedinjection/implementations/GuiceDefaultModuleInclusions.java b/src/main/java/com/guicedee/guicedinjection/implementations/GuiceDefaultModuleInclusions.java index 0897d12..bfbffd7 100644 --- a/src/main/java/com/guicedee/guicedinjection/implementations/GuiceDefaultModuleInclusions.java +++ b/src/main/java/com/guicedee/guicedinjection/implementations/GuiceDefaultModuleInclusions.java @@ -1,7 +1,6 @@ package com.guicedee.guicedinjection.implementations; import com.guicedee.guicedinjection.interfaces.IGuiceScanModuleInclusions; -import jakarta.validation.constraints.NotNull; import java.util.HashSet; import java.util.Set; @@ -10,8 +9,7 @@ public class GuiceDefaultModuleInclusions implements IGuiceScanModuleInclusions { @Override - public @NotNull - Set includeModules() + public Set includeModules() { Set strings = new HashSet<>(); return strings; diff --git a/src/main/java/com/guicedee/guicedinjection/implementations/JobServiceProvision.java b/src/main/java/com/guicedee/guicedinjection/implementations/JobServiceProvision.java new file mode 100644 index 0000000..0631fda --- /dev/null +++ b/src/main/java/com/guicedee/guicedinjection/implementations/JobServiceProvision.java @@ -0,0 +1,14 @@ +package com.guicedee.guicedinjection.implementations; + +import com.guicedee.guicedinjection.*; +import com.guicedee.guicedinjection.interfaces.*; + +public class JobServiceProvision implements IJobServiceProvider +{ + @Override + public IJobService get() + { + return JobService.INSTANCE; + } + +} diff --git a/src/main/java/com/guicedee/guicedinjection/injections/ContextBinderGuice.java b/src/main/java/com/guicedee/guicedinjection/injections/ContextBinderGuice.java index 37ae739..c628429 100644 --- a/src/main/java/com/guicedee/guicedinjection/injections/ContextBinderGuice.java +++ b/src/main/java/com/guicedee/guicedinjection/injections/ContextBinderGuice.java @@ -1,14 +1,16 @@ package com.guicedee.guicedinjection.injections; +import com.google.inject.AbstractModule; import com.google.inject.Singleton; import com.guicedee.guicedinjection.GuiceConfig; import com.guicedee.guicedinjection.GuiceContext; -import com.guicedee.guicedinjection.abstractions.GuiceInjectorModule; -import com.guicedee.guicedinjection.interfaces.IGuiceDefaultBinder; -import com.guicedee.guicedinjection.interfaces.JobService; + +import com.guicedee.guicedinjection.JobService; +import com.guicedee.guicedinjection.interfaces.*; import com.guicedee.guicedinjection.properties.GlobalProperties; import io.github.classgraph.ScanResult; -import com.guicedee.logger.LogFactory; +import lombok.extern.java.Log; + import java.util.logging.Logger; @@ -16,36 +18,34 @@ * Binds the basic objects for the Guice Context to be injected everywhere */ @SuppressWarnings("unused") +@Log public class ContextBinderGuice - implements IGuiceDefaultBinder { - private static final Logger log = LogFactory.getLog("GuiceContextBinder"); - - public ContextBinderGuice() { - //No config required - } - - @Override - public void onBind(GuiceInjectorModule module) { - ContextBinderGuice.log.fine("Bound GuiceConfig.class"); - module.bind(GuiceConfig.class) - .toProvider(() -> GuiceContext.instance() - .getConfig()) - .in(Singleton.class); - - ContextBinderGuice.log.fine("Bound GlobalProperties.class"); - module.bind(GlobalProperties.class) - .asEagerSingleton(); - - ContextBinderGuice.log.fine("Bound ScanResult.class"); - module.bind(ScanResult.class) - .toProvider(() -> GuiceContext.instance() - .getScanResult()) - .in(Singleton.class); - - ContextBinderGuice.log.fine("Bound JobService.class"); - module.bind(JobService.class) - .asEagerSingleton(); - } - - + extends AbstractModule + implements IGuiceModule { + public ContextBinderGuice() { + //No config required + } + + @Override + public void configure() { + ContextBinderGuice.log.fine("Bound GuiceConfig.class"); + bind(GuiceConfig.class) + .toProvider(() -> GuiceContext.instance().getConfig()); + + ContextBinderGuice.log.fine("Bound GlobalProperties.class"); + bind(GlobalProperties.class) + .asEagerSingleton(); + + ContextBinderGuice.log.fine("Bound ScanResult.class"); + bind(ScanResult.class) + .toProvider(() -> GuiceContext.instance() + .getScanResult()) + .in(Singleton.class); + + ContextBinderGuice.log.fine("Bound JobService.class"); + bind(IJobService.class) + .toInstance(JobService.INSTANCE); + bind(JobService.class) + .toInstance(JobService.INSTANCE); + } } diff --git a/src/main/java/com/guicedee/guicedinjection/interfaces/IDefaultBinder.java b/src/main/java/com/guicedee/guicedinjection/interfaces/IDefaultBinder.java deleted file mode 100644 index 33f7b4e..0000000 --- a/src/main/java/com/guicedee/guicedinjection/interfaces/IDefaultBinder.java +++ /dev/null @@ -1,36 +0,0 @@ -/* - * Copyright (C) 2017 GedMarc - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ -package com.guicedee.guicedinjection.interfaces; - -import com.google.inject.AbstractModule; - -/** - * @param The module to bind - * @author GedMarc - */ -@FunctionalInterface -public interface IDefaultBinder { - - /** - * Performs the binding with the injection module that is required - * - * @param module The module being passed in - */ - void onBind(M module); - - -} diff --git a/src/main/java/com/guicedee/guicedinjection/interfaces/IDefaultService.java b/src/main/java/com/guicedee/guicedinjection/interfaces/IDefaultService.java deleted file mode 100644 index 128cf3b..0000000 --- a/src/main/java/com/guicedee/guicedinjection/interfaces/IDefaultService.java +++ /dev/null @@ -1,185 +0,0 @@ -package com.guicedee.guicedinjection.interfaces; - -import com.guicedee.guicedinjection.GuiceConfig; -import com.guicedee.guicedinjection.GuiceContext; -import com.guicedee.logger.LogFactory; -import io.github.classgraph.ClassInfo; - -import jakarta.validation.constraints.NotNull; - -import java.util.*; -import java.util.concurrent.ConcurrentHashMap; -import java.util.logging.Level; - -import static com.guicedee.guicedinjection.GuiceContext.*; -/** - * Supplies standard set changer and comparable's for services - * - * @param - */ -public interface IDefaultService> - extends Comparable, Comparator { - Map> loaderClasses = new ConcurrentHashMap<>(); - - /** - * Method loaderToSet, converts a ServiceLoader into a TreeSet - * - * @param loader of type ServiceLoader - * @return Set - */ - @SuppressWarnings("unchecked") - @NotNull - static > Set loaderToSet(ServiceLoader loader) { - @SuppressWarnings("rawtypes") - Set loadeds = new HashSet<>(); - - String type = loader.toString(); - type = type.replace("java.util.ServiceLoader[", ""); - type = type.substring(0, type.length() - 1); - - if (!loaderClasses.containsKey(type)) { - GuiceConfig config = GuiceContext.instance().getConfig(); - if (config.isServiceLoadWithClassPath()) { - for (ClassInfo classInfo : instance() - .getScanResult() - .getClassesImplementing(type)) { - Class load = (Class) classInfo.loadClass(); - loadeds.add(load); - } - } - try { - for (T newInstance : loader) { - loadeds.add(newInstance.getClass()); - } - } catch (Throwable T) { - LogFactory.getLog("IDefaultService").log(Level.SEVERE, "Unable to provide instance of " + type + " to TreeSet", T); - } - loaderClasses.put(type, loadeds); - } - - Set outcomes = new TreeSet<>(); - for (Class aClass : loaderClasses.get(type)) { - outcomes.add((T) GuiceContext.get(aClass)); - } - return outcomes; - } - - static > Set> loadClassSet(ServiceLoader loader) { - String type = loader.toString(); - type = type.replace("java.util.ServiceLoader[", ""); - type = type.substring(0, type.length() - 1); - - if (!loaderClasses.containsKey(type)) { - Set loadeds = new HashSet<>(); - GuiceConfig config = GuiceContext.instance().getConfig(); - if (config.isServiceLoadWithClassPath()) { - for (ClassInfo classInfo : instance() - .getScanResult() - .getClassesImplementing(type)) { - @SuppressWarnings("unchecked") - Class load = (Class) classInfo.loadClass(); - loadeds.add(load); - } - } - try { - for (T newInstance : loader) { - //noinspection unchecked - loadeds.add((Class) newInstance.getClass()); - } - } catch (Throwable T) { - LogFactory.getLog("IDefaultService").log(Level.SEVERE, "Unable to provide instance of " + type + " to TreeSet", T); - } - loaderClasses.put(type, loadeds); - } - //noinspection unchecked - return (Set)loaderClasses.get(type); - } - - /** - * Method loaderToSet, converts a ServiceLoader into a TreeSet - * - * @param loader of type ServiceLoader - * @return Set - */ - @SuppressWarnings("unchecked") - @NotNull - static Set loaderToSetNoInjection(ServiceLoader loader) { - Set> loadeds = new HashSet<>(); - GuiceConfig config = GuiceContext.instance().getConfig(); - String type = loader.toString(); - type = type.replace("java.util.ServiceLoader[", ""); - type = type.substring(0, type.length() - 1); - if (config.isServiceLoadWithClassPath() && !buildingInjector) { - for (ClassInfo classInfo : instance() - .getScanResult() - .getClassesImplementing(type)) { - Class load = (Class) classInfo.loadClass(); - loadeds.add(load); - } - } - Set> completed = new LinkedHashSet<>(); - Set output = new LinkedHashSet<>(); - try { - for (T newInstance : loader) { - output.add(newInstance); - completed.add((Class) newInstance.getClass()); - } - } catch (Throwable T) { - LogFactory.getLog("IDefaultService").log(Level.SEVERE, "Cannot load services - ", T); - } - for (Class newInstance : loadeds) { - if (completed.contains(newInstance)) { - continue; - } - try { - output.add((T) newInstance.getDeclaredConstructor()); - } catch (NoSuchMethodException e) { - LogFactory.getLog("IDefaultService") - .log(Level.SEVERE, "Cannot load a service through default constructor", e); - } - } - return output; - } - - /** - * Method compare ... - * - * @param o1 of type J - * @param o2 of type J - * @return int - */ - @Override - default int compare(J o1, J o2) { - if (o1 == null || o2 == null) { - return -1; - } - return o1.sortOrder() - .compareTo(o2.sortOrder()); - } - - /** - * Default Sort Order 100 - * - * @return 100 - */ - default Integer sortOrder() { - return 100; - } - - /** - * Method compareTo ... - * - * @param o of type J - * @return int - */ - @Override - default int compareTo(@NotNull J o) { - int sort = sortOrder().compareTo(o.sortOrder()); - if (sort == 0) { - return -1; - } - return sort; - } - - -} diff --git a/src/main/java/com/guicedee/guicedinjection/interfaces/IFileContentsPatternScanner.java b/src/main/java/com/guicedee/guicedinjection/interfaces/IFileContentsPatternScanner.java deleted file mode 100644 index fed1766..0000000 --- a/src/main/java/com/guicedee/guicedinjection/interfaces/IFileContentsPatternScanner.java +++ /dev/null @@ -1,20 +0,0 @@ -package com.guicedee.guicedinjection.interfaces; - -import io.github.classgraph.ResourceList; - -import java.util.Map; -import java.util.regex.Pattern; - -/** - * Marks the class as a file scanner - */ -@FunctionalInterface -public interface IFileContentsPatternScanner -{ - /** - * Returns a contents processor to run on match - * - * @return the maps of file identifiers and contents - */ - Map onMatch(); -} diff --git a/src/main/java/com/guicedee/guicedinjection/interfaces/IFileContentsScanner.java b/src/main/java/com/guicedee/guicedinjection/interfaces/IFileContentsScanner.java deleted file mode 100644 index 97fdaa1..0000000 --- a/src/main/java/com/guicedee/guicedinjection/interfaces/IFileContentsScanner.java +++ /dev/null @@ -1,19 +0,0 @@ -package com.guicedee.guicedinjection.interfaces; - -import io.github.classgraph.ResourceList; - -import java.util.Map; - -/** - * Marks the class as a file scanner - */ -@FunctionalInterface -public interface IFileContentsScanner -{ - /** - * Returns a contents processor to run on match - * - * @return the maps of file identifiers and contents - */ - Map onMatch(); -} diff --git a/src/main/java/com/guicedee/guicedinjection/interfaces/IGuiceConfigurator.java b/src/main/java/com/guicedee/guicedinjection/interfaces/IGuiceConfigurator.java deleted file mode 100644 index d20f73c..0000000 --- a/src/main/java/com/guicedee/guicedinjection/interfaces/IGuiceConfigurator.java +++ /dev/null @@ -1,19 +0,0 @@ -package com.guicedee.guicedinjection.interfaces; - -import com.guicedee.guicedinjection.GuiceConfig; - -/** - * Service Locator Interface for granular configuration of the GuiceContext and Injector - */ -@FunctionalInterface -public interface IGuiceConfigurator { - /** - * Configuers the guice instance - * - * @param config The configuration object coming in - * @return The required guice configuration - */ - GuiceConfig configure(GuiceConfig config); - - -} diff --git a/src/main/java/com/guicedee/guicedinjection/interfaces/IGuiceContextInternalBinder.java b/src/main/java/com/guicedee/guicedinjection/interfaces/IGuiceContextInternalBinder.java deleted file mode 100644 index 77ce68e..0000000 --- a/src/main/java/com/guicedee/guicedinjection/interfaces/IGuiceContextInternalBinder.java +++ /dev/null @@ -1,9 +0,0 @@ -package com.guicedee.guicedinjection.interfaces; - -import com.google.inject.AbstractModule; - -@SuppressWarnings("unused") -public interface IGuiceContextInternalBinder - extends IDefaultBinder { - -} diff --git a/src/main/java/com/guicedee/guicedinjection/interfaces/IGuiceDefaultBinder.java b/src/main/java/com/guicedee/guicedinjection/interfaces/IGuiceDefaultBinder.java deleted file mode 100644 index 4ee0bec..0000000 --- a/src/main/java/com/guicedee/guicedinjection/interfaces/IGuiceDefaultBinder.java +++ /dev/null @@ -1,8 +0,0 @@ -package com.guicedee.guicedinjection.interfaces; - -import com.guicedee.guicedinjection.abstractions.GuiceInjectorModule; - -public interface IGuiceDefaultBinder, M extends GuiceInjectorModule> - extends IDefaultService, IDefaultBinder { - -} diff --git a/src/main/java/com/guicedee/guicedinjection/interfaces/IGuiceModule.java b/src/main/java/com/guicedee/guicedinjection/interfaces/IGuiceModule.java deleted file mode 100644 index 68252ed..0000000 --- a/src/main/java/com/guicedee/guicedinjection/interfaces/IGuiceModule.java +++ /dev/null @@ -1,9 +0,0 @@ -package com.guicedee.guicedinjection.interfaces; - -/** - * Service Locator for configuring the module - */ -public interface IGuiceModule> - extends IDefaultService { - -} diff --git a/src/main/java/com/guicedee/guicedinjection/interfaces/IGuicePostStartup.java b/src/main/java/com/guicedee/guicedinjection/interfaces/IGuicePostStartup.java deleted file mode 100644 index be9f839..0000000 --- a/src/main/java/com/guicedee/guicedinjection/interfaces/IGuicePostStartup.java +++ /dev/null @@ -1,47 +0,0 @@ -/* - * Copyright (C) 2017 GedMarc - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ -package com.guicedee.guicedinjection.interfaces; - -/** - * Executes immediately after Guice has been initialized - * - * @author GedMarc - * @since 15 May 2017 - */ -public interface IGuicePostStartup> - extends IDefaultService, Runnable { - - /** - * Runs immediately after the post load - */ - void postLoad(); - - /** - * Sets the order in which this must run, default 100. - * - * @return the sort order to return - */ - @Override - default Integer sortOrder() { - return 50; - } - - default void run() { - postLoad(); - } - -} diff --git a/src/main/java/com/guicedee/guicedinjection/interfaces/IGuicePreDestroy.java b/src/main/java/com/guicedee/guicedinjection/interfaces/IGuicePreDestroy.java deleted file mode 100644 index c2637c5..0000000 --- a/src/main/java/com/guicedee/guicedinjection/interfaces/IGuicePreDestroy.java +++ /dev/null @@ -1,31 +0,0 @@ -/* - * Copyright (C) 2017 GedMarc - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ -package com.guicedee.guicedinjection.interfaces; - -/** - * Initializes before Guice has been injected - * - * @author GedMarc - * @since 15 May 2017 - */ -public interface IGuicePreDestroy> extends IDefaultService -{ - /** - * Runs on startup - */ - void onDestroy(); -} diff --git a/src/main/java/com/guicedee/guicedinjection/interfaces/IGuicePreStartup.java b/src/main/java/com/guicedee/guicedinjection/interfaces/IGuicePreStartup.java deleted file mode 100644 index 0f1fd4f..0000000 --- a/src/main/java/com/guicedee/guicedinjection/interfaces/IGuicePreStartup.java +++ /dev/null @@ -1,47 +0,0 @@ -/* - * Copyright (C) 2017 GedMarc - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ -package com.guicedee.guicedinjection.interfaces; - -import com.guicedee.guicedinjection.interfaces.annotations.INotInjectable; - -/** - * Initializes before Guice has been injected - * - * @author GedMarc - * @since 15 May 2017 - */ -@INotInjectable -public interface IGuicePreStartup> - extends IDefaultService { - - /** - * Runs on startup - */ - void onStartup(); - - /** - * Sort order for startup, Default 100. - * - * @return the sort order never null - */ - @Override - default Integer sortOrder() { - return 100; - } - - -} diff --git a/src/main/java/com/guicedee/guicedinjection/interfaces/IGuiceScanJarExclusions.java b/src/main/java/com/guicedee/guicedinjection/interfaces/IGuiceScanJarExclusions.java deleted file mode 100644 index a7e23c6..0000000 --- a/src/main/java/com/guicedee/guicedinjection/interfaces/IGuiceScanJarExclusions.java +++ /dev/null @@ -1,20 +0,0 @@ -package com.guicedee.guicedinjection.interfaces; - -import jakarta.validation.constraints.NotNull; -import java.util.Set; - -/** - * Marks JAR files referenced from libraries to be excluded from all scans - */ -@FunctionalInterface -public interface IGuiceScanJarExclusions> - extends IDefaultService { - /** - * Excludes the given jars for scanning - * - * @return - */ - @NotNull Set excludeJars(); - - -} diff --git a/src/main/java/com/guicedee/guicedinjection/interfaces/IGuiceScanJarInclusions.java b/src/main/java/com/guicedee/guicedinjection/interfaces/IGuiceScanJarInclusions.java deleted file mode 100644 index d52a0c0..0000000 --- a/src/main/java/com/guicedee/guicedinjection/interfaces/IGuiceScanJarInclusions.java +++ /dev/null @@ -1,21 +0,0 @@ -package com.guicedee.guicedinjection.interfaces; - -import jakarta.validation.constraints.NotNull; - -import java.util.Set; - -/** - * Marks JAR files referenced from libraries to be excluded from all scans - */ -@FunctionalInterface -public interface IGuiceScanJarInclusions> - extends IDefaultService { - /** - * Excludes the given jars for scanning - * - * @return - */ - @NotNull Set includeJars(); - - -} diff --git a/src/main/java/com/guicedee/guicedinjection/interfaces/IGuiceScanModuleExclusions.java b/src/main/java/com/guicedee/guicedinjection/interfaces/IGuiceScanModuleExclusions.java deleted file mode 100644 index 051cbe1..0000000 --- a/src/main/java/com/guicedee/guicedinjection/interfaces/IGuiceScanModuleExclusions.java +++ /dev/null @@ -1,20 +0,0 @@ -package com.guicedee.guicedinjection.interfaces; - -import jakarta.validation.constraints.NotNull; -import java.util.Set; - -/** - * Marks JAR files referenced from libraries to be excluded from all scans - */ -@FunctionalInterface -public interface IGuiceScanModuleExclusions> - extends IDefaultService { - /** - * Excludes the given jars for scanning - * - * @return A set - */ - @NotNull Set 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/JobService.java b/src/main/java/com/guicedee/guicedinjection/interfaces/JobService.java deleted file mode 100644 index 8b04c99..0000000 --- a/src/main/java/com/guicedee/guicedinjection/interfaces/JobService.java +++ /dev/null @@ -1,294 +0,0 @@ -package com.guicedee.guicedinjection.interfaces; - -import com.google.inject.Singleton; -import com.guicedee.guicedinjection.GuiceContext; -import com.guicedee.logger.LogFactory; - -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.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 - */ - -@Singleton -public class JobService - implements IGuicePreDestroy { - private static final Logger log = LogFactory.getLog("JobService"); - private final Map serviceMap = new ConcurrentHashMap<>(); - private final Map pollingMap = new ConcurrentHashMap<>(); - private final Map maxQueueCount = new ConcurrentHashMap<>(); - - public JobService() { - //No config required - } - - /** - * Gets a list of all job pools currently registered - * - * @return - */ - public Set getJobPools() { - return serviceMap.keySet(); - } - - /** - * Returns the list of repeating task pools registered - * - * @return - */ - 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) { - ExecutorService es = serviceMap.get(pool); - if (es == null) { - log.warning("Pool " + pool + " was not registered"); - return null; - } - - es.shutdown(); - try { - log.finer("Waiting for pool " + pool + " to shutdown cleanly."); - es.awaitTermination(GuiceContext.defaultWaitTime, GuiceContext.defaultWaitUnit); - } catch (Exception e) { - log.log(Level.SEVERE, "Couldn't shut down pool" + pool + " cleanly in 60 seconds. Forcing."); - } - 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) { - ScheduledExecutorService es = pollingMap.get(pool); - if (es == null) { - 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(GuiceContext.defaultWaitTime, GuiceContext.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(); - } - 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)) { - removeJob(name); - } - serviceMap.put(name, executorService); - if (!maxQueueCount.containsKey(name)) { - maxQueueCount.put(name, 20); - } - if (executorService instanceof ForkJoinPool) { - ForkJoinPool pool = (ForkJoinPool) executorService; - } - else if (executorService instanceof ThreadPoolExecutor) { - ThreadPoolExecutor executor = (ThreadPoolExecutor) executorService; - executor.setMaximumPoolSize(maxQueueCount.get(name)); - executor.setKeepAliveTime(GuiceContext.defaultWaitTime, GuiceContext.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)) { - 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()) { - registerJobPool(jobPoolName, Executors.newWorkStealingPool()); - } - - ExecutorService service = serviceMap.get(jobPoolName); - if (getCurrentTaskCount(service) >= maxQueueCount.get(jobPoolName)) { - log.log(Level.FINER, maxQueueCount + " Hit - Finishing before next run"); - removeJob(jobPoolName); - service = registerJobPool(jobPoolName, newWorkStealingPool()); - } - 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()) { - registerJobPool(jobPoolName, newWorkStealingPool()); - } - - ExecutorService service = serviceMap.get(jobPoolName); - if (getCurrentTaskCount(service) >= maxQueueCount.get(jobPoolName)) { - log.log(Level.FINER, maxQueueCount + " Hit - Finishing before next run"); - removeJob(jobPoolName); - service = registerJobPool(jobPoolName, newWorkStealingPool()); - } - service.submit(thread); - return service; - } - - public void waitForJob(String jobName) { - waitForJob(jobName, GuiceContext.defaultWaitTime, GuiceContext.defaultWaitUnit); - } - - public void waitForJob(String jobName, long timeout, TimeUnit unit) { - if (!serviceMap.containsKey(jobName)) { - return; - } - ExecutorService service = serviceMap.get(jobName); - service.shutdown(); - try { - service.awaitTermination(timeout, unit); - } catch (InterruptedException e) { - log.log(Level.WARNING, "Thread didn't close cleanly, make sure running times are acceptable", e); - } - } - - /** - * 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()) { - registerJobPollingPool(jobPoolName, Executors.newScheduledThreadPool(Runtime.getRuntime() - .availableProcessors())); - } - ScheduledExecutorService service = pollingMap.get(jobPoolName); - service.scheduleAtFixedRate(thread, 1L, delay, unit); - return service; - } - - /** - * Adds a static run once job to the monitored collections - * - * @param jobPoolName - * @param thread - */ - public ScheduledExecutorService addPollingJob(String jobPoolName, Runnable thread, long initialDelay, long delay, TimeUnit unit) { - if (!pollingMap.containsKey(jobPoolName) || pollingMap.get(jobPoolName).isTerminated() || pollingMap.get(jobPoolName).isShutdown()) { - registerJobPollingPool(jobPoolName, Executors.newScheduledThreadPool(Runtime.getRuntime() - .availableProcessors())); - } - ScheduledExecutorService service = pollingMap.get(jobPoolName); - service.scheduleAtFixedRate(thread, initialDelay, delay, unit); - return service; - } - - /** - * Static instance giver - * - * @return The running instance - */ - public static JobService getInstance() { - return GuiceContext.get(JobService.class); - } - - /** - * Shutdowns - */ - public void destroy() { - log.config("Destroying all running jobs..."); - serviceMap.forEach((key, value) -> - { - log.config("Shutting Down [" + key + "]"); - removeJob(key); - }); - pollingMap.forEach((key, value) -> - { - log.config("Shutting Down Poll Job [" + key + "]"); - removePollingJob(key); - }); - log.config("All jobs destroyed"); - } - - private int getCurrentTaskCount(ExecutorService service) { - if (service instanceof ForkJoinPool) { - ForkJoinPool pool = (ForkJoinPool) service; - return (int) pool.getQueuedTaskCount(); - } - else if (service instanceof ThreadPoolExecutor) { - ThreadPoolExecutor executor = (ThreadPoolExecutor) service; - return (int) executor.getTaskCount(); - } - return 0; - } - - public void setMaxQueueCount(String queueName, int queueCount) { - maxQueueCount.put(queueName, queueCount); - } - - @Override - public void onDestroy() { - destroy(); - } - - @Override - public Integer sortOrder() { - return Integer.MIN_VALUE + 8; - } - - -} diff --git a/src/main/java/com/guicedee/guicedinjection/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/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 8cb98f9..0000000 --- a/src/main/java/com/guicedee/guicedinjection/json/LocalDateDeserializer.java +++ /dev/null @@ -1,53 +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 com.guicedee.logger.LogFactory; - -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.*; - - -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) - { - LogFactory.getLog(LocalDateTimeDeserializer.class).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 45a76e4..0000000 --- a/src/main/java/com/guicedee/guicedinjection/json/LocalDateTimeDeserializer.java +++ /dev/null @@ -1,172 +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 com.guicedee.logger.LogFactory; - -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.*; - - -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) - { - LogFactory.getLog(LocalDateTimeDeserializer.class) - .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 9dbf5d0..0000000 --- a/src/main/java/com/guicedee/guicedinjection/json/ObjectMapperBinder.java +++ /dev/null @@ -1,153 +0,0 @@ -package com.guicedee.guicedinjection.json; - -import com.fasterxml.jackson.annotation.*; -import com.fasterxml.jackson.core.*; -import com.fasterxml.jackson.databind.*; -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 static com.fasterxml.jackson.core.JsonParser.Feature.*; -import static com.guicedee.guicedinjection.interfaces.ObjectBinderKeys.*; - -public class ObjectMapperBinder - implements IGuiceDefaultBinder -{ - /** - * Field log - */ - private static final java.util.logging.Logger log = LogFactory.getLog("ObjectMapperBinding"); - - /** - * If the object mapper must behave as a singleton - */ - public static boolean singleton = true; - - /** - * Method onBind ... - * - * @param module of type GuiceInjectorModule - */ - @SuppressWarnings("deprecation") - @Override - public void onBind(GuiceInjectorModule module) - { - 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) - { - module - .bind(DefaultObjectMapper) - .toProvider(p) - .in(Singleton.class); - }else { - module.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)); - - 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)); - - 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) - ); - - 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) - ); - - - 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)); - - 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)); - - 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) - ); - } - - /** - * 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 dcf260a..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 com.guicedee.logger.LogFactory; - -import java.io.IOException; -import java.time.*; -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.StaticStrings.*; - - -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 - { - LogFactory.getLog(getClass()) - .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 d9aa361..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 com.guicedee.logger.LogFactory; - -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.*; - - -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) - { - LogFactory.getLog(OffsetTimeSerializer.class).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 6ae4982..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 com.guicedee.logger.LogFactory; - -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.*; - - -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) - { - LogFactory.getLog(ZonedDateTimeDeserializer.class).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/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 ecae064..0000000 --- a/src/main/java/com/guicedee/guicedinjection/properties/GlobalProperties.java +++ /dev/null @@ -1,219 +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 com.guicedee.logger.*; - -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) -public class GlobalProperties -{ - private static final Logger log = LogFactory.getLog("GlobalPropertyMaps"); - - 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 996e969..4e65e85 100644 --- a/src/main/java/com/guicedee/guicedinjection/representations/ICopyable.java +++ b/src/main/java/com/guicedee/guicedinjection/representations/ICopyable.java @@ -3,13 +3,15 @@ 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 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 +33,7 @@ default J updateNonNullField(J source) { fieldTarget.set(this, value); } - } - catch (IllegalAccessException e) + } catch (IllegalAccessException e) { e.printStackTrace(); } @@ -64,17 +65,15 @@ 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); 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/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 6002c48..0000000 --- a/src/main/java/com/guicedee/guicedinjection/representations/excel/ExcelReader.java +++ /dev/null @@ -1,465 +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 com.guicedee.logger.LogFactory; -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"}) - -public class ExcelReader - implements AutoCloseable -{ - private static final Logger log = LogFactory.getLog("Excel Reader"); - - 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 56% rename from src/jre11/java/module-info.java rename to src/main/java/module-info.java index 47e8c8a..b9fa788 100644 --- a/src/jre11/java/module-info.java +++ b/src/main/java/module-info.java @@ -1,44 +1,36 @@ -import com.guicedee.guicedinjection.json.*; +import com.guicedee.guicedinjection.JobService; +import com.guicedee.guicedinjection.implementations.*; +import com.guicedee.guicedinjection.interfaces.*; 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.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; - 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; + + requires static org.slf4j; + requires static lombok; + + exports com.guicedee.guicedinjection; + //exports com.guicedee.guicedinjection.exceptions; + //exports com.guicedee.guicedinjection.abstractions; + //exports com.guicedee.guicedinjection.pairing; + //exports com.guicedee.services.jsonrepresentation.json; 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; uses com.guicedee.guicedinjection.interfaces.IGuicePostStartup; uses com.guicedee.guicedinjection.interfaces.IPathContentsScanner; @@ -48,19 +40,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; //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 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.json to com.fasterxml.jackson.databind; - - opens com.guicedee.guicedinjection.pairing; } 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 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.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 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.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/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/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/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 89% rename from src/test/java/com/guicedee/guicedinjection/FileSearchTest.java rename to src/test/java/com/guicedee/tests/FileSearchTest.java index e6e368c..75c2100 100644 --- a/src/test/java/com/guicedee/guicedinjection/FileSearchTest.java +++ b/src/test/java/com/guicedee/tests/FileSearchTest.java @@ -1,7 +1,8 @@ -package com.guicedee.guicedinjection; +package com.guicedee.tests; +import com.guicedee.client.*; +import com.guicedee.guicedinjection.GuiceContext; import com.guicedee.guicedinjection.interfaces.IPathContentsRejectListScanner; -import com.guicedee.logger.LogFactory; import io.github.classgraph.ResourceList; import org.junit.jupiter.api.Test; @@ -14,7 +15,7 @@ public class FileSearchTest { @Test public void findJSFiles() { - LogFactory.configureConsoleColourOutput(Level.FINE); + // LogFactory.configureConsoleColourOutput(Level.FINE); GuiceContext.instance().getConfig() .setPathScanning(true) .setExcludeModulesAndJars(true) @@ -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/guicedinjection/GlobalPropertiesTest.java b/src/test/java/com/guicedee/tests/GlobalPropertiesTest.java similarity index 86% rename from src/test/java/com/guicedee/guicedinjection/GlobalPropertiesTest.java rename to src/test/java/com/guicedee/tests/GlobalPropertiesTest.java index e540204..94b22c1 100644 --- a/src/test/java/com/guicedee/guicedinjection/GlobalPropertiesTest.java +++ b/src/test/java/com/guicedee/tests/GlobalPropertiesTest.java @@ -1,7 +1,8 @@ -package com.guicedee.guicedinjection; +package com.guicedee.tests; +import com.guicedee.guicedinjection.GuiceContext; 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 +16,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/tests/GuiceContextTest.java similarity index 73% rename from src/test/java/com/guicedee/guicedinjection/GuiceContextTest.java rename to src/test/java/com/guicedee/tests/GuiceContextTest.java index 7b5a0a5..ef42082 100644 --- a/src/test/java/com/guicedee/guicedinjection/GuiceContextTest.java +++ b/src/test/java/com/guicedee/tests/GuiceContextTest.java @@ -3,12 +3,14 @@ * 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.client.*; +import com.guicedee.guicedinjection.GuiceContext; 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 +23,7 @@ public class GuiceContextTest { @BeforeAll public static void pre() { - LogFactory.configureConsoleColourOutput(Level.FINE); + //LogFactory.configureConsoleColourOutput(Level.FINE); GuiceContext.instance() .getConfig() .setServiceLoadWithClassPath(true); @@ -29,7 +31,8 @@ public static void pre() { @Test public void testInjection() { - GuiceContext.inject(); + IGuiceContext + .getContext().inject(); } } diff --git a/src/test/java/com/guicedee/guicedinjection/IGuiceConfigTest.java b/src/test/java/com/guicedee/tests/IGuiceConfigTest.java similarity index 69% rename from src/test/java/com/guicedee/guicedinjection/IGuiceConfigTest.java rename to src/test/java/com/guicedee/tests/IGuiceConfigTest.java index fccb730..9b13002 100644 --- a/src/test/java/com/guicedee/guicedinjection/IGuiceConfigTest.java +++ b/src/test/java/com/guicedee/tests/IGuiceConfigTest.java @@ -1,26 +1,30 @@ -package com.guicedee.guicedinjection; +package com.guicedee.tests; +import com.guicedee.client.*; +import com.guicedee.guicedinjection.GuiceConfig; +import com.guicedee.guicedinjection.GuiceContext; +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()); - GuiceContext.inject(); - GuiceConfig config = GuiceContext.get(GuiceConfig.class); - + IGuiceContext.getContext().inject(); + GuiceConfig config = IGuiceContext.get(GuiceConfig.class); + config = GuiceContext.instance().getConfig(); + assertTrue(config.isServiceLoadWithClassPath()); assertTrue(config.isAnnotationScanning()); assertTrue(config.isFieldInfo()); @@ -32,11 +36,10 @@ public void testConfig() } @Override - public GuiceConfig configure(GuiceConfig config) + 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/IGuiceContextTestConfigurator.java b/src/test/java/com/guicedee/tests/IGuiceContextTestConfigurator.java similarity index 61% rename from src/test/java/com/guicedee/guicedinjection/IGuiceContextTestConfigurator.java rename to src/test/java/com/guicedee/tests/IGuiceContextTestConfigurator.java index 69bd45f..7048fd2 100644 --- a/src/test/java/com/guicedee/guicedinjection/IGuiceContextTestConfigurator.java +++ b/src/test/java/com/guicedee/tests/IGuiceContextTestConfigurator.java @@ -1,12 +1,13 @@ -package com.guicedee.guicedinjection; +package com.guicedee.tests; +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; } diff --git a/src/test/java/com/guicedee/guicedinjection/OptionalPairTest.java b/src/test/java/com/guicedee/tests/OptionalPairTest.java similarity index 77% rename from src/test/java/com/guicedee/guicedinjection/OptionalPairTest.java rename to src/test/java/com/guicedee/tests/OptionalPairTest.java index a5f70e3..9c8aa03 100644 --- a/src/test/java/com/guicedee/guicedinjection/OptionalPairTest.java +++ b/src/test/java/com/guicedee/tests/OptionalPairTest.java @@ -1,5 +1,7 @@ -package com.guicedee.guicedinjection; +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; import org.junit.jupiter.api.Assertions; @@ -8,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/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/tests/ParallelPostStartupTest1.java b/src/test/java/com/guicedee/tests/ParallelPostStartupTest1.java new file mode 100644 index 0000000..1db134c --- /dev/null +++ b/src/test/java/com/guicedee/tests/ParallelPostStartupTest1.java @@ -0,0 +1,18 @@ +package com.guicedee.tests; + +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/tests/ParallelPostStartupTest2.java b/src/test/java/com/guicedee/tests/ParallelPostStartupTest2.java new file mode 100644 index 0000000..028767c --- /dev/null +++ b/src/test/java/com/guicedee/tests/ParallelPostStartupTest2.java @@ -0,0 +1,18 @@ +package com.guicedee.tests; + +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/java/com/guicedee/guicedinjection/PsvmTest.java b/src/test/java/com/guicedee/tests/PsvmTest.java similarity index 53% rename from src/test/java/com/guicedee/guicedinjection/PsvmTest.java rename to src/test/java/com/guicedee/tests/PsvmTest.java index 753fb5f..ba2a121 100644 --- a/src/test/java/com/guicedee/guicedinjection/PsvmTest.java +++ b/src/test/java/com/guicedee/tests/PsvmTest.java @@ -1,4 +1,7 @@ -package com.guicedee.guicedinjection; +package com.guicedee.tests; + +import com.guicedee.client.*; +import com.guicedee.guicedinjection.GuiceContext; public class PsvmTest { @@ -8,6 +11,7 @@ public static void main(String[] args) GuiceContext.instance() .getConfig() .setServiceLoadWithClassPath(true); - GuiceContext.inject(); + IGuiceContext + .getContext().inject(); } } diff --git a/src/test/java/module-info.java b/src/test/java/module-info.java new file mode 100644 index 0000000..fa2e43f --- /dev/null +++ b/src/test/java/module-info.java @@ -0,0 +1,12 @@ +module guice.injection.tests { + requires com.guicedee.guicedinjection; + + requires static lombok; + + 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 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 new file mode 100644 index 0000000..525220c --- /dev/null +++ b/src/test/resources/META-INF/services/com.guicedee.guicedinjection.interfaces.IGuicePostStartup @@ -0,0 +1,2 @@ +com.guicedee.tests.ParallelPostStartupTest1 +com.guicedee.tests.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