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 /** * 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 exampleHere'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 methodHere 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 println(exec(time())) 2) A call by name exampleNext, 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
That's a simple call by name example in Scala. |
Scala - Be careful using mutable fields (var) in equals methodsThe classic book, Programming in Scala, states that you need to be careful about using
Personally, I think I've always defined # 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 Regarding Scala, the book states, "after the change to the |
An example of using the Geolocation web service at hostip.info using ScalaThis 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 ScalaHere'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 |
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 2Just 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 sessionThe 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 |
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 " [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...)
|