Play Framework 2.1 Scala - form binding for date - forms

I want to create a form binding in Play Framework 2.1, for a form that has date/time fields. Is there any standard verifier for date/time input? I understand that the page form should also send the date/time in a particular format. Does anyone know of any prefab solution for that? Or can describe how to implement one by myself?

Play 2.1 has built-in support for Twitter Bootstrap; if you take that route then Bootstrap Date Picker is a good call for client-side (i.e. ensuring date is sent as yyyy-mm-dd or other valid date format).
With the client taken care of, server-side Play 2.1 supports JodaTime, so you can bind the post'd form date like so:
object FooForm {
import play.api.data.{Form, Forms}, Forms._
val mapper = mapping(
'fooDate-> jodaDate("yyyy-MM-dd")
)(Foo.apply)(Foo.unapply)
val form = Form( mapper )
}

Like #virtualeyes said, from the client side, DatePicker will generate the correct data format (dd/MM/yyyy by default).
However, Play Framework then needs to unmarshall the Date format correctly using bindFronRequest (client -> server).
Also Play needs to generate the correct Date string representation when generating the Form, which will be sent to the view (controller -> view). In java this can be done providing a DataBinder.
An example of this can be found in that issue opened on GitHub

Related

How to provide translations for field names with Symfony2/Doctrine2 via REST?

We have a backend built on FOSRestBundle (JMSSerializer) based on Symfony2/Doctrine2.
Our API e.g. delivers for some entity something like: 'valid_from': '2015-12-31' in a REST/JSON response.
Our AngularJS frontend consumes this REST API and e.g. presents some form to the user:
Valid from: 31.12.2015
Now I am wondering what's the best way to have a central/or maintainable place for a mapping like:
an English label for field key 'valid_from' is 'Valid from'
To my understanding all Translatable extensions for Doctrine (like Gedmo Kpn etc.) are to translate content (e.g. 'category' = 'Product' in English and = 'Produkt' in German) but not schema.
And of course I cannot change/adapt the field key to the language because it's the identifier for the frontend.
What I thought so far:
Use some mapping file between field_key, language_key and
translation on frontend.
Issue here is that the frontend needs to know a lot and ideally any change in the API can be done thoroughly by the backend developers.
Use some mapping file between field_key, language_key and
translation on frontend.
As we use annotations for our Entity model and JSMSerializer I'd need to open a totally new space for just translation information. Doesn't sound too convincing.
Create custom annotation with properties
Current idea is to use custom annotation (which would be cacheable and could be gathered and provided as one JSON e.g. to the frontend) with my entity properties.
That means any backend developer could immediately check for translation keys at least as soon as the API changes.
Something like:
#ORM\Column(name='product', type='string')
#FieldNameTranslation([
['lng'=> 'de-DE'],['text']=>'Product'],
['lng'=> 'en-En'],['text']=>'Produkt'])
A further idea could be just to provide some translation key like:
#FieldNameTranslation(key='FIELD_PRODUCT')
and use Symfony's translation component and have the content in translation yml files.
What is your opinion? Is there any 'best in class' approach for this?

XPages REST and date format

I have an XPages page which contains the REST service component. I'm using the "documentJsonService".
Awesome component and everything else is working fine, but I'm having issues with the date formats and don't know what to do.
The Notes Document where I'm reading the data from, contains a DateTime item having a proper date e.g. 01.09.2014 (finnish format: dd.MM.yyyy). The REST component returns the date in "2014-09-01" (string). This is fine. However when I do a HTTP POST to the server with the same exact data, Domino changes the "2014-09-01" string date into 09.01.2014 Notes Date time item.
Don't know any more what to do. Why Domino gives date in format A and when I give it back in same format, something strange happens.
This same happens on Linux and Windows environments.
Domino version is 9.0.1.
Thanks already. I'm more or less lost with this "feature" :)
I would say: broken as designed. To my knowledge the JSON format returned is always in the form yyyy-mm-dd, while the format expected when posting depends on the browser locale. You would need to "hack around it".
I'm not a big fan of the ready baked JSON services, I'd rather roll my own, where I can be very specific with the formats and (more importantly) add validation before I write data back. You can find a sample on my blog
Basically you implement a bean like this:
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.ibm.domino.services.ServiceException;
import com.ibm.domino.services.rest.RestServiceEngine;
import com.ibm.xsp.extlib.component.rest.CustomService;
import com.ibm.xsp.extlib.component.rest.CustomServiceBean;
public class CustomSearchHelper extends CustomServiceBean {
#Override
public void renderService(CustomService service, RestServiceEngine engine) throws ServiceException {
HttpServletRequest request = engine.getHttpRequest();
HttpServletResponse response = engine.getHttpResponse();
response.setHeader("Content-Type", "application/json; charset=UTF-8");
// Your code goes here!
}
}
you need to check in the request what method GET or POST was used, but then it is easy to continue. While you are on it: the OpenNTF Domino API makes your life much easier.

