renderJson without template - java

I have controller with
render(messages);
And i have route
GET / Application.index
I want to implement some rest features, and add this route
GET /api/index Application.index(format:'json')
I have template not found exception. How can i say to play use renderJSON() when format is json without any code changes?

As you use the render() method, Play! will search a template file with the name of the action (detail on Play! website : http://www.playframework.org/documentation/1.2.2/controllers#template).
You have to use renderJSON(params...), it will bypass the default template!

Your use case doesn't really make sense. In the standard render() call, you are likely passing some pojos to the template to use (or none at all), this is a varargs method. In the renderJSON() call you always need to pass an object which can be serialized to json by the Gson library, or a string with is already in json.
Add a new method to your Application class that handles json responses:
# normal index page
GET / Application.index
# api request
GET /api/index Application.indexJson

Related

Swagger doesn't read Path parameter: #Path("folder{path:.*}")

I have a problem getting Swagger to generate correct documentation for an API call that has an optional path parameter.
I'm building an API that peers into a hierarchical structure, similar to a file system. I want to call the same method to get the root structure as I do to get a sub resource. E.g:
Get the root: /folder
Get a sub folder: /folder/path/to
My Jax-rs method looks like this:
#GET #Path("folder{path:.*}")
Response folderContents(#ApiParam(value = "The folder to list", required = false) #PathParam("path") String path)
{...}
My method call works, but my swagger documentation is incorrect and doesn't work. Swagger-ui generates GET calls that look like this when I run it:
http://localhost:8080/storage-war/rest/filestore/folder{path:.*}
I'm looking for a way to either force Swagger to generate the correct signature or rebuild my regular expression so that my generated Swagger is correct.
Previously I'v tried using #Path("folder/{path:.}")*; his generated correct Swagger documentation but didn't match my no path given case. I've also tried #Path("/folder{p:/?}{path:(.)}")*; This produced a working method call but incorrect Swagger docs.
Is there a straightforward way to do what I'm looking for?
Edit:
In the end I created separate method calls for root and folders. Then I decorated the root call with it with #ApiOperation(hidden = true). This way I have an extra method in my code but only one method show up in my Swagger docs.
#GET #Path("folder/{path:.*}")
Response folderContents(#PathParam("path") String path)
{...}
#GET #Path("folder")
#ApiOperation(hidden = true)
Response rootContents()
{...}
In swagger, path parameters are always required. Understanding that in many frameworks and in practice they can be optional, but in the swagger definition they are required. See https://github.com/OAI/OpenAPI-Specification/blob/master/versions/2.0.md#fixed-fields-7

What is the best way to get one param from form (Play2 Framework)?

I am want to create simple form for searching records via one parameter (for example, name).
Seems like creating a class with one property (name) and than use helpers for forms - is not a best way.
Is there any examles how can I get POST data from request and fetch property value from that data?
Thanks a lot for wasting your time.
You already answered your own question, I just want to provide some more information:
You are right about creating a class with one single property, however keep in mind that you can use validation annotations (like #Required, #Email, etc.) in this class - so if there is some (super) complex logic behind this property this might also be a valuable option.
The second solution would be to use DynamicForms - you use them when you don't really have a model that is backing up the submission form. It goes like this:
public static Result index() {
DynamicForm requestData = Form.form().bindFromRequest();
String name = requestData.get("name");
return ok(name);
}
And of course the third option to get the values is like you mentioned:
String name = request().body().asFormUrlEncoded().get("name")[0];
If you do not what to use form validation, I don't think you need to create a class. Instead, you can use AJAX function like $.ajax(), that will be route to your specific controller function. Moreover, you can call your model function from your controller then at last return the result. The result will be caught by the $.ajax() function.
$.ajax
type: "POST"
url: url
data: data
success: success
dataType: dataType

How to define a play route to pass an int[] param to the action

I am new to Java, Playframework and Scala. I am trying to create a route to my action using an array, but am getting an error. I know the error says to use a custom query binder, but I also found spots that refer to this being supported in play 2.1. I am using 2.2.1. Is there something that I am missing, or do I need to create a custom QueryStringBinder? Is there a better way to do this?
Route -
GET /someAction controllers.MyController.someAction(employees:Array[Int])
Controller Action -
public static Result someAction(Array<int> employees)
{
...
}
Error :
No QueryString binder found for type Array[Int]. Try to implement an implicit QueryStringBindable for this type.

Retrieve hashmap values from java servlet to flex

I am working on "migration from JSP to FLEX, and java as back-end. I am novice in java and JSP.
I am stuck at getting values from a java servlet where it takes httprequest and there is a function called forward(request,response) which responds as JSP page with requried values in it.
Now I need to change that and get only data from that servlet and use that in flex.
Problem:
case1: When using httpservice it takes result as string, but unable to get as object.
case2: If I use RemoteObject , it needs method in java servlet to get return value, which is not present in existing servlet.
Can I get any suggestions on this problem.
Thank You
case1: you don't use forward anymore, you set the type of data you want to return, for example:
response.setContentType("application/json");
... and returning data in servlet is done by writing data to a stream like:
PrintWriter out = response.getWriter();
out.print(object);
but it's a while ago since I did this, so there may be some small problem you will face...
case2: if you are using servlet, it's correct to use HTTPService, RemoteObject will not work, it is used differently....
Now, if I can, I would suggest diferent thing to use than servlets - to obtain data from a java server to Flex - I love to use GraniteDS.
I will just state some benefits I see, in case you are interested:
It is easy to setup:
- in java, you will just add a graniteDS library, two config files (granite+services-config xmls) add a granite servlet config to web.xml
- in flex there is also granite library and services-config.xml
When set up, using it is also flowleslly easy - you have a class with a method (or simple bean or ejb) in Java which just return an object of any type! And that's it in Java
In flex, in this case you use RemoteObject which you just call that remote java method and in result handler you get your dataGranite will take care of serializing+transfer+deserializing and just give you the Object (either just dynamic {} or even exact class type)

GRAILS: method for permalink/slug generation?

Does anybody have a quick method to generate slugs and permalinks in Grails 1.3.7/2.0.0.RC1?
The main restriction: this method should work with non-latin characters.
Russian/bulgarian cirillic, deutsch umlauts etc...
Any suggestions ?
Grails 2.0.0.RC1
From the 2.0.0.RC1 docs:
Link Generation API
A general purpose LinkGenerator class is now available that is usable
anywhere within a Grails application and not just within the context
of a controller. For example if you need to generate links in a
service or an asynchronous background job outside the scope of a
request:
LinkGenerator grailsLinkGenerator
def generateLink() { grailsLinkGenerator.link(controller:"book", action:"list") }
Although it's not stated explicitly, I assume the reference to grailsLinkGenerator is obtained via dependency injection
Grails 1.3.7
You can use either the createLink or resource tags to generate links. If you're generating permalinks, I assume you'll want these to be absolute URLs. If so, you'll need to use either the absolute or base attribute when using these tags.
If you use the absolute attribute, be sure to set the value of grails.serverURL in Config.groovy
Link Permanence
The text above describes how to generate links to resources in a Grails application, but doesn't say anything about how to make these links permanent. AFAIK, the link to a resource will always remain the same as long as you don't change anything that is used in the URL mapping scheme (as defined in UrlMappings.groovy)
By default the URL mapping scheme uses
the resource's ID
the controller name
the action name
So if you never change these for the links of interest, you should be good.
As easy as:
title.replaceAll("[\\W]+", "-")
That makes it.

Categories