Why is JSF applying the Bean Validation of a shadowed private field? - jsf

I have encountered some surprising behaviour in Hibernate Validator and JSF. I would like to know whether the behaviour is a bug, or a misunderstanding in my own expectations.
I have this Facelets page:
<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html">
<h:body>
<h:form>
<h:inputText value="#{backingBean.someClass.someField}"/>
<h:commandButton value="submit" action="#{backingBean.submit1()}"/>
</h:form>
</h:body>
</html>
And I have this backing bean:
import java.util.Set;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;
import org.hibernate.validator.constraints.NotEmpty;
#ManagedBean
#RequestScoped
public class BackingBean {
private SomeClass someClass = new SomeSubClass();
public SomeClass getSomeClass() {
return someClass;
}
public void setSomeClass(SomeClass someClass) {
this.someClass = someClass;
}
public void submit1() {
System.out.println("BackingBean: " + someClass.getSomeField());
((SomeSubClass) someClass).submit2();
}
public static class SomeClass {
private String someField;
public String getSomeField() {
return someField;
}
public void setSomeField(String someField) {
this.someField = someField;
}
}
public static class SomeSubClass extends SomeClass {
#NotEmpty
private String someField;
private void submit2() {
System.out.println("SomeSubClass: " + someField);
}
}
public static void main(String[] args) {
ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
Validator validator = factory.getValidator();
SomeClass someClass = new SomeSubClass();
someClass.setSomeField("ham");
Set<ConstraintViolation<SomeClass>> errors = validator.validate(someClass);
for (ConstraintViolation<SomeClass> error : errors) {
System.out.println(error);
}
}
}
Note that SomeSubClass.someField has the same name as a private variable in the parent class. This should not matter because you cannot shadow a private field.
Two things to note:
If you run the main method in BackingBean, the validator will always return a validation error (message "may not be empty") because SomeSubClass.someField is always null. This behaviour seems correct to me.
If you submit the form with a blank value, you will receive a "may not be empty" error message; if you enter a value, it will pass validation, but you will see in the console that the value of SomeSubClass.someField is still null. This behaviour seems incorrect to me.
If you change the name of SomeSubClass.someField to someField2, you may submit the form with an empty value. This behaviour seems incorrect to me.
It appears that the JSF's Validation Phase and Hibernate Validator disagree on this behaviour. JSF is applying the #NotEmpty validator of a private field in a subclass to a field of the same name in the parent class, but Hibernate Validator does not show this behaviour when tested in isolation.
Can anyone explain this behaviour? Is it a bug, or a misunderstanding in my own expectations?
Using:
GlassFish Server Open Source Edition 3.1.2.2
Mojarra 2.1.6
Hibernate Validator 4.3.0.Final

