Source code snippets (examples)

This is a list of Alvin Alexander's source code snippets (simple source code examples).

Scala - How to declare an empty immutable Set (SortedSet)

I just saw this code that shows how to declare an empty immutable SortedSet in Scala, and wanted to save it as a helpful snippet here:

/**
 * The node ring gossipped that contains only members that are Up.
 */
var nodes: immutable.SortedSet[Address] = immutable.SortedSet.empty

A simple Scala call-by-name example

Here's a simple Scala call-by-name example. I'll show the normal approach to writing a method and passing in a parameter, and then show a call-by-name (pass by name) example.

1) A "normal" Scala method

Here I show how to pass a parameter to a method "normally", i.e., call by value:

object Test extends App {

  def time(): Long = {
    println("In time()")
    System.nanoTime
  }

  def exec(t: Long): Long = {
    println("Entered exec, calling t ...")
    println("t = " + t)
    println("Calling t again ...")
    t
  }

  println(exec(time()))

}

The output looks like this:

In time()
Entered exec, calling t ...
t = 1363909521286596000
Calling t again ...
1363909521286596000

As expected, the values for t are the same. This is because the value of t is determined when this line is invoked:

println(exec(time()))

2) A call by name example

Next, make the method parameter a call by name parameter:

object Test extends App {

  def time() = {
    println("Entered time() ...")
    System.nanoTime
  }

  // uses a by-name parameter here
  def exec(t: => Long) = {
    println("Entered exec, calling t ...")
    println("t = " + t)
    println("Calling t again ...")
    t
  }

  println(exec(time()))

}

The output is different:

Entered exec, calling t ...
Entered time() ...
t = 1363909593759120000
Calling t again ...
Entered time() ...
1363909593759480000

The two t invocations yield different results. As stated in the Scala language specification, this is because:

This indicates that the argument is not evaluated at the point of function application, but instead is evaluated at each use within the function. That is, the argument is evaluated using call-by-name.

That's a simple call by name example in Scala.

Scala - Be careful using mutable fields (var) in equals methods

The classic book, Programming in Scala, states that you need to be careful about using var fields when defining equals methods. They specifically state:

Pitfall #3: Defining equals in terms of mutable fields.

Personally, I think I've always defined equals methods with mutable fields, at least in Java. They share the following source code example that demonstrates a problem when defining an equals method in a Scala class when used in a collection.

# create the class
scala> class Point(var x: Int, var y: Int) {
     |   override def hashCode = 41 * (41 + x) + y
     |   override def equals(other: Any) = other match { 
     |     case that: Point => this.x == that.x && this.y == that.y 
     |     case _ => false 
     |   }
     | }
defined class Point

# create an instance
scala> val p = new Point(1, 2)
p: Point = Point@6bc

# create a collection with the point instance
scala> val coll = scala.collection.immutable.HashSet(p)
coll: scala.collection.immutable.HashSet[Point] = Set(Point@6bc)

# the collection contains the point (this is good, and normal)
scala> coll contains p
res8: Boolean = true

# change a property of the instance
scala> p.x += 1

# BAM! the collection no longer appears to contain the instance
scala> coll contains p
res10: Boolean = false

# huh, the iterator can see it
scala> coll.iterator contains p
res11: Boolean = true

