Looking for method argument validation framework based on AOP and annotations [closed] - java

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.
Closed 7 years ago.
Improve this question
I'm looking for argument validation framework which:
1) Allows specifying argument constraints via annontations (like OVal, JaValid)
2) Validation code automatically injected (during compilation or runtime) into methods (i.e. no explicit call to Validator object is required)
Example of what i'm looking for:
public class Person {
private String name;
....
//Method which arguments should be validated
public void setName(#NotBlank String name){
//<---validating code should be injected here
this.name = name;
}
}
//Example of call to the validated method
...
Person person = new Person();
person.setName("John");
...
Example of code i'm trying to avoid
...
Validator validator = new Validator(...);//glue code
Person person = new Person();
person.setName("John");
validator.validate(person);//glue code
...
Thanks for answers!

I think you meant "automatically injected during compilation or runtime", right?
I had the same problem. My solution was Spring Validation and self-written AOP layer (about three classes).
My validation code looks like this:
#Validational( validators =
{"com.mycompany.MyValidator"} )
public void myMethod( String paramToValidate )

Related

Should client pull full object information or field only when required from REST? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 1 year ago.
Improve this question
Current I has the below server scenario
---------------------------------------------------------Redis Cache
Client <--(Low Latency/instantly)--> REST API <----+
---------------------------------------------------------Database
Dude to the low latency between client and api i decided to do the cache at api side
which also mean the client will not be caching
then I start to think about the question
Assume I have a Person class which contains name and money field that I have in my client
and the API support fetching all Person's information at once with api.com/person
or fetching Person's information one by one with api.com/person?fields=name and api.com/person?fields=money
should i request all of the information when the object is being created like this
Class Person {
String name;
int money;
public Person() {
JsonObject data = getJsonData(`api.com/person`);
this.name = data.get('name');
this.name = data.get('money');
}
public String getName() {
return name;
}
public int getMoney() {
return money;
}
}
in this case, if the client only require Name of Person, but the object also pull the money from
server which is wasted for traffic or etc.
or, i can replace the getName() function be like this
public String getName() {
JsonObject data = getJsonData(`api.com/person?fields=name`);
return data.get('name');
}
which does not waste any fields
but the downside is, when client require both Name and Money field
it would then double up the request required
I dont know which one is better for my case, any further explain are very welcome too.
You could use a builder pattern to build person object by building proper url for fetching one or more fields in a single api hit. e.g.
new PersonBuilder().addName().build(); // url attribute of PersonBuilder in this case should be "api.com/person?fields=name"
or
new PersonBuilder().addName().addMoney().build(); // url attribute of PersonBuilder in this case should be "api.com/person?fields=name,money"
in build() method, you could call different setter methods based on what you added using addName(), addMoney() by maintaining different booleans in PersonBuilder corresponding to each field e.g. nameAdded = true, moneyAdded =false.
This way you will never need to hit the api multiple times.

How to get Spring bean by name [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
How can I get the bean by passing only the class name using BeanFactoryUtils
I'm trying below, but this is not working
import org.springframework.beans.factory.BeanFactoryUtils;
baseDao= BeanFactoryUtils.originalBeanName("RegionDaoImpl");
RegionDao
#Component
public class RegionDaoImpl implements BaseDao<Region> {
...
}
Any suggestions?
You need a ListableBeanFactory, then you call beanOfType(), e.g.:
RegionDaoImpl dao = BeanFactoryUtils.beanOfType(beanFactory, RegionDaoImpl.class);
Generally, the ListableBeanFactory will be an ApplicationContext, so you need the application context of your Spring application. How to get that depends on your application type, and where the code calling beanOfType() is located.
It is usually better to let Spring auto-wire the object into your class, which does the same thing, i.e. lookup the bean by type.
#Component
public class SomeComponent {
#Autowire
private RegionDaoImpl regionDao;
...
}
If you want to lookup by name, you'd call beanFactory.getBean(), but that seems kind of redundant:
RegionDaoImpl dao = beanFactory.getBean("RegionDaoImpl", RegionDaoImpl.class);

How jsp can access getters and setters in superclass, Spring MVC [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
Using spring MVC
I have some class with property, and getter\setter to get access to this property
class a{
private String something;
public void setSomething(String something){
this.something = something;}
public String getSomething(){
return something;
}
And I have subclass with some new property, getter and setter in it
class b extends a{
private String newProp;
public void setNewProp(String newProp){
this.newProp = newProp;}
public String getNewProp(){
return newProp;
}
When I trying to get property value in jsp, that defined in superclass like this
${b-inst.something}
I've got "is not readable or had invalid getter" error
Is it possible to get access to that superclass property without changing this property to protected, and writing it's getter\setter in subclass(because I'm losing inheritance benefits in that way)?
You should use correct case for the property: userName instead of username (just like your firstName and lastName properties)

Spring validation don't follow the POJO principle [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I've read this guide: http://spring.io/guides/gs/validating-form-input/
I see that the spring's approach of validating a form is to annotate the
properties of a object (which can be a POJO), with validation constraints
like #Min, #Max, #Size, etc..
This is not the best approach to mess-up POJO objects with this
annotations.
How do you write your code for validation a form in spring framework?
Spring offers a design for validation (and data binding) that does not exclude either one of them. Spring features a Validator interface that you can use to validate objects.
The Validator interface works using an Errors object so that while validating, validators can report validation failures to the Errors object.
Person POJO:
public class Person {
private String name;
private int age;
// the usual getters and setters...
}
Implementing a Validator:
public class PersonValidator implements Validator {
/**
* This Validator validates just Person instances
*/
public boolean supports(Class clazz) {
return Person.class.equals(clazz);
}
public void validate(Object obj, Errors e) {
ValidationUtils.rejectIfEmpty(e, "name", "name.empty");
Person p = (Person) obj;
if (p.getAge() 110) {
e.rejectValue("age", "too.darn.old");
}
}
}
Documentaction about Validation, Data Binding in Spring Framework 3.x
There is definitely some debate about whether or not you should use annotations on the POJO or not.
My personal opinion is that if you are not going to be sharing the POJO between modules, annotation configuration is perfectly acceptable.
If you want the validation constrains to be configured without annotations, you should look at Hibernate Validator's (Hibernate Validator is the reference implementation of this JSR 349) XML configuration. The reference for that configuration is here.
Also check out this (somewhat older) post for a tutorial.

How to implement pagination in Spring MVC 3 [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.
Closed 5 years ago.
Improve this question
Is there any out-of-the-box, easy to implement, standard pagination component/tag-lib or code-sample available for pagination in Spring MVC?
Have a look at PagedListHolder and other classes from org.springframework.beans.support.
See the JPetstore in the samples for some examples, e.g. in SearchProductsController.java:
public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception {
String keyword = request.getParameter("keyword");
if (keyword != null) {
if (!StringUtils.hasLength(keyword)) {
return new ModelAndView("Error", "message", "Please enter a keyword to search for, then press the search button.");
}
PagedListHolder productList = new PagedListHolder(this.petStore.searchProductList(keyword.toLowerCase()));
productList.setPageSize(4);
request.getSession().setAttribute("SearchProductsController_productList", productList);
return new ModelAndView("SearchProducts", "productList", productList);
}
else {
String page = request.getParameter("page");
PagedListHolder productList = (PagedListHolder) request.getSession().getAttribute("SearchProductsController_productList");
if (productList == null) {
return new ModelAndView("Error", "message", "Your session has timed out. Please start over again.");
}
if ("next".equals(page)) {
productList.nextPage();
}
else if ("previous".equals(page)) {
productList.previousPage();
}
return new ModelAndView("SearchProducts", "productList", productList);
}
}
I was looking for a way to do that, too, but didn't find any standard component or taglib. I think mainly because paging can become very specific since you need to retrieve your data with paging from the database already (if you are using Hibernate you can easily do that using the Criteria API). I came up with something like this:
public class Pager
{
private int page;
private int results;
private String sortOrder;
private String sortColumn;
// Getters and setters
}
#Controller
public class StuffController
{
#Autowired SomeEntityService someEntityService;
#RequestMapping("/test.html", method = Method.GET)
public void getStuffPaged(#RequestParam("id") String id, Pager pager, ModelMap mm)
{
mm.addAttribute("entities", someEntityService.get(id, pager));
}
}
If you now perform a request to http://domain/app/test.html?id=10&page=1&results=30&sortOrder=asc you will get the pager Object in your request.
Have you ever heard about the Spring Data JPA project? There is a nice flexible solution using the Pagable interface. I've found it to be the simplest way to achieve clean, boilerplate-free pagination. Check out more at the Spring Data JPA homepage.
No one comes to mind and Google also doesn't reveal any specific components for that (although it gives pretty much concrete examples and hints). But in theory just a bunch of buttons and one (or two) request parameters are more than sufficient. Then let the SQL/DB do its work. I've posted an answer to similar question in JSP/Servlet/DAO context before here.
It basically boils down to pass firstrow (index of first row to be displayed in a page) around as request parameter and having two buttons/links in the pagination form which in/decrements the firstrow with rowcount (amount of rows displayed at once in a page) in combination with a SQL query which returns a subset of the results with help of under each LIMIT, OFFSET clauses, or subselects, or specific functions, depending on the DB in question. See the aforelinked answer for detailed code examples and SQL queries.
Here's a link to the Spring Data JPA reference docs, where they have a very clean approach to web pagination.
I published an open source java library focused on pagination with spring framework some time ago.
Although it has not been very successful perhaps someone may be interested in trying it.
There are examples for using it with
Swing
DisplayTag
YUI Datatable
Vaadin
The online examples are somewhat obsolete, better download the jdal-samples file from sourceforge.

Categories