Batch json strings processing using playframework in Scala - json

I use API which might either return a single json string, a batch of json strings or the string PROCESSING_TIMEOUT, e.g.:
{"id":123,"field1":"test1"}
or:
{"id":123,"field1":"test1"}
{"id":456,"field2":"test2"}
{"id":789,"field3":"test3"}
or (in case of asynchronous processing timeout in remote API)
PROCESSING_TIMEOUT
In the function getRestContent I want to be able to correcty process all these possible outputs, including also the timeout errors. In the current version of the function I lack the possibility to process batch json strings. I think that the best option would be that the function returns List<JsValue> instead of JsValue.
How can I do this modification using Play Framework.
def getRestContent(url:String,param:String,paramValue:String): JsValue = {
var output : JsValue = null
var httpOutput : String = null
try {
val response: HttpResponse[String] = Http(url).timeout(connTimeoutMs = 10000000, readTimeoutMs = 10000000).param(param,paramValue).asString
httpOutput = response.body
} catch
{
case ex: Exception => {
println("Failed connection with remote API")
}
}
if (!httpOutput.contains("PROCESSING_TIMEOUT") && httpOutput != null)
{
try {
output = Json.parse(httpOutput)
}
catch
{
case ex: Exception => {
println("Failed to process a document")
}
}
}
else
{
println("Asynchronous processing timeout")
}
if (output != null)
{
return output
}
else {
return new JsObject(Map("empty" -> JsNumber(0)))
}
}

Disregarding Play Framework your code is not Scala-flavored in general.
Below is a simple example of how better to approach such task in more Scala-way.
Highlights: use scala.util.Try wrapper to normally work with exceptions in a functional way, use pattern matching and monadic map and other methods of collections.
I hope the code below is self-explanatory. I mimicked the API. It returns Strings and not JSON but your 3 basic cases are sufficiently emulated: single line, multiple lines and exceptional case.
Try to run the program few times and you will see that all 3 cases are handled correctly:
import scala.util.{Failure, Success, Try, Random}
/**
* Created by Alex on 3/10/2016.
*/
object Temp {
case class Item(name:String, value:Int)
object API{
def getTimeOutResponse:String = throw new TimeoutException("no luck this time")
def getSingleLineResponse = "{name: \"Alex\", value: 1}"
def getMultiLineResponse = "{name: \"Alex\", value: 1}\n{name: \"HackerDuck\", value: 2}"
def getRandomResponse = (Math.abs(Random.nextInt() % 3)) match{
case 0 => getTimeOutResponse
case 1 => getSingleLineResponse
case 2 => getMultiLineResponse
}
}
def getResults:List[Item]={
Try(API.getRandomResponse) match{
case Success(s) =>{
s.split("\n").toList.map{item =>
val parts = item.split(", ")
Item(parts(0).replace("{name: ", "").replace("\"", ""), parts(1).replace("value: ", "").replace("}", "").toInt)
}
}
case Failure(_) =>{
println("API timeout happened")
List.empty[Item]
}
}
}
def main(args:Array[String])={
println(getResults)
println(getResults)
println(getResults)
}
}
A sample output from my console:
API timeout happened
List()
List(Item(Alex,1))
List(Item(Alex,1), Item(HackerDuck,2))
Process finished with exit code 0
The code becomes less cluttered without all these if statements and !=null and alike. Also you can streamline conversion of your elements sequence to List in one place.

Related

Handle exception for Scala Async and Future variable, error accessing variable name outside try block

#scala.throws[scala.Exception]
def processQuery(searchQuery : scala.Predef.String) : scala.concurrent.Future[io.circe.Json] = { /* compiled code */ }
How do I declare the searchResult variable at line 3 so that it can be initailized inside the try block and can be processed if it's successful after and outside the try block. Or, is there any other way to handle the exception? The file containing processQuery function is not editable to me, it's read-only.
def index = Action.async{ implicit request =>
val query = request.body.asText.get
var searchResult : scala.concurrent.Future[io.circe.Json] = Future[io.circe.Json] //line 3
var jsonVal = ""
try {
searchResult = search.processQuery(query)
} catch {
case e :Throwable => jsonVal = e.getMessage
}
searchResult onSuccess ({
case result => jsonVal = result.toString()
})
searchResult.map{ result =>
Ok(Json.parse(jsonVal))
}
}
if declared in the way it has been declared it's showing compilation error
Would using the recover method help you? I also suggest to avoid var and use a more functional approach if possible. In my world (and play Json library), I would hope to get to something like:
def index = Action.async { implicit request =>
processQuery(request.body.asText.get).map { json =>
Ok(Json.obj("success" -> true, "result" -> json))
}.recover {
case e: Throwable => Ok(Json.obj("success" -> false, "message" -> e.getMessage))
}
}
I guess it may be necessary to put the code in another whole try catch:
try {
processQuery....
...
} catch {
...
}
I have here a way to validate on the incoming JSON and fold on the result of the validation:
def returnToNormalPowerPlant(id: Int) = Action.async(parse.tolerantJson) { request =>
request.body.validate[ReturnToNormalCommand].fold(
errors => {
Future.successful{
BadRequest(
Json.obj("status" -> "error", "message" -> JsError.toJson(errors))
)
}
},
returnToNormalCommand => {
actorFor(id) flatMap {
case None =>
Future.successful {
NotFound(s"HTTP 404 :: PowerPlant with ID $id not found")
}
case Some(actorRef) =>
sendCommand(actorRef, id, returnToNormalCommand)
}
}
)
}

