0

I currently have a working Scalactra servlet.

class MyScalatraServlet extends MyScalatraWebAppStack {
   get("/") {
      response.getWriter().println("Test")
      val scDate = com.example.app.ScalaDate.printDate()
      response.getWriter().println(scDate)
      val cmd = "spark-submit --jars /home/cloudera/Desktop/SparkDisc/lib/DME.jar/..../discovery_2.10-1.0.jar hdfs:/user/cloudera/sample0.txt"//hard coded file path
      val output = cmd.!! // Captures the output
      response.getWriter().println(output)
   }
}

The file path is currently hard coded. Is there anything I can do to allow the user to enter in the filepath parameters? An help is greatly appreicited!

hiropon
  • 1,675
  • 2
  • 18
  • 41

1 Answers1

3

Use GET or POST, you can input parameter, like this:

import org.scalatra._
import scalate.ScalateSupport
import com.google.gson.Gson
import java.util.concurrent.TimeUnit
import java.util.Date

class Queue(var id: String, var act: String, var waitSec: Int) {
  override def toString = id + ", " + act + ", " + waitSec.toString
}

class MyScalatraServlet extends ScalatraServlet with ScalateSupport {

  get("/hello/:query") {
    <html>
      <body>
        <pre>
          {params("query")}
        </pre>
      </body>
    </html>
  }

  post("/hello") {

    println("A request comes: " + "%tF %<tT" format new Date)

    val jsonString = request.body
    try {
      val gson = new Gson
      val queue = gson.fromJson(jsonString, classOf[Queue])
      // for debugging
      println("Your name: " + queue)

      if (queue.act.equals("stop")) {
        println("Wait for: " + queue.waitSec.toString)
        TimeUnit.SECONDS.sleep(queue.waitSec)
      }

      response.addHeader("ACK", "GOT IT")
    } catch {
      case e: Exception =>
        e.printStackTrace
        response.addHeader("ACK", "BOOM!")
    }
  }

  notFound {
    // Try to render a ScalateTemplate if no route matched
    findTemplate(requestPath) map { path =>
      contentType = "text/html"
      layoutTemplate(path)
    } orElse serveStaticResource() getOrElse resourceNotFound()
  }
}
  1. GET

You should refer Scalatra 2.4 guide ... Routes You can see inputted query by accessing http://localhost:8080/hello/query
But, I think inputting filepath by query is not good manner.

  1. POST

Above example, you can make it stop processing servlet. Following JSON is useful to handle this code.

{"id":"001","act":"stop","waitSec":100}

Exec curl like this:

$ curl -i -X POST -d "{\"id\":\"001\",\"act\":\"stop\",\"waitSec\":100}" http://localhost:8080/hello -H "Content-Type: application/json"

For example, you can replace JSON key&value for filepath.

hiropon
  • 1,675
  • 2
  • 18
  • 41