Short source code examples

As a brief note to self, I use these Java keytool commands to add/update the SSL certificate for accessing a website named alphavantage.co:

I just noticed this quirk when trying to create an array of characters with the Scala Array.range method:

# works as expected
('a' to 'e').toArray              // Array[Char] = Array(a, b, c, d, e)

# surprise: Array.range always returns Array[Int]
val a = Array.range('a', 'e')     // Array[Int] = Array(97, 98, 99, 100)

I was surprised to see that the Scaladoc for the Array object states that the second example is expected behavior; Array.range always returns an Array[Int]. I suspect this has something to do with a Scala Array being backed by a Java array, but I didn’t dig into the source code to confirm this.

For much more information about arrays, see my Scala Array class examples tutorial.

As a brief note to self, here’s an example JavaFX application written in Scala:

object MainWindow {
    def main(args: Array[String]) {
        Application.launch(classOf[MainWindow], args: _*)
    }
}

class MainWindow extends Application  {
    override def start(stage: Stage) {
        val borderPane = new MainBorderPane
        val scene = new Scene(borderPane, 600, 400)
        scene.getStylesheets.add(getClass.getResource("pizza.css").toExternalForm)
        stage.setScene(scene)
        stage.setTitle("Al’s Pizza")
        stage.show
    }
}

As a brief note to self, when you need to control spacing at the top of the title page (titlepage) in a LaTeX document, use the \vspace command, as shown in this example:

If you want to implement About, Preferences, and Quit handlers with Java 9 and newer on MacOS systems, this example Java source code shows how to do it:

As a quick Scala tip, if you haven’t worked with the flatMap on an Option much, it can help to know that flatMap’s function should return an Option, which you can see in this REPL example:

scala> Some(1).flatMap{ i => Option(i) }
res0: Option[Int] = Some(1)

You can tell this by looking at the function signature in the scaladoc for the flatMap method on the Option class:

Here’s an example of how to connect to a JDBC database with Scala. I have no idea why I got into the try/catch/finally details in a trivial little example like this, but if you want to see how to connect to a database with JDBC and query that database with a JDBC Statement (which yields a ResultSet), I hope this example is a little helpful:

Here’s another ScalikeJdbc example. The main benefits of this example are:

  • It shows how to perform a SQL SELECT with ScalikeJdbc
  • How to map the ResultSet values to create a series of objects from the ResultSet
  • How to connect to a database with ScalikeJdbc using a JDBC style of connecting (as opposed to putting the JDBC parameters in a configuration file)

Here’s the ScalikeJdbc example code:

Here’s an example of how to write a SQL UPDATE query with ScalikeJdbc:

def updateUrlClickGeoInfo(urlClickId: Long, gi: GeoInfo): Int = NamedDB('kbhr) localTx { implicit session =>
    sql"""
    update url_clicks
    set city = ${gi.city}, state = ${gi.state}, country = ${gi.country}
    where id = ${urlClickId}
    """.update.apply()
}

(As a note to self, this code comes from my PopulateKbhrGeo1 app.)

Here’s another ScalikeJdbc SQL SELECT example. A few unique things about this example is that it shows the JDBC-style parameters; it shows how to use a case class and the “service” style approach; it shows how to use the WrappedResultSet as shown. Here’s the code:

Here’s another ScalikeJdbc SQL SELECT example. I don’t think this one relies on a configuration file, it just uses the JDBC parameters shown:

Here’s another ScalikeJdbc SQL SELECT query example. In this example I use the concept of a “service,” which I probably originally got from the ScalikeJdbc website:

I don’t have time to write about ScalikeJdbc right now, so I’ll just say that it’s been working well for me. Here’s one of the first test examples I created, a simple SQL SELECT query that prints some output from a database table:

As a note to self, if you want to use JDBC, MySQL, and Anorm with the Play Framework 2.6, you’ll need a libraryDependencies entry like this in your SBT build.sbt file:

libraryDependencies ++= Seq(
    guice,
    "org.scalatestplus.play" %% "scalatestplus-play" % "3.1.2" % Test,
    jdbc,
    "mysql" % "mysql-connector-java" % "5.1.46",
    "com.typesafe.play" %% "anorm" % "2.5.3"
)

 

As a note to self, this is how I wrote a “group by” and “order by” SQL query that gives me the number of times each country code occurs in a database table named url_clicks:

select country, count(1) as the_count
from url_clicks
where url_id=6
and country != ''
group by country
order by the_count desc

Results of this query look like this:

US, 50
CA, 30
GB, 15

That tells me that 50 people in the US clicked on the link with the id=6, 30 people from CA clicked on the same link, and 15 people from GB clicked on that link as well.

As a brief note, I was trying to run a Scala application inside SBT today and kept getting this “out of memory” error:

[error] (run-main-0) java.lang.OutOfMemoryError: GC overhead limit exceeded
java.lang.OutOfMemoryError: GC overhead limit exceeded

The solution to the problem was to allocate more memory when I start SBT. To give SBT more RAM I first issue this command at the command line:

If you need to manually specify the custom location of a Lightbend Config configuration file when running a Scala or Java application, I can confirm that this java command setting works:

java -Dconfig.file=my_app.conf [the rest of your app parameters]
     -------------------------

In my case I read the Lightbend Config file like this in my Scala application:

If you ever need to batch-insert a lot of records into a MySQL/MariaDB database using the JDBC PreparedStatement (as in preparedStatement.executeBatch()) be sure to change the MySQL URL to use the rewriteBatchedStatements, as shown here:

"jdbc:mysql://localhost:8889/DATABASE?rewriteBatchedStatements=true"

For a recent project I needed to batch-insert about eleven million records into a MySQL database, and the runtime was about 55 minutes. Once I added rewriteBatchedStatements=true to the MySQL URL, the batch-insert time was reduced down to only three minutes. That one little change made all the difference.

At some point I’ll get all of my Scala “date utilities” together in a single class (object, actually), but until then, here are a couple of date utility methods I wrote for my Scrupal6 project (a replacement for Drupal 6):

If you happen to need Scala method to perform an MD5 hash on a string, here you go:

def md5HashString(s: String): String = {
    import java.security.MessageDigest
    import java.math.BigInteger
    val md = MessageDigest.getInstance("MD5")
    val digest = md.digest(s.getBytes)
    val bigInt = new BigInteger(1,digest)
    val hashedString = bigInt.toString(16)
    hashedString
}