Play Framework 2.4 how to use return statement in Action controller - scala

is there a way to return a value inside Action controller.
I have a method in my User model which returns the number of friends of a given user.
def nrOfFriends(current_user: Long): Int = {
DB.withConnection{ implicit connection =>
var nr: Int = SQL("select count(*) from friend where user_id_1=" + current_user + " or user_id_2=" + current_user).as(scalar[Int].single)
nr
}
}
In my controller, I just want to return the value from the model
def freunde() = IsAuthenticated { username => _ =>
User.findByUsername(username).map { user =>
var nr: Int = Friend.nrOfFriends(user.id.get)
Ok(""+nr)
}.getOrElse(Forbidden)
}
But in the way that is written, it will print "empty string " concatenated with the number
If I replace Ok(""+nr) with Ok(nr) I receive the following error:
"Cannot write an instance of Int to HTTP response. Try to define a Writeable[Int]"
I need for my action to return a value so that I can pass the value from the action to header.views.html inside the navbar something like that
#Freund.freunde Friends

if you want your response to just be the value of nr you can simply call nr.toString:
def freunde() = IsAuthenticated { username => _ =>
User.findByUsername(username).map { user =>
var nr: Int = Friend.nrOfFriends(user.id.get)
Ok(nr.toString)
}.getOrElse(Forbidden)
}
The error you're getting makes reference to the fact that Int doesn't have an implicit Writeable[Int] in scope. So play doesn't know how display an Int in an http response.
You can add make Int writeable by putting this in scope:
implicit val intWriteable = play.api.http.Writeable[Int](_.toString.getBytes, None)
Then you would be able to just say:
Ok(nr)
without error.
However, it sounds like you just want the result of nrOfFriends inside an unrelated template. If that's the case, you should be using an Action at all. Instead just call your model function inside the template where you need the data.
#User.nrOfFriends(user.id) Friends
Of course you would need to pass in the user to the template as well.
You didn't post a full sample of all the code involved in what you are trying to accomplish so I think this is the best I can do for now. Perhaps try posting the base template that your <a> is in.
An important point is that Actions are for production an HTTP response, and not just plain data internally to the application.

An action of a controller handles a request and generates a result to be sent to the client. In other words, an action returns a play.api.mvc.Result value, representing the HTTP response to send to the web client. In your example Ok constructs a 200 OK response. The body of the response must be one of the predefined types, including text/plain, json, and html. The number of a friends is an integer and is NOT an acceptable type of the body. Therefore, a simple way to address this problem is to convert it into a text/plain using .toString().
On the other hand, you can define a writer for Int that lets Play know how to convert an integer into a json format.
For more details, please take a look at this https://www.playframework.com/documentation/2.2.x/ScalaActions.

Related

Handling and manipulating a list of http responses

I'm currently trying to implement API logic to fetch multiple images from a server.
This server accepts an image id and return an HTTP response that contains the image in PNG format as an entity.
Right now, we want to add a new endpoint that accepts a list of images IDs and return a list of all the images:
I have done the following:
def getImagesFromIds(IdsList: List[String]): Future[List[HttpResponse]] = {
Future.sequence {
IdsList.map(
id => getImageById(id)
)
}
}
this function will receive a list of ids and will call the getImageById to fetch all the images, it will return a list of HttpResponse.
And for the route definition, I have done the following:
def getImagesByIdsListRoute: Route = get {
path("by-ids-list") {
entity(as[List[String]]){
upcs =>
complete(getImagesFromIds(upcs))
}
}
}
But I'm getting the following error message:
no implicits found for parameter m: marshalling.toresponsemarshallable[list[httpresponse]]
Does Any one know how we can marshall a list of http responses, or if there is any way to improve this logic to fetch multiple http responses ?
If I understand correctly, you want to download multiple images and return them as a HTTP response.
The problems with your current attempt
The call to the API made via getImageById returns a HttpResponse. You can't be sure what is the result of this API call. If it fails, the response won't contain any image at all.
You are trying to return List[HttpResponse] as your response. How should this response be serialized? Akka doesn't know what you mean by that and tries to find a marshaller which will serialize your object (for example to JSON) but can't find one.
Returning a list of images requires zipping them. You can't return multiple entities in a single HTTP response.
Possible approach
You have to change getImageById so that it checks what is in the HttpResponse and returns the entity bytes.
Example:
response match {
case HttpResponse(StatusCodes.OK, _, entity, _) =>
entity.dataBytes
case resp # HttpResponse(code, _, _, _) =>
// Response failed and we don't care about the response entity
// Details: https://doc.akka.io/docs/akka-http/current/implications-of-streaming-http-entity.html
resp.discardEntityBytes()
// Decide yourself how you want to handle failures
throw new RuntimeException("Request failed, response code: " + code)
}
dataBytes returns a Source so you'll end up with a List of Sources. You have to concatenate them via, for example via concat.
The result stream has to be zipped via Compression.gzip.
Finally, the stream can be put in the complete method of getImagesByIdsListRoute.

Gatling session - get attribute as Long

