Posts in the “scala” category

How to load an XML URL in Scala (contents of an XML web page)

Scala XML FAQ: How do I load an XML URL in Scala? (How do I read/download the contents of an XML URL in Scala?)

To load the contents of an XML URL (web page) in Scala, such as an RSS news feed or RESTful web service, just use the load method of the Scala XML class:

val xml = XML.load("http://www.devdaily.com/rss.xml")

Here's an example of what this looks like in the Scala REPL:

Scala: How to download and process XML data (such as an RSS feed)

I was looking for a good way to access XML resources (like RSS feeds) in Scala, and I currently like the idea of using ScalaJ-HTTP to access the URL and download the XML content, and then using the Scala XML library to process the XML string I download from the URL.

This example Scala program shows my current approach:

import scalaj.http.{Http, HttpResponse}
import scala.xml.XML

object GetXml extends App
{
    // get the xml content using scalaj-http
    val response: HttpResponse[String] = Http("http://www.chicagotribune.com/sports/rss2.0.xml")
                                        .timeout(connTimeoutMs = 2000, readTimeoutMs = 5000)
                                        .asString
    val xmlString = response.body

    // convert the `String` to a `scala.xml.Elem`
    val xml = XML.loadString(xmlString)

    // handle the xml as desired ...
    val titleNodes = (xml \\ "item" \ "title")
    val headlines = for {
        t <- titleNodes
    } yield t.text
    headlines.foreach(println)

}

A few notes about this application:

  • I like using ScalaJ-HTTP to download the content as an HTTP GET request, in part because I like to be able to easily set timeout values on the GET request.
  • Once I get the XML from the URL, it’s easy to convert that to a Scala XML object using XML.loadString.
  • Once I have the XML like that, I can then process it however I want to.

The build.sbt file

If you want to test this on your own computer, the only other thing you need (besides having Scala and SBT installed) is a build.sbt file to go along with it. Here’s mine:

name := "ScalajHttpXml"

version := "1.0"

scalaVersion := "2.11.7"

resolvers += "Typesafe Repository" at "http://repo.typesafe.com/typesafe/releases/"

libraryDependencies ++= Seq(
    "org.scalaj" %% "scalaj-http" % "2.3.0",
    "org.scala-lang.modules" %% "scala-xml" % "1.0.3"
)

scalacOptions += "-deprecation"

Once you have that Scala source code and build.sbt file, you can test this Scala/HTTP/XML solution on your system. (Note that the Scala XML project is now separate from the base Scala libraries.)

“Alexa written with Akka” = Aleka

[toc]

As a way of demonstrating how to write code with Akka, Scala, and functional programming (FP), I started creating a new project this weekend. I named it Aleka, because it may eventually be like Amazon’s Echo/Alexa, written with Akka (and Scala).

(I suppose a better name might be “Ekko,” after Echo, but I have a niece named Aleka, so unless she objects, this works for me.)

How to turn off (disable) Akka logging

Using Akka logging is a great thing, until you need to turn it off. In short, to disable Akka logging, you need to create a file named application.conf in your SBT src/main/resources folder, and set the loglevel to “OFF” in that file, like this:

#
# see http://doc.akka.io/docs/akka/snapshot/general/configuration.html
#
akka {

    # options: OFF, ERROR, WARNING, INFO, DEBUG
    loglevel = "OFF"

}

I show the other log levels in the comments in that file, but setting it to OFF disables Akka logging.

When I refer to Akka logging, I’m referring to logging when you have an Akka actor that extends ActorLogging.

Functional error handling in Scala

Because functional programming is like algebra, there are no null values or exceptions. But of course you can still have exceptions when you try to access servers that are down or files that are missing, so what can you do? This lesson demonstrates the techniques of functional error handling in Scala.

Scala best practice: How to use the Option/Some/None pattern

[toc]

This is an excerpt from the Scala Cookbook (partially modified for the internet). This is Recipe 20.6, “Scala best practice: How to use the Option/Some/None pattern.”

Problem

For a variety of reasons, including removing null values from your Scala code, you want to use what I call the Option/Some/None pattern. Or, if you’re interested in a problem (exception) that occurred while processing code, you may want to return Try/Success/Failure from a method instead of Option/Some/None.

Scala trait examples and syntax

This page contains a collection of Scala trait examples. I created many of these examples when I was writing the Scala Cookbook. Unlike the Cookbook, where I explain these examples in great detail, on this page I’m just sharing many of the examples so you can use this as a trait reference page. (The Cookbook actually contains more examples than this page.)

Without any more introduction, here are the examples.

[toc hidden:1]

How to stop JavaFX clients in SBT

As a brief note, you need this setting in your build.sbt file if you want JavaFX client/GUI applications to properly stop in SBT:

// see: https://stackoverflow.com/questions/5137460/sbt-stop-run-without-exiting
fork in run := true

Conversely, if you don’t use that setting and then you stop your JavaFX app that you started inside SBT, the app won’t stop properly and it will leave a Java process running, and at that point about all you can do is kill SBT and restart it, which gets annoying after a very short while. That setting causes SBT to create and run the JavaFX app in a new JVM. As noted in the code, I found that setting on SO.

A Scala/JavaFX WebSocket client

As a brief note today, I started to create a little Scala/JavaFX WebSocket client based on the Java-WebSocket project. I initially created it to test my Play Framework WebSocket example. I had hoped to be able to easily get to the server response request headers, but atm I don’t see a way to do that.

That being said, this is what the Scala/JavaFX WebSocket client currently looks like:

A Scala/JavaFX WebSocket client

And here’s its source code:

A sample Scala/JavaFX application

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
    }
}

(Almost) The simplest possible Play Framework and Scala WebSocket example

In this article I show how to write a WebSocket server using the Play Framework and Scala. My goal is to create the simplest possible WebSocket server so you can see how the basics work.

To demonstrate the WebSocket server I also created an HTML/JavaScript client. It isn’t quite as simple as the server, but I decided to keep some extra code in the client in case you have problems and need some debugging help.

Simple Scala Akka Actor examples (Hello, world examples)

Scala Actors FAQ: Can you share a Scala Akka Actors example/tutorial?

Sure. Most of the Scala Akka Actor tutorials I see jump right into the deep end, throwing you into some tough concepts right away. Personally I'm more into the "crawl before you walk approach," and to that end, here are some simple Akka Actor examples, of the "Hello, world" variety.

A simple Akka "Hello, world" example

My first Akka Actor example is about as simple as I can make it:

A Scala shell script example (and discussion)

Scala shell script FAQ: How do I create a Unix/Linux shell script to run a small Scala script?

If you want to run a Scala script as a Unix or Linux shell script -- such as hello.sh -- write your script like this: