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

- * - * @param stream - * @param objectType - * @param sheetName - * @param - * @return - * @throws ExcelRenderingException - */ - default List fromExcel(InputStream stream, Class objectType, String sheetName) throws ExcelRenderingException - { - try (ExcelReader excelReader = new ExcelReader(stream, "xlsx")) - { - return excelReader.getRecords(sheetName, objectType); - } - catch (IOException e) - { - throw new ExcelRenderingException("Cannot read the excel file"); - } - catch (Exception e) - { - throw new ExcelRenderingException("General error with the excel file", e); - } - } - - default String toExcel() - { - return null; - } - - -} diff --git a/src/main/java/com/guicedee/guicedinjection/representations/IJsonRepresentation.java b/src/main/java/com/guicedee/guicedinjection/representations/IJsonRepresentation.java deleted file mode 100644 index 946eb6a..0000000 --- a/src/main/java/com/guicedee/guicedinjection/representations/IJsonRepresentation.java +++ /dev/null @@ -1,309 +0,0 @@ -package com.guicedee.guicedinjection.representations; - -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.core.type.TypeReference; -import com.fasterxml.jackson.databind.*; -import com.guicedee.guicedinjection.GuiceContext; -import com.guicedee.guicedinjection.exceptions.JsonRenderException; -import com.guicedee.guicedinjection.interfaces.ObjectBinderKeys; - -import java.io.*; -import java.net.URL; -import java.util.*; - -import static com.guicedee.guicedinjection.interfaces.ObjectBinderKeys.*; - -@SuppressWarnings("unused") -public interface IJsonRepresentation extends ICopyable -{ - /** - * Serializes this object as JSON - * - * @return The rendered JSON or an empty string - */ - default String toJson() - { - return toJson(false); - } - - /** - * Serializes this object as JSON - * - * @return The rendered JSON or an empty string - */ - default String toJson(boolean tiny) - { - ObjectMapper objectMapper = GuiceContext.get(DefaultObjectMapper); - try - { - if (tiny) - { - return objectMapper.disable(SerializationFeature.INDENT_OUTPUT) - .writeValueAsString(this); - } - else - { - return objectMapper.writerWithDefaultPrettyPrinter() - .writeValueAsString(this); - } - } - catch (JsonProcessingException e) - { - throw new JsonRenderException("Unable to serialize as JSON", e); - } - } - - /** - * Deserializes this object from a JSON String (updates the current object) - * - * @param json The JSON String - * @return This object updated - */ - default J fromJson(String json) - { - ObjectMapper objectMapper = GuiceContext.get(DefaultObjectMapper); - try - { - return objectMapper.readerForUpdating(this) - .readValue(json); - } - catch (IOException e) - { - throw new JsonRenderException("Unable to serialize as JSON", e); - } - } - - /** - * Deserializes this object from a JSON String (updates the current object) - * - * @param json The JSON String - * @return This object updated - */ - @SuppressWarnings({"UnusedReturnValue"}) - default List fromJsonArray(String json) - { - ObjectMapper objectMapper = GuiceContext.get(DefaultObjectMapper); - try - { - return objectMapper.readerFor(new TypeReference>() {}) - .readValue(json); - } - catch (IOException e) - { - throw new JsonRenderException("Unable to serialize as JSON", e); - } - } - - /** - * Deserializes this object from a JSON String (updates the current object) - * - * @param json The JSON String - * @return This object updated - */ - @SuppressWarnings({"UnusedReturnValue"}) - default Set fromJsonArrayUnique(String json, @SuppressWarnings("unused") - Class type) - { - ObjectMapper objectMapper = GuiceContext.get(DefaultObjectMapper); - try - { - return objectMapper.readerFor(new TypeReference>() {}) - .readValue(json); - } - catch (IOException e) - { - throw new JsonRenderException("Unable to serialize as JSON", e); - } - } - - /** - * Read direct from the stream - * - * @param - * @param file the stream - * @param clazz - * @return - * @throws IOException - */ - static T From(InputStream file, Class clazz) throws IOException - { - return getJsonObjectReader().forType(clazz) - .readValue(file); - } - - - /** - * Read from a file - * - * @param - * @param file - * @param clazz - * @return - * @throws IOException - */ - static T From(File file, Class clazz) throws IOException - { - return getJsonObjectReader().forType(clazz) - .readValue(file); - } - - /** - * Read from a reader - * - * @param - * @param file - * @param clazz - * @return - * @throws IOException - */ - static T From(Reader file, Class clazz) throws IOException - { - return getJsonObjectReader().forType(clazz) - .readValue(file); - } - - static ObjectReader getJsonObjectReader() - { - return GuiceContext.get(ObjectBinderKeys.JSONObjectReader); - } - - /** - * Read from a content string - * - * @param - * @param content - * @param clazz - * @return - * @throws IOException - */ - static T From(String content, Class clazz) throws IOException - { - return getJsonObjectReader().forType(clazz) - .readValue(content); - } - - /** - * Read from a URL - * - * @param - * @param content - * @param clazz - * @return - * @throws IOException - */ - static T From(URL content, Class clazz) throws IOException - { - return getJsonObjectReader().forType(clazz) - .readValue(content); - } - - - /** - * Read direct from the stream - * - * @param - * @param file the stream - * @param clazz - * @return - * @throws IOException - */ - static List fromToList(InputStream file, Class clazz) - { - T list = null; - try - { - list = GuiceContext.get(DefaultObjectMapper) - .reader() - .forType(clazz) - .readValue(file); - } - catch (IOException e) - { - throw new JsonRenderException("Unable to read the input stream ", e); - } - ArrayList lists = new ArrayList<>(); - lists.addAll(Arrays.asList((T[]) list)); - return lists; - } - - /** - * Read from a URL - * - * @param - * @param content - * @param clazz - * @return - * @throws IOException - */ - static List fromToList(URL content, Class clazz) throws IOException - { - T list = GuiceContext.get(DefaultObjectMapper) - .reader() - .forType(clazz) - .readValue(content); - ArrayList lists = new ArrayList<>(); - lists.addAll(Arrays.asList((T[]) list)); - return lists; - } - - /** - * Read from a file - * - * @param - * @param file - * @param clazz - * @return - * @throws IOException - */ - static List fromToList(File file, Class clazz) throws IOException - { - T list = GuiceContext.get(DefaultObjectMapper) - .reader() - .forType(clazz) - .readValue(file); - ArrayList lists = new ArrayList<>(); - lists.addAll(Arrays.asList((T[]) list)); - return lists; - } - - /** - * Read from a reader - * - * @param - * @param file - * @param clazz - * @return - * @throws IOException - */ - static List fromToList(Reader file, Class clazz) throws IOException - { - T list = GuiceContext.get(DefaultObjectMapper) - .reader() - .forType(clazz) - .readValue(file); - ArrayList lists = new ArrayList<>(); - lists.addAll(Arrays.asList((T[]) list)); - return lists; - } - - /** - * Read from a content string - * - * @param - * @param content - * @param clazz - * @return - * @throws IOException - */ - static List fromToList(String content, Class clazz) throws IOException - { - T list = GuiceContext.get(DefaultObjectMapper) - .reader() - .forType(clazz) - .readValue(content); - ArrayList lists = new ArrayList<>(); - lists.addAll(Arrays.asList((T[]) list)); - return lists; - } - -} diff --git a/src/main/java/com/guicedee/guicedinjection/representations/IXmlRepresentation.java b/src/main/java/com/guicedee/guicedinjection/representations/IXmlRepresentation.java deleted file mode 100644 index 9c430ea..0000000 --- a/src/main/java/com/guicedee/guicedinjection/representations/IXmlRepresentation.java +++ /dev/null @@ -1,106 +0,0 @@ -package com.guicedee.guicedinjection.representations; - -import com.guicedee.guicedinjection.exceptions.XmlRenderException; -import com.guicedee.guicedinjection.pairing.Pair; -import jakarta.xml.bind.*; - -import javax.xml.namespace.QName; -import javax.xml.stream.XMLInputFactory; -import javax.xml.stream.XMLStreamException; -import javax.xml.stream.XMLStreamReader; -import java.io.StringReader; -import java.io.StringWriter; -import java.lang.reflect.InvocationTargetException; -/** - * Makes any object representable as XML - * - * @param - */ -public interface IXmlRepresentation { - - @SuppressWarnings("unchecked") - default J fromXml(String xml, Class type) { - try { - J instance = type.getDeclaredConstructor() - .newInstance(); - JAXBContext context = null; - if (XmlContexts.JAXB.containsKey(type)) { - context = XmlContexts.JAXB.get(type); - } else { - context = JAXBContext.newInstance(type); - XmlContexts.JAXB.put(type, context); - } - JAXBIntrospector introspector = context.createJAXBIntrospector(); - Unmarshaller unmarshaller = context.createUnmarshaller(); - if (null == introspector.getElementName(instance)) { - XMLInputFactory factory = XMLInputFactory.newFactory(); - factory.setProperty(XMLInputFactory.IS_SUPPORTING_EXTERNAL_ENTITIES, Boolean.FALSE); - factory.setProperty(XMLInputFactory.SUPPORT_DTD, Boolean.FALSE); - - XMLStreamReader streamReader = factory.createXMLStreamReader( - new StringReader(xml)); - JAXBElement customer = unmarshaller.unmarshal(streamReader, type); - instance = customer.getValue(); - } else { - instance = (J) unmarshaller.unmarshal(new StringReader(xml)); - } - return instance; - } catch (IllegalAccessException T) { - throw new XmlRenderException("Unable to IllegalAccessException ", T); - } catch (IllegalArgumentException T) { - throw new XmlRenderException("Unable to IllegalArgumentException ", T); - } catch (InstantiationException T) { - throw new XmlRenderException("Unable to InstantiationException ", T); - } catch (NoSuchMethodException T) { - throw new XmlRenderException("Unable to NoSuchMethodException ", T); - } catch (SecurityException T) { - throw new XmlRenderException("Unable to SecurityException ", T); - } catch (InvocationTargetException T) { - throw new XmlRenderException("Unable to InvocationTargetException ", T); - } catch (JAXBException T) { - throw new XmlRenderException("Unable to JAXBException ", T); - } catch (XMLStreamException T) { - throw new XmlRenderException("Unable to XMLStreamException ", T); - } - } - - @SuppressWarnings("unchecked") - default String toXml() { - Object requestObject = this; - try (StringWriter stringWriter = new StringWriter()) { - JAXBContext context = null; - if (XmlContexts.JAXB.containsKey(requestObject.getClass())) { - context = XmlContexts.JAXB.get(requestObject.getClass()); - } else { - context = JAXBContext.newInstance(requestObject.getClass()); - XmlContexts.JAXB.put(requestObject.getClass(), context); - } - if (requestObject instanceof Pair) { - Pair p = (Pair) requestObject; - Class keyType = p.getKey() - .getClass(); - Class valueType = p.getValue() - .getClass(); - context = JAXBContext.newInstance(requestObject.getClass(), keyType, valueType); - } - JAXBIntrospector introspector = context.createJAXBIntrospector(); - Marshaller marshaller = context.createMarshaller(); - if (null == introspector.getElementName(requestObject)) { - - @SuppressWarnings("rawtypes") - JAXBElement jaxbElement = new JAXBElement(new QName(requestObject.getClass() - .getSimpleName()), - requestObject.getClass(), requestObject); - marshaller.setProperty("com.sun.xml.bind.xmlDeclaration", Boolean.FALSE); - marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE); - marshaller.setProperty(Marshaller.JAXB_FRAGMENT, true); - marshaller.marshal(jaxbElement, stringWriter); - } else { - marshaller.marshal(requestObject, stringWriter); - } - return stringWriter.toString(); - } catch (Exception e) { - throw new XmlRenderException("Unable to marshal string writer from log intercepter", e); - } - } -} diff --git a/src/main/java/com/guicedee/guicedinjection/representations/XmlContexts.java b/src/main/java/com/guicedee/guicedinjection/representations/XmlContexts.java deleted file mode 100644 index 87e0c45..0000000 --- a/src/main/java/com/guicedee/guicedinjection/representations/XmlContexts.java +++ /dev/null @@ -1,12 +0,0 @@ -package com.guicedee.guicedinjection.representations; - -import jakarta.xml.bind.JAXBContext; - -import java.util.Map; -import java.util.concurrent.ConcurrentHashMap; - -class XmlContexts { - public static final Map, JAXBContext> JAXB = new ConcurrentHashMap<>(); - - private XmlContexts(){} -} diff --git a/src/main/java/com/guicedee/guicedinjection/representations/excel/ExcelReader.java b/src/main/java/com/guicedee/guicedinjection/representations/excel/ExcelReader.java deleted file mode 100644 index 12ce15c..0000000 --- a/src/main/java/com/guicedee/guicedinjection/representations/excel/ExcelReader.java +++ /dev/null @@ -1,463 +0,0 @@ -package com.guicedee.guicedinjection.representations.excel; - -import com.fasterxml.jackson.databind.ObjectMapper; -import com.guicedee.guicedinjection.GuiceContext; -import com.guicedee.guicedinjection.exceptions.ExcelRenderingException; -import lombok.extern.java.Log; -import org.apache.poi.hssf.usermodel.HSSFWorkbook; -import org.apache.poi.ss.usermodel.*; -import org.apache.poi.xssf.usermodel.XSSFWorkbook; -import org.json.JSONObject; - -import java.io.ByteArrayOutputStream; -import java.io.InputStream; -import java.math.BigDecimal; -import java.sql.Timestamp; -import java.util.*; -import java.util.logging.Level; -import java.util.logging.Logger; - -import static com.guicedee.guicedinjection.interfaces.ObjectBinderKeys.*; -import static com.guicedee.guicedinjection.json.StaticStrings.*; -import static java.math.BigDecimal.*; - -/** - * This class is used when a spreadsheet needs to be generated dynamically - * - * @author Ernst Created:23 Oct 2013 - */ -@SuppressWarnings({"WeakerAccess", "unused"}) -@Log -public class ExcelReader - implements AutoCloseable -{ - private InputStream inputStream; - - private HSSFWorkbook oldStyle; - private XSSFWorkbook xwb; - private boolean isH; - private Sheet currentSheet; - - /** - * Constructs with a file to read - */ - public ExcelReader(InputStream inputStream, String extension) throws ExcelRenderingException - { - this(inputStream, extension, 0); - } - - /** - * Constructs with a file to create - */ - public ExcelReader(InputStream inputStream, String extension, int sheet) throws ExcelRenderingException - { - if (inputStream == null) - { - throw new ExcelRenderingException("Inputstream for document is null"); - } - this.inputStream = inputStream; - if (extension.equalsIgnoreCase("xls")) - { - try - { - oldStyle = new HSSFWorkbook(inputStream); - } - catch (Throwable e) - { - log.log(Level.SEVERE,"Unable to excel ",e); - throw new ExcelRenderingException("Cannot open xls workbook",e); - } - this.currentSheet = oldStyle.getSheetAt(sheet); - isH = true; - } - else - { - try - { - xwb = new XSSFWorkbook(inputStream); - } - catch (Throwable e) - { - log.log(Level.SEVERE,"Unable to excel ",e); - throw new ExcelRenderingException("Cannot open xlsx workbook", e); - } - this.currentSheet = xwb.getSheetAt(sheet); - isH = false; - } - } - - public Workbook getWorkbook() - { - if (isH) - { - return oldStyle; - } - else - { - return xwb; - } - } - - /** - * Creates the cell headers - */ - public void writeHeader(List headers) - { - Row row = currentSheet.createRow(0); - int counter = 0; - for (String item : headers) - { - Cell cell = row.createCell(counter); - cell.setCellValue(item); - counter++; - } - } - - /** - * Fetches a sheets complete data for the given number of records - * - * @param sheetNumber - * The sheet number starts at 0 - * @param start - * How many rows to skip - * @param records - * The number of rows to return - * - * @return - */ - public Object[][] fetchRows(int sheetNumber, int start, int records) - { - int totalSheetRows = getRowCount(sheetNumber) + 1; - int totalRowColumns = getColCount(sheetNumber); - if (records > totalSheetRows) - { - records = totalSheetRows; - } - int arraySize = records - start; - if (arraySize == 0) - { - arraySize = 1; - } - else if (arraySize < 0) - { - arraySize = arraySize * -1; - } - Object[][] tableOut = new Object[arraySize][getColCount(sheetNumber)]; - Sheet sheet; - if (isH) - { - sheet = oldStyle.getSheetAt(sheetNumber); - } - else - { - sheet = xwb.getSheetAt(sheetNumber); - } - int rowN = 0; - int cellN = 0; - int skip = 0; - try - { - for (Row row : sheet) - { - if (skip < start) - { - skip++; - continue; - } - cellN = 0; - int tCs = getColCount(sheetNumber); - for (int cn = 0; cn < tCs; cn++) - { - Cell cell = row.getCell(cn, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK); - CellType cellType = cell.getCellType(); - switch (cellType) - { - case BLANK: - { - tableOut[rowN][cellN] = STRING_EMPTY; - break; - } - case NUMERIC: - { - tableOut[rowN][cellN] = cell.getNumericCellValue(); - if (tableOut[rowN][cellN] instanceof Double) - { - Double d = (Double) tableOut[rowN][cellN]; - if (new BigDecimal(d).equals(ZERO)) - { - tableOut[rowN][cellN] = 0; - } - } - break; - } - case STRING: - { - tableOut[rowN][cellN] = cell.getStringCellValue(); - break; - } - case FORMULA: - { - FormulaEvaluator evaluator; - if (isH) - { - evaluator = oldStyle.getCreationHelper() - .createFormulaEvaluator(); - } - else - { - evaluator = xwb.getCreationHelper() - .createFormulaEvaluator(); - } - CellValue cellValue = evaluator.evaluate(cell); - Double valueD = cellValue.getNumberValue(); - tableOut[rowN][cellN] = valueD; - break; - } - case BOOLEAN: - { - tableOut[rowN][cellN] = cell.getBooleanCellValue(); - break; - } - default: - { - break; - } - } - cellN++; - if (totalRowColumns == cellN) - { - break; - } - } - rowN++; - if (records == rowN) - { - break; - } - } - } - catch (ArrayIndexOutOfBoundsException e) - { - log.log(Level.WARNING, "Reached the end of the file before hitting the max results. logic error.", e); - } - catch (Exception e) - { - log.log(Level.WARNING, "Couldn't go through the whole excel file - ", e); - } - return tableOut; - } - - /** - * Returns the number of columns - * - * @param sheetNo - * - * @return - */ - public int getColCount(int sheetNo) - { - Sheet sheet; - if (isH) - { - sheet = oldStyle.getSheetAt(sheetNo); - } - else - { - sheet = xwb.getSheetAt(sheetNo); - } - - Row row = sheet.getRow(sheetNo); - return row.getLastCellNum(); - } - - public int getRowCount(int sheetNo) - { - if (isH) - { - return oldStyle.getSheetAt(sheetNo) - .getLastRowNum() + 1; - } - else - { - return xwb.getSheetAt(sheetNo) - .getLastRowNum() + 1; - } - } - - /** - * Writes a row of strings to the given row number (created) - */ - public void writeRow(int rowNumber, List headers) - { - Row row = currentSheet.createRow(rowNumber); - int counter = 0; - for (String item : headers) - { - Cell cell = row.createCell(counter); - cell.setCellValue(item); - counter++; - } - } - - /** - * Writes data to a spreadsheet row - */ - @SuppressWarnings("ConstantConditions") - public void writeRow(int rowNumber, Object[] rowData) - { - Row row = currentSheet.createRow(rowNumber); - int counter = 0; - for (Object item : rowData) - { - Cell cell = row.createCell(counter); - if (item == null) - { - item = ""; - } - String ftype = item.getClass() - .getName(); - if (ftype.equals("java.lang.String")) - { - cell.setCellValue((String) item); - } - else if (ftype.equals("java.lang.Boolean") || ftype.equals("boolean")) - { - cell.setCellValue((Boolean) item); - } - else if (ftype.equals("java.util.Date")) - { - cell.setCellValue((Date) item); - } - else if (ftype.equals("java.sql.Timestamp")) - { - Timestamp obj = (Timestamp) item; - Date temp = new Date(obj.getTime()); - cell.setCellValue(temp); - } - else if (ftype.equals("int") || ftype.equals("java.lang.Integer")) - { - cell.setCellValue((Integer) item); - } - else if (ftype.equals("long") || ftype.equals("java.lang.Long") || ftype.equals("java.math.BigInteger")) - { - cell.setCellValue((Long) item); - } - else if (ftype.equals("java.math.BigDecimal")) - { - cell.setCellValue(((BigDecimal) item).doubleValue()); - } - else - { - cell.setCellValue((Double) item); - } - counter++; - } - } - - public Row getRow(int rowNumber) - { - return currentSheet.getRow(rowNumber); - } - - public Cell getCell(int rowNumber, int cellNumber) - { - return currentSheet.getRow(rowNumber) - .getCell(cellNumber); - } - - public byte[] get() - { - byte[] output = null; - try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) - { - if (isH) - { - oldStyle.write(baos); - } - else - { - xwb.write(baos); - } - output = baos.toByteArray(); - } - catch (Exception e) - { - log.log(Level.SEVERE, "Unable to get the byte array for the excel file", e); - } - return output; - } - - @SuppressWarnings("unchecked") - public List getRecords(String sheetName, Class type) - { - int sheetLocation = getWorkbook().getSheetIndex(sheetName); - Object[][] rows = this.fetchRows(sheetLocation, 0, getRowCount(sheetLocation)); - Object[] headerRow = rows[0]; - List output = new ArrayList<>(); - Map> cells = new TreeMap<>(); - for (int i = 1; i < rows.length; i++) - { - //Cell - cells.put(i, new LinkedHashMap<>()); - JSONObject rowData = new JSONObject(); - for (int j = 0; j < getColCount(sheetLocation); j++) - { - if (rows[i][j] instanceof BigDecimal) - { - rowData.put(headerRow[j].toString(), ((BigDecimal) rows[i][j]).toPlainString()); - } - else - { - rowData.put(headerRow[j].toString(), rows[i][j]) - .toString(); - } - if(rows[i][j] != null) - { - cells.get(i) - .put(headerRow[j].toString(), rows[i][j].toString()); - } - else - { - //end of row? - } - //cells.put(i, rows[i][j].toString().trim()); - } - String outcome = rowData.toString(); - try - { - ObjectMapper om = GuiceContext.get(DefaultObjectMapper); - T typed = om.readValue(outcome, type); - output.add(typed); - } - catch (Exception e) - { - log.log(Level.SEVERE, "Unable to build an object from the references - " + outcome, e); - } - } - return output; - } - - @Override - public void close() throws Exception - { - try - { - if (isH) - { - oldStyle.close(); - } - else - { - xwb.close(); - } - - } - catch (Exception e) - { - log.log(Level.SEVERE, "Unable to write the excel file out", e); - } - inputStream.close(); - } - - -} diff --git a/src/jre11/java/com/guicedee/guicedinjection/urls/JrtUrlConnection.java b/src/main/java/com/guicedee/guicedinjection/urls/JrtUrlConnection.java similarity index 100% rename from src/jre11/java/com/guicedee/guicedinjection/urls/JrtUrlConnection.java rename to src/main/java/com/guicedee/guicedinjection/urls/JrtUrlConnection.java diff --git a/src/jre11/java/com/guicedee/guicedinjection/urls/JrtUrlHandler.java b/src/main/java/com/guicedee/guicedinjection/urls/JrtUrlHandler.java similarity index 100% rename from src/jre11/java/com/guicedee/guicedinjection/urls/JrtUrlHandler.java rename to src/main/java/com/guicedee/guicedinjection/urls/JrtUrlHandler.java diff --git a/src/jre11/java/module-info.java b/src/main/java/module-info.java similarity index 78% rename from src/jre11/java/module-info.java rename to src/main/java/module-info.java index 7131fbb..f7de039 100644 --- a/src/jre11/java/module-info.java +++ b/src/main/java/module-info.java @@ -1,36 +1,21 @@ -import com.guicedee.guicedinjection.json.*; - module com.guicedee.guicedinjection { - requires transitive com.guicedee.client; requires transitive com.google.guice; requires transitive io.github.classgraph; - requires transitive com.fasterxml.jackson.databind; - requires transitive com.fasterxml.jackson.annotation; - requires transitive com.fasterxml.jackson.datatype.jsr310; //requires transitive com.guicedee.logmaster; requires transitive org.apache.commons.lang3; - requires transitive jakarta.xml.bind; - - requires static java.sql; - requires static org.json; - requires static org.apache.poi.ooxml; - requires static org.apache.poi.poi; - - requires static java.xml; requires static org.slf4j; requires static lombok; - exports com.guicedee.guicedinjection; - exports com.guicedee.guicedinjection.exceptions; + //exports com.guicedee.guicedinjection.exceptions; exports com.guicedee.guicedinjection.abstractions; exports com.guicedee.guicedinjection.pairing; - exports com.guicedee.guicedinjection.json; + //exports com.guicedee.services.jsonrepresentation.json; exports com.guicedee.guicedinjection.properties; exports com.guicedee.guicedinjection.representations; @@ -54,14 +39,13 @@ provides com.guicedee.guicedinjection.interfaces.IGuiceScanModuleExclusions with com.guicedee.guicedinjection.implementations.GuiceDefaultModuleExclusions; provides com.guicedee.guicedinjection.interfaces.IGuiceScanJarExclusions with com.guicedee.guicedinjection.implementations.GuiceDefaultModuleExclusions; - provides com.guicedee.guicedinjection.interfaces.IGuiceModule with com.guicedee.guicedinjection.injections.ContextBinderGuice, ObjectMapperBinder; + provides com.guicedee.guicedinjection.interfaces.IGuiceModule with com.guicedee.guicedinjection.injections.ContextBinderGuice; //provides com.guicedee.guicedinjection.interfaces.IGuiceModule with com.guicedee.guicedinjection.abstractions.GuiceInjectorModule; provides java.net.spi.URLStreamHandlerProvider with com.guicedee.guicedinjection.urls.JrtUrlHandler; opens com.guicedee.guicedinjection to com.fasterxml.jackson.databind; opens com.guicedee.guicedinjection.properties to com.fasterxml.jackson.databind; - opens com.guicedee.guicedinjection.json to com.fasterxml.jackson.databind; - + opens com.guicedee.guicedinjection.pairing; } diff --git a/src/main/resources/META-INF/services/com.guicedee.guicedinjection.interfaces.IGuiceModule b/src/main/resources/META-INF/services/com.guicedee.guicedinjection.interfaces.IGuiceModule index e69de29..fd77f94 100644 --- a/src/main/resources/META-INF/services/com.guicedee.guicedinjection.interfaces.IGuiceModule +++ b/src/main/resources/META-INF/services/com.guicedee.guicedinjection.interfaces.IGuiceModule @@ -0,0 +1 @@ +com.guicedee.guicedinjection.injections.ContextBinderGuice \ No newline at end of file diff --git a/src/main/resources/META-INF/services/com.guicedee.guicedinjection.interfaces.IGuiceScanModuleInclusions b/src/main/resources/META-INF/services/com.guicedee.guicedinjection.interfaces.IGuiceScanModuleInclusions index e69de29..b4ebcda 100644 --- a/src/main/resources/META-INF/services/com.guicedee.guicedinjection.interfaces.IGuiceScanModuleInclusions +++ b/src/main/resources/META-INF/services/com.guicedee.guicedinjection.interfaces.IGuiceScanModuleInclusions @@ -0,0 +1 @@ +com.guicedee.guicedinjection.implementations.GuiceDefaultModuleInclusions \ No newline at end of file diff --git a/src/test/java/com/guicedee/guicedinjection/IGuiceConfigTest.java b/src/test/java/com/guicedee/guicedinjection/IGuiceConfigTest.java index e9ecc92..aa03d6a 100644 --- a/src/test/java/com/guicedee/guicedinjection/IGuiceConfigTest.java +++ b/src/test/java/com/guicedee/guicedinjection/IGuiceConfigTest.java @@ -22,7 +22,8 @@ public void testConfig() .add(new IGuiceConfigTest()); GuiceContext.inject(); GuiceConfig config = GuiceContext.get(GuiceConfig.class); - + config = GuiceContext.instance().getConfig(); + assertTrue(config.isServiceLoadWithClassPath()); assertTrue(config.isAnnotationScanning()); assertTrue(config.isFieldInfo()); @@ -38,7 +39,6 @@ public IGuiceConfig configure(IGuiceConfig config) { config.setIgnoreMethodVisibility(true) .setExcludeModulesAndJars(true) - .setServiceLoadWithClassPath(true) .setExcludePaths(true) .setAllowPaths(true) .setIncludePackages(true) diff --git a/src/test/java/com/guicedee/guicedinjection/LocalDateTimeDeserializationTest.java b/src/test/java/com/guicedee/guicedinjection/LocalDateTimeDeserializationTest.java deleted file mode 100644 index 604dc3d..0000000 --- a/src/test/java/com/guicedee/guicedinjection/LocalDateTimeDeserializationTest.java +++ /dev/null @@ -1,55 +0,0 @@ -package com.guicedee.guicedinjection; - -import com.guicedee.guicedinjection.json.LocalDateTimeDeserializer; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.Test; - -import java.io.IOException; -import java.time.LocalDateTime; -import java.time.format.DateTimeFormatter; -import java.time.format.DateTimeFormatterBuilder; -import java.time.format.DateTimeParseException; -import java.time.format.FormatStyle; -import java.time.temporal.ChronoField; - -import static com.guicedee.guicedinjection.json.LocalDateTimeDeserializer.formats; - -public class LocalDateTimeDeserializationTest -{ - @Test - public void testLdt() throws IOException - { - - LocalDateTime ldt = LocalDateTime.parse("2020-05-11T04:59:20.052125", formats[4]); - LocalDateTime ldt4 = LocalDateTime.parse("2020-05-11 04:59:20.052125", formats[4]); - LocalDateTime ldt5 = LocalDateTime.parse("2020-05-11T07:53:52.467080", formats[4]); - LocalDateTime ldt2 = LocalDateTime.parse("2020-05-11T04:59:20.052", formats[4]); - LocalDateTime ldt3 = LocalDateTime.parse("2020-05-11T04:59:20.052123456", formats[4]); - LocalDateTime ldt33 = LocalDateTime.parse("2020/05/11T04", formats[4]); - LocalDateTime ldt43 = LocalDateTime.parse("2020/05/11T04:30", formats[4]); - LocalDateTime ldt53 = LocalDateTime.parse("2020/05/11T04:30:00", formats[4]); - LocalDateTime ldt73 = LocalDateTime.parse("2020/05/11 04:30", formats[4]); - LocalDateTime ldt83 = LocalDateTime.parse("2020/05/11 04:30:00", formats[4]); - - LocalDateTime.parse("2020-05-11", formats[4]); - LocalDateTime.parse("2020/05/11 04", formats[4]); - LocalDateTime.parse("2020/05/11", formats[4]); - - //this must be local time -> it must fail - Assertions.assertThrows(DateTimeParseException.class, () -> LocalDateTime.parse("04:14", formats[4])); - Assertions.assertThrows(DateTimeParseException.class, () -> LocalDateTime.parse("04:14:20", formats[4])); - Assertions.assertThrows(DateTimeParseException.class, () -> LocalDateTime.parse("04", formats[4])); - - //direct access conversion - new LocalDateTimeDeserializer().convert("2020-05-11T04:59:20.052125"); - new LocalDateTimeDeserializer().convert("2020-05-11T07:53:52.467080"); - new LocalDateTimeDeserializer().convert("2020-05-11T04:59:20.052"); - new LocalDateTimeDeserializer().convert("2016-10-02T20:15:30-06:00"); - new LocalDateTimeDeserializer().convert("2020-05-11T04:59:20.052+01:00"); - new LocalDateTimeDeserializer().convert("2016-12-02T11:15:30-05:00"); - new LocalDateTimeDeserializer().convert("2016-12-02T11:15:30Z"); - new LocalDateTimeDeserializer().convert("2020-05-11T04:59:20.052123456"); - - System.out.println("all parsed"); - } -} diff --git a/src/test/java/com/guicedee/guicedinjection/ParallelPostStartupTest1.java b/src/test/java/com/guicedee/guicedinjection/ParallelPostStartupTest1.java new file mode 100644 index 0000000..4fc1271 --- /dev/null +++ b/src/test/java/com/guicedee/guicedinjection/ParallelPostStartupTest1.java @@ -0,0 +1,18 @@ +package com.guicedee.guicedinjection; + +import com.guicedee.guicedinjection.interfaces.IGuicePostStartup; + +public class ParallelPostStartupTest1 implements IGuicePostStartup +{ + @Override + public void postLoad() + { + System.out.println("Starting 1"); + } + + @Override + public Integer sortOrder() + { + return 200; + } +} diff --git a/src/test/java/com/guicedee/guicedinjection/ParallelPostStartupTest2.java b/src/test/java/com/guicedee/guicedinjection/ParallelPostStartupTest2.java new file mode 100644 index 0000000..a900b44 --- /dev/null +++ b/src/test/java/com/guicedee/guicedinjection/ParallelPostStartupTest2.java @@ -0,0 +1,18 @@ +package com.guicedee.guicedinjection; + +import com.guicedee.guicedinjection.interfaces.IGuicePostStartup; + +public class ParallelPostStartupTest2 implements IGuicePostStartup +{ + @Override + public void postLoad() + { + System.out.println("Starting 2"); + } + + @Override + public Integer sortOrder() + { + return 200; + } +} diff --git a/src/test/resources/META-INF/services/com.guicedee.guicedinjection.interfaces.IGuicePostStartup b/src/test/resources/META-INF/services/com.guicedee.guicedinjection.interfaces.IGuicePostStartup new file mode 100644 index 0000000..f480432 --- /dev/null +++ b/src/test/resources/META-INF/services/com.guicedee.guicedinjection.interfaces.IGuicePostStartup @@ -0,0 +1,2 @@ +com.guicedee.guicedinjection.ParallelPostStartupTest1 +com.guicedee.guicedinjection.ParallelPostStartupTest2 \ No newline at end of file diff --git a/src/test/resources/logback.xml b/src/test/resources/logback.xml new file mode 100644 index 0000000..d59ef06 --- /dev/null +++ b/src/test/resources/logback.xml @@ -0,0 +1,7 @@ + + + + %d %highlight(%-5level) [%thread] %cyan(%logger{15}): %msg%n + + \ No newline at end of file