How to generate validation rules on back-end side? - java

Client is webapp in browser, and back-end is written in Java (Spring Boot). Business flow is following: entity is requested from server → user fills the form → form is sent to back-end. The form should be validated both on front- and back-end sides. The validation rules depend on values inside the entity. I want to avoid duplication of code that is responsible for deriving the validation rules. I think the best way would be for back-end to add validation rules in response for requested entity, so that front-end could use them. Is there a common approach for such problem?

Altough I've never used it I can recommend you to get familiar with Open Api https://swagger.io/specification/
That is the specification which is implemented by the various engines: https://github.com/OAI/OpenAPI-Specification/blob/master/IMPLEMENTATIONS.md
Each engine provides code generation based on contract written in contract-file. It should be possible to achive some simple combinational validation. I'm pretty sure that if you want to get some sequential complex validtation which value is based on database state you will end up doing it by yourself.

Related

RESTful API with Spring MVC and GWT and overlay types

I have developed a simple Spring MVC RESTful API and now I moved to the stage to create a simple GWT project to perform some requests to this api and obviously I choose that the communication will be done by exchanging JSON messages.
When receiving a response I will have to unmarshall it to a POJO.
I am aware that the general approach is to create the so called 'overlay types' but that looks to me as a mere duplicate of the java classes I wrote in api.
So the question is:
why shouldn't I simply create a common api that simply contains the common classes to perform this marshalling/unmarshalling?
I can clearly see that the main benefit is that if any change is needed you won't have to change also the overlay types.
Assuming that you can define interfaces for your pojo, you can share those Interfaces in client and server side (common package)
In server side you have to code your implementations which are used for the RESTful api.
In client side, the implementation of those interfaces can be done automatically with generators. For this you can use gwtquery databinding or gwt autobeans.
To request your RESTful api, you can use either gwtquery ajax or gwt requestbuilder
Each option has its advantages, normally I use gwtquery because its simplicity and because its databinding approach is more lightweight, otherwise, with autobeans you can create your POJOS using autobeans factories in both client and server sides. If you already have developed your backend this is not a goal for you though.
The REST response can be consumed by any client and not specifically one client. If I understand your question correctly, you want to build the logic of marshalling and unmarshalling inside your REST API. Ideally it violates Single Responsibility Principal. You might need to change the mapping logic if the service changes so you are touching two different aspects of an API where as only one component requires change.
Also, the REST API should ideally be designed to be client agnostic. It is your specific requirement to translate them to POJO but another client might want to consume it as simple plain JSON. If you provide an overlay type, your code will be quite loosely coupled.
If your server side class (Player for example) can be serialized/desirialized without any problems, then you can send it to client side without any overlay type / conversion (serialization to JSON on server -> transport -> desirialization from JSON on client). On client side you can use RestyGWT for example to archieve automatic desirialization process. Overlay types and conversion process are necessary only in the case when Player instance cannot be serialized (for example it is backed by Hibernate).

How to integrate results from RESTful api with JSF?

