commit cc3781226b5a98f73aaf94a853eb6de642f7d5ce Author: Paul Reilly Date: Tue Jun 27 18:00:01 2023 -0500 Initial Commit This is like 60% done, still need to implement a few more things in each respective configuration type. diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..dfe0770 --- /dev/null +++ b/.gitattributes @@ -0,0 +1,2 @@ +# Auto detect text files and perform LF normalization +* text=auto diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..0454b39 --- /dev/null +++ b/.gitignore @@ -0,0 +1,28 @@ +# Compiled class file +*.class + +# Log file +*.log + +# BlueJ files +*.ctxt + +# Mobile Tools for Java (J2ME) +.mtj.tmp/ + +# Package Files # +*.jar +*.war +*.nar +*.ear +*.zip +*.tar.gz +*.rar + +# virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml +hs_err_pid* +replay_pid* + +# idea stuff +.gradle/ +.idea/ diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..0e259d4 --- /dev/null +++ b/LICENSE @@ -0,0 +1,121 @@ +Creative Commons Legal Code + +CC0 1.0 Universal + + CREATIVE COMMONS CORPORATION IS NOT A LAW FIRM AND DOES NOT PROVIDE + LEGAL SERVICES. DISTRIBUTION OF THIS DOCUMENT DOES NOT CREATE AN + ATTORNEY-CLIENT RELATIONSHIP. CREATIVE COMMONS PROVIDES THIS + INFORMATION ON AN "AS-IS" BASIS. CREATIVE COMMONS MAKES NO WARRANTIES + REGARDING THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS + PROVIDED HEREUNDER, AND DISCLAIMS LIABILITY FOR DAMAGES RESULTING FROM + THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS PROVIDED + HEREUNDER. + +Statement of Purpose + +The laws of most jurisdictions throughout the world automatically confer +exclusive Copyright and Related Rights (defined below) upon the creator +and subsequent owner(s) (each and all, an "owner") of an original work of +authorship and/or a database (each, a "Work"). + +Certain owners wish to permanently relinquish those rights to a Work for +the purpose of contributing to a commons of creative, cultural and +scientific works ("Commons") that the public can reliably and without fear +of later claims of infringement build upon, modify, incorporate in other +works, reuse and redistribute as freely as possible in any form whatsoever +and for any purposes, including without limitation commercial purposes. +These owners may contribute to the Commons to promote the ideal of a free +culture and the further production of creative, cultural and scientific +works, or to gain reputation or greater distribution for their Work in +part through the use and efforts of others. + +For these and/or other purposes and motivations, and without any +expectation of additional consideration or compensation, the person +associating CC0 with a Work (the "Affirmer"), to the extent that he or she +is an owner of Copyright and Related Rights in the Work, voluntarily +elects to apply CC0 to the Work and publicly distribute the Work under its +terms, with knowledge of his or her Copyright and Related Rights in the +Work and the meaning and intended legal effect of CC0 on those rights. + +1. Copyright and Related Rights. A Work made available under CC0 may be +protected by copyright and related or neighboring rights ("Copyright and +Related Rights"). Copyright and Related Rights include, but are not +limited to, the following: + + i. the right to reproduce, adapt, distribute, perform, display, + communicate, and translate a Work; + ii. moral rights retained by the original author(s) and/or performer(s); +iii. publicity and privacy rights pertaining to a person's image or + likeness depicted in a Work; + iv. rights protecting against unfair competition in regards to a Work, + subject to the limitations in paragraph 4(a), below; + v. rights protecting the extraction, dissemination, use and reuse of data + in a Work; + vi. database rights (such as those arising under Directive 96/9/EC of the + European Parliament and of the Council of 11 March 1996 on the legal + protection of databases, and under any national implementation + thereof, including any amended or successor version of such + directive); and +vii. other similar, equivalent or corresponding rights throughout the + world based on applicable law or treaty, and any national + implementations thereof. + +2. Waiver. To the greatest extent permitted by, but not in contravention +of, applicable law, Affirmer hereby overtly, fully, permanently, +irrevocably and unconditionally waives, abandons, and surrenders all of +Affirmer's Copyright and Related Rights and associated claims and causes +of action, whether now known or unknown (including existing as well as +future claims and causes of action), in the Work (i) in all territories +worldwide, (ii) for the maximum duration provided by applicable law or +treaty (including future time extensions), (iii) in any current or future +medium and for any number of copies, and (iv) for any purpose whatsoever, +including without limitation commercial, advertising or promotional +purposes (the "Waiver"). Affirmer makes the Waiver for the benefit of each +member of the public at large and to the detriment of Affirmer's heirs and +successors, fully intending that such Waiver shall not be subject to +revocation, rescission, cancellation, termination, or any other legal or +equitable action to disrupt the quiet enjoyment of the Work by the public +as contemplated by Affirmer's express Statement of Purpose. + +3. Public License Fallback. Should any part of the Waiver for any reason +be judged legally invalid or ineffective under applicable law, then the +Waiver shall be preserved to the maximum extent permitted taking into +account Affirmer's express Statement of Purpose. In addition, to the +extent the Waiver is so judged Affirmer hereby grants to each affected +person a royalty-free, non transferable, non sublicensable, non exclusive, +irrevocable and unconditional license to exercise Affirmer's Copyright and +Related Rights in the Work (i) in all territories worldwide, (ii) for the +maximum duration provided by applicable law or treaty (including future +time extensions), (iii) in any current or future medium and for any number +of copies, and (iv) for any purpose whatsoever, including without +limitation commercial, advertising or promotional purposes (the +"License"). The License shall be deemed effective as of the date CC0 was +applied by Affirmer to the Work. Should any part of the License for any +reason be judged legally invalid or ineffective under applicable law, such +partial invalidity or ineffectiveness shall not invalidate the remainder +of the License, and in such case Affirmer hereby affirms that he or she +will not (i) exercise any of his or her remaining Copyright and Related +Rights in the Work or (ii) assert any associated claims and causes of +action with respect to the Work, in either case contrary to Affirmer's +express Statement of Purpose. + +4. Limitations and Disclaimers. + + a. No trademark or patent rights held by Affirmer are waived, abandoned, + surrendered, licensed or otherwise affected by this document. + b. Affirmer offers the Work as-is and makes no representations or + warranties of any kind concerning the Work, express, implied, + statutory or otherwise, including without limitation warranties of + title, merchantability, fitness for a particular purpose, non + infringement, or the absence of latent or other defects, accuracy, or + the present or absence of errors, whether or not discoverable, all to + the greatest extent permissible under applicable law. + c. Affirmer disclaims responsibility for clearing rights of other persons + that may apply to the Work or any use thereof, including without + limitation any person's Copyright and Related Rights in the Work. + Further, Affirmer disclaims responsibility for obtaining any necessary + consents, permissions or other rights required for any use of the + Work. + d. Affirmer understands and acknowledges that Creative Commons is not a + party to this document and has no duty or obligation with respect to + this CC0 or use of the Work. diff --git a/README.md b/README.md new file mode 100644 index 0000000..13e0df0 --- /dev/null +++ b/README.md @@ -0,0 +1,2 @@ +# Configurator + A general purpose configuration library for TOML, JSON, YAML, and Properties files without having to create separate implementations for each file type. diff --git a/build.gradle b/build.gradle new file mode 100644 index 0000000..46a05ee --- /dev/null +++ b/build.gradle @@ -0,0 +1,24 @@ +plugins { + id 'java' +} + +group = 'app.simplexdev' +version = '1.0-SNAPSHOT' + +repositories { + mavenCentral() +} + +dependencies { + implementation 'org.jetbrains:annotations:24.0.0' + implementation 'com.google.code.gson:gson:2.10' + implementation 'org.yaml:snakeyaml:2.0' + implementation 'com.moandjiezana.toml:toml4j:0.7.2' + + testImplementation platform('org.junit:junit-bom:5.9.1') + testImplementation 'org.junit.jupiter:junit-jupiter' +} + +test { + useJUnitPlatform() +} \ No newline at end of file diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000..4b2fb2f --- /dev/null +++ b/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,6 @@ +#Mon Jun 26 08:38:59 CDT 2023 +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-8.0-bin.zip +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/gradlew b/gradlew new file mode 100644 index 0000000..1b6c787 --- /dev/null +++ b/gradlew @@ -0,0 +1,234 @@ +#!/bin/sh + +# +# Copyright © 2015-2021 the original authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +############################################################################## +# +# Gradle start up script for POSIX generated by Gradle. +# +# Important for running: +# +# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is +# noncompliant, but you have some other compliant shell such as ksh or +# bash, then to run this script, type that shell name before the whole +# command line, like: +# +# ksh Gradle +# +# Busybox and similar reduced shells will NOT work, because this script +# requires all of these POSIX shell features: +# * functions; +# * expansions «$var», «${var}», «${var:-default}», «${var+SET}», +# «${var#prefix}», «${var%suffix}», and «$( cmd )»; +# * compound commands having a testable exit status, especially «case»; +# * various built-in commands including «command», «set», and «ulimit». +# +# Important for patching: +# +# (2) This script targets any POSIX shell, so it avoids extensions provided +# by Bash, Ksh, etc; in particular arrays are avoided. +# +# The "traditional" practice of packing multiple parameters into a +# space-separated string is a well documented source of bugs and security +# problems, so this is (mostly) avoided, by progressively accumulating +# options in "$@", and eventually passing that to Java. +# +# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, +# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; +# see the in-line comments for details. +# +# There are tweaks for specific operating systems such as AIX, CygWin, +# Darwin, MinGW, and NonStop. +# +# (3) This script is generated from the Groovy template +# https://github.com/gradle/gradle/blob/master/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt +# within the Gradle project. +# +# You can find Gradle at https://github.com/gradle/gradle/. +# +############################################################################## + +# Attempt to set APP_HOME + +# Resolve links: $0 may be a link +app_path=$0 + +# Need this for daisy-chained symlinks. +while + APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path + [ -h "$app_path" ] +do + ls=$( ls -ld "$app_path" ) + link=${ls#*' -> '} + case $link in #( + /*) app_path=$link ;; #( + *) app_path=$APP_HOME$link ;; + esac +done + +APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit + +APP_NAME="Gradle" +APP_BASE_NAME=${0##*/} + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD=maximum + +warn () { + echo "$*" +} >&2 + +die () { + echo + echo "$*" + echo + exit 1 +} >&2 + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "$( uname )" in #( + CYGWIN* ) cygwin=true ;; #( + Darwin* ) darwin=true ;; #( + MSYS* | MINGW* ) msys=true ;; #( + NONSTOP* ) nonstop=true ;; +esac + +CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD=$JAVA_HOME/jre/sh/java + else + JAVACMD=$JAVA_HOME/bin/java + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD=java + which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." +fi + +# Increase the maximum file descriptors if we can. +if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then + case $MAX_FD in #( + max*) + MAX_FD=$( ulimit -H -n ) || + warn "Could not query maximum file descriptor limit" + esac + case $MAX_FD in #( + '' | soft) :;; #( + *) + ulimit -n "$MAX_FD" || + warn "Could not set maximum file descriptor limit to $MAX_FD" + esac +fi + +# Collect all arguments for the java command, stacking in reverse order: +# * args from the command line +# * the main class name +# * -classpath +# * -D...appname settings +# * --module-path (only if needed) +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. + +# For Cygwin or MSYS, switch paths to Windows format before running java +if "$cygwin" || "$msys" ; then + APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) + CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) + + JAVACMD=$( cygpath --unix "$JAVACMD" ) + + # Now convert the arguments - kludge to limit ourselves to /bin/sh + for arg do + if + case $arg in #( + -*) false ;; # don't mess with options #( + /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath + [ -e "$t" ] ;; #( + *) false ;; + esac + then + arg=$( cygpath --path --ignore --mixed "$arg" ) + fi + # Roll the args list around exactly as many times as the number of + # args, so each arg winds up back in the position where it started, but + # possibly modified. + # + # NB: a `for` loop captures its iteration list before it begins, so + # changing the positional parameters here affects neither the number of + # iterations, nor the values presented in `arg`. + shift # remove old arg + set -- "$@" "$arg" # push replacement arg + done +fi + +# Collect all arguments for the java command; +# * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of +# shell script including quotes and variable substitutions, so put them in +# double quotes to make sure that they get re-expanded; and +# * put everything else in single quotes, so that it's not re-expanded. + +set -- \ + "-Dorg.gradle.appname=$APP_BASE_NAME" \ + -classpath "$CLASSPATH" \ + org.gradle.wrapper.GradleWrapperMain \ + "$@" + +# Use "xargs" to parse quoted args. +# +# With -n1 it outputs one arg per line, with the quotes and backslashes removed. +# +# In Bash we could simply go: +# +# readarray ARGS < <( xargs -n1 <<<"$var" ) && +# set -- "${ARGS[@]}" "$@" +# +# but POSIX shell has neither arrays nor command substitution, so instead we +# post-process each arg (as a line of input to sed) to backslash-escape any +# character that might be a shell metacharacter, then use eval to reverse +# that process (while maintaining the separation between arguments), and wrap +# the whole thing up as a single "set" statement. +# +# This will of course break if any of these variables contains a newline or +# an unmatched quote. +# + +eval "set -- $( + printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | + xargs -n1 | + sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | + tr '\n' ' ' + )" '"$@"' + +exec "$JAVACMD" "$@" diff --git a/gradlew.bat b/gradlew.bat new file mode 100644 index 0000000..107acd3 --- /dev/null +++ b/gradlew.bat @@ -0,0 +1,89 @@ +@rem +@rem Copyright 2015 the original author or authors. +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem You may obtain a copy of the License at +@rem +@rem https://www.apache.org/licenses/LICENSE-2.0 +@rem +@rem Unless required by applicable law or agreed to in writing, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. +@rem + +@if "%DEBUG%" == "" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +set DIRNAME=%~dp0 +if "%DIRNAME%" == "" set DIRNAME=. +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Resolve any "." and ".." in APP_HOME to make it shorter. +for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if "%ERRORLEVEL%" == "0" goto execute + +echo. +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto execute + +echo. +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* + +:end +@rem End local scope for the variables with windows NT shell +if "%ERRORLEVEL%"=="0" goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 +exit /b 1 + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/settings.gradle b/settings.gradle new file mode 100644 index 0000000..eba465c --- /dev/null +++ b/settings.gradle @@ -0,0 +1,2 @@ +rootProject.name = 'Configurator' + diff --git a/src/main/java/app/simplexdev/Configurator.java b/src/main/java/app/simplexdev/Configurator.java new file mode 100644 index 0000000..d1e9234 --- /dev/null +++ b/src/main/java/app/simplexdev/Configurator.java @@ -0,0 +1,152 @@ +package app.simplexdev; + +import app.simplexdev.config.Configuration; +import app.simplexdev.data.ConfigType; +import app.simplexdev.data.Resource; +import app.simplexdev.parser.JSONParser; +import app.simplexdev.parser.PropertiesParser; +import app.simplexdev.parser.TomlParser; +import app.simplexdev.parser.YamlParser; +import java.io.File; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.IOException; +import java.util.logging.Logger; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +public final class Configurator +{ + private static final Logger LOGGER = Logger.getLogger(Configurator.class.getSimpleName()); + + private Configuration configuration = null; + + public Configurator(final String name, final File location, final ConfigType type) + { + this(name, location, type, null); + } + + public Configurator(final String name, final File location, final ConfigType type, final Resource defaultResource) + { + this(name, location, type, defaultResource, false); + } + + public Configurator(final String name, final File location, final ConfigType type, final Resource defaultResource, + final boolean copyDefaults) + { + if (copyDefaults) + { + copyDefaults(name, location, type, defaultResource); + } + else + { + processNormally(name, location, type, defaultResource); + } + } + + private void processNormally(String name, File location, ConfigType type, Resource defaultResource) + { + if (location.mkdirs()) + getLogger().info("Created directory " + location.getAbsolutePath()); + + final File config = new File(location, name + type.getExtension()); + try + { + if (config.createNewFile() && defaultResource != null) + { + try (final FileOutputStream fos = new FileOutputStream(config)) + { + fos.write(defaultResource.getContent()); + } + + getLogger().info("Created file " + config.getAbsolutePath()); + } + } + catch (final IOException ex) + { + getLogger().severe("Failed to create file " + config.getAbsolutePath()); + ex.printStackTrace(); + } + + try (final FileInputStream fis = new FileInputStream(config)) + { + switch (type) + { + case JSON -> this.configuration = new JSONParser().parse(fis); + case YAML -> this.configuration = new YamlParser().parse(fis); + case PROPERTIES -> this.configuration = new PropertiesParser().parse(fis); + case TOML -> this.configuration = new TomlParser().parse(fis); + default -> throw new IllegalArgumentException("Invalid config type."); + } + } + catch (IOException e) + { + getLogger().severe("Failed to read file " + config.getAbsolutePath()); + e.printStackTrace(); + } + } + + private void copyDefaults(String name, File location, ConfigType type, Resource defaultResource) + { + if (defaultResource == null) + throw new IllegalArgumentException("Default resource cannot be null."); + + if (!defaultResource.getName().split("\\.")[0].equalsIgnoreCase(name)) + throw new IllegalArgumentException( + "The name of the default resource must be the same as the name of the configuration file."); + + if (location.mkdirs()) + getLogger().info("Created directory " + location.getAbsolutePath()); + + final File config = new File(location, name + type.getExtension()); + try + { + if (config.createNewFile()) + getLogger().info("Created file " + config.getAbsolutePath()); + } + catch (final IOException ex) + { + getLogger().severe("Failed to create file " + config.getAbsolutePath()); + ex.printStackTrace(); + } + + try (final FileOutputStream fos = new FileOutputStream(config)) + { + fos.write(defaultResource.getContent()); + } + catch (final IOException ex) + { + getLogger().severe("Failed to write to file " + config.getAbsolutePath()); + ex.printStackTrace(); + } + + try (final FileInputStream fis = new FileInputStream(config)) + { + switch (type) + { + case JSON -> this.configuration = new JSONParser().parse(fis); + case YAML -> this.configuration = new YamlParser().parse(fis); + case PROPERTIES -> this.configuration = new PropertiesParser().parse(fis); + case TOML -> this.configuration = new TomlParser().parse(fis); + default -> throw new IllegalArgumentException("Invalid config type."); + } + } + catch (IOException e) + { + getLogger().severe("Failed to read file " + config.getAbsolutePath()); + e.printStackTrace(); + } + } + + @NotNull + public static Logger getLogger() + { + return LOGGER; + } + + @Nullable + public Configuration getConfig() + { + return this.configuration; + } +} diff --git a/src/main/java/app/simplexdev/config/Configuration.java b/src/main/java/app/simplexdev/config/Configuration.java new file mode 100644 index 0000000..dbf4fde --- /dev/null +++ b/src/main/java/app/simplexdev/config/Configuration.java @@ -0,0 +1,12 @@ +package app.simplexdev.config; + +import app.simplexdev.data.ConfigType; +import app.simplexdev.parser.Parser; +import java.util.Map; + +public interface Configuration extends Section +{ + ConfigType getConfigurationType(); + + Parser getConfigurationParser(); +} diff --git a/src/main/java/app/simplexdev/config/Section.java b/src/main/java/app/simplexdev/config/Section.java new file mode 100644 index 0000000..6aa88bf --- /dev/null +++ b/src/main/java/app/simplexdev/config/Section.java @@ -0,0 +1,39 @@ +package app.simplexdev.config; + +import java.util.List; +import java.util.Map; + +public interface Section +{ + String getName(); + + Section getSection(final String path); + + Boolean getBoolean(final String path); + + Integer getInteger(final String path); + + Double getDouble(final String path); + + String getString(final String path); + + Long getLong(final String path); + + Float getFloat(final String path); + + Short getShort(final String path); + + Byte getByte(final String path); + + Object get(final String path); + + List getStringList(final String path); + + List getList(final String path, final Class type); + + Map getMap(String path, Class valueType); + + T get(final String path, final Class type); + + void set(final String path, final Object value); +} diff --git a/src/main/java/app/simplexdev/config/json/JsonConfig.java b/src/main/java/app/simplexdev/config/json/JsonConfig.java new file mode 100644 index 0000000..41bd8ae --- /dev/null +++ b/src/main/java/app/simplexdev/config/json/JsonConfig.java @@ -0,0 +1,154 @@ +package app.simplexdev.config.json; + +import app.simplexdev.config.Configuration; +import app.simplexdev.config.Section; +import app.simplexdev.data.ConfigType; +import app.simplexdev.parser.JSONParser; +import app.simplexdev.parser.Parser; + +import com.google.gson.Gson; +import com.google.gson.JsonArray; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +public class JsonConfig implements Configuration +{ + + private final JSONParser configurationParser; + private final String name; + private final JsonObject jsonObject; + + public JsonConfig(JsonObject jsonObject) { + this.configurationParser = new JSONParser(); + this.name = "config"; + this.jsonObject = jsonObject; + } + + public JsonObject getJsonObject() { + return jsonObject; + } + + @Override + public ConfigType getConfigurationType() { + return ConfigType.JSON; + } + + @Override + public Parser getConfigurationParser() { + return configurationParser; + } + + @Override + public String getName() { + return name; + } + + @Override + public Section getSection(String path) { + JsonObject sectionObject = jsonObject.getAsJsonObject(path); + if (sectionObject != null) { + return new JsonConfig(sectionObject); + } + return null; + } + + @Override + public Boolean getBoolean(String path) { + return jsonObject.getAsJsonPrimitive(path).getAsBoolean(); + } + + @Override + public Integer getInteger(String path) { + return jsonObject.getAsJsonPrimitive(path).getAsInt(); + } + + @Override + public Double getDouble(String path) { + return jsonObject.getAsJsonPrimitive(path).getAsDouble(); + } + + @Override + public String getString(String path) { + return jsonObject.getAsJsonPrimitive(path).getAsString(); + } + + @Override + public Long getLong(String path) { + return jsonObject.getAsJsonPrimitive(path).getAsLong(); + } + + @Override + public Float getFloat(String path) { + return jsonObject.getAsJsonPrimitive(path).getAsFloat(); + } + + @Override + public Short getShort(String path) { + return jsonObject.getAsJsonPrimitive(path).getAsShort(); + } + + @Override + public Byte getByte(String path) { + return jsonObject.getAsJsonPrimitive(path).getAsByte(); + } + + @Override + public Object get(String path) { + return jsonObject.get(path); + } + + @Override + public List getStringList(String path) { + JsonArray jsonArray = jsonObject.getAsJsonArray(path); + if (jsonArray != null) { + List stringList = new ArrayList<>(); + for (JsonElement element : jsonArray) { + stringList.add(element.getAsString()); + } + return stringList; + } + return null; + } + + @Override + public List getList(String path, Class type) { + JsonArray jsonArray = jsonObject.getAsJsonArray(path); + if (jsonArray != null) { + List list = new ArrayList<>(); + for (JsonElement element : jsonArray) { + list.add(new Gson().fromJson(element, type)); + } + return list; + } + return null; + } + + @Override + public Map getMap(String path, Class valueType) { + JsonObject mapObject = jsonObject.getAsJsonObject(path); + if (mapObject != null) { + Map map = new HashMap<>(); + for (Map.Entry entry : mapObject.entrySet()) { + String key = new Gson().fromJson(entry.getKey(), String.class); + Object value = new Gson().fromJson(entry.getValue(), valueType); + map.put(key, value); + } + return map; + } + return null; + } + + @Override + public T get(String path, Class type) { + return new Gson().fromJson(jsonObject.get(path), type); + } + + @Override + public void set(String path, Object value) { + jsonObject.add(path, new Gson().toJsonTree(value)); + } +} diff --git a/src/main/java/app/simplexdev/config/properties/PropertiesConfig.java b/src/main/java/app/simplexdev/config/properties/PropertiesConfig.java new file mode 100644 index 0000000..56d9229 --- /dev/null +++ b/src/main/java/app/simplexdev/config/properties/PropertiesConfig.java @@ -0,0 +1,119 @@ +package app.simplexdev.config.properties; + +import app.simplexdev.config.Configuration; +import app.simplexdev.config.Section; +import app.simplexdev.data.ConfigType; +import app.simplexdev.parser.PropertiesParser; +import java.util.List; +import java.util.Map; + +public class PropertiesConfig implements Configuration +{ + @Override + public ConfigType getConfigurationType() + { + return null; + } + + @Override + public PropertiesParser getConfigurationParser() + { + return null; + } + + @Override + public String getName() + { + return null; + } + + @Override + public Section getSection(String path) + { + return null; + } + + @Override + public Boolean getBoolean(String path) + { + return null; + } + + @Override + public Integer getInteger(String path) + { + return null; + } + + @Override + public Double getDouble(String path) + { + return null; + } + + @Override + public String getString(String path) + { + return null; + } + + @Override + public Long getLong(String path) + { + return null; + } + + @Override + public Float getFloat(String path) + { + return null; + } + + @Override + public Short getShort(String path) + { + return null; + } + + @Override + public Byte getByte(String path) + { + return null; + } + + @Override + public Object get(String path) + { + return null; + } + + @Override + public List getStringList(String path) + { + return null; + } + + @Override + public List getList(String path, Class type) + { + return null; + } + + @Override + public Map getMap(String path, Class valueType) + { + return null; + } + + @Override + public T get(String path, Class type) + { + return null; + } + + @Override + public void set(String path, Object value) + { + + } +} diff --git a/src/main/java/app/simplexdev/config/toml/TomlConfig.java b/src/main/java/app/simplexdev/config/toml/TomlConfig.java new file mode 100644 index 0000000..2c10dd7 --- /dev/null +++ b/src/main/java/app/simplexdev/config/toml/TomlConfig.java @@ -0,0 +1,123 @@ +package app.simplexdev.config.toml; + +import app.simplexdev.config.Configuration; +import app.simplexdev.config.Section; +import app.simplexdev.data.ConfigType; +import app.simplexdev.parser.Parser; + +import app.simplexdev.parser.TomlParser; +import com.moandjiezana.toml.Toml; +import java.util.List; +import java.util.Map; + +public class TomlConfig implements Configuration +{ + + private final Parser configurationParser; + private final String name; + private final TomlConfiguration tomlConfiguration; + + public TomlConfig(TomlConfiguration tomlConfiguration) { + this.configurationParser = new TomlParser(); + this.name = "config"; + this.tomlConfiguration = tomlConfiguration; + } + + @Override + public ConfigType getConfigurationType() { + return ConfigType.TOML; + } + + public TomlConfiguration getToml() { + return tomlConfiguration; + } + + @Override + public Parser getConfigurationParser() { + return configurationParser; + } + + @Override + public String getName() { + return name; + } + + @Override + public Section getSection(String path) { + Object sectionObject = tomlConfiguration.get(path); + if (sectionObject instanceof TomlConfiguration) { + return new TomlConfig((TomlConfiguration) sectionObject); + } + return null; + } + + @Override + public Boolean getBoolean(String path) { + return tomlConfiguration.getBoolean(path); + } + + @Override + public Integer getInteger(String path) { + return tomlConfiguration.getLong(path).intValue(); + } + + @Override + public Double getDouble(String path) { + return tomlConfiguration.getDouble(path); + } + + @Override + public String getString(String path) { + return tomlConfiguration.getString(path); + } + + @Override + public Long getLong(String path) { + return tomlConfiguration.getLong(path); + } + + @Override + public Float getFloat(String path) { + return tomlConfiguration.getDouble(path).floatValue(); + } + + @Override + public Short getShort(String path) { + return tomlConfiguration.getLong(path).shortValue(); + } + + @Override + public Byte getByte(String path) { + return tomlConfiguration.getLong(path).byteValue(); + } + + @Override + public Object get(String path) { + return tomlConfiguration.get(path); + } + + @Override + public List getStringList(String path) { + return tomlConfiguration.getStringList(path); + } + + @Override + public List getList(String path, Class type) { + return tomlConfiguration.getList(path, type); + } + + @Override + public Map getMap(String path, Class valueType) { + return tomlConfiguration.getTable(path); + } + + @Override + public T get(String path, Class type) throws UnsupportedOperationException { + throw new UnsupportedOperationException(); + } + + @Override + public void set(String path, Object value) { + tomlConfiguration.set(path, value); + } +} diff --git a/src/main/java/app/simplexdev/config/toml/TomlConfiguration.java b/src/main/java/app/simplexdev/config/toml/TomlConfiguration.java new file mode 100644 index 0000000..9d8fb06 --- /dev/null +++ b/src/main/java/app/simplexdev/config/toml/TomlConfiguration.java @@ -0,0 +1,139 @@ +package app.simplexdev.config.toml; + +import com.moandjiezana.toml.Toml; +import com.moandjiezana.toml.TomlWriter; +import java.io.*; +import java.nio.charset.StandardCharsets; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +public final class TomlConfiguration +{ + + private Toml toml; + + public TomlConfiguration() + { + this.toml = new Toml(); + } + + public TomlConfiguration(final Toml toml) { + this.toml = toml; + } + + public void load(String filePath) throws IOException + { + try (FileInputStream fileInputStream = new FileInputStream(filePath); + InputStreamReader reader = new InputStreamReader(fileInputStream, StandardCharsets.UTF_8)) + { + toml.read(reader); + } + } + + public void save(String filePath) throws IOException + { + try (FileOutputStream fileOutputStream = new FileOutputStream(filePath); + OutputStreamWriter writer = new OutputStreamWriter(fileOutputStream, StandardCharsets.UTF_8)) + { + writer.write(toml.toString()); + } + } + + public Boolean getBoolean(String path) + { + return toml.getBoolean(path); + } + + public Integer getInteger(String path) + { + return toml.getLong(path).intValue(); + } + + public Double getDouble(String path) + { + return toml.getDouble(path); + } + + public String getString(String path) + { + return toml.getString(path); + } + + public Long getLong(String path) + { + return toml.getLong(path); + } + + public Float getFloat(String path) + { + return toml.getDouble(path).floatValue(); + } + + public Short getShort(String path) + { + return toml.getLong(path).shortValue(); + } + + public Byte getByte(String path) + { + return toml.getLong(path).byteValue(); + } + + public Object get(String path) throws UnsupportedOperationException + { + throw new UnsupportedOperationException(); + } + + public List getStringList(String path) + { + return toml.getList(path); + } + + public List getList(String path, Class type) + { + return toml.getList(path); + } + + public Map getTable(String path) + { + return toml.getTable(path).toMap(); + } + + public T get(String path, Class type) throws UnsupportedOperationException + { + throw new UnsupportedOperationException(); + } + + public void set(String path, Object value) throws IOException + { + Map tomlData = toml.toMap(); + setRecursive(tomlData, path, value); + + ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); + TomlWriter tomlWriter = new TomlWriter.Builder().build(); + tomlWriter.write(tomlData, outputStream); + + InputStream inputStream = new ByteArrayInputStream(outputStream.toByteArray()); + toml = new Toml().read(inputStream); + + } + + @SuppressWarnings("unchecked") + private void setRecursive(Map data, String path, Object value) + { + String[] parts = path.split("\\."); + + Map current = data; + for (int i = 0; i < parts.length - 1; i++) + { + String part = parts[i]; + if (!current.containsKey(part) || !(current.get(part) instanceof Map)) + { + current.put(part, new HashMap<>()); + } + current = (Map) current.get(part); + } + current.put(parts[parts.length - 1], value); + } +} diff --git a/src/main/java/app/simplexdev/config/yaml/YamlConfig.java b/src/main/java/app/simplexdev/config/yaml/YamlConfig.java new file mode 100644 index 0000000..3bb28cc --- /dev/null +++ b/src/main/java/app/simplexdev/config/yaml/YamlConfig.java @@ -0,0 +1,118 @@ +package app.simplexdev.config.yaml; + +import app.simplexdev.config.Configuration; +import app.simplexdev.config.Section; +import app.simplexdev.data.ConfigType; +import app.simplexdev.parser.Parser; + +import app.simplexdev.parser.YamlParser; +import java.util.List; +import java.util.Map; + +public class YamlConfig implements Configuration +{ + + private final Parser configurationParser; + private final String name; + private final YamlConfiguration yamlConfiguration; + + public YamlConfig(YamlConfiguration yamlConfiguration) { + this.configurationParser = new YamlParser(); + this.name = "config"; + this.yamlConfiguration = yamlConfiguration; + } + + @Override + public ConfigType getConfigurationType() { + return ConfigType.YAML; + } + + @Override + public Parser getConfigurationParser() { + return configurationParser; + } + + @Override + public String getName() { + return name; + } + + @Override + public Section getSection(String path) { + Object sectionObject = yamlConfiguration.get(path); + if (sectionObject instanceof YamlConfiguration) { + return new YamlConfig((YamlConfiguration) sectionObject); + } + return null; + } + + @Override + public Boolean getBoolean(String path) { + return yamlConfiguration.getBoolean(path); + } + + @Override + public Integer getInteger(String path) { + return yamlConfiguration.getInteger(path); + } + + @Override + public Double getDouble(String path) { + return yamlConfiguration.getDouble(path); + } + + @Override + public String getString(String path) { + return yamlConfiguration.getString(path); + } + + @Override + public Long getLong(String path) { + return yamlConfiguration.getLong(path); + } + + @Override + public Float getFloat(String path) { + return yamlConfiguration.getFloat(path); + } + + @Override + public Short getShort(String path) { + return yamlConfiguration.getShort(path); + } + + @Override + public Byte getByte(String path) { + return yamlConfiguration.getByte(path); + } + + @Override + public Object get(String path) { + return yamlConfiguration.get(path); + } + + @Override + public List getStringList(String path) { + return yamlConfiguration.getStringList(path); + } + + @Override + public List getList(String path, Class type) { + return yamlConfiguration.getList(path, type); + } + + @Override + public Map getMap(String path, Class valueType) { + return yamlConfiguration.getMap(path, valueType); + } + + @Override + public T get(String path, Class type) { + return yamlConfiguration.get(path, type); + } + + @Override + public void set(String path, Object value) { + yamlConfiguration.set(path, value); + } +} diff --git a/src/main/java/app/simplexdev/config/yaml/YamlConfiguration.java b/src/main/java/app/simplexdev/config/yaml/YamlConfiguration.java new file mode 100644 index 0000000..4ed3bc8 --- /dev/null +++ b/src/main/java/app/simplexdev/config/yaml/YamlConfiguration.java @@ -0,0 +1,173 @@ +package app.simplexdev.config.yaml; + +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.InputStreamReader; +import java.io.OutputStreamWriter; +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import org.yaml.snakeyaml.Yaml; + +public final class YamlConfiguration +{ + + private final Map data; + + public YamlConfiguration() + { + this.data = new HashMap<>(); + } + + public void load(String filePath) throws IOException + { + try (FileInputStream fileInputStream = new FileInputStream(filePath); + InputStreamReader reader = new InputStreamReader(fileInputStream, StandardCharsets.UTF_8)) + { + Yaml yaml = new Yaml(); + this.data.clear(); + this.data.putAll(yaml.load(reader)); + } + } + + public void save(String filePath) throws IOException + { + try (FileOutputStream fileOutputStream = new FileOutputStream(filePath); + OutputStreamWriter writer = new OutputStreamWriter(fileOutputStream, StandardCharsets.UTF_8)) + { + Yaml yaml = new Yaml(); + yaml.dump(data, writer); + } + } + + public Boolean getBoolean(String path) + { + return get(path, Boolean.class); + } + + public Integer getInteger(String path) + { + return get(path, Integer.class); + } + + public Double getDouble(String path) + { + return get(path, Double.class); + } + + public String getString(String path) + { + return get(path, String.class); + } + + public Long getLong(String path) + { + return get(path, Long.class); + } + + public Float getFloat(String path) + { + return get(path, Float.class); + } + + public Short getShort(String path) + { + return get(path, Short.class); + } + + public Byte getByte(String path) + { + return get(path, Byte.class); + } + + public List getStringList(String path) + { + return get(path, List.class); + } + + public List getList(String path, Class type) + { + List list = new ArrayList<>(); + List rawList = get(path, List.class); + if (rawList != null) + { + for (Object element : rawList) + { + if (type.isInstance(element)) + { + list.add(type.cast(element)); + } + } + } + return list; + } + + public Map getMap(String path, Class valueType) + { + Map map = new HashMap<>(); + Map rawMap = get(path, Map.class); + if (rawMap != null) + { + for (Map.Entry entry : rawMap.entrySet()) + { + Object rawKey = entry.getKey(); + Object rawValue = entry.getValue(); + if (rawKey instanceof String key && valueType.isInstance(rawValue)) + { + Object value = valueType.cast(rawValue); + map.put(key, value); + } + } + } + return map; + } + + public T get(String path, Class type) + { + Object value = get(path); + if (type.isInstance(value)) + { + return type.cast(value); + } + return null; + } + + public void set(String path, Object value) + { + put(path, value); + } + + public Object get(String path) + { + String[] parts = path.split("\\."); + Object current = data; + for (String part : parts) + { + if (current instanceof Map) + { + current = ((Map) current).get(part); + } + else + { + return null; + } + } + return current; + } + + @SuppressWarnings("unchecked") + private void put(String path, Object value) + { + String[] parts = path.split("\\."); + Map current = data; + for (int i = 0; i < parts.length - 1; i++) + { + String part = parts[i]; + current = (Map) current.computeIfAbsent(part, k -> new HashMap<>()); + } + current.put(parts[parts.length - 1], value); + } +} diff --git a/src/main/java/app/simplexdev/data/Byter.java b/src/main/java/app/simplexdev/data/Byter.java new file mode 100644 index 0000000..9699834 --- /dev/null +++ b/src/main/java/app/simplexdev/data/Byter.java @@ -0,0 +1,56 @@ +package app.simplexdev.data; + +import java.nio.charset.Charset; +import java.util.Base64; + +public final class Byter +{ + private Byter() + { + throw new AssertionError(); + } + + public static byte[] decode(final String s) + { + return Base64.getDecoder().decode(s); + } + + public static String encode(final byte[] bytes) + { + return Base64.getEncoder().encodeToString(bytes); + } + + public static String read(final byte[] bytes, final Charset charset) + { + return new String(bytes, charset); + } + + public static byte[] write(final String s, final Charset charset) + { + return s.getBytes(charset); + } + + public static byte shift(final byte b, final int shift) + { + return (byte) (b >> shift); + } + + public static byte unsignedShift(final byte b, final int shift) + { + return (byte) (b >>> shift); + } + + public static byte preservedShift(final byte b, final int shift) + { + final int preserved = (b & 0x010000FF) & 0x0700FF; + final int shifted = b >> shift; + return (byte) (shifted | preserved); + } + + public static byte preservedUnsignedShift(final byte b, final int shift) + { + final int preserved = (b & 0x010000FF) & 0x0700FF; + final int shifted = b >>> shift; + return (byte) (shifted | preserved); + } +} diff --git a/src/main/java/app/simplexdev/data/ConfigType.java b/src/main/java/app/simplexdev/data/ConfigType.java new file mode 100644 index 0000000..b8102a6 --- /dev/null +++ b/src/main/java/app/simplexdev/data/ConfigType.java @@ -0,0 +1,19 @@ +package app.simplexdev.data; + +public enum ConfigType +{ + YAML(".yml"), + JSON(".json"), + PROPERTIES(".properties"), + TOML(".toml"); + + private final String extension; + + ConfigType(final String extension) { + this.extension = extension; + } + + public final String getExtension() { + return this.extension; + } +} diff --git a/src/main/java/app/simplexdev/data/Resource.java b/src/main/java/app/simplexdev/data/Resource.java new file mode 100644 index 0000000..6af8053 --- /dev/null +++ b/src/main/java/app/simplexdev/data/Resource.java @@ -0,0 +1,8 @@ +package app.simplexdev.data; + +public interface Resource +{ + String getName(); + + byte[] getContent(); +} diff --git a/src/main/java/app/simplexdev/data/StorableObject.java b/src/main/java/app/simplexdev/data/StorableObject.java new file mode 100644 index 0000000..1988f4b --- /dev/null +++ b/src/main/java/app/simplexdev/data/StorableObject.java @@ -0,0 +1,67 @@ +package app.simplexdev.data; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.ObjectInputStream; +import java.io.ObjectOutputStream; +import java.util.Base64; +import org.jetbrains.annotations.Nullable; + +public class StorableObject +{ + private final T object; + + public StorableObject(T object) + { + this.object = object; + } + + public static T fromBase64(String base64, Class type) + { + byte[] data = Base64.getDecoder().decode(base64); + return fromBytes(data, type); + } + + static T fromBytes(byte[] bytes, Class type) + { + try (ByteArrayInputStream bais = new ByteArrayInputStream(bytes); + ObjectInputStream ois = new ObjectInputStream(bais)) + { + return type.cast(ois.readObject()); + } + catch (IOException | ClassNotFoundException | ClassCastException ex) + { + ex.printStackTrace(); + return null; + } + } + + public byte @Nullable [] toBytes() + { + try (ByteArrayOutputStream baos = new ByteArrayOutputStream(); + ObjectOutputStream oos = new ObjectOutputStream(baos)) + { + oos.writeObject(this.object); + return baos.toByteArray(); + } + catch (IOException ex) + { + ex.printStackTrace(); + return null; + } + } + + @Nullable + public String toBase64() + { + final byte[] data = toBytes(); + + if (data != null) + { + return Base64.getEncoder().encodeToString(data); + } + + return null; + } +} diff --git a/src/main/java/app/simplexdev/parser/JSONParser.java b/src/main/java/app/simplexdev/parser/JSONParser.java new file mode 100644 index 0000000..01fe3e0 --- /dev/null +++ b/src/main/java/app/simplexdev/parser/JSONParser.java @@ -0,0 +1,61 @@ +package app.simplexdev.parser; + +import app.simplexdev.config.json.JsonConfig; +import com.google.gson.Gson; +import com.google.gson.JsonObject; + +import com.google.gson.JsonParser; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.InputStreamReader; +import java.nio.charset.StandardCharsets; + +public class JSONParser implements Parser { + @Override + public JsonConfig parse(FileInputStream fileInputStream) throws IOException { + try (InputStreamReader reader = new InputStreamReader(fileInputStream, StandardCharsets.UTF_8)) { + JsonObject jsonObject = JsonParser.parseReader(reader).getAsJsonObject(); + return new JsonConfig(jsonObject); + } + } + + @Override + public void save(JsonConfig jsonConfig, String filePath) throws IOException { + JsonObject jsonObject = jsonConfig.getJsonObject(); + String jsonString = jsonObject.toString(); + byte[] bytes = jsonString.getBytes(StandardCharsets.UTF_8); + try (FileOutputStream fileOutputStream = new FileOutputStream(filePath)) { + fileOutputStream.write(bytes); + } + } + + @Override + public String getFileExtension() { + return ".json"; + } + + @Override + public String getFileName() { + return "config"; + } + + @Override + public S read(String filePath, Class type) throws IOException { + try (FileInputStream fileInputStream = new FileInputStream(filePath); + InputStreamReader reader = new InputStreamReader(fileInputStream, StandardCharsets.UTF_8)) { + Gson gson = new Gson(); + return gson.fromJson(reader, type); + } + } + + @Override + public void write(String filePath, S object) throws IOException { + Gson gson = new Gson(); + String jsonString = gson.toJson(object); + byte[] bytes = jsonString.getBytes(StandardCharsets.UTF_8); + try (FileOutputStream fileOutputStream = new FileOutputStream(filePath)) { + fileOutputStream.write(bytes); + } + } +} diff --git a/src/main/java/app/simplexdev/parser/Parser.java b/src/main/java/app/simplexdev/parser/Parser.java new file mode 100644 index 0000000..6debdd2 --- /dev/null +++ b/src/main/java/app/simplexdev/parser/Parser.java @@ -0,0 +1,20 @@ +package app.simplexdev.parser; + +import app.simplexdev.config.Section; +import java.io.FileInputStream; +import java.io.IOException; + +public interface Parser +{ + T parse(final FileInputStream p0) throws IOException; + + void save(final T p0, final String p1) throws IOException; + + String getFileExtension(); + + String getFileName(); + + S read(final String p0, final Class p1) throws IOException; + + void write(final String p0, final S p1) throws IOException; +} diff --git a/src/main/java/app/simplexdev/parser/PropertiesParser.java b/src/main/java/app/simplexdev/parser/PropertiesParser.java new file mode 100644 index 0000000..a7a676d --- /dev/null +++ b/src/main/java/app/simplexdev/parser/PropertiesParser.java @@ -0,0 +1,44 @@ +package app.simplexdev.parser; + +import app.simplexdev.config.Configuration; +import app.simplexdev.config.properties.PropertiesConfig; +import java.io.FileInputStream; +import java.io.IOException; + +public class PropertiesParser implements Parser +{ + @Override + public PropertiesConfig parse(final FileInputStream p0) + { + return null; + } + + @Override + public void save(final PropertiesConfig p0, final String p1) + { + } + + @Override + public String getFileExtension() + { + return null; + } + + @Override + public String getFileName() + { + return null; + } + + @Override + public S read(String p0, Class p1) throws IOException + { + return null; + } + + @Override + public void write(String p0, S p1) throws IOException + { + + } +} diff --git a/src/main/java/app/simplexdev/parser/TomlParser.java b/src/main/java/app/simplexdev/parser/TomlParser.java new file mode 100644 index 0000000..5541a33 --- /dev/null +++ b/src/main/java/app/simplexdev/parser/TomlParser.java @@ -0,0 +1,62 @@ +package app.simplexdev.parser; + +import app.simplexdev.config.toml.TomlConfig; +import app.simplexdev.config.toml.TomlConfiguration; +import com.moandjiezana.toml.Toml; +import com.moandjiezana.toml.TomlWriter; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.InputStreamReader; +import java.io.OutputStreamWriter; +import java.nio.charset.StandardCharsets; + +public class TomlParser implements Parser { + + @Override + public TomlConfig parse(FileInputStream input) throws IOException { + try (InputStreamReader reader = new InputStreamReader(input, StandardCharsets.UTF_8)) { + Toml toml = new Toml().read(reader); + TomlConfiguration configuration = new TomlConfiguration(toml); + return new TomlConfig(configuration); + } + } + + @Override + public void save(TomlConfig config, String filePath) throws IOException { + try (FileOutputStream output = new FileOutputStream(filePath); + OutputStreamWriter writer = new OutputStreamWriter(output, StandardCharsets.UTF_8)) { + TomlWriter tomlWriter = new TomlWriter.Builder().build(); + String tomlString = tomlWriter.write(config.getToml()); + writer.write(tomlString); + } + } + + @Override + public String getFileExtension() { + return ".toml"; + } + + @Override + public String getFileName() { + return "Toml"; + } + + @Override + public S read(String filePath, Class type) throws IOException { + try (FileInputStream input = new FileInputStream(filePath); + InputStreamReader reader = new InputStreamReader(input, StandardCharsets.UTF_8)) { + Toml toml = new Toml().read(reader); + return toml.to(type); + } + } + + @Override + public void write(String filePath, S object) throws IOException { + try (FileOutputStream output = new FileOutputStream(filePath); + OutputStreamWriter writer = new OutputStreamWriter(output, StandardCharsets.UTF_8)) { + TomlWriter tomlWriter = new TomlWriter.Builder().build(); + tomlWriter.write(object, writer); + } + } +} diff --git a/src/main/java/app/simplexdev/parser/YamlParser.java b/src/main/java/app/simplexdev/parser/YamlParser.java new file mode 100644 index 0000000..7ffbf7d --- /dev/null +++ b/src/main/java/app/simplexdev/parser/YamlParser.java @@ -0,0 +1,63 @@ +package app.simplexdev.parser; + +import app.simplexdev.config.yaml.YamlConfig; +import org.yaml.snakeyaml.Yaml; + +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.InputStreamReader; +import java.io.OutputStreamWriter; +import java.nio.charset.StandardCharsets; + +public class YamlParser implements Parser { + + @Override + public YamlConfig parse(FileInputStream fileInputStream) throws IOException { + Yaml yaml = new Yaml(); + try (InputStreamReader reader = new InputStreamReader(fileInputStream, StandardCharsets.UTF_8)) { + Object parsedData = yaml.load(reader); + if (parsedData instanceof YamlConfig) { + return (YamlConfig) parsedData; + } else { + throw new IOException("Invalid YAML data. Unable to parse into YamlConfig."); + } + } + } + + @Override + public void save(YamlConfig yamlConfig, String filePath) throws IOException { + Yaml yaml = new Yaml(); + String yamlString = yaml.dump(yamlConfig); + try (OutputStreamWriter writer = new OutputStreamWriter(new FileOutputStream(filePath), StandardCharsets.UTF_8)) { + writer.write(yamlString); + } + } + + @Override + public String getFileExtension() { + return ".yaml"; + } + + @Override + public String getFileName() { + return "config"; + } + + @Override + public S read(String filePath, Class type) throws IOException { + try (FileInputStream fileInputStream = new FileInputStream(filePath)) { + Yaml yaml = new Yaml(); + return yaml.loadAs(fileInputStream, type); + } + } + + @Override + public void write(String filePath, S object) throws IOException { + Yaml yaml = new Yaml(); + String yamlString = yaml.dump(object); + try (OutputStreamWriter writer = new OutputStreamWriter(new FileOutputStream(filePath), StandardCharsets.UTF_8)) { + writer.write(yamlString); + } + } +}