I am a new in Scala and got some problems with casting from String to Long. I try to get Gatling session value as Long in request. Before in exec() part, I try to set the userId value
def setUserId(): ChainBuilder = {
exec(session => session
.set("userId", Random.nextLong())
)
}
Next, in request creator I want to use it like that because I need a new userId every call:
object UserRequestCreator {
def sampleUserRequest(currency: String): Request = {
Data data = new Data()
data.setUserId("${userId}".toLong)
data.setCurrency(currency)
}
}
Test scenario:
exec(setUserId())
.exec(http("postUser")
.post(endpointUser).asXml
.headers(headers)
.body(StringBody(toXmlString(sampleUserRequest("EUR"), classOf[Request])))
.check(status.is(200))
but receive error:
java.lang.NumberFormatException: For input string: "${userId}"
How to fix that in Scala?
I also try Long.valueOf, JLong.parseLong("${userId"}, 16), Try(BigDecimal(...)) and more but nothing can help. I think the problem is with $ symbol, but I don't see any different way to get this value from the session. Maybe it is possible to store Long in the Gating session?
From the documentation and based on your current code, one way to do it is like that:
// with a function payload
http("name").post("/")
.body(StringBody(session => s"""{ "foo": "${session("dynamicValueKey").as[String]}" }"""))
Thus, in your case:
StringBody(session => toXmlString(sampleUserRequest(session)("EUR"), classOf[Request])
def sampleUserRequest(session: Session)(currency: String): Request = {
//...
data.setUserId(session("userId").as[Long])
}

How to read query parameters in akka-http?

I know akka-http libraries marshal and unmarshal to class type while processing request.But now, I need to read request-parameters of GET request. I tried parameter() method and It is returning ParamDefAux type but i need those values as strings types
I check for answer at below questions.
How can I parse out get request parameters in spray-routing?
Query parameters for GET requests using Akka HTTP (formally known as Spray)
but can't do what i need.
Please tell me how can i extract query parameters from request. OR How can I extract required value from ParamDefAux
Request URL
http://host:port/path?key=authType&value=Basic345
Get method definition
val propName = parameter("key")
val propValue = parameter("value")
complete(persistanceMgr.deleteSetting(propName,propValue))
My method declarations
def deleteSetting(name:String,value:String): Future[String] = Future{
code...
}
For a request like http://host:port/path?key=authType&value=Basic345 try
path("path") {
get {
parameters('key.as[String], 'value.as[String]) { (key, value) =>
complete {
someFunction(key,value)
}
}
}
}
Even though being less explicit in the code, you can also extract all the query parameters at once from the context. You can use as follows:
// Previous part of the Akka HTTP routes ...
extract(_.request.uri.query()) { params =>
complete {
someFunction(key,value)
}
}
If you wish extract query parameters as one piece
extract(ctx => ctx.request.uri.queryString(charset = Charset.defaultCharset)) { queryParams =>
//useyourMethod()
}

Gatling httpRequest with dynamic method from collection

I want to build a Gatling scenario from a collection of structured data (StructuredDataCollection).
My problem is, that I'm unable to pass in the "method" (as in HTTP method) from an element from the collection into the http call of the actual test.
Here's a code snippet.
def testScenario(duration: Int) = scenario("SO").during(duration) {
exec {
session => {
val test = StructuredDataCollection.next()
val title = test.title
val method = test.method // Not being used, because it does not work like that :(
val endpoint = test.endpoint
val requiredParameters = test.requiredParameters
val code = test.code
session
.set("title", title)
.set("methodFUG", method).set("endpoint", endpoint)
.set("requiredParameters", requiredParameters)
.set("code", code)
}
}
.exec(
http("${title}")
.httpRequest("get", "${endpoint}") // TODO: method can't be passed in as an expression.
.queryParamMap("${requiredParameters}")
.check(status.is("${code}"))
)
}
As you can see, I've hard-coded "get", but I'll need that to be replaced with the actual value from the method property from the current selected item from the collection.
Unfortunately, Gatling's DSL isn't available in all the places where you'd expect it to be, and it's just reading that as a string.
It took me some time to realize, that
http("${title}").httpRequest("${methodFUG}", "${endpoint}") will actually make a HTTP call with the invalid method "${methodFUG}" and not the value from the collection element, which could be "GET", "POST", "PUT", "DELETE", and so on.
httpRequest signature is (method: String, url: Expression[String]), see documentation.
It cannot take an Expression, only a static String.

Gatling Conditional on Response Body

I am currently using Gatling and I have a scenario whereby I perform a number of GET requests and depending on the body of the responses I would like to perform a different scenario.
I have this at the moment that doesn't appear to work as expected -
val repeatSpin = scenario("repeatScenario1").repeat(10) {
exec(
scenario1
)
.doIf(bodyString => bodyString.equals("<SwitchEvent/>")){
exec(scenario2)
}
}
What am I doing wrong?
It looks like you've got the .doIf parameters wrong - it either takes a key in the session and the value you expect, like:
.doIf("${bodyString}", "<SwitchEvent/>") { myChain }
Or, an Expression[Boolean] - the argument you get is the session; to get values out of a session you do something like session("bodyString").as[String]. So, passing a function to the doIf could look like
.doIf(session => session("bodyString").as[String].equals("<SwitchEvent/>")) { myChain }