I don't have time to test this with Java right now, but this was a huge surprise to me when I first learned about it. As mentioned, I always used mutable fields in Java. Take the case of a Person class and a person's name; if their last name changes, it needs to be changed, and if that person instance is in a collection, I always assumed that instance could still be found. (As a practical matter I don't remember ever needing to do this with a HashSet or HashMap.)

Regarding Scala, the book states, "after the change to the x field, the point p ended up in the wrong hash bucket of the set coll. That is, its original hash bucket no longer corresponded to the new value of its hash code."

An example of using the Geolocation web service at hostip.info using Scala

This is a quick example of how to use the geolocation web service at http://www.hostip.info/use.html using Scala:

/**
 * an example of how to use the geolocation web service at
 * http://www.hostip.info/use.html
 * using scala
 */
object GetRestContent extends App {

  val url = "http://api.hostip.info/get_json.php?ip=12.215.42.19"
  val result = scala.io.Source.fromURL(url).mkString
  println(result)

}

I don't show how to handle the JSON string in this example, but if you search this website you'll find other Scala JSON examples.

Create a list all files beneath a directory in Scala

Here's a snippet of Scala code I use to get a list of all files beneath a given directory:

/**
 * Get a recursive listing of all files underneath the given directory.
 * from stackoverflow.com/questions/2637643/how-do-i-list-all-files-in-a-subdirectory-in-scala
 */
def getRecursiveListOfFiles(dir: File): Array[File] = {
  val these = dir.listFiles
  these ++ these.filter(_.isDirectory).flatMap(getRecursiveListOfFiles)
}

I use this code in my FileUtils class in my Blue Parrot app. The full source of the FileUtils class is at https://github.com/alvinj/BlueParrot/blob/master/src/main/scala/com/alvi....

Scala - Get content from a REST URL (get REST content)

Here's a simple way to get content from a REST web service using Scala:

object GetUrlContent extends App {

  val url = "http://api.hostip.info/get_json.php?ip=12.215.42.19"
  val result = scala.io.Source.fromURL(url).mkString
  println(result)

}

That's a simple, "new" way I do it with Scala. However, note that it handles timeouts very poorly, such as if the web service you're calling is down or running slowly.

FWIW, here's an old approach I used to retrieve REST content (content from a REST URL):

  /**
   * Returns the text content from a REST URL. Returns a blank String if there
   * is a problem. (Probably should use Option/Some/None; I didn't know about it
   * back then.)
   */
  def getRestContent(url:String): String = {
    val httpClient = new DefaultHttpClient()
    val httpResponse = httpClient.execute(new HttpGet(url))
    val entity = httpResponse.getEntity()
    var content = ""
    if (entity != null) {
      val inputStream = entity.getContent()
      content = io.Source.fromInputStream(inputStream).getLines.mkString
      inputStream.close
    }
    httpClient.getConnectionManager().shutdown()
    return content
  }

This function just returns the content as a String, and then you can extract whatever you need from the String once you have it.

I don't have time to condense all my content right now, but if you search the website for other REST examples, you'll see how to properly handle timeouts when calling a REST web service.

A Scala 'send email' class (uses the JavaMail API)

Scala doesn't have any special email handling facilities, so I just use my normal Java approach to send mail.

Here's the source code for my Scala 'send email' class. It's basically just a port of my previous Java 'send email' class, and requires the Java Mail API and Activation Framework jar files:

import javax.mail._
import javax.mail.internet._
import java.util.Date
import java.util.Properties
import scala.collection.JavaConversions._

class MailAgent(to: String,
                cc: String,
                bcc: String,
                from: String,
                subject: String,
                content: String,
                smtpHost: String)
{
  var message: Message = null

  message = createMessage
  message.setFrom(new InternetAddress(from))
  setToCcBccRecipients

  message.setSentDate(new Date())
  message.setSubject(subject)
  message.setText(content)

  // throws MessagingException
  def sendMessage {
    Transport.send(message)
  }

  def createMessage: Message = {
    val properties = new Properties()
    properties.put("mail.smtp.host", smtpHost)
    val session = Session.getDefaultInstance(properties, null)
    return new MimeMessage(session)
  }

  // throws AddressException, MessagingException
  def setToCcBccRecipients {
    setMessageRecipients(to, Message.RecipientType.TO)
    if (cc != null) {
      setMessageRecipients(cc, Message.RecipientType.CC)
    }
    if (bcc != null) {
      setMessageRecipients(bcc, Message.RecipientType.BCC)
    }
  }

  // throws AddressException, MessagingException
  def setMessageRecipients(recipient: String, recipientType: Message.RecipientType) {
    // had to do the asInstanceOf[...] call here to make scala happy
    val addressArray = buildInternetAddressArray(recipient).asInstanceOf[Array[Address]]
    if ((addressArray != null) && (addressArray.length > 0))
    {
      message.setRecipients(recipientType, addressArray)
    }
  }

  // throws AddressException
  def buildInternetAddressArray(address: String): Array[InternetAddress] = {
    // could test for a null or blank String but I'm letting parse just throw an exception
    return InternetAddress.parse(address)
  }

}

I'll add an example that shows how to use this Scala email class at some point in the future, but I hope that's pretty obvious.

How to get/read a cookie in the Play Framework 2

Just a quick note today that if you need to read a cookie when using the Play Framework 2, one of these approaches should work:

// option 1
request.cookies.get("name")

// option 2
Http.Request.current().cookies.get("name")

You can find more information about these approaches at these links:

Play Framework - How to logout and destroy the session

The following example from the Play Framework 'zentasks' application shows how to do a logout, and destroy the user's session at the same time:

/**
 * Logout and clean the session.
 */
def logout = Action {
  Redirect(routes.Application.login).withNewSession.flashing(
    "success" -> "You've been logged out"
  )
}  

The withNewSession method destroys the old session.

Running the Play Framework on a different port than the default port (9000)

Play FAQ: How do I run the Play Framework web server on a different port than the default port (9000)?

Solution: At the Play console, instead of just typing "run" to run the server, type "run 8080" to run the server on port 8080. Here's the command at the Play console prompt, and the output:

[forms] $ run 8080

--- (Running the application from SBT, auto-reloading is enabled) ---

[info] play - Listening for HTTP on port 8080...

(Server started, use Ctrl+D to stop and go back to the console...)