Showing posts with label Scala. Show all posts
Showing posts with label Scala. Show all posts

Friday, February 9, 2018

Minimal Scala Play

If you just need Scala Play for some quick testing/demo of Scala code, even the Scala Play Starter Example is too heavy. It has a lot of example code that is not needed and too much security for something to be run and accessed only locally.

Here is how to trim down the Scala Play Starter Example. First is the conf/application.conf file. All that is needed for the whole file is:

play.filters {
  hosts { allowed = ["."] }
  headers { contentSecurityPolicy = "default-src * 'unsafe-inline'" }
}

The hosts.allowed allows connections from external sources, and headers.contentSecurityPolicy allows things like remotely hosted Javascript (e.g. http://code.jquery.com/jquery-3.3.1.min.js) and Javascript inline directly in HTML elements (i.e. disable CSP and go back to 2016).

Then the conf/routes file:

GET     /                controllers.HomeController.index
GET     /mywebservice    controllers.MyWebServiceController.get(inputdata)

Specifically, you can delete the /count and /message routes, and then add whatever routes you need for web services (like /mywebservice above).

In the app directory:

rm -rf filters
rm -rf services
rm Module.scala
rm controllers/AyncController.scala
rm controllers/CountController.scala
rm views/main.scala.html
rm views/welcome.scala.html

And then in views/index.scala.html you can just delete all the code therein and write your own regular HTML and not bother with the Twirl template language if you don't need it.

Finally, you'll need to create controllers/MyWebServiceController.scala. You can use HomeController.scala as a template and add in import play.api.libs.json._ to gain access to the Play JSON APIs for parsing and generating JSON.

controllers/MyWebServiceController.scala

package controllers

import javax.inject._
import play.api.libs.json._
import play.api.mvc._

@Singleton
class MyWebServiceController @Inject()(cc: ControllerComponents) extends AbstractController(cc) {

  def get(inputdata:String) = Action {
    val a = Json.parse(inputdata)
    val r = // do stuff with a
    Ok(Json.toJson(r))
  }
}

Saturday, October 3, 2015

Minimal Scala pom.xml for Maven

You would think it would be easy to find an example pom.xml for Scala somewhere on the web. It's not. And the example one at http://www.scala-lang.org/old/node/345 doesn't work because its <sourcedir>src/main/java</sourcedir> excludes all your Scala files from src/main/scala!

Without further ado, below is a minimal pom.xml for Scala.
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.technicaltidbit</groupId>
    <artifactId>scala-hello-world</artifactId>
    <version>1.0-SNAPSHOT</version>
    <dependencies>
        <dependency>
            <groupId>org.scala-lang</groupId>
            <artifactId>scala-library</artifactId>
            <version>2.10.5</version>
        </dependency>
    </dependencies>
    <build>
        <plugins>
            <plugin>
                <groupId>org.scala-tools</groupId>
                <artifactId>maven-scala-plugin</artifactId>
                <executions>
                    <execution>
                        <goals>
                            <goal>compile</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>
</project>

Tuesday, September 22, 2015

Four ways to retrieve Scala Option value

Suppose you have the Scala value assignment below, and wish to append " World", but only if the value is not None (from Option[]).

val s = Some("Hello")

There are four different Option[] idioms to accomplish this:
  1. The Java-like way

    if (s.isDefined) s.get + " World" else "No hello"
     
  2. The Pattern Matching way

    s match { case Some(s) => s + " World"; case _ => "No hello" }
     
  3. The Classic Scala way

    s.map(_ + " World").getOrElse("No hello")
     
  4. The Scala 2.10 way

    s.fold("No hello")(_ + " World")

Thursday, September 12, 2013

Ctrl-C shutdown hook in Scala

If you need to intercept Ctrl-C, SIGINT, SIGHUP, etc. in Scala, and handle it on the main thread, it is necessary to join() back to the main thread from within the shutdown hook as below because, unlike C signal handlers, the process terminates at the end of the shutdown handler, even though there is no explicit call to System.exit().

object ctrlctest {
  @volatile var keepRunning = true

  def main(args: Array[String]) {
    val mainThread = Thread.currentThread();
    Runtime.getRuntime.addShutdownHook(new Thread() {override def run = {
      println("inside addShutDownHook handler")
      keepRunning = false
      mainThread.join()
    }})
    while (keepRunning) {println("in while loop")}
    // Graceful shutdown code goes here that needs to be on the main thread
    println("Exiting main")
  }
}
And the resulting output is:
in while loop
in while loop
in while loop
inside addShutDownHook handler
in while loop
Exiting main