Java and Scala Dynamic Load of a Class

I was in the need to dynamically create a Object from the Database and execute a method to run a task. This object can be different based on the requirements from user input.

/**
  * Handle Execution returned from database
  *
  * @param ex
  * @param text
  * @param sender
  */
def handleExecution(ex: Execution, text: String, sender: Sender): Unit = {

  if (ex.execution.split(":").size == 3 ) {
    val cname = ex.execution.split(":")(1)
    val fname = ex.execution.split(":")(2)

    try {
      val theclass = Class.forName(cname).newInstance().asInstanceOf[TExecutionService]

      if (theclass.isInstanceOf[TExecutionService]) {
        val output = theclass.run(text)
        Logger.debug("Output from " + cname + ".run " + text + " -- " + output)
        handleOutput(output, sender)
      }
    } catch {
      case exception: Throwable => {
        Logger.debug("Error in HandleExecution " + ex + " with exception " + exception)
        throw exception
      }
    }
  }

 

Although Scala is a Typed Language it was not difficult to assure that I would have a run method for the returned class and execute this code dynamically.

 

Scala Playframework connect to mysql

I’m writting this because I had issues following the documentation that comes with playframework
the docs are wrong or at least for me it gave me an error.

The docs states that to connect to a mysql database server you have to do the following:

If you need to connect to another JDBC-compliant database, first add the corresponding driver library to your application dependencies in build.sbt e.g.:

libraryDependencies += "mysql" % "mysql-connector-java" % "5.1.18"

This above works ok, I had no problems.

Then add the corresponding JDBC configuration to the conf/application.conf file:

db.url=jdbc:mysql:database_name
db.driver=org.mysql.Driver
db.user=root
db.pass=secret

This above now has problems namely the db.driver section it returned me an error
java.lang.ClassNotFoundException: org.mysql.Driver

Searching the internet I found this answer

http://solvedstack.com/questions/steps-needed-to-use-mysql-database-with-play-framework-2-0

So the correct working version is:

db.default.driver=com.mysql.jdbc.Driver
db.default.user=root
db.default.pass=secret

db.default.url=”jdbc:mysql://localhost/database_name?characterEncoding=UTF-8″

Maybe for others this is easy to spot but for me it wasn’t.