How to pass results from RESTful service to JSF components? I read many postings, but couldn't find a straightforward method. Using RESTful APIs wherever possible is the main requirement for my application. Performance is also a key as thousands of data elements will be processed in a day. If I can't find a solution in JSF, I might have to switch to another technology..
Therefore, I'm asking in case I'm missing something completely from other postings since I'm new. Here are a couple of simple scenarios.
On a JSF page, there is a datatable (Primefaces Checkbox based selection). The datatable displays records available (up to thousands). The datatable needs to be loaded through a RESTful api on the fly. Below is the code for my datatable.
<p:dataTable id="addSampleTable" var="sample" value="#{testBean.sampleDataModel}"
selection="#{testBean.selectedSamples}" >
<p:column selectionMode="multiple" style="width:2%" />
<p:column headerText="Sample">
<h:outputText value="#{sample.name}" />
</p:column>
</p:dataTable>
What's the best way to load the data? Is there a performance concern if every time I have to call the API from the server side (as opposed to client side using jquery and plain html)?
Second scenario, on the same page, there is also a button that allows user to add new record through another RESTful api. In turn, the newly added record should be displayed in the datatable.
After I call the RESTful API to insert a record, the api also returns the record that was created. How can I insert this new record into my datamodel #{testBean.sampleDataModel} so that I don't have to load the entire table again? I suppose I can replace this datatable with plain html and append the new record to the table using jQuery, but then I can't leverage the selection table from JSF.
What are my options?
Your question seems to be too broad, however I try to give some answers.
How to pass results from RESTful service to JSF components?
You can use the pattern implemented by NetBeans' guys. If you use this IDE, there is an option to automatically Build RESTful web services from database. Essentially, this pattern create all DAO basic functionalities in an abstract generic class called AbstractFacade. Then, for each concrete Entity class present in your JPA representation, it creates a Stateless class extending AbstractFacade, and adds jax-rs annotations to it in order to let it expose the Entity class through RESTful web service.
You can then access the service directly by EJB injection. Just use #EJB annotation to inject your service in any container-managed class (in the same application, but also in other applications provided that you use portable JNDI naming rules). In particular, you'll be interested in injecting the facade classes in the managed beans backing your facelets components.
What's the best way to load the data? Is there a performance concern if every time I have to call the API from the server side (as opposed to client side using jquery and plain html)?
Since you need to display thousands of records, your best bet is using Primefaces' lazy loading in your datatable. Your application will then call the db only for retrieving the few tens of records displayed in the current page. Absolutely avoid displaying more than those records, otherwise the client browser will likely be negatively impacted.
How can I insert this new record into my datamodel #{testBean.sampleDataModel} so that I don't have to load the entire table again?
Please distinguish between loading from db and loading in jsf. You can program your backing bean in order to call the db (which is usually the most expensive operation) only when you think it's necessary. As far as I know, both JSF's and PrimeFaces' dataTable implementations don't give you the possibility to manage the table contents at a row level: at every ajax update, the entire table will be reloaded. However, as already said, this won't impact your application's performances as long as you have correctly programmed your backing bean (i.e. choosing the right bean scope and avoid calling the db service in getters).
Useful Links:
NetBeans' tutorial about RESTful web services
Rubinoff's article about the pattern used by Netbeans' RESTful web services
PrimeFaces showCase about lazy loading
How to choose the right bean scope
Why JSF calls getters multiple times
Although this question is a little bit old, it's still a current issue. I'm not happy with the anwsers above because the both technologies mentioned above are together a missmatch.
The most important question here is: Does the given RESTful API actually act as a ...
service/buisness layer or ...
... does it provide CRUD operations only? If it only provides typical CRUD operations, it acts as a persistance layer and there is a need for a service layer.
In the second case, you can implement your service layer in a technology of your choice, JSF backed beans or even EJBs are a good choice. In the Java EE context the JAX-RS specification is a good choice, Jersey is an implementation of this specification. You can use this client API to access the RESTful API from Java: [1]
But...
When you design a complete new application, ensure your RESTful api provides not just CRUD operations but also provide higher leven service layer operations (accessed by https POST method) and deal with security concerns.
In this case heterogeneous systems like webapplications, mobile webapps, native mobile apps and so on can access the service layer directly and the particular view (the REST service consumer) is loosly coupled with the service layer (wich is a good thing in software engineering in general).
My opinion: forget old fashioned server side web frameworks like JSF, Struts and so on, provide a RESTful API with service layer operations and use JavaScript frameworks like AngularJS in order to access the RESTful operations directly... mobile apps are the next step. The complete Java EE technology stack is a little bit rusty ;-)
[1] https://jersey.java.net/documentation/latest/user-guide.html#client
What's the best way to load the data? Is there a performance concern if every time I have to call the API from the server side (as opposed to client side using jquery and plain html)?
Yes, there is a performance concern. The best way is to load your collection once into page context and operate on the list in this context. Then once you have done all your changes you synchronize with the stateless REST service.
How can I insert this new record into my datamodel #{testBean.sampleDataModel} so that I don't have to load the entire table again?I suppose I can replace this datatable with plain html and append the new record to the table using jQuery, but then I can't leverage the selection table from JSF.
No, you don't have to do that! There are several JSF datatable implementations which use AJAX partial submit, the datatable code already includes the logic you describe above. Your collection in page scope is extended with the new element without rerendering the whole list again.

Java server side form validation using DTO and hash map

I am developing an app using MVC pattern.
Controllers: servlets
Model: I am following DAO/DTO pattern for accessing database
View: simple JSP EL and JSTL
For accessing database I am using DAO pattern. I want to put validation method and a HashMap for error messages inside the DTO classes for validating FORM data, something similar to Putting validation method and hashmap into DTO.
My question is - this a right approach? If not what is an ideal way for doing this?
As a summary: I want to know real world solutions for server side form validation when we are using DAO/DTO pattern. Please help me.
I believe you need to treat separately the architecture you're implementing and the frameworks you're using to implement the architecture.
Java has a rich set of tools for working on the three standard tiers of your application and choices depend on some factors like expected load and server resources, if you have a two or three users application then it is just a matter of taste.
In terms of DAO/DTO then you have also some options, for example you can build your Data access layer with hibernate and then for your service layer API use DTO's. In this situation you probably want to use a tool for mapping between your domain model and your DTO's (for example jDTO Binder).
Another common approach is to use Spring JDBC Template, there you can go a little bit more crazy and use the same Domain objects as part of the Service layer API.
Finally, the truth is, you can do this by the book or you can do it completely different choice is based on your scenario, taste and experience.

