Short source code examples

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
}

As a brief note to self, I just used this SQL SELECT query to show both (a) master/summary information about each URL row in the urls database table, and also (b) detail information in the form of the number of rows in the url_clicks database table for each row in the urls table:

As a brief note today, if you want to see how to create a Scala case class that defines multiple alternate constructors, I hope this example is helpful:

If you ever need to work with HTTP request headers in a Play Framework application, I hope the following examples will help. I was just looking at trying to access request headers like “User-Agent” and “Referer,” and ran a few tests.

Note: I put all of the Scala code that follows in Play Framework controller actions, then accessed the URL that was associated with those actions in the Play routes file, using the latest version of the Firefox browser on a MacOS system.

As a quick note to self, one way to implement paging in a Play Framework application is to use the limit and offset arguments in a MySQL query. This way you can show X number of objects on one web page, then give the user Next and Previous links so they can scroll backwards and forwards through the dataset.

To implement paging with a MySQL query, use the limit and offset query parameters, as shown in this example:

If you’re using Java or Scala and need to write a pattern that matches a range of characters, where those characters occur between a minimum and maximum number of times in the pattern, the following example shows a solution I’m currently using.

The idea is that the pattern "[a-zA-Z0-9]{1,4}" means, “Match a string that has only the characters a-z, A-Z, and 0-9, where those characters occur a minimum of one time and a maximum of four times.” The following tests in the Scala REPL shows how this works:

As a brief note to self, when you need to change Play Framework logging, such as to change it to more of a debug mode, edit the logback.xml file and add/change entries like these:

As a quick note, here’s a Java method that will round a float to the nearest half value, such as 1.0, 1.5, 2.0, 2.5, etc.:

/**
 * converts as follows:
 * 1.1  -> 1.0
 * 1.3  -> 1.5
 * 2.1  -> 2.0
 * 2.25 -> 2.5
 */
public static float roundToHalf(float f) {
    return Math.round(f * 2) / 2.0f;
}

The comments show how this function converts the example float values to their nearest half value, so I won’t add any more details here. I don’t remember the origin of this algorithm — I just found it in some old code, thought it was clever, and thought I’d share it here.

As a note to self, this JavaScript code gets multiple, random, unique elements from a JavaScript array and displays three of those elements in the second div:

One thing I never thought about before is that if you need to get multiple, unique, random elements from a list of elements, one solution to the problem is to shuffle the list and then take as many elements as you want/need. For instance, if you want three unique, random elements from a list of integers in Scala, you can do this:

scala> val list = List(1,2,3,4,5,1,2,3,4,5)
list: List[Int] = List(1, 2, 3, 4, 5, 1, 2, 3, 4, 5)

scala> val uniq = list.distinct
uniq: List[Int] = List(1, 2, 3, 4, 5)

scala> val shuffled = scala.util.Random.shuffle(uniq)
shuffled: List[Int] = List(1, 4, 5, 2, 3)

scala> val firstThree = shuffled.take(3)
firstThree: List[Int] = List(1, 4, 5)

As that solution shows, you start with a simple list; get the unique/distinct elements from the list; shuffle those elements to create a new list; then take the first three elements from the shuffled list. That’s probably not a great solution for huge lists, but for many simple lists it’s a way to get multiple random elements from the list.

Scala date FAQ: How do I determine the day of the year in Scala?

Solution: Use the Java Calendar class, as shown here:

scala> import java.util.Calendar
import java.util.Calendar

scala> Calendar.getInstance.get(Calendar.DAY_OF_YEAR)
res0: Int = 104

I’m writing this on April 14, 2018, which is the 104th day of the year.

As a brief note today, if you want to know if your Drupal 8 web pages are being cached, take a look at the headers that are returned by your Drupal 8 URLs. Here’s an example using the curl command:

It’s embarrassing how long it took to get this to work, but if you ever need to select a single row from a database using Play Framework (version 2.6), Anorm, and singleOpt, I hope this example is helpful, and will save you time and frustration:

If you ever need to include multiple Play Framework 2.6 validators for a template form field, the uri field below shows the syntax that worked for me: