Play Framework Scala Environment Variables not found - scala

Sup,
I'm trying to setup environment variables for my project in Play2.4 Scala.
I have set variables in run configuration in Intellij.
What's annoying Scala doesn't seem to see those.
I keep getting errors of configuration not specified for keys I used env variables.
When i start the application those shows in the console:
"C:\Program Files\Java\jdk1.8.0_25\bin\java" -Dfile.encoding=UTF8 -DMAIL_PORT=587 -DDB_URI=mongodb://uri -Djline.terminal=none -Dsbt.log.noformat=true -Dsbt.global.base=C:\Users\Haito\AppData\Local\Temp\sbt-global-plugin7stub -Xms512M -Xmx1024M -Xss1M -XX:+CMSClassUnloadingEnabled -XX:MaxPermSize=256M -classpath C:\Users\Haito\.IntelliJIdea14\config\plugins\Scala\launcher\sbt-launch.jar xsbt.boot.Boot "project root" ~run
And the configuration file:
mongodb.uri = ${?DB_URI}
play.mailer {
host=${?MAIL_HOST}
port=${?MAIL_PORT}
ssl=false
tls=true
user=${?MAIL_USERNAME}
password=${?MAIL_PASSWD}
debug=false
mock=false
}
And i keep getting those:
Missing configuration key 'mongodb.db'!
Of course my problem is not that my mongo driver. My problem is that the config is not being fed with environment variables. Mailer which also uses environment variables for configs. When I paste the actual URI except the ${?DB_URI} it works.
Build:
resolvers += "scalaz-bintray" at "http://dl.bintray.com/scalaz/releases"
resolvers += "Sonatype Snapshots" at "https://oss.sonatype.org/content/repositories/snapshots/"
libraryDependencies ++= Seq(
"org.reactivemongo" %% "play2-reactivemongo" % "0.11.2.play24"
)
libraryDependencies ++= Seq(
"com.typesafe.play" %% "play-mailer" % "3.0.1"
)

This is a bug in IntelliJ. Setting the "Environment variables" field in the Play run configuration sets system properties, not environment variables.
If you configure environment variables manually somewhere like .bash_profile then you can certainly use them in your application.conf like:
db.default.url = ${?DB_URL}

When i start the application those shows in the console:
"C:\Program Files\Java\jdk1.8.0_25\bin\java" -Dfile.encoding=UTF8 -DMAIL_PORT=587 -DDB_URI=mongodb://uri -Djline.terminal=none -Dsbt.log.noformat=true -Dsbt.global.base=C:\Users\Haito\AppData\Local\Temp\sbt-global-plugin7stub -Xms512M -Xmx1024M -Xss1M -XX:+CMSClassUnloadingEnabled -XX:MaxPermSize=256M -classpath C:\Users\Haito\.IntelliJIdea14\config\plugins\Scala\launcher\sbt-launch.jar xsbt.boot.Boot "project root" ~run
-D doesn't set environment variables, it sets JVM system properties. You should be able to set environment variables from the run configuration as well, but a different part of the dialog.
Also, Play's documentation doesn't say it looks at environment variables at all:
As well as the application.conf file, configuration comes from a couple of other places.
Default settings are loaded from any reference.conf files found on the classpath. Most Play JARs include a reference.conf file with default settings. Settings in application.conf will override settings in reference.conf files.
It’s also possible to set configuration using system properties. System properties override application.conf settings.
I.e. passing -Dmongodb.uri=... should work.
Later on it does say
For substitutions which are not found in the configuration tree, implementations may try to resolve them by looking at system environment variables or other external sources of configuration. (More detail on environment variables in a later section.)
but this is just a quote from HOCON README.
You need to looks at the code loading the config to check if it does use one of the methods which include environment variables.

If your mongodb url contains parameters like mongodb://xxxxxxxxxx?key=value then intellij will silently remove that env variable.

Related

How to set SCALACTIC_FILL_FILE_PATHNAMES=yes (or other environment variable) for scalac from sbt?

I would like to use full paths in ScalaTest reporter. The value LineInFile.filePathname tells me I should:
Please set the environment variable SCALACTIC_FILL_FILE_PATHNAMES to yes at compile time to enable this feature.
Can I do this from sbt, or do I have to launch SBT with a different environment? Scalac seems to be running in the same JVM as sbt, and there is a question Scala: Unable to set environment variable telling me I cannot modify my own environment.
I have tried following, none of them seems to set the variable for the compiler:
scalacOptions ++= Seq(
"-deprecation", "-unchecked",
"-DSCALACTIC_FILL_FILE_PATHNAMES=yes"
),
Compile / envVars := Map("SCALACTIC_FILL_FILE_PATHNAMES" -> "yes"),
Test / envVars := Map("SCALACTIC_FILL_FILE_PATHNAMES" -> "yes"),
As far as I know, sbt doesn't run scalac in a separate process (which would allow it to set environment variables), so you'd have to run sbt in an environment with that set.
Note that -D sets Java properties. While it's fairly common for software to allow environment variables and properties to be treated similarly (e.g. Lightbend Config), that's not standard.
The mechanism for setting the environment will depend on how you are launching sbt. If using a Bourne-style shell like bash:
export SCALACTIC_FILL_FILE_PATHNAMES=yes
sbt
or
SCALACTIC_FILL_FILE_PATHNAMES=yes sbt
IDEs and CI/CD tooling may launch sbt directly, in which case check the documentation for those tools.

