Scala :intellij : Typesafe Config : ArrayIndexOutOfBoundsException

when i running below code in ide, i’m getting
/**
Exception in thread “main” java.lang.ArrayIndexOutOfBoundsException: 0
at testjdbc$.main(testjdbc.scala:28)
at testjdbc.main(testjdbc.scala)
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 com.intellij.rt.execution.application.AppMain.main(AppMain.java:147)

**/
getConfig(args(0)). -> This should work!! I’m not sure where is the error!

import java.sql.DriverManager
import com.typesafe.config._

case class EmployeesCommission(first_name: String,
last_name: String,
salary: Double,
commission_pct: Double) {
override def toString(): String = {
s"first_name: " + first_name + “;” + “last_name: " + last_name +
”;" + “commission amount:” + getCommissionAmount()
}

def getCommissionAmount(): Any = {
if(commission_pct == null) {
“Not eligible”
} else salary * commission_pct
}
}

object testjdbc {
def main(args: Array[String]): Unit = {
val props = ConfigFactory.load()
val driver = "com.mysql.jdbc.Driver"
val host = props.getConfig(args(0)).getString(“host”)
val port = props.getConfig(args(0)).getString(“port”)
val db = props.getConfig(args(0)).getString(“db”)
val url = “jdbc:mysql://” + host + “:” + port + “/” + db
val username = props.getConfig(args(0)).getString(“user”)
val password = props.getConfig(args(0)).getString(“pw”)

Class.forName(driver);
val connection = DriverManager.getConnection(url, username, password)
val statement = connection.createStatement()
val resultSet = statement.executeQuery(s"SELECT first_name, last_name, " +
  "salary, commission_pct FROM employees")

while ( resultSet.next() ) {
  val e = EmployeesCommission(resultSet.getString("first_name"),
    resultSet.getString("last_name"),
    resultSet.getDouble("salary"),
    resultSet.getDouble("commission_pct"))
  println(e)
}

}
}

Adding more Info :

Instead of below set of code,
val host = props.getConfig(args(0)).getString(“host”)
val port = props.getConfig(args(0)).getString(“port”)
val db = props.getConfig(args(0)).getString(“db”)
val un = props.getConfig(args(0)).getString(“user”)
val PWD = props.getConfig(args(0)).getString(“pw”)

I have added below code to run successfully,

val host = props.getString(“dev.host”)
val port = props.getString(“dev.port”)
val db = props.getString(“dev.db”)
val un = props.getString(“dev.user”)
val PWD = props.getString(“dev.pw”)

But Need to know why why its failing for args(0)! Any idea?

When you are using args(0), you need to pass argument dev or prod as per our content.

2 Likes

Thanks @itversity, i have missed that! Now its working!