How to handle a PSQL exception and return in my JSON action

I have a JSON action that returns a very simple JSON object that looks like:
case class InsertResponse(success: Boolean, message: String)
My action that returns JSON looks like:
def insertUser = Action.async(BodyParsers.parse.json) { request =>
val userReq = request.body.validate[UserRequest]
userReq.fold(
errors => {
Future(Ok(....))
},
userR => {
val insertResultFut =
for {
user <- .......
} yield ....
Ok(insertResponse.toJson)
}
)
}
So I want to catch certain exceptions that the insertResultFut call may throw, as it calls my slick database layer that inserts into the database.
I want to guard against a PSQLException that is thrown if the users email is a duplicate, how can I catch this error with futures?
If there is an exception, and it is a PSQLException for a duplicate key, I want to catch that and also set my InsertResponse success flag to false etc.
Thoughts?
You can use Future#recover for this case:
insertResultFut.recover {
case exe: PSQLException if exe.getMessage.contains("duplicate") => BadRequest(InsertResponse(false, "duplicate").toJson)
}

How to return json from Play Scala controller?

I would like to know that how can I return json response data from Play(2.2.x) Scala controller class to display on my view page ? I have json objects in Postgresql database(table name: "test" and having: id and name). Please provide me any solutions for it.
I have tried the following cases(a and b), but I am not sure why I am not getting the response(like: names) on my controller, so I can show them on my view page ? since I am very new to Play/Scala and Postgresql.
case a. If I give like:
model:
def getTestValuesFromTable() = {
DB.withConnection { implicit connection =>
val selectJson =SQL("select name from test").on().apply().collect {
case Row(id:Long, Some(name:String)) =>
new TestContent(name)
}
//.head
//JsObject(selectJson().map { row => row[Long]("id").toString -> JsString(row[String]("name")) }.toSeq)
}
}
controller:
def getTest = Action {
val response = TestContent.getTestValuesFromTable()
Ok("Done")
//Ok(response)
}
Output is: Done(application is executing fine without any exceptions, of course json data is not coming since I am returning: Done only, so getting output: "Done")
case b. If I do like this: getting error: not enough arguments for method apply: (n: Int)models.Testname in trait LinearSeqOptimized. Unspecified value parameter n. I really not sure how can I get my response for it ?
controller:
def getTest = Action {
val response = TestContent.getTestValuesFromTable()
// Ok("Done")
Ok(response)
}
model:
def getTestValuesFromTable(): JsValue = {
DB.withConnection { implicit connection =>
val selectJson = SQL("select * from test")
JsObject(selectJson().map { row => row[Long]("id").toString -> JsString(row[String]("name")) }.toSeq)
// val selectJson =SQL("select name from test").on().apply().collect {
// case Row(id:Long, Some(name:String)) =>
// new TestContent(name)
// }
//.head
JsObject(selectJson().map { row => row[Long]("id").toString -> JsString(row[String]("name")) }.toSeq)//not enough arguments for method apply: (n: Int)models.Testname in trait LinearSeqOptimized. Unspecified value parameter n.
}
}
Please let me know how to get my response ?
getJsonValuesFromTable method return nothing (Unit). To fix it change definition of this method to
def getJsonValuesFromTable(testContent: TestContent) = {
or explicitly setting type:
def getJsonValuesFromTable(testContent: TestContent): Unit = {
Also as a next step to let client know that you are returning json, you should set content type:
Ok(Json.obj(response)).as("application/json")

Scala - Can I define a function that receives any function as a parameter?

Is it possible, in Scala, to define a function that would receive any other function as a parameter?
It should be something like the following:
object Module extends SecureModule{
val bc = new MyBC()
def method(parameter: Type) = {
exec(bc.method(parameter))
}
def method2(parameter1: Type1, parameter2: Type2) = {
exec(bc.method2(parameter1,parameter2))
}
}
trait SecureModule {
def exec(f: ANY_PARAMETER => ANY_RESULT) = {
//some extra processing
f
}
}
is it possible? If so, how could I achieve this?
Thank you in advance.
The nice thing about scala is that you can create what seems to be your own syntax.
If what you want to do is wrap an operation so that you can do pre and post processing, as well as control the execution context, then you do this by using call-by-name parameters. For example, if we just wanted to time how long a block of code takes, then we could do something like this:
def timer[T](block: => T): (T,Long) = {
val startDate = new Date()
val result = block
val endDate = new Date()
(result, endDate.getTime()-startDate.getTime())
}
We can use it like this:
val (result,duration) = timer {
1+3
}
Or like this
val (result,duration) = timer {
"hello" + " world!"
}
And the result will have the correct type from the block that you pass in while also giving you the duration that you expect.
I am under the impression that your description is somewhat misleading.
The way I understand it, what you (might) want to do is delaying the execution of the bc.method calls until some other code has been performed.
If so, try this:
object Module extends SecureModule{
val bc = new MyBC()
def method(parameter: Type) = {
exec(() => bc.method(parameter))
}
def method2(parameter1: Type1, parameter2: Type2) = {
exec(() => bc.method2(parameter1,parameter2))
}
}
trait SecureModule {
def exec[Result](f: () => Result): Result = {
//some extra processing
f()
}
}
You can't take any function as a parameter. What would you even do it?
At best, you can take any function that has a specific number of parameters.
For example, here, f takes one argument and returns a value.
def exec[A,B](f: A => B)
And here, f takes two arguments:
def exec[A,B,C](f: (A, B) => C)
If you don't care about the return type of the function, you could always use Any instead of a type parameter, since functions are covariant in their return type:
def exec[A](f: A => Any)

Grails JSON converter and JSONObject code breaks when moved to src/groovy

I am trying to move some code from a grails service file into src/groovy for better reuse.
import grails.converters.JSON
import org.codehaus.groovy.grails.web.json.JSONObject
class JsonUtils {
// seems like a clunky way to accomplish converting a domainObject
// to its json api like object, but couldn't find anything better.
def jsonify(obj, ArrayList removeableKeys = []) {
def theJson = obj as JSON
def reParsedJson = JSON.parse(theJson.toString())
removeableKeys.each { reParsedJson.remove(it) }
return reParsedJson
}
// essentially just turns nested JSONObject.Null things into java null things
// which don't get choked on down the road so much.
def cleanJson(json) {
if (json instanceof List) {
json = json.collect(cleanJsonList)
} else if (json instanceof Map) {
json = json.collectEntries(cleanJsonMap)
}
return json
}
private def cleanJsonList = {
if (it instanceof List) {
it.collect(cleanJsonList)
} else if (it instanceof Map) {
it.collectEntries(cleanJsonMap)
} else {
(it.class == JSONObject.Null) ? null : it
}
}
private def cleanJsonMap = { key, value ->
if (value instanceof List) {
[key, value.collect(cleanJsonList)]
} else if (value instanceof Map) {
[key, value.collectEntries(cleanJsonMap)]
} else {
[key, (value.class == JSONObject.Null) ? null : value]
}
}
}
but when I try to call jsonify or cleanJson from services I get MissingMethodExceptions
example call from grails service file:
def animal = Animal.read(params.animal_id)
if (animal) json.animal = JsonUtils.jsonify(animal, ['tests','vaccinations','label'])
error:
No signature of method: static org.JsonUtils.jsonify() is applicable for argument types: (org.Animal, java.util.ArrayList) values: [ ...]]\ Possible solutions: jsonify(java.lang.Object, java.util.ArrayList), jsonify(java.lang.Object), notify()
Also tried making the jsonify take an animal jsonify(Animal obj, ...) then it just said Possible solutions: jsonify(org.Animal, ...
The cleanJson method was meant to deal with JSONObject.Null things which have caused problems for us before.
example call:
def safeJson = JsonUtils.cleanJson(json) // json is request.JSON from the controller
error:
groovy.lang.MissingMethodException: No signature of method: static org.JsonUtils.cleanJson() is applicable for argument types: (org.codehaus.groovy.grails.web.json.JSONObject) values: [[...]]
Possible solutions: cleanJson(org.codehaus.groovy.grails.web.json.JSONObject)
All this code worked as it is when it was in service file. I am running grails 2.3.11 BTW
You've declared jsonify() and cleanJson() as instance methods and try to use them as static. Declare them as static and it should work:
class JsonUtils {
def static jsonify(obj, ArrayList removeableKeys = []) {
(...)
}
def static cleanJson(json) {
(...)
}
}
You need to define jsonify() and cleanJson() as static in order to call them statically.