Grails REST API hide "class" in respond list

I'm using Grails 2.3.2 working on a REST API using the built in Grails REST support. I'm having trouble getting rid of the "class" element in the JSON response. Based on a tutorial by Bobby Warner, I have found adding the following to the resources.groovy file:
meterRenderer(JsonRenderer, Meter) {
excludes = ['class']
}
This works fine for show, but for the index controller function, I'm responding with a list of Meters. In this, the "class" doesn't go away. What does it take to get rid of this in the list response?
Edit: To clarify, I am looking for a way to leverage the Content Negotiation feature of Grails new respond functionality without locking myself down to render as JSON implementions.
I guess if you switch to using GSON (github) instead of JSON then you need not worry about that particular exclusion.
That is driven by a config setting provided by the plugin as grails.converters.gson.domain.include.class (default is false).
nickdos' SO link had the answer. I added the following to my BootStrap.groovy:
grails.converters.JSON.registerObjectMarshaller(Meter) {
return it.properties.findAll {k,v -> k != 'class'}
}
And the respond call results in no "class" item. Oddly enough, I lost the "id" item in the process, but I'll save that for another SO question. :)

CalDav request example

I'm building a CalDAV server (in Java, using third-party library), pls help me with this:
If the request is: return all events in a calendar whose start date is between [date1, date2], then what type of request is it? and the parameters of the request?
I intend to put a servlet for a client to query. I'm wondering if I have to make a servlet for each type of requests: GET,HEAD,OPTIONS,PUT (target exists),PUT (no target exists),PROPPATCH,PROPFIND,DELETE,LOCK (target exists),LOCK (no target exists), MKCOL, MKCALENDAR,UNLOCK,REPORT,FREEBUSY
Thanks.
First question: You want to use a timerange based calendar query. See https://www.rfc-editor.org/rfc/rfc4791#section-7.8.1
Second question: You need only one servlet. Typically, you verwrite its default service() method to dispatch to separate handlers, one for each method (REPORT, PUT,...).

Guidance on a better way to retain filtering options when using ASP.NET MVC 2

I have an ASP.NET MVC 2 application which in part allows a user to filter data and view that data in a JQGrid.
Currently this consists of a controller which initialises my filter model and configures how I wish my grid to be displayed. This information is used by a view and a partial view to display the filter and the grid shell. I use an editor template to display my filter. The JQGrid makes use of a JsonResult controller action (GET) to retrieve the results of the filter (with the addition of the paging offered by the grid - only a single page of data is returned by the GET request. The Uri used by the grid to request data contains the filter model as a RouteValue - and currently contains a string representation of the current state of the filter. A custom IModelBinder is used to convert this representation back into an instance of the filter model class.
The user can change the filter and press a submit button to get different results - this is then picked up by an (HttpPost) ViewResult action which takes the filter model - reconstituted by a further model binder and causes the grid shell to be updated.
So I have:
FilterModel
Represents the user's desired filtering characteristics
FilterModelEditorTemplateSubmissionBinder : DefaultModelBinder - used to convert the request information supplied from a user changing their filtering characteristics into the appropriate FilterModel instance.
FilterModelStringRepresentationBinder : IModelBinder - used to convert the encoded filter from the JQGrid GET request for data so the correct request is made of the service which is ultimately performing the query and returning the relevant data.
ViewResult Index() - constructs a default filter, configures the grid specification and returns the view to render the filter's editor template, and the grid shell.
[HttpPost]ViewResult Filter(FilterModel filter) - takes the new filter characteristics and returns the same view as Index(). Uses FilterModelEditorTemplateSubmissionBinder to bind the filter model.
JsonResult GetData(FilterModel filter, string sidx, string sord, int page, int rows) - called from the JQGrid in order to retrieve the data. Uses FilterModelStringRepresentationBinder to bind the filter model.
As a complication, my filter model contains a option to select a single value from a collection of items. This collection is retrieved from a service request and I don't want to keep querying for this data everytime I show the filter, currently I get it if the property is null, and then include the options hidden in the editor template and encoding in the string representation. These options are then reconstituted by the relevant model binder.
Although this approach works I can't help but feel that I am having to basically reinvent viewstate in order to maintain my filter and the included options. As I am new to ASP.NET MVC but am very happy with classic ASP and ASP.NET Web Forms I thought I'd throw this out there for comment and guidance as to find a way which more closely fits with the MVC pattern.
It seems to me that the best way in to divide some actions which provide pure data for the jqGrid from other controller action. Such jqGrid-oriented actions can have prototype like:
JsonResult GetData(string filter, string sidx, string sord, int page, int rows)
I personally prefer to implement this part as WCF service and to have this WCF service as a part of the same ASP.NET site. In general it's much more the matter of taste and depends on your other project requirements.
This part of you ASP.NET site could implement users authentication which you need and can be tested with unit tests exactly like other actions of your controllers.
The views of the ASP.NET MVC site can have empty data for jqGrids, and have only correct URLs and probably generate the HTML code depends on the users permission in the site. Every page will fill the data of jqGrids with respect of the corresponds requests to the server (request to the corresponding GetData action).
You can use HTTP GET for the data for the best data caching. The caching of data is the subject of a separate discussion. If you do this, you should use prmNames: { nd:null } in the definition of jqGrid to remove unique nd parameter with the timestamp added per default to every GET request. To have full control of the data caching on the server side you can for example add in HTTP headers of the server responses both "Cache-Control" set to "max-age=0" and "ETag" header with the value calculated based of the data returned in the response. You should test whether the request from the client has "If-None-Match" HTTP header with the value of "ETag" coresponds the data cached on the client. Then you should verify whether the current data on the server (in the database) are changed and, if there are not changed, generate a response with an empty body (set SuppressEntityBody to true) and return "304 Not Modified" status code (HttpStatusCode.NotModified) instead of default "200 OK". A more detail explanation is much more longer.
If you don't want optimize you site for caching of HTTP GET data for jqGrids you can either use HTTP POST or don't use prmNames: { nd:null } parameter.
The code inside of JsonResult GetData(string filter, string sidx, string sord, int page, int rows) is not very short of cause. You should deserialise JSON data from the filter string and then construct the request to the data model depends on the method of the data access which you use (LINQ to SQL, Entity Model or SqlCommand with SqlDataReader). Because you have this part already implemented it has no sense to discuss this part.
Probably the main part of my suggestion is the usage of clear separation of controller actions which provide the data for all your jqGrids and the usage of MVC views with empty data (having only <table id="list"></table><div id="pager"></div>). You should also has no doubt with having a relative long code for analyzing of filters which come from the Advance Searching feature of the jqGrid and generating or the corresponding requests to your data model. Just implement it one time. In my implementation the code in also relatively complex, but it is already written one time, it works and it can be used for all new jqGrids.
I made this once, very simple.
pseudo code:
Controller
[HttpGet]
public ActionResult getList(int? id){
return PartialView("Index", new ListViewModel(id??0))
}
ViewModel
public class ListViewModel{
//ObjectAmountPerPage is the amount of object you want per page, you can modify this as //parameter so the user
//can choose the amount
public int ObjectAmountPerPage = 20 //you can make this into a variable of any sort, db/configfile/parameter
public List<YourObjectName> ObjectList;
public int CurrentPage;
public ListViewModel(id){
Currentpage = id;
using (MyDataContext db = new MyDataContext()){
ObjectList = db.YourObjectName.OrderBy(object=>object.somefield).getListFromStartIndexToEndIndex(id*ObjectAmountPerPage ,(id*ObjectAmountPerPage) +20).toList();
}
}
}
Now Create A RenderPartial:
PartialView
<#page inherit="IEnumerable<ListViewMode>">
<%foreach(YourObjectName object in Model.ObjectList){%>
Create a table with your fields
<%}%>
And create a view that implements your Jquery, other components+your partialView
View
<javascript>
$(function(){
$("#nextpage").click(function(){
(/controller/getlist/$("#nextpage").val(),function(data){$("#yourlist").html = data});
});
});
</javascript>
<div id="yourlist">
<%=Html.RenderPartial("YourPartialView", new ListViewModel())%>
</div>
<something id="nextpage" value"<%=Model.CurentPage+1%>">next page</something>
I hope this helps, this is according to the MVC- mv-mv-c principle ;)
Model-View -(modelview) - control