├── .gitignore ├── .travis.yml ├── LICENSE ├── README.md ├── build.gradle.kts ├── gradle.properties ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat ├── settings.gradle └── src ├── main └── kotlin │ └── com │ └── kerooker │ └── simpleproperties │ ├── SimpleProperties.kt │ └── internal │ ├── classloader │ └── ClassLoaderExtensions.kt │ ├── file │ └── PropertyFileLoader.kt │ └── profile │ └── SystemProfileLoader.kt └── test ├── kotlin └── com │ └── kerooker │ └── simpleproperties │ ├── SimplePropertiesTest.kt │ └── internal │ ├── file │ └── PropertyFileLoaderTest.kt │ └── profile │ └── SystemProfileLoaderTest.kt └── resources ├── application-default-override.properties ├── application-prod.properties ├── application.properties ├── non_default ├── application-prod.properties └── application.properties └── without_default └── application-qa.properties /.gitignore: -------------------------------------------------------------------------------- 1 | .gradle/ 2 | .idea/ 3 | build/ 4 | .kotlintest/ 5 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: java 2 | 3 | sudo: false 4 | 5 | before_cache: 6 | - rm -f $HOME/.gradle/caches/modules-2/modules-2.lock 7 | - rm -fr $HOME/.gradle/caches/*/plugin-resolution/ 8 | 9 | cache: 10 | directories: 11 | - "$HOME/.gradle/caches/" 12 | - "$HOME/.gradle/wrapper/" 13 | - "$HOME/.m2/repository/" 14 | 15 | script: "./gradlew build" -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2019 Leonardo Colman Lopes 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | 2 | # Simple Properties 3 | 4 | 5 | [![Build Status](https://travis-ci.com/LeoColman/SimpleProperties.svg?branch=master)](https://travis-ci.com/LeoColman/SimpleProperties) [![GitHub](https://img.shields.io/github/license/LeoColman/SimpleProperties.svg)](https://github.com/Kerooker/SimpleProperties/blob/master/LICENSE) [![Maven Central](https://img.shields.io/maven-central/v/com.kerooker.simpleproperties/simple-properties.svg)](https://search.maven.org/search?q=g:com.kerooker.simpleproperties) 6 | 7 | ## Introduction 8 | 9 | Aplications might behave differently in different environments. One might have a specific configuration for Production Environment, which is different from Development Environment. 10 | 11 | With simple properties, you can configure a different profile of properties for each of your environments, and access them through an easy to use DSL. 12 | 13 | This library was inspired and is very similar to [**Spring Profiles**](https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-external-config.html), but only for Properties, and in a simpler way. 14 | 15 | ## Adding to your project 16 | Edit your `build.gradle` to contain the following dependency, from Maven Central: 17 | 18 | ``` 19 | implementation("com.kerooker.simpleproperties:simple-properties:{currentVersion}") 20 | ``` 21 | 22 | ## Usage Example 23 | 24 | ```kotlin 25 | 26 | object MySystemProperties { 27 | 28 | private val simpleProperties = SimpleProperties() 29 | 30 | val databaseUrl: String = simpleProperties["my.database.url"] 31 | 32 | } 33 | 34 | ``` 35 | 36 | | File | Value of "my.database.url" | 37 | | --- | --- | 38 | | application-local.properties | localhost:3306 | 39 | | application-qa.properties | qa.database.server.intranet:3306 | 40 | | application-prod.properties | prod.database.server.intranet:7725 | 41 | 42 | 43 | Launching app: 44 | 45 | With local profile: 46 | 47 | `java -jar myapp.jar -Dactive_profiles=local` 48 | 49 | ```kotlin 50 | MySystemProperties.databaseUrl == "localhost:3306" 51 | ``` 52 | 53 | With production profile: 54 | `java -jar myapp.jar -Dactive_profiles=prod` 55 | ```kotlin 56 | MySystemProperties.databaseUrl == "prod.database.server.intranet:7725" 57 | ``` 58 | 59 | ## Default profile 60 | 61 | SimpleProperties will always try to read an optional default file `application.properties`. Any profile may override properties from the default file. 62 | 63 | ## Configuring profiles 64 | 65 | SimpleProperties will try to find your profiles in some places: 66 | 67 | 1. System Environment Variables 68 | 2. Java Properties 69 | 3. Defined at instantiation 70 | 1. `SimpleProperties(profiles = listOf("qa"))` 71 | 72 | ## More than one profile 73 | 74 | Multiple profiles may be used at once, in a comma separated value in case of System (`-Dactive_profiles=foo,bar,baz`). 75 | 76 | If keys are overriden, the last profile in the list will take priority. 77 | 78 | ## Where to place files 79 | 80 | Files are expected to be in the classpath. In `Spring`, this is usually done by placing the file in the `resources` folder, and this is allowed in Simple Properties too: 81 | 82 | ``` 83 | MyProject 84 | `-- src 85 | `-- main 86 | |-- kotlin 87 | | |-- Foo.kt 88 | | `-- Bar.kt 89 | `-- resources 90 | |-- application.properties 91 | |-- application-foo.properties 92 | `-- application-bar.properties 93 | ``` 94 | 95 | 96 | You can customize where your files will be placed when creating the `SimpleProperties` instance: 97 | 98 | ```kotlin 99 | SimpleProperties(filesLocation = "foo/bar") 100 | ``` 101 | 102 | Which allows for example the structure 103 | ``` 104 | MyProject 105 | `-- resources 106 | `-- foo 107 | `-- bar 108 | |-- application.properties 109 | `-- application-foo.properties 110 | ``` 111 | -------------------------------------------------------------------------------- /build.gradle.kts: -------------------------------------------------------------------------------- 1 | import org.jetbrains.dokka.gradle.DokkaTask 2 | import org.jetbrains.kotlin.gradle.tasks.KotlinCompile 3 | 4 | plugins { 5 | kotlin("jvm") version "1.3.21" 6 | `maven-publish` 7 | signing 8 | id("org.jetbrains.dokka") version "0.9.17" 9 | 10 | } 11 | 12 | group = "com.kerooker.simpleproperties" 13 | version = "1.0.1" 14 | 15 | repositories { 16 | mavenCentral() 17 | } 18 | 19 | dependencies { 20 | implementation(kotlin("stdlib-jdk8")) 21 | testImplementation(group = "io.kotlintest", name = "kotlintest-runner-junit5", version = "3.3.2") 22 | } 23 | 24 | tasks.withType { 25 | kotlinOptions.jvmTarget = "1.8" 26 | } 27 | 28 | tasks.withType { 29 | useJUnitPlatform() 30 | } 31 | 32 | val sourcesJar by tasks.registering(Jar::class) { 33 | classifier = "sources" 34 | from(sourceSets.getByName("main").allSource) 35 | } 36 | 37 | val javadocJar by tasks.registering(Jar::class) { 38 | val javadoc = tasks["dokka"] as DokkaTask 39 | javadoc.outputFormat = "javadoc" 40 | javadoc.outputDirectory = "$buildDir/javadoc" 41 | dependsOn(javadoc) 42 | classifier = "javadoc" 43 | from(javadoc.outputDirectory) 44 | } 45 | 46 | publishing { 47 | repositories { 48 | 49 | maven("https://oss.sonatype.org/service/local/staging/deploy/maven2") { 50 | credentials { 51 | username = System.getProperty("OSSRH_USERNAME") 52 | password = System.getProperty("OSSRH_PASSWORD") 53 | } 54 | } 55 | } 56 | 57 | publications { 58 | 59 | register("mavenJava", MavenPublication::class) { 60 | from(components["java"]) 61 | artifact(sourcesJar.get()) 62 | artifact(javadocJar.get()) 63 | 64 | pom { 65 | name.set("Simple Properties") 66 | description.set("Simple Properties") 67 | url.set("https://www.github.com/Kerooker/SimpleProperties") 68 | 69 | 70 | scm { 71 | connection.set("scm:git:http://www.github.com/Kerooker/SimpleProperties/") 72 | developerConnection.set("scm:git:http://github.com/Kerooker/") 73 | url.set("https://www.github.com/Kerooker/SimpleProperties") 74 | } 75 | 76 | licenses { 77 | license { 78 | name.set("MIT") 79 | url.set("https://opensource.org/licenses/MIT") 80 | } 81 | } 82 | 83 | developers { 84 | developer { 85 | id.set("Kerooker") 86 | name.set("Leonardo Colman Lopes") 87 | email.set("leonardo.colman98@gmail.com") 88 | } 89 | } 90 | } 91 | } 92 | } 93 | } 94 | 95 | signing { 96 | useGpgCmd() 97 | sign(publishing.publications["mavenJava"]) 98 | } -------------------------------------------------------------------------------- /gradle.properties: -------------------------------------------------------------------------------- 1 | kotlin.code.style=official -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/LeoColman/SimpleProperties/214f97f236a0598324103095d21fcc37d012787f/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionBase=GRADLE_USER_HOME 2 | distributionPath=wrapper/dists 3 | distributionUrl=https\://services.gradle.org/distributions/gradle-4.10.3-bin.zip 4 | zipStoreBase=GRADLE_USER_HOME 5 | zipStorePath=wrapper/dists 6 | -------------------------------------------------------------------------------- /gradlew: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env sh 2 | 3 | ############################################################################## 4 | ## 5 | ## Gradle start up script for UN*X 6 | ## 7 | ############################################################################## 8 | 9 | # Attempt to set APP_HOME 10 | # Resolve links: $0 may be a link 11 | PRG="$0" 12 | # Need this for relative symlinks. 13 | while [ -h "$PRG" ] ; do 14 | ls=`ls -ld "$PRG"` 15 | link=`expr "$ls" : '.*-> \(.*\)$'` 16 | if expr "$link" : '/.*' > /dev/null; then 17 | PRG="$link" 18 | else 19 | PRG=`dirname "$PRG"`"/$link" 20 | fi 21 | done 22 | SAVED="`pwd`" 23 | cd "`dirname \"$PRG\"`/" >/dev/null 24 | APP_HOME="`pwd -P`" 25 | cd "$SAVED" >/dev/null 26 | 27 | APP_NAME="Gradle" 28 | APP_BASE_NAME=`basename "$0"` 29 | 30 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 31 | DEFAULT_JVM_OPTS="" 32 | 33 | # Use the maximum available, or set MAX_FD != -1 to use that value. 34 | MAX_FD="maximum" 35 | 36 | warn () { 37 | echo "$*" 38 | } 39 | 40 | die () { 41 | echo 42 | echo "$*" 43 | echo 44 | exit 1 45 | } 46 | 47 | # OS specific support (must be 'true' or 'false'). 48 | cygwin=false 49 | msys=false 50 | darwin=false 51 | nonstop=false 52 | case "`uname`" in 53 | CYGWIN* ) 54 | cygwin=true 55 | ;; 56 | Darwin* ) 57 | darwin=true 58 | ;; 59 | MINGW* ) 60 | msys=true 61 | ;; 62 | NONSTOP* ) 63 | nonstop=true 64 | ;; 65 | esac 66 | 67 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 68 | 69 | # Determine the Java command to use to start the JVM. 70 | if [ -n "$JAVA_HOME" ] ; then 71 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 72 | # IBM's JDK on AIX uses strange locations for the executables 73 | JAVACMD="$JAVA_HOME/jre/sh/java" 74 | else 75 | JAVACMD="$JAVA_HOME/bin/java" 76 | fi 77 | if [ ! -x "$JAVACMD" ] ; then 78 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 79 | 80 | Please set the JAVA_HOME variable in your environment to match the 81 | location of your Java installation." 82 | fi 83 | else 84 | JAVACMD="java" 85 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 86 | 87 | Please set the JAVA_HOME variable in your environment to match the 88 | location of your Java installation." 89 | fi 90 | 91 | # Increase the maximum file descriptors if we can. 92 | if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then 93 | MAX_FD_LIMIT=`ulimit -H -n` 94 | if [ $? -eq 0 ] ; then 95 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then 96 | MAX_FD="$MAX_FD_LIMIT" 97 | fi 98 | ulimit -n $MAX_FD 99 | if [ $? -ne 0 ] ; then 100 | warn "Could not set maximum file descriptor limit: $MAX_FD" 101 | fi 102 | else 103 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" 104 | fi 105 | fi 106 | 107 | # For Darwin, add options to specify how the application appears in the dock 108 | if $darwin; then 109 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" 110 | fi 111 | 112 | # For Cygwin, switch paths to Windows format before running java 113 | if $cygwin ; then 114 | APP_HOME=`cygpath --path --mixed "$APP_HOME"` 115 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` 116 | JAVACMD=`cygpath --unix "$JAVACMD"` 117 | 118 | # We build the pattern for arguments to be converted via cygpath 119 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` 120 | SEP="" 121 | for dir in $ROOTDIRSRAW ; do 122 | ROOTDIRS="$ROOTDIRS$SEP$dir" 123 | SEP="|" 124 | done 125 | OURCYGPATTERN="(^($ROOTDIRS))" 126 | # Add a user-defined pattern to the cygpath arguments 127 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then 128 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" 129 | fi 130 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 131 | i=0 132 | for arg in "$@" ; do 133 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` 134 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option 135 | 136 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition 137 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` 138 | else 139 | eval `echo args$i`="\"$arg\"" 140 | fi 141 | i=$((i+1)) 142 | done 143 | case $i in 144 | (0) set -- ;; 145 | (1) set -- "$args0" ;; 146 | (2) set -- "$args0" "$args1" ;; 147 | (3) set -- "$args0" "$args1" "$args2" ;; 148 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;; 149 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; 150 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; 151 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; 152 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; 153 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; 154 | esac 155 | fi 156 | 157 | # Escape application args 158 | save () { 159 | for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done 160 | echo " " 161 | } 162 | APP_ARGS=$(save "$@") 163 | 164 | # Collect all arguments for the java command, following the shell quoting and substitution rules 165 | eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" 166 | 167 | # by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong 168 | if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then 169 | cd "$(dirname "$0")" 170 | fi 171 | 172 | exec "$JAVACMD" "$@" 173 | -------------------------------------------------------------------------------- /gradlew.bat: -------------------------------------------------------------------------------- 1 | @if "%DEBUG%" == "" @echo off 2 | @rem ########################################################################## 3 | @rem 4 | @rem Gradle startup script for Windows 5 | @rem 6 | @rem ########################################################################## 7 | 8 | @rem Set local scope for the variables with windows NT shell 9 | if "%OS%"=="Windows_NT" setlocal 10 | 11 | set DIRNAME=%~dp0 12 | if "%DIRNAME%" == "" set DIRNAME=. 13 | set APP_BASE_NAME=%~n0 14 | set APP_HOME=%DIRNAME% 15 | 16 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 17 | set DEFAULT_JVM_OPTS= 18 | 19 | @rem Find java.exe 20 | if defined JAVA_HOME goto findJavaFromJavaHome 21 | 22 | set JAVA_EXE=java.exe 23 | %JAVA_EXE% -version >NUL 2>&1 24 | if "%ERRORLEVEL%" == "0" goto init 25 | 26 | echo. 27 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 28 | echo. 29 | echo Please set the JAVA_HOME variable in your environment to match the 30 | echo location of your Java installation. 31 | 32 | goto fail 33 | 34 | :findJavaFromJavaHome 35 | set JAVA_HOME=%JAVA_HOME:"=% 36 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 37 | 38 | if exist "%JAVA_EXE%" goto init 39 | 40 | echo. 41 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 42 | echo. 43 | echo Please set the JAVA_HOME variable in your environment to match the 44 | echo location of your Java installation. 45 | 46 | goto fail 47 | 48 | :init 49 | @rem Get command-line arguments, handling Windows variants 50 | 51 | if not "%OS%" == "Windows_NT" goto win9xME_args 52 | 53 | :win9xME_args 54 | @rem Slurp the command line arguments. 55 | set CMD_LINE_ARGS= 56 | set _SKIP=2 57 | 58 | :win9xME_args_slurp 59 | if "x%~1" == "x" goto execute 60 | 61 | set CMD_LINE_ARGS=%* 62 | 63 | :execute 64 | @rem Setup the command line 65 | 66 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 67 | 68 | @rem Execute Gradle 69 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% 70 | 71 | :end 72 | @rem End local scope for the variables with windows NT shell 73 | if "%ERRORLEVEL%"=="0" goto mainEnd 74 | 75 | :fail 76 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 77 | rem the _cmd.exe /c_ return code! 78 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 79 | exit /b 1 80 | 81 | :mainEnd 82 | if "%OS%"=="Windows_NT" endlocal 83 | 84 | :omega 85 | -------------------------------------------------------------------------------- /settings.gradle: -------------------------------------------------------------------------------- 1 | rootProject.name = 'simple-properties' -------------------------------------------------------------------------------- /src/main/kotlin/com/kerooker/simpleproperties/SimpleProperties.kt: -------------------------------------------------------------------------------- 1 | package com.kerooker.simpleproperties 2 | 3 | import com.kerooker.simpleproperties.internal.file.PropertyFileLoader 4 | import com.kerooker.simpleproperties.internal.profile.SystemProfileLoader 5 | 6 | /** 7 | * Enhanced [java.util.Properties] that reads from the classpath 8 | * 9 | * The SimpleProperties class reads profile properties defined in [filesLocation] (defaults to root). To select the profiles 10 | * to be loaded, you can either pass them in [profiles] (defaults to empty) or System Environment Variables/System Properties, 11 | * through the key `active_profiles`, for example `active_profiles=prod,mysql`. 12 | * 13 | * The profiles will be loaded in the order they're defined, so any property defined by a profile will be overriden by 14 | * another profile if it's loaded after it. 15 | * 16 | * This class also reads a default profile, called `application.properties`. This will be loaded first, and any other profile 17 | * may override its properties. 18 | * 19 | * 20 | * @param [profiles] The profiles you want to load. For example `listOf("prod", "mysql")`. Defaults to empty 21 | * @param [filesLocation] Where this should fetch properties from. Defaults to root (.) 22 | */ 23 | public class SimpleProperties( 24 | private val profiles: List = emptyList(), 25 | private val filesLocation: String = "" 26 | ) { 27 | 28 | private val props: Map = with(PropertyFileLoader(filesLocation)) { 29 | val map = loadDefaultFile().toMutableMap() 30 | (profiles + SystemProfileLoader().loadProfiles().distinct()).forEach { map += loadProfileFile(it) } 31 | map.toMap() 32 | } 33 | 34 | /** 35 | * Fetches [key] from the properties 36 | * 37 | * If the key is defined in multiple profiles, the value present in the last declared profile is returned. If the 38 | * key is undefined, this will throw a [PropertyNotDefinedException]. 39 | * 40 | * @see [getOptional] 41 | * @param [key] The key to find in the properties 42 | * @throws [PropertyNotDefinedException] If [key] isn't defined in any profile 43 | */ 44 | public operator fun get(key: String): String { 45 | return props[key] ?: throw PropertyNotDefinedException(key) 46 | } 47 | 48 | /** 49 | * Fetches [key] from the properties, or null if it's undefined 50 | * 51 | * Similarly to [get], this will fetch the key from the properties. If it's defined in multiple profiles, the value 52 | * in the last declared profile is returned. If the key is undefined, this will return null. 53 | * 54 | * @see [get] 55 | * @param [key] The key to find in the properties 56 | */ 57 | public fun getOptional(key: String): String? { 58 | return props[key] 59 | } 60 | 61 | } 62 | 63 | /** 64 | * Thrown when a key is fetched from the properties, but doesn't exist 65 | */ 66 | public class PropertyNotDefinedException( 67 | missingProperty: String 68 | ) : RuntimeException("Property <$missingProperty> is not defined. Use simpleProperty.getOptional(\"$missingProperty\") instead") -------------------------------------------------------------------------------- /src/main/kotlin/com/kerooker/simpleproperties/internal/classloader/ClassLoaderExtensions.kt: -------------------------------------------------------------------------------- 1 | package com.kerooker.simpleproperties.internal.classloader 2 | 3 | internal val T.classLoader 4 | get() = this::class.java.classLoader -------------------------------------------------------------------------------- /src/main/kotlin/com/kerooker/simpleproperties/internal/file/PropertyFileLoader.kt: -------------------------------------------------------------------------------- 1 | package com.kerooker.simpleproperties.internal.file 2 | 3 | import com.kerooker.simpleproperties.internal.classloader.classLoader 4 | import java.io.InputStream 5 | import java.util.Properties 6 | 7 | internal class PropertyFileLoader( 8 | private val filesLocation: String = "" 9 | ) { 10 | 11 | fun loadDefaultFile(): Map { 12 | return try { 13 | mapPropertyFile("application.properties") 14 | } catch (_: Throwable) { 15 | emptyMap() 16 | } 17 | } 18 | 19 | fun loadProfileFile(profile: String): Map { 20 | return try { 21 | mapPropertyFile("application-$profile.properties") 22 | } catch(_: Throwable) { 23 | throw FailedToLoadProfileException(profile, filesLocation) 24 | } 25 | } 26 | 27 | private fun mapPropertyFile(fileName: String) = streamFileFromClasspath(fileName.withDirectory()).toMap() 28 | 29 | private fun String.withDirectory(): String { 30 | return if(filesLocation == "") this else "$filesLocation/$this" 31 | } 32 | 33 | private fun streamFileFromClasspath(fileName: String) = classLoader.getResourceAsStream(fileName) 34 | 35 | @Suppress("UNCHECKED_CAST") 36 | private fun InputStream.toMap(): Map { 37 | val props = Properties() 38 | props.load(this) 39 | return props.toMap() as Map 40 | } 41 | } 42 | 43 | internal class FailedToLoadProfileException( 44 | profile: String, location: String 45 | ) : RuntimeException("Could not load profile <$profile> from <$location>") 46 | -------------------------------------------------------------------------------- /src/main/kotlin/com/kerooker/simpleproperties/internal/profile/SystemProfileLoader.kt: -------------------------------------------------------------------------------- 1 | package com.kerooker.simpleproperties.internal.profile 2 | 3 | import java.lang.System.getProperty 4 | import java.lang.System.getenv 5 | 6 | internal class SystemProfileLoader { 7 | 8 | fun loadProfiles(): List = environmentProfiles().ifEmpty { propertyProfiles() } 9 | 10 | private fun environmentProfiles() = getenv("active_profiles").extractProfiles() 11 | 12 | private fun propertyProfiles() = getProperty("active_profiles").extractProfiles() 13 | 14 | private fun String?.extractProfiles() = this?.split(",") ?: emptyList() 15 | } -------------------------------------------------------------------------------- /src/test/kotlin/com/kerooker/simpleproperties/SimplePropertiesTest.kt: -------------------------------------------------------------------------------- 1 | package com.kerooker.simpleproperties 2 | 3 | import io.kotlintest.extensions.system.withEnvironment 4 | import io.kotlintest.extensions.system.withSystemProperty 5 | import io.kotlintest.shouldBe 6 | import io.kotlintest.shouldThrow 7 | import io.kotlintest.shouldThrowAny 8 | import io.kotlintest.specs.FunSpec 9 | 10 | class SimplePropertiesTest : FunSpec() { 11 | 12 | init { 13 | test("Should load default properties from default location if no profile is set") { 14 | val props = SimpleProperties() 15 | 16 | props["default-from-default"] shouldBe "DefaultFromDefault" 17 | } 18 | 19 | test("Should throw exception when key doesnt exist") { 20 | val props = SimpleProperties() 21 | 22 | val exception = shouldThrow { props["inexistent-key"] } 23 | 24 | exception.message shouldBe "Property is not defined. Use simpleProperty.getOptional(\"inexistent-key\") instead" 25 | } 26 | 27 | test("Should return property if it is present and loaded optionally") { 28 | val props = SimpleProperties() 29 | 30 | props.getOptional("default-from-default") shouldBe "DefaultFromDefault" 31 | } 32 | 33 | test("Should not throw exception if property is not present and loaded optionally") { 34 | val props = SimpleProperties() 35 | 36 | props.getOptional("inexistent-key") shouldBe null 37 | } 38 | 39 | test("Should load values from both default and profile") { 40 | val props = SimpleProperties(profiles = listOf("prod")) 41 | 42 | props["default-from-default"] shouldBe "DefaultFromDefault" 43 | props["prod-from-default"] shouldBe "ProdFromDefault" 44 | } 45 | 46 | test("Should override values from default if present in profile") { 47 | val props = SimpleProperties(profiles = listOf("default-override")) 48 | 49 | props["default-from-default"] shouldBe "Overriden" 50 | } 51 | 52 | test("Should load profiles from environment") { 53 | withEnvironment("active_profiles","prod") { 54 | val props = SimpleProperties() 55 | 56 | props["prod-from-default"] shouldBe "ProdFromDefault" 57 | } 58 | } 59 | 60 | test("Should load profiles from properties") { 61 | withSystemProperty("active_profiles", "prod") { 62 | val props = SimpleProperties() 63 | props["prod-from-default"] shouldBe "ProdFromDefault" 64 | } 65 | } 66 | 67 | test("Should allow changing default profile location") { 68 | val props = SimpleProperties(filesLocation = "non_default") 69 | 70 | props["default-from-non-default"] shouldBe "DefaultFromNonDefault" 71 | } 72 | 73 | test("Should load profile, even if there is no application.properties file") { 74 | val props = SimpleProperties(filesLocation = "without_default", profiles = listOf("qa")) 75 | 76 | props["qa-property"] shouldBe "QaProperty" 77 | } 78 | 79 | test("Should throw an exception on initialization if profile does not exist") { 80 | 81 | shouldThrowAny { SimpleProperties(listOf("InexistentProfile")) } 82 | } 83 | 84 | } 85 | 86 | } -------------------------------------------------------------------------------- /src/test/kotlin/com/kerooker/simpleproperties/internal/file/PropertyFileLoaderTest.kt: -------------------------------------------------------------------------------- 1 | package com.kerooker.simpleproperties.internal.file 2 | 3 | import io.kotlintest.shouldBe 4 | import io.kotlintest.shouldThrow 5 | import io.kotlintest.specs.FunSpec 6 | 7 | class PropertyFileLoaderTest : FunSpec() { 8 | 9 | init { 10 | 11 | test("Should load from relative path if an empty file location is provided") { 12 | PropertyFileLoader("").loadDefaultFile() shouldBe mapOf( 13 | "default-from-default" to "DefaultFromDefault", 14 | "default-from-default2" to "DefaultFromDefault2" 15 | ) 16 | } 17 | 18 | test("Should load default file (application.properties) from default location (root)") { 19 | PropertyFileLoader().loadDefaultFile() shouldBe mapOf( 20 | "default-from-default" to "DefaultFromDefault", 21 | "default-from-default2" to "DefaultFromDefault2" 22 | ) 23 | } 24 | 25 | test("Should load default file (application.properties) from non-default location") { 26 | PropertyFileLoader(filesLocation = "non_default").loadDefaultFile() shouldBe mapOf( 27 | "default-from-non-default" to "DefaultFromNonDefault", 28 | "default-from-non-default2" to "DefaultFromNonDefault2" 29 | ) 30 | } 31 | 32 | test("Should load profile file from default location (root") { 33 | PropertyFileLoader().loadProfileFile("prod") shouldBe mapOf( 34 | "prod-from-default" to "ProdFromDefault", 35 | "prod-from-default2" to "ProdFromDefault2" 36 | ) 37 | } 38 | 39 | test("Should load profile file from non-default location") { 40 | PropertyFileLoader(filesLocation = "non_default").loadProfileFile("prod") shouldBe mapOf( 41 | "prod-from-non-default" to "ProdFromNonDefault", 42 | "prod-from-non-default2" to "ProdFromNonDefault2" 43 | ) 44 | } 45 | 46 | test("Should return empty map if application.properties doesn't exist") { 47 | PropertyFileLoader(filesLocation = "without_default").loadDefaultFile() shouldBe emptyMap() 48 | } 49 | 50 | test("Should throw exception if profile does not exist") { 51 | val exception = shouldThrow { PropertyFileLoader("folderLocation").loadProfileFile("inexistent") } 52 | exception.message shouldBe "Could not load profile from " 53 | } 54 | } 55 | 56 | } -------------------------------------------------------------------------------- /src/test/kotlin/com/kerooker/simpleproperties/internal/profile/SystemProfileLoaderTest.kt: -------------------------------------------------------------------------------- 1 | package com.kerooker.simpleproperties.internal.profile 2 | 3 | import io.kotlintest.extensions.system.withEnvironment 4 | import io.kotlintest.extensions.system.withSystemProperty 5 | import io.kotlintest.matchers.collections.shouldContainExactlyInAnyOrder 6 | import io.kotlintest.shouldBe 7 | import io.kotlintest.specs.FunSpec 8 | 9 | class SystemProfileLoaderTest : FunSpec() { 10 | 11 | init { 12 | 13 | test("Should return no profiles if nothing is present in System Environment or Properties") { 14 | loadProfiles() shouldBe emptyList() 15 | } 16 | 17 | test("Should return a profile if one profile is present in System Environment") { 18 | withEnvironment("active_profiles", "prod") { 19 | loadProfiles() shouldBe listOf("prod") 20 | } 21 | } 22 | 23 | test("Should return multiple profiles if more than one profile is present in System Environment") { 24 | withEnvironment("active_profiles", "prod,qa,dev") { 25 | loadProfiles() shouldContainExactlyInAnyOrder listOf("prod", "qa", "dev") 26 | } 27 | } 28 | 29 | test("Should return the profiles in the order they were declared in the System Environment") { 30 | withEnvironment("active_profiles", "b,c,a") { 31 | loadProfiles() shouldBe listOf("b", "c", "a") 32 | } 33 | } 34 | 35 | test("Should a profile if one profile is presentn in System Properties") { 36 | withSystemProperty("active_profiles", "prod") { 37 | loadProfiles() shouldBe listOf("prod") 38 | } 39 | } 40 | 41 | test("Should return multiple profiles if more than one profile is present in System Properties") { 42 | withSystemProperty("active_profiles", "prod,qa,dev") { 43 | loadProfiles() shouldContainExactlyInAnyOrder listOf("prod", "qa", "dev") 44 | } 45 | } 46 | 47 | test("Should return the profiles in the order they were declared in the System Properties") { 48 | withSystemProperty("active_profiles", "b,c,a") { 49 | loadProfiles() shouldBe listOf("b", "c", "a") 50 | } 51 | } 52 | 53 | test("Should give priority to System Environment if profiles are present in both") { 54 | withEnvironment("active_profiles", "prod,dev,qa") { 55 | withSystemProperty("active_profiles", "a,b,c") { 56 | loadProfiles() shouldContainExactlyInAnyOrder listOf("prod", "dev", "qa") 57 | } 58 | } 59 | } 60 | } 61 | 62 | private fun loadProfiles() = SystemProfileLoader().loadProfiles() 63 | 64 | } -------------------------------------------------------------------------------- /src/test/resources/application-default-override.properties: -------------------------------------------------------------------------------- 1 | default-from-default=Overriden -------------------------------------------------------------------------------- /src/test/resources/application-prod.properties: -------------------------------------------------------------------------------- 1 | prod-from-default=ProdFromDefault 2 | prod-from-default2=ProdFromDefault2 -------------------------------------------------------------------------------- /src/test/resources/application.properties: -------------------------------------------------------------------------------- 1 | default-from-default=DefaultFromDefault 2 | default-from-default2=DefaultFromDefault2 -------------------------------------------------------------------------------- /src/test/resources/non_default/application-prod.properties: -------------------------------------------------------------------------------- 1 | prod-from-non-default=ProdFromNonDefault 2 | prod-from-non-default2=ProdFromNonDefault2 -------------------------------------------------------------------------------- /src/test/resources/non_default/application.properties: -------------------------------------------------------------------------------- 1 | default-from-non-default=DefaultFromNonDefault 2 | default-from-non-default2=DefaultFromNonDefault2 -------------------------------------------------------------------------------- /src/test/resources/without_default/application-qa.properties: -------------------------------------------------------------------------------- 1 | qa-property=QaProperty --------------------------------------------------------------------------------