cdimascio / dotenv-kotlin Goto Github PK
View Code? Open in Web Editor NEW๐๏ธ Dotenv is a module that loads environment variables from a .env file
License: Apache License 2.0
๐๏ธ Dotenv is a module that loads environment variables from a .env file
License: Apache License 2.0
Cool project! I'd like to try it and I just had a couple questions.
When the jar file is compiled, are the env vars compiled with it? is there a way to do that? or should the .env
file reside next to the jar file for it to be read?
Hi @cdimascio The latest release is not available on Maven url. Latest release is 6.3.1 but on the maven is 6.2.2. Thanks.
https://mavenlibs.com/maven/dependency/io.github.cdimascio
OS: MacOS v10.13.4
Java version: JavaSE-1.8
Dotenv version: 3.1.0
When configuring the directory Dotenv
uses it seems to make a difference weather or not you use a dot in the path.
The following code works just fine:
Dotenv env = Dotenv.configure().directory("./").load();
However this code throws an error:
Dotenv env = Dotenv.configure().directory("/").load();
Exception in thread "main" io.github.cdimascio.dotenv.DotEnvException: Could not find /.env on the classpath
at io.github.cdimascio.dotenv.internal.ClasspathHelper.loadFileFromClasspath(ClassPathHelper.kt:28)
at io.github.cdimascio.dotenv.internal.DotenvReader.read(DotenvReader.kt:26)
at io.github.cdimascio.dotenv.internal.DotenvParser.parse(DotenvParser.kt:18)
at io.github.cdimascio.dotenv.DotenvBuilder.load(Dotenv.kt:48)
at dotenv_test.Main.main(Main.java:9)
Removing the configuration entirely should according to the documentation load the dotenv
file from the root of the project: ./
however this throws an error too. Which seems especially weird to me.
Is there any way to use a multi-line value in the .env
file?
I've tried using double quotes, single quotes, backticks plus the \n
char but I get the literal \n
characters in the string when evaluated in Java code.
Like used in this bit of code:
val dotenv: Dotenv = dotenv{
filename = ".env"
}
dotenv.entries(Dotenv.Filter.DECLARED_IN_ENV_FILE).forEach { println(it) }
Error: Could not find or load main class io.cdimascio.DotenvKt
It happens when I try to run the jar from a docker container. I guess the docker doesn't find the java classpath for Dotenv.
I use gradle - so in the dependencies I have: compile 'io.github.cdimascio:java-dotenv:5.2.1'
Any ideas what to do? Do I need the actual Dotenv.kt file in my project?
I'm using this dotenv
Java implementation in a scripted Jenkins pipeline and would like to load env vars from a CI env vars file we pull down from S3.
Apologies if this is stated somewhere in the code or documentation (I poked around extensively, but could not find anything). I would like to only load env vars from a .env
file and not mix them w/ system/host env vars.
I have this:
@Grab('io.github.cdimascio:java-dotenv:5.0.1')
import io.github.cdimascio.dotenv.Dotenv
import io.github.cdimascio.dotenv.DotenvEntry
Dotenv dotenv = Dotenv.configure()
.filename("ci-env-file-test")
.ignoreIfMissing()
.load()
for (DotenvEntry e : dotenv.entries()) {
System.out.println("${e.getKey()}=${e.getValue()}")
}
This outputs the env vars in my test CI env vars file, but also mixes them with my system/host env vars. I see the use case for this, for sure. I also saw: https://github.com/cdimascio/java-dotenv/issues/25, which seems to imply the dotenv.entries()
in v5.0.0
and below would do what I want, but @Grab
'ing that version (w/ my code above) still returns the env vars from my CI test file and my system/host env vars.
Am I missing a param I can pass to the configure .load()
... or?
ps: this is a great lib!
I was wondering if there was any way to make the variables in the .env
file globally available throughout my entire java application.
It seems as though configuring and loading the variables returns a Map
of sorts from which you can retrieve all of the values. However I have to configure and load this variable in every file from which I wish to use it.
Dotenv env = Dotenv.configure().directory("./").load();
Is there any way I can load them once and use them everywhere? Perhaps even through the native System.getenv()
static method? Running the configuration and loading once from my public static main
method or something.
The error;
Exception in thread "main" java.lang.IncompatibleClassChangeError: Method 'io.github.cdimascio.dotenv.DotenvBuilder io.github.cdimascio.dotenv.Dotenv.configure()' must be Methodref constant
at io.github.cdimascio.dotenv.DslKt.dotenv(Dsl.kt:13)
at bot.hibikibot.HibikiBot.<clinit>(HibikiBot.kt:45)
at bot.hibikibot.HibikiBotKt.main(HibikiBot.kt:154)
at bot.hibikibot.HibikiBotKt$main$2.invoke(HibikiBot.kt)
at bot.hibikibot.HibikiBotKt$main$2.invoke(HibikiBot.kt)
at kotlin.coroutines.intrinsics.IntrinsicsKt__IntrinsicsJvmKt$createCoroutineUnintercepted$$inlined$createCoroutineFromSuspendFunction$IntrinsicsKt__IntrinsicsJvmKt$1.invokeSuspend(IntrinsicsJvm.kt:205)
at kotlin.coroutines.jvm.internal.BaseContinuationImpl.resumeWith(ContinuationImpl.kt:33)
at kotlin.coroutines.ContinuationKt.startCoroutine(Continuation.kt:115)
at kotlin.coroutines.jvm.internal.RunSuspendKt.runSuspend(RunSuspend.kt:19)
at bot.hibikibot.HibikiBotKt.main(HibikiBot.kt)
Code;
val env = dotenv {
directory = "./resources"
filename = "hb.env"
}
var token: String = env["PROD_TOKEN"]!!
if (args.any { it == "--dev" }) {
token = env["DEV_TOKEN"]!!
}
Steps to reproduce:
checkout project: https://github.com/cdimascio/kotlin-spring-mvc-template
replace 3.1.3 library version with 5.1.3
create .env
file under src/main/resources
verify that running gradle bootRun
command resolves .env file location correctly.
verify that running gradle bootJar && java -jar build/libs/example-service-1.0.0.jar
doesn't resolve .env
files location properly
Tested also with 3.1.3 version and it was working correctly back then.
Update:
Last working version: 3.1.4
First not working version: 3.1.5
I put the .env file inside / src / main / resources but still still giving the following error when I run .jar.
Caused by: io.github.cdimascio.dotenv.DotEnvException: Could not find ./.env on the classpath
at io.github.cdimascio.dotenv.internal.ClasspathHelper.loadFileFromClasspath(ClassPathHelper.kt:37)
at io.github.cdimascio.dotenv.internal.DotenvReader.read(DotenvReader.kt:36)
at io.github.cdimascio.dotenv.internal.DotenvParser.parse(DotenvParser.kt:26)
at io.github.cdimascio.dotenv.DotenvBuilder.load(Dotenv.kt:119)
at io.github.cdimascio.dotenv.Dotenv$Instance.load(Dotenv.kt:32)
at io.github.cdimascio.dotenv.Dotenv.load(Dotenv.kt)
at com.org.teammove.utils.UtilDotenv.getEnv(UtilDotenv.java:10)
at com.org.teammove.utils.UtilConectorPostgreSQL.getHOST_LOGIN(UtilConectorPostgreSQL.java:8)
at com.org.teammove.autenticacao.AutenticacaoDatabaseConfig.dataSource(AutenticacaoDatabaseConfig.java:15)
at com.org.teammove.autenticacao.AutenticacaoDatabaseConfig$$EnhancerBySpringCGLIB$$c94cd15a.CGLIB$dataSource$0(<generated>)
at com.org.teammove.autenticacao.AutenticacaoDatabaseConfig$$EnhancerBySpringCGLIB$$c94cd15a$$FastClassBySpringCGLIB$$e0a583b5.invoke(<generated>)
at org.springframework.cglib.proxy.MethodProxy.invokeSuper(MethodProxy.java:228)
at org.springframework.context.annotation.ConfigurationClassEnhancer$BeanMethodInterceptor.intercept(ConfigurationClassEnhancer.java:361)
at com.org.teammove.autenticacao.AutenticacaoDatabaseConfig$$EnhancerBySpringCGLIB$$c94cd15a.dataSource(<generated>)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:154)
... 50 more
Version used is 5.1.1
I ended up viewing the other issues created, but none solved my problem.
How works with quoted variables?
export JDBC_URL="jdbc:hive2://[domain]:10000/default;principal=hive/_HOST@[REALM]"
String url = JDBC_URL;
Connection conn = DriverManager.getConnection(url.replace("\"", ""));
Change version from 6.2.1 to 6.2.2 in the readme gradle.
Hi There,
I was happy to find your project, However I found that it requires kotlin
libraries to run.
Trying the following failed.
<groupId>io.github.cdimascio</groupId>
<artifactId>java-dotenv</artifactId>
<version>5.2.2</version>
<exclusions>
<exclusion>
<groupId>org.jetbrains.kotlin</groupId>
<artifactId>kotlin-stdlib</artifactId>
</exclusion>
</exclusions>
</dependency>
Is there no way we can compile this project for Java runtime only?
I need to keep my dependencies as light as possible, expected this project to be very small and not requiring any additional libraries.
Thanks.
The default configuration fails to load on Windows, even though the .env
file exists.
Expected behaviour
Dotenv env = Dotenv.load()
loads fine.
Actual behaviour
Throws an "missing .env file" exception.
Workaround
Dotenv env = Dotenv.configure().directory(".").load()
How to get environment variables inside docker container?
Use Case:
Lets say I want to pass environment variables to my docker container but I don't want to make .env
file part of the docker image. I would set environment variables in docker's yaml file and they will be available to the application running inside the container through System.getenv()
. However In my case dotenv.load()
would throw exception that /.env file is not on classpath
. However dotenv does gets environment variables from system but in the scenario where .env
isn't part of the container then it would fail throwing the exception.
what's the best practice for integrating this library as early as possible in a gradle based spring boot app? i was hoping that all gradle tasks (for example db migration tasks) would ingest the .env and use that configuration.
Detected crashes for users using older versions of Android (API <= 24, i.e. Android 7 and older).
Setup is in line with your docs/examples and works just fine for newer versions of Android.
Stack traces:
Fatal Exception: java.lang.NoClassDefFoundError
Failed resolution of: Ljava/nio/file/Paths;
io.github.cdimascio.dotenv.internal.DotenvReader.read (DotenvReader.java:33)
io.github.cdimascio.dotenv.internal.DotenvParser.lines (DotenvParser.java:52)
io.github.cdimascio.dotenv.internal.DotenvParser.parse (DotenvParser.java:34)
io.github.cdimascio.dotenv.DotenvBuilder.load (DotenvBuilder.java:77)
io.github.cdimascio.dotenv.DslKt.dotenv (DslKt.java:19)
se.collectorbank.collectorbankbankapp.activities.CollectorActivity. (CollectorActivity.java:48)
se.collectorbank.collectorbankbankapp.activities.LoginActivity.access$startMainActivity (LoginActivity.java:58)
java.lang.Class.newInstance (Class.java)
android.app.Instrumentation.newActivity (Instrumentation.java:1083)
android.app.ActivityThread.performLaunchActivity (ActivityThread.java:2682)
android.app.ActivityThread.handleLaunchActivity (ActivityThread.java:2864)
android.app.ActivityThread.-wrap12 (ActivityThread.java)
android.app.ActivityThread$H.handleMessage (ActivityThread.java:1567)
android.os.Handler.dispatchMessage (Handler.java:105)
android.os.Looper.loop (Looper.java:156)
android.app.ActivityThread.main (ActivityThread.java:6517)
java.lang.reflect.Method.invoke (Method.java)
com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run (ZygoteInit.java:942)
com.android.internal.os.ZygoteInit.main (ZygoteInit.java:832)
Caused by java.lang.ClassNotFoundException
Didn't find class "java.nio.file.Paths" on path: DexPathList[[zip file "/data/app/se.collector.bankapp-1/base.apk"],nativeLibraryDirectories=[/data/app/se.collector.bankapp-1/lib/arm64, /system/lib64, /vendor/lib64, /system/vendor/lib64, /product/lib64]]
dalvik.system.BaseDexClassLoader.findClass (BaseDexClassLoader.java:56)
java.lang.ClassLoader.loadClass (ClassLoader.java:380)
java.lang.ClassLoader.loadClass (ClassLoader.java:312)
arrow_right
io.github.cdimascio.dotenv.internal.DotenvReader.read (DotenvReader.java:33)
io.github.cdimascio.dotenv.internal.DotenvParser.lines (DotenvParser.java:52)
io.github.cdimascio.dotenv.internal.DotenvParser.parse (DotenvParser.java:34)
io.github.cdimascio.dotenv.DotenvBuilder.load (DotenvBuilder.java:77)
io.github.cdimascio.dotenv.DslKt.dotenv (DslKt.java:19)
se.collectorbank.collectorbankbankapp.activities.CollectorActivity. (CollectorActivity.java:48)
se.collectorbank.collectorbankbankapp.activities.LoginActivity.access$startMainActivity (LoginActivity.java:58)
java.lang.Class.newInstance (Class.java)
android.app.Instrumentation.newActivity (Instrumentation.java:1083)
android.app.ActivityThread.performLaunchActivity (ActivityThread.java:2682)
android.app.ActivityThread.handleLaunchActivity (ActivityThread.java:2864)
android.app.ActivityThread.-wrap12 (ActivityThread.java)
android.app.ActivityThread$H.handleMessage (ActivityThread.java:1567)
android.os.Handler.dispatchMessage (Handler.java:105)
android.os.Looper.loop (Looper.java:156)
android.app.ActivityThread.main (ActivityThread.java:6517)
java.lang.reflect.Method.invoke (Method.java)
com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run (ZygoteInit.java:942)
com.android.internal.os.ZygoteInit.main (ZygoteInit.java:832)
While debugging issue #11 I found some interesting behaviour in the following tests:
I added the following line to the DotEnvReader: println("[dotenv] location: $location")
, which results in the following output for all the above tests: [dotenv] location: /missing//.env
All tests have setting the directory with the value /missing/.env
in common.
I guess we need to swap the order of operations to remove the duplicate slash.
The current solution would reduce the following valid path /missing/.env/
to the wrong /missing/
I just made a fresh fork of java-dotenv and after cloning my fork and running mvn test
i receive a lot of test failures. The error is always the same.
[ERROR] Failures:
[ERROR] DotEnvDslTest.dotenvIgnoreMalformed:34 expected:<C:\Users\adm[]> but was:<C:\Users\adm[\]>
[ERROR] DotEnvDslTest.dotenvIgnoreMissing:91 expected:<C:\Users\adm[]> but was:<C:\Users\adm[\]>
[ERROR] DotEnvDslTest.resourceCurrent:72 expected:<C:\Users\adm[]> but was:<C:\Users\adm[\]>
[ERROR] DotEnvDslTest.resourceFilename:60 expected:<C:\Users\adm[]> but was:<C:\Users\adm[\]>
[ERROR] DotEnvDslTest.resourceRelative:47 expected:<C:\Users\adm[]> but was:<C:\Users\adm[\]>
[ERROR] DotEnvTest.dotenvFilename:57 expected:<C:\Users\adm[]> but was:<C:\Users\adm[\]>
[ERROR] DotEnvTest.dotenvIgnoreMalformed:38 expected:<C:\Users\adm[]> but was:<C:\Users\adm[\]>
[ERROR] DotEnvTest.dotenvIgnoreMissing:101 expected:<C:\Users\adm[]> but was:<C:\Users\adm[\]>
[ERROR] DotEnvTest.resourceCurrent:82 expected:<C:\Users\adm[]> but was:<C:\Users\adm[\]>
[ERROR] DotEnvTest.resourceRelative:70 expected:<C:\Users\adm[]> but was:<C:\Users\adm[\]>
[INFO]
[ERROR] Tests run: 14, Failures: 10, Errors: 0, Skipped: 0
In my real world project I fixed this [issue #11] by specifying the directory as "."
:
Dotenv.configure().directory(".").ignoreIfMissing().load();
Afternoon,
Thanks for this, been trying to learn Java and using this file for a project I am building.
Just wanted to ask as I am currently having an issue with regards to Travis-ci and it reading my .env file. I know we shouldn't upload it to Github so have kept the file locally but when my setup goes through Travis before loading to Heroku it gives me the following error message:
io.github.cdimascio.dotenv.DotEnvException: Could not find /.env on the classpath
Would this be a situation where I have to set the classpath somewhere for it to know where to get the environment variables from? Know I have used .env with Node.js and didn't commit the files to GitHub but t knew the variables when the project was launched to Heroku.
Apologies if I sound a bit of a beginner. Thanks
I want some variables from system env variables but .env file needs to be there. I don't want create .env file if i want to use env var from system .
Dotenv.entries()
returns the set of variables as specified in a .env file, ignoring any values in the environment.
Dotenv.get()
on the other hand does use environment variables to override values specified in a .env file.
If somebody has an example integrating java-dotenv with SpringBoot 2.x, please share code snippet. Thanks
Currently Dotenv
will throw an error if it is loaded when no .env
file is present in the project. This causes a couple of problems especially when dealing with CI.
It is advised to not include the .env
file in source control, this means there will be no .env
file present when a service like Travis CI downloads the repository for testing. A service like Travis CI does export plenty of environment variables that can be used. Besides that CI services offer ways to export custom environment variables.
However it would be weird to have to switch between methods of retrieving environment variables just because you don't have the file. Just because there is no .env
file present doesn't mean that there are no environment variables that are needed.
Perhaps a warning would be in order. Perhaps including an error for env
variables that are not specified. (Note that leaving a variable might be different from not including one. A password can be blank for instance.)
Can this lib work on Android? here is the error I got when trying to use it
java.lang.NoClassDefFoundError: Failed resolution of: Ljava/nio/file/Paths;
at io.github.cdimascio.dotenv.internal.DotenvReader.read(DotenvReader.kt:20)
at io.github.cdimascio.dotenv.internal.DotenvParser.parse(DotenvParser.kt:18)
at io.github.cdimascio.dotenv.DotenvBuilder.load(Dotenv.kt:43)
at io.github.cdimascio.dotenv.Dotenv$Instance.load(Dotenv.kt:9)
at io.github.cdimascio.dotenv.Dotenv.load(Dotenv.kt)
It does not seem that the 6.3.0 version of the package was published anywhere. I cannot see it on mavencentral.
It does seem to be published to github package repository, but that is useless for most people.
Hello, I am building a spring boot application with java-dotenv.
The .env is under "src/main/resources" folder and the application works perfectly when I start the application in my IDE(Intellj Idea).
A jar file is created by gradle when I build the project and I will get the following errors if I execute the jar file directly.
Suppressed: io.github.cdimascio.dotenv.DotEnvException: Could not find .\.env on the file system
I have read this project for reference and the project I created is similar to the kotlin-spring-mvc-template.
Not sure what was wrong. I would appreciate if you would give me some help.
Q: Why should I use dotenv.get(โMY_ENV_VARโ) instead of System.getenv(โMY_ENV_VARโ)
A: Since Java does not provide a way to set environment variables on a currently running process, vars listed in .env cannot be set and thus cannot be retrieved using System.getenv(โฆ).
Given that System.getenv("MY_ENV_VAR")
doesn't allow adding new environment variables at runtime, the other option is to plug the dotenv configured variables into System.setProperty()
.
This will allow libraries to use either System.getProperty("MY_ENV_VAR")
or dotenv.get("MY_ENV_VAR")
.
A simple change would look like this after Dotenv is created.
Dotenv
.load()
.entries()
.filter(entry -> System.getProperty(entry.getKey) == null)
.forEach(entry -> System.setProperty(entry.getKey(), entry.getValue()));
A declarative, efficient, and flexible JavaScript library for building user interfaces.
๐ Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. ๐๐๐
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google โค๏ธ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.