Change sbt boot and ivy dirs via environment variables

Is it possible to set .sbt and .ivy2 directories via environment variables?
I can override these parameters when i run sbt like that:
sbt -Dsbt.boot.directory=/tmp/.sbt/boot -Dsbt.ivy.home=/tmp/.ivy2 version
I thought this would work:
export sbt.boot.directory=/tmp/.sbt/boot
export sbt.ivy.home=/tmp/.ivy/home
sbt version
but it doesn't work...
Second question: how can i bypass sbt config launcher? (http://www.scala-sbt.org/0.13/docs/Launcher-Configuration.html) when running sbt?
You can set JAVA_OPTS or SBT_OPTS environment variables with the runtime parameters for the SBT. The difference is that JAVA_OPTS effects also other Java based applications while SBT_OPTS only effects the SBT. For example:
export SBT_OPTS="-Dsbt.ivy.home=/tmp/.ivy/home -Dsbt.boot.directory=/tmp/.sbt/boot"
When you run the SBT from the command-line, it will use these parameters. However, if you launch it from IntelliJ IDEA, it will not use them. IDEA launches the SBT JAR directly and SBT's VM parameters have to be configured in the IDEA sbt settings per project.
For the second question, it is unclear what you mean by bypass. It is possible to run the SBT jar directly instead of the sbt launcher script. For example:
java -server -Xmx1536M -Dsbt.ivy.home=/tmp/.ivy/home -jar /<install-path>/sbt/bin/sbt-launch.jar

scala project is not taking logback xml configuration when passed via JVM argument

I have a scala project where i am using scala-slf4j logging and logback. When the project is executed via command line as below
java -jar <sample_project.jar> -Dlogback.configurationFile=/tmp/logback.xml
It uses logger class as 'ch.qos.logback.classic.Logger' but is not taking the logback.xml configuration.
Same works fine if i put the logback configuration xml under /src/main/resources.
import org.slf4j.LoggerFactory
object SampleProj {
val logger = LoggerFactory.getLogger(this.getClass)
logger.info("SCALA Logging")
}
build.sbt
"ch.qos.logback" % "logback-classic" % "1.1.2",
"com.typesafe.scala-logging" %% "scala-logging-slf4j" % "2.1.2",
Another approach which is tried is extracted the scala project jar and executed the main class as below
java com.test.SampleProj -Dlogback.configurationFile=/tmp/logback.xml
Some other methods i tried was,
Set the classpath and put the logback xml
passing as "-Dlogger.file=/tmp/logger.xml"
passing as -Dlogger.resource=/tmp/logger.xml
Can someone help me in resolving this.
Thanks
Arguments to the java should be as below.
java -Dlogback.configurationFile=/tmp/logback.xml com.test.SampleProj
In my case, the solutions above were not enough. My problem was that the logback.xml file was not read by default.
I believe that the solution provided at http://www.scala-sbt.org/0.13/docs/Setup-Notes.html, by specifying the file encoding works, it is better to fix that from the shell.
In my shell, I run the following:
export LC_ALL="en_US.UTF-8"
export LC_CTYPE="en_US.UTF-8"
sudo dpkg-reconfigure locales
After that, the logback.xml was read properly.

Importing MySQL JDBC driver in lift

I'm trying to establish a database connection in my lift app using the mysql jdbc driver. I included the jar file in the eclipse build path, but building with importing the jar using import com.mysql._the app with sbt always throws the error:
object mysql is not a member of package com
Setting the classpath in the sdb.bat didn't help neither setting the system classpath variable.
set SCRIPT_DIR=%~dp0
java -Dscala.userjavacp=true -cp "%SCRIPT_DIR%\src\main\java\mysql.jar" -XX:+CMSClassUnloadingEnabled -XX:MaxPermSize=256m -Xmx1024M -Xss2M -jar "%SCRIPT_DIR%\sbt-launch-0.12.1.jar" %*
SBT doesn't know anything about Eclipse build path. You need to add dependencies in the way SBT understands, e.g.:
add jars to lib and they will be placed on the project classpath. Not much else to it!
I would suggest using the SBT Eclipse plugin and then use SBT to manage your dependencies which should keep the two programs in sync.
So, for MySQL, you'd want to modify your sbt configuration in your project to include:
libraryDependencies += "mysql" % "mysql-connector-java" % "5.1.6"
Then all you would need to do is launch sbt, and type eclipse to update your Eclipse configuration files with the correct classpath. When you restart Eclipse, everything should work.
The plugin will also pick up files in the lib directory as noted in the other answer.

How to specify JVM maximum heap size "-Xmx" for running an application with "run" action in SBT?

My application does large data arrays processing and needs more memory than JVM gives by default. I know in Java it's specified by "-Xmx" option. How do I set SBT up to use particular "-Xmx" value to run an application with "run" action?
For forked processes you should look at Build.scala
To modify the java options for forked processes you need to specify them in the Build.scala (or whatever you've named your build) like this:
val buildSettings = Defaults.defaultSettings ++ Seq(
//…
javaOptions += "-Xmx1G",
//…
)
This will give you the proper options without modifying JAVA_OPTS globally, and it will put custom JAVA_OPTS in an sbt generated start-script
For non forked processes it's most convenient to set the config via sbtopts or sbtconfig depending on your sbt version.
Since sbt 0.13.6 .sbtconfig is deprecated. Modify /usr/local/etc/sbtopts along these lines:
-J-Xms512M
-J-Xmx3536M
-J-Xss1M
-J-XX:+CMSClassUnloadingEnabled
-J-XX:+UseConcMarkSweepGC
-J-XX:MaxPermSize=724M
-J-agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=5005
You can also create an .sbtopts file in the root of your SBT project using the same syntax as in the /usr/local/etc/sbtopts file. This makes the project self-contained.
Before sbt 0.13.6 you could set the options in .sbtconfig for non forked processes:
Check where sbt is:
$ which sbt
/usr/local/bin/sbt
Look at the contents:
$ cat /usr/local/bin/sbt
#!/bin/sh
test -f ~/.sbtconfig && . ~/.sbtconfig
exec java ${SBT_OPTS} -jar /usr/local/Cellar/sbt/0.12.1/libexec/sbt-launch.jar "$#"
Set the correct jvm options to prevent OOM (both regular and PermGen):
$ cat ~/.sbtconfig
SBT_OPTS="-Xms512M -Xmx3536M -Xss1M
-XX:+CMSClassUnloadingEnabled
-XX:+UseConcMarkSweepGC -XX:MaxPermSize=724M"
If you want to set SBT_OPTS only for the current run of sbt you can use env SBT_OPTS=".." sbt as suggested by Googol Shan. Or you can use the option added in Sbt 12: sbt -mem 2048. This gets unwieldy for longer lists of options, but it might help if you have different projects with different needs.
Note that CMSClassUnloadingEnabled in concert with UseConcMarkSweepGC helps keep the PermGen space clean, but depending on what frameworks you use you might have an actual leak on PermGen, which eventually forces a restart.
In sbt version 12 onwards there is an option for this:
$sbt -mem 2048
If you run sbt on linux shell, you can use:
env JAVA_OPTS="-Xmx512m" sbt run
This is my usually used command to run my sbt project.
.sbtconfig is deprecated starting with SBT 0.13.6. Instead, I configured these options in /usr/local/etc/sbtopts in the following way:
-J-Xms512M
-J-Xmx3536M
-J-Xss1M
-J-XX:+CMSClassUnloadingEnabled
-J-XX:+UseConcMarkSweepGC
-J-XX:MaxPermSize=724M
-J-agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=5005
Try this:
class ForkRun(info: ProjectInfo) extends DefaultProject(info) {
override def fork = Some(new ForkScalaRun {
override def runJVMOptions = super.runJVMOptions ++ Seq("-Xmx512m")
override def scalaJars = Seq(buildLibraryJar.asFile, buildCompilerJar.asFile)
})
}
There's one way I know of. Set the environment variable JAVA_OPTS.
JAVA_OPTS='-Xmx512m'
I have not found a way to do this as a command parameter.
Use JAVA_OPTS for setting with environment variable.
Use -J-X options to sbt for individual options, e.g. -J-Xmx2048 -J-XX:MaxPermSize=512
Newer versions of sbt have a "-mem" option.
The javaOptions += "-XX:MaxPermSize=1024" in our build.sbt as referenced by #iwein above worked for us when we were seeing a java.lang.OutOfMemoryError thrown while running Specs2 tests through sbt.
The environment variable is _JAVA_OPTIONS, which needs to be set.
Once you set _JAVA_OPTIONS, and when you sbt, sbt will show the message using JAVA_OPTIONS and the values.
Alternatively you could set javaOption in the sbt or .scala file
e.g
javaOptions += "-Xmx1G"
From sbt shell you could run show javaOptions to see the values that are set.
sbt lets you list the JVM options you need to run your project on a file named
.jvmopts
in the root of your project.
then add the java options that you want
cat .jvmopts
-Xms512M
-Xmx4096M
-Xss2M
-XX:MaxMetaspaceSize=1024M
it is tested and works in windows 10
https://www.lagomframework.com/documentation/1.4.x/scala/JVMMemoryOnDev.html
javaOptions in Test += "-Xmx1G"
This sets the JVM options for tests. Works also with jvm forking (fork in Test := true).