The dangers of using AJAX as a front end for the website

We have Java EE backend for database access. Servlets ask for XML data and send XML response according to them. Now we have to write frontend for it. The idea is to communicate with backend through jQuery AJAX sending xml requests to Java backend and process data on client side.
Question is: Are there any security holes, and is it worth of writing frontend using Java/JSP?
Security hole can happen regardless of the technology you use. Both XML & Jquery & Ajax and Java & JSP can have security holes. You have to consider what information resides where, how would hacker hack your application etc.
It's far too general a question to answer, but when writing a client-side application you would typically need to put some consideration into:
ensuring that security controls such as input validation and authorisation checking are still performed correctly on the server side and not left to client-controlled JavaScript to sort out. You should not assume that an attacker cannot call an AJAX action just because the feature that does so is not visible in the UI; have a tester try to manually send AJAX requests for logged-in actions or actions on resources belonging to one user, when logged out or logged in as a different user.
ensuring that the client-side script doesn't have any HTML-injection holes resulting in XSS vulnerabilities. For example in jQuery use of html() (or the related append(), before() etc manipulation methods) with a string of markup that contains variables - use the $('<element>', {dynamic attributes}) creation shortcut instead. Similarly in plain JS prefer createElement/setAttribute to innerHTML.
ensuring that the client-side script doesn't have any JS-injection holes resulting in XSS vulnerabilities. Avoid setting strings for timeouts or inline event handlers; use function objects and proper event handling (eg jQuery .on()) instead.
When considering writing an application as client-side JS+AJAX instead of middle-tier HTML+forms, the question you have to ask is whether you can survive your app being unusable in user agents that don't support the JavaScript you require:
legacy browsers
new browsers hitting bugs you don't know about yet
crucially - search engines
if you're happy with that, and doing the additional work to make JS usable/accessible, then it can make sense.

Should I duplicate validation in my MVC layer and Service layer?

I'm feeling a little conflicted at the moment. I have a web application using Stripes for an MVC framework and Spring/Hibernate for the back-end. I have an account registration method in my MVC layer which requires the following validation:
Username is not already taken
The provided email address is not already associated with another account
I have a validation method in Stripes (MVC layer) that checks these two cases but was wondering whether my service layer should duplicate these checks? If the service layer interface was exposed as a web service then I think the validation would be a good idea, but if it's only used in the context of a web application is it required?
Edit: I'm not intending to duplicate the validation code - I mean duplicating the validation method calls in two places.
I see my options as:
Duplicate the validation calls in both MVC and service layer
Only perform this validation in the MVC layer
Only perform this validation in the service layer.
What's best practice here? I'm looking for advice/opinions on which option I should go with and why.
Note that there are simple validation checks on the input fields of the registration form (like checking for blanks) and that I think these should be handled by the MVC validation only; I'm only concerned about more complex validations.
Don't duplicate code. Use JSR303 Bean Validation so you can use the same validation logic in all layers of your app.
Hibernate Validator (a separate project from the Hibernate ORM stuff) provides the reference implementation of this interface. It is dead simple to use, you can get started with it very quickly.
In my opinion you should diferenciate two kinds of validations:
The Format data validation: Which should be validated in the presentation layer (MVC in your case). Normally both in the client and the server side
The Bussines data validation: Which should be validated in the service layer
In your case your validations are related to business rules, so I will put them only in the service layer.
In addition, if you duplicate your validations in both layers you will be making the same queries twice, slowing down the performance of your application.
Annie,
Good question, I have asked myself the same in many occasions. Here's what I ended up with (until now).
The purest (but tedious) approach is to invoke the validation logic in both layers.
the pragmatic approach could be to only invoke it in web-land (e.g. your controllers).
I think there is no answer that ends all discussion. I think that it depends on the context of your project. If the project-size is modest (in terms of people and size of codebase) and you are confident that not a whole lot of code will be developed by others that invoke your service API (to an extent that you will not be able to oversee), then doing the validation in the web-layer only may well suffice.
However, if you expect many clients you may need a higher-level security. When I say security here, I refer to it as the level of consistency-guarantees that you need.
If that level is high, there is no way around it: you will have to do it in both the service (for security) and the web layer (mostly to be able to provide end-users with an acceptable experience).
So the key driver here is security and how much of it you really need. If you need a lot, you go for the 'purist' approach. If your application doesn't exactly make decisions that concern matters of life and death, you go for the pragmatic approach.
Ideally, do the validation in both layers, since your service layer may be used with a client other than the current mvc layer
Reuse the validation mechanism at both places (Bean validation, for example)

Categories

Resources