JSF uses EL to get/set model values conform Javabean rules. EL uses reflection to inspect and invoke public getters and setters. In other words, #{backingBean.someClass.someField} actually uses getSomeField() and setSomeField() to get/set the model/submitted value. The field being manipulated is then actually the one in SomeClass.
Bean Validation uses reflection to inspect fields and ignores the presence of public getters/setters. In other words, BV of #{backingBean.someClass.someField} actually takes place on SomeSubClass.
This explains everything. But I agree that this is confusing and appears "incorrect". It'll work as expected when you also override the getter and setter in SomeSubClass.
public static class SomeSubClass extends SomeClass {
#NotEmpty
private String someField;
private void submit2() {
System.out.println("SomeSubClass: " + someField);
}
#Override
public String getSomeField() {
return someField;
}
#Override
public void setSomeField(String someField) {
this.someField = someField;
}
}
This way EL will see it and use that as model value.
This is however awkward (an #Override which merely calls super will flip static code style analysis tools like Sonar, PMD, Findbugs, etc). A better alternative is to move #NotEmpty to an overridden getter:
public static class SomeSubClass extends SomeClass {
private void submit2() {
System.out.println("SomeSubClass: " + getSomeField());
}
#Override
#NotEmpty
public String getSomeField() {
return super.getSomeField();
}
}
BV also supports this construct, so it'll stay working.

Related

JSF in combination with Bean Validation: ConstraintViolationException

I try to use JSF in combination with Bean Validation. Basically, everything works well, the validation works as expected, I get the correct message, but there is an exception on my Glassfish console:
Warnung: EJB5184:A system exception occurred during an invocation on EJB MyEntityFacade, method: public void com.mycompany.testbv.AbstractFacade.create(java.lang.Object)
Warnung: javax.ejb.EJBException
at com.sun.ejb.containers.EJBContainerTransactionManager.processSystemException(EJBContainerTransactionManager.java:748)
....
....
at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.run(AbstractThreadPool.java:544)
at java.lang.Thread.run(Thread.java:744)
Caused by: javax.validation.ConstraintViolationException: Bean Validation constraint(s) violated while executing Automatic Bean Validation on callback event:'prePersist'. Please refer to embedded ConstraintViolations for details.
This exception occurs if I use custom constraints as well as predefined constraints.
Here is my sample code.
Sample Entity:
#Entity
#ValidEntity
public class MyEntity implements Serializable {
private static final long serialVersionUID = 3104398374500914142L;
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
#Size(min = 2)
private String name;
public MyEntity(String name) {
this.name = name;
}
public MyEntity() {
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
Custom constraint:
#Constraint(validatedBy = MyValidator.class)
#Target({FIELD, METHOD, TYPE})
#Retention(RUNTIME)
public #interface ValidEntity {
String message() default "fail";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
}
Custom validator:
public class MyValidator implements ConstraintValidator<ValidEntity, MyEntity>{
#Override
public void initialize(ValidEntity a) {
}
#Override
public boolean isValid(MyEntity t, ConstraintValidatorContext cvc) {
return false;
}
}
Sample Controller:
#Named
#SessionScoped
public class MyController implements Serializable {
private static final long serialVersionUID = -6739023629679382999L;
#Inject
MyEntityFacade myEntityFacade;
String text;
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
public void saveNewEntity() {
try {
myEntityFacade.create(new MyEntity(text));
} catch (Exception e) {
Throwable t = e;
while (t != null) {
if (t instanceof ConstraintViolationException) {
FacesContext context = FacesContext.getCurrentInstance();
Set<ConstraintViolation<?>> constraintViolations = ((ConstraintViolationException) t).getConstraintViolations();
for (ConstraintViolation<?> constraintViolation : constraintViolations) {
FacesMessage facesMessage = new FacesMessage(constraintViolation.getMessage());
facesMessage.setSeverity(FacesMessage.SEVERITY_ERROR);
context.addMessage(null, facesMessage);
}
}
t = t.getCause();
}
}
}
}
Sample jsf page:
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://xmlns.jcp.org/jsf/html">
<h:head></h:head>
<h:body>
<h:form>
<h:messages id="messages" />
<h:inputText value="#{myController.text}" />
<h:commandButton value="Save" action="#{myController.saveNewEntity()}" />
</h:form>
</h:body>
</html>
The MyEntityFacade only calls persist from entity manager.
As mentioned before, the application is running fine and the correct messages are shwon, but I want to avoid this exception in the Glassfish console.
Setting the validation mode in persistence.xml to NONE as discussed here is no option, because I want a validation.
I use JSF in version 2.2, the implementation is Mojarra. The version of Bean Validation is 1.1, the implementation is Hibernate Validator.
Application Server is Glassfish 4.0.
Class-level constraints do not work with JSF. Take a look at this answer. When you press the 'Save' button JSF checks only if name has at least 2 chars and does not take into account the ValidEntity constraint. JPA, on the other hand, complains that the bean is not valid and throws an exception.
UPDATE
1) the #Size constraint is on MyEntity.name property while in the facelet you have MyController.text property. In the JSF perspective there is nothing to validate. It has no knowledge of the MyEntity at all.
2) ValidEntity is always invalid, so JPA will always throw the exception (unless you disable validation) even if you properly set the MyEntity.name in the facelet.

Custom component inside <ui:repeat> doesn't find iterated item during encode

I'm trying to create a custom component for displaying an Entity with a certain form. So I've created my #FacesComponent and he's working but only when he is not inside a loop like <ui:repeat>. When I'm using the following code, my component is displaying null values for price and photo but not for name. Do you have an explaination ?
XHTML code :
<ui:define name="content">
<f:view>
<h:form>
<ui:repeat value="#{dataManagedBean.listNewestCocktails}" var="item" varStatus="status">
<h:outputText value="#{item.price}"/> <!--working very well-->
<t:cocktailVignette idPrefix="newCocktails" name="foo" price="#{item.price}" urlPhoto="#{item.photoURI}"/> <!-- not working the getPrice here -->
</ui:repeat>
<!--<t:cocktailVignette idPrefix="allCocktails" name="OSEF" price="20" urlPhoto="osefdelurl" ></t:cocktailVignette> -->
</h:form>
</f:view>
My component code :
package component;
import java.io.IOException;
import javax.faces.context.FacesContext;
import javax.faces.component.FacesComponent;
import javax.faces.component.UIComponentBase;
import javax.faces.context.ResponseWriter;
#FacesComponent(value = "CocktailVignette")
public class CocktailVignette extends UIComponentBase {
private String idPrefix;
private String name;
private String price;
private String urlPhoto;
public String getIdPrefix() {
return idPrefix;
}
public void setIdPrefix(String idPrefix) {
this.idPrefix = idPrefix;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPrice() {
return price;
}
public void setPrice(String price) {
this.price = price;
}
public String getUrlPhoto() {
return urlPhoto;
}
public void setUrlPhoto(String urlPhoto) {
this.urlPhoto = urlPhoto;
}
#Override
public String getFamily() {
return "CocktailVignette";
}
#Override
public void encodeBegin(FacesContext context) throws IOException {
ResponseWriter writer = context.getResponseWriter();
writer.write("<div id=\""+idPrefix+name+"\" class=\"cocktail-vignette\">");
writer.write("<h2>"+name+"</h2>");
writer.write("<h3>"+price+"</h3>");
writer.write("</div>");
}
}
Thanks a lot :) I'm trying but nothing is working ...
All of component's attributes which are sensitive to changes in state (e.g. the value being dependent on <ui:repeat var>, at least those which is not known during view build time but during view render time only), must delegate the storage of attribute value to the state helper as available by inherited getStateHelper() method.
Kickoff example:
public String getPrice() {
return (String) getStateHelper().eval("price");
}
public void setPrice(String price) {
getStateHelper().put("price", price);
}
Apply the same for all other attributes and get rid of the instance variable declarations. Important note is that the state helper key ("price" in above example) must be exactly the same as attribute name.
See also:
How to save state when extending UIComponentBase

ManagedProperty not injected in #FacesConverter

I'm trying to inject a ManagedBean in my FacesConverted the following way:
#ManagedBean
#RequestScoped
#FacesConverter(forClass = Group.class)
public class GroupConverter implements Converter {
#ManagedProperty("#{groupService}")
private GroupService groupService;
#Override
public Group getAsObject(FacesContext context, UIComponent arg1,
String groupName) {
return groupService.findGroupByName(groupName);
}
#Override
public String getAsString(FacesContext arg0, UIComponent arg1, Object group) {
return ((Group) group).getName();
}
public GroupService getGroupService() {
return groupService;
}
public void setGroupService(GroupService groupService) {
this.groupService = groupService;
}
}
The problem is that groupService isn't being injected and I get a NullPointerEx. Shouldn't it be autowired automatically since it's also a ManagedBean? It all works when I change "getAsObject" to "return new Group();" obviously.
Any ideas?
It is likely that you are not resolving the managed bean name.
#ManagedBean(name = "myConverter")
#RequestScoped
#FacesConverter(value = "myConverter")
public class MyConverter implements Converter {
For example, consider these two components:
<h:inputText converter="myConverter" value="#{foo.prop}" />
<h:inputText converter="#{myConverter}" value="#{bar.prop}" />
When the converter is set on the first component, it will be created by Application.createConverter. A converter is not a managed bean. The same rules apply if you match a converter by type.
In the second component, a value expression is used to return a class that implements Converter. This uses the usual managed bean mechanisms. In this case, the #FacesConverter annotation is irrelevant.

#ManagedProperty - Inject one request scoped bean into another request scoped bean

I have this SearchBean:
#ManagedBean(name = "searchBean")
#RequestScoped
public class SearchBean implements Serializable
{
private String input = null;
// getter methods
public String getInput() {
return input;
}
// setter method
public void setInput(String input) {
this.input = input;
}
public String Submit() {
return null;
}
}
Can I inject it into another bean using #ManagedProperty. For example:
#ManagedBean(name = "bookBean")
#RequestScoped
public class BookBean implements Serializable
{
#ManagedProperty(value = "#{searchBean}")
private SearchBean searchBean;
#PostConstruct
public void init()
{
System.out.println("Value: " + searchBean.getInput());
}
public SearchBean getSearchBean() {
return searchBean;
}
public void setSearchBean(SearchBean searchBean) {
this.searchBean = searchBean;
}
}
And the Facelet (search.xhtml):
<h:form id="formSearch">
<h:commandButton value="Search" action="#{searchBean.Submit}" />
</h:form>
UPDATE: I have search.xhtml inserted into book.xhtml via a ui:insert component as follow:
<h:form id="formBooks">
<ui:insert name="search">
<ui:include src="/templates/common/search.xhtml"/>
</ui:insert>
</h:form>
The searchBean.getInput() method above should return a value as a result of a form's submission. Is the above method of injection possible?
I assume that SearchBean.input will be bound to an input field:
public class SearchBean implements Serializable {
private String input = null;
Something like this:
<h:inputText value="#{searchBean.input}" />
If so, then this will be null:
#PostConstruct
public void init()
{
System.out.println("Value: " + searchBean.getInput());
}
But, assuming a value has been set, it will not be null when this method is invoked:
public String Submit() {
return null;
}
Image from Richard Hightower's JSF for nonbelievers: The JSF application lifecycle.
The reason is due to how the JSF lifecycle works:
When #{searchBean...} is first resolved and found not to exist:
The bean is instantiated
Any dependency injections are performed (there aren't any in this case)
#PostConstruct method is invoked
The bean is placed into scope
Assuming the Apply Request Values and Validations phases succeed, SearchBean.setInput(String) is invoked in the Update Model Values phase
SearchBean.Submit() is invoked in the Invoke Application phase
This process is defined in the JSF specification.
Now, if SearchBean.input were injected directly from the parameter map, it would not be null during #PostConstruct:
#ManagedProperty(value = "#{param.someParamName}")
private String input;
However, there aren't any real advantages to this - you're skipping any input validation and you can't use SearchBean.input as a field binding because it will be overwritten in the Update Model Values phase.
The SearchBean.Submit() method is where your application logic for performing the search should go.

Executing the ActionListener of a (Primefaces) menu item leads to an IllegalStateException

In JSF backed bean I got an IllegalStateException when the programmatically added action listener of a programmatically added Primefaces menu item is called. I tried both request and session scope but both are leading to the same error. Obviously there's need -- according to the stack trace -- to restore the view when an action listener is executed and I let my ToolbarBean implement Serializable with no different effect. What should I consider in order to get this to work?
User interface definition
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:p="http://primefaces.prime.com.tr/ui">
<h:head>
<title>TITLE</title>
</h:head>
<h:body>
<h:form>
<p:menu model="#{toolbarBean.model}" type="tiered" />
</h:form>
</h:body>
</html>
Backed bean providing the menu
#Named
#Scope("request")
public class ToolbarBean implements Serializable {
private static final long serialVersionUID = -8556751897482662530L;
public ToolbarBean() {
model = new DefaultMenuModel();
MenuItem item;
// Direct menu item
item = new MenuItem();
item.setValue("Menuitem 1");
item.addActionListener(new ActionListener() {
#Override
public void processAction(ActionEvent event)
throws AbortProcessingException {
System.out.println(event.toString());
}
});
model.addMenuItem(item);
item = new MenuItem();
item.setValue("Menuitem 2");
item.addActionListener(new ActionListener() {
#Override
public void processAction(ActionEvent event)
throws AbortProcessingException {
System.out.println(event.toString());
}
});
model.addMenuItem(item);
}
private MenuModel model;
public MenuModel getModel() {
return model;
}
}
Exception when clicking one of the menu buttons
javax.faces.FacesException: java.lang.IllegalStateException: java.lang.InstantiationException: id.co.sofcograha.baseui.ToolbarBean$1
at javax.faces.component.UIComponent.invokeOnComponent(UIComponent.java:1284)
at javax.faces.component.UIComponentBase.invokeOnComponent(UIComponentBase.java:673)
at javax.faces.component.UIComponent.invokeOnComponent(UIComponent.java:1290)
at javax.faces.component.UIComponentBase.invokeOnComponent(UIComponentBase.java:673)
at javax.faces.component.UIComponent.invokeOnComponent(UIComponent.java:1290)
at javax.faces.component.UIComponentBase.invokeOnComponent(UIComponentBase.java:673)
at javax.faces.component.UIComponent.invokeOnComponent(UIComponent.java:1290)
at javax.faces.component.UIComponentBase.invokeOnComponent(UIComponentBase.java:673)
at com.sun.faces.application.view.StateManagementStrategyImpl.restoreView(StateManagementStrategyImpl.java:297)
at com.sun.faces.application.StateManagerImpl.restoreView(StateManagerImpl.java:177)
at com.sun.faces.application.view.ViewHandlingStrategy.restoreView(ViewHandlingStrategy.java:119)
at com.sun.faces.application.view.FaceletViewHandlingStrategy.restoreView(FaceletViewHandlingStrategy.java:438)
at com.sun.faces.application.view.MultiViewHandler.restoreView(MultiViewHandler.java:144)
at javax.faces.application.ViewHandlerWrapper.restoreView(ViewHandlerWrapper.java:284)
at com.sun.faces.lifecycle.RestoreViewPhase.execute(RestoreViewPhase.java:182)
at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:97)
at com.sun.faces.lifecycle.RestoreViewPhase.doPhase(RestoreViewPhase.java:107)
at com.sun.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:114)
at javax.faces.webapp.FacesServlet.service(FacesServlet.java:308)
EL (read: reflection) cannot access/construct anonymous classes. Refactor them into fullworthy classes.
So, replace
item.addActionListener(new ActionListener() {
#Override
public void processAction(ActionEvent event)
throws AbortProcessingException {
System.out.println(event.toString());
}
});
by
item.addActionListener(new FooActionListener());
and
public class FooActionListener implements ActionListener {
#Override
public void processAction(ActionEvent event)
throws AbortProcessingException {
System.out.println(event.toString());
}
}
See also:
How to invoke a JSF action on an anonymous class?
It looks like an additional restriction is that the ActionListener class have no contructor arguments, which kind of adds insult to injury here. As far as I can see the addActionListener probably just stores the class name of the object passed to it.
In fact if the intent was to make this listener unusable by preventing any data being passed to the listener from your backing bean they could hardly have done more.
You get another IllegalStateException if you try subclassing MenuItem.
You can't pass an object containing data to MenuItem as a value, it requires a String.
It doesn't seem to allow the listener as an inner class.
But I think I may have cracked it, by putting the needed data in the attributes map of the menu item.
Here's what I wound up with:
public class MenuSelectListener implements ActionListener {
public static final String MENU_ACTION_KEY = "menu.action.delegate";
private final static Log log = LogFactory.getLog(MenuSelectListener.class);
#Override
public void processAction(ActionEvent ae) throws AbortProcessingException {
System.out.println("listener invoked");
if (ae.getComponent() instanceof MenuItem) {
Runnable delegate = (Runnable) ae.getComponent().getAttributes().get(MENU_ACTION_KEY);
if(delegate != null)
delegate.run();
else
log.error("Menu action has no runnable");
} else {
log.error("Listener, wrong component class: " + ae.getComponent().getClass().getName());
}
}
}
To set up an item:-
item.setValue("Cancel");
sm.getChildren().add(item);
item.addActionListener(new MenuSelectListener());
item.getAttributes().put(MenuSelectListener.MENU_ACTION_KEY, new MiscActionDelegate(MiscActions.close));
With:
private class MiscActionDelegate implements Runnable, Serializable {
(works as an inner class, but cannot be anonymous).

Resources