Use EntityManager in Validator [duplicate] - jsf

How can I inject a dependency like #EJB, #PersistenceContext, #Inject, #AutoWired, etc in a #FacesValidator? In my specific case I need to inject a Spring managed bean via #AutoWired:
#FacesValidator("emailExistValidator")
public class EmailExistValidator implements Validator {
#Autowired
private UserDao userDao;
// ...
}
However, it didn't get injected and it remains null, resulting in java.lang.NullPointerException.
It seems that #EJB, #PersistenceContext and #Inject also doesn't work.
How do I inject a service dependency in my validator so that I can access the DB?

JSF 2.3+
If you're already on JSF 2.3 or newer, and want to inject CDI-supported artifacts via e.g. #EJB, #PersistenceContext or #Inject, then simply add managed=true to the #FacesValidator annotation to make it CDI-managed.
#FacesValidator(value="emailExistValidator", managed=true)
JSF 2.2-
If you're not on JSF 2.3 or newer yet, then you basically need to make it a managed bean. Use Spring's #Component, CDI's #Named or JSF's #ManagedBean instead of #FacesValidator in order to make it a managed bean and thus eligible for dependency injection.
E.g., assuming that you want to use CDI's #Named:
#Named
#ApplicationScoped
public class EmailExistValidator implements Validator {
// ...
}
You also need to reference it as a managed bean by #{name} in EL instead of as a validator ID in hardcoded string. Thus, so
<h:inputText ... validator="#{emailExistValidator.validate}" />
instead of
<h:inputText ... validator="emailExistValidator" />
or
<f:validator binding="#{emailExistValidator}" />
instead of
<f:validator validatorId="emailExistValidator" />
For EJBs there's a workaround by manually grabbing it from JNDI, see also Getting an #EJB in #FacesConverter and #FacesValidator.
If you happen to use JSF utility library OmniFaces, since version 1.6 it adds transparent support for using #Inject and #EJB in a #FacesValidator class without any additional configuration or annotations. See also the CDI #FacesValidator showcase example.
See also:
CDI Injection into a FacesConverter
What's new in JSF 2.2 - Injection

You can now inject into JSF validators if you're using Java EE 8 and/or JSF 2.3.
Tested using Mojarra 2.3.9.payara-p2 on Payara Server 5.192 #badassfish.
<?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://xmlns.jcp.org/jsf/html">
<h:body>
Hello from Facelets
<h:form>
<h:messages/>
<h:inputText value="#{someBean.txtField}" validator="someValidator"/>
</h:form>
</h:body>
</html>
import javax.inject.Named;
import javax.enterprise.context.Dependent;
#Named(value = "someBean")
#Dependent
public class SomeBean {
private String txtField;
public String getTxtField() {
return txtField;
}
public void setTxtField(String txtField) {
this.txtField = txtField;
}
}
import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.validator.FacesValidator;
import javax.faces.validator.Validator;
import javax.faces.validator.ValidatorException;
import javax.inject.Inject;
#FacesValidator(value = "someValidator", managed = true)
public class CustomValidator implements Validator<String> {
#Inject
NewClass newClass;
#Override
public void validate(FacesContext context, UIComponent component, String value)
throws ValidatorException {
System.out.println("validator running");
System.out.println("injected bean: " + newClass);
if (value != null && value.equals("badvalue")) {
throw new ValidatorException(new FacesMessage(newClass.getMessage()));
}
}
}
public class NewClass {
public String getMessage() {
return "secret message";
}
}
import javax.faces.annotation.FacesConfig;
// WITHOUT THIS INJECTION WILL NOT WORK!
#FacesConfig(version = FacesConfig.Version.JSF_2_3)
public class ConfigurationBean {
}
Should render something like:
I banged my head on the wall for about an hour before realizing the need for ConfigurationBean. From the documentation:
FacesConfig.Version.JSF_2_3
This value indicates CDI should be used for EL resolution as well as enabling JSF CDI injection, as specified in Section 5.6.3 "CDI for EL Resolution" and Section 5.9 "CDI Integration"
And from this GitHub issue, https://github.com/eclipse-ee4j/glassfish/issues/22094:
By default, JSF 2.3 runs in a compatibility mode with previous releases of JSF, unless a CDI managed bean is included in the application with the annotation #javax.faces.annotation.FacesConfig. To switch into a JSF 2.3 mode you will need a configuration bean like below: (shows ConfigurationBean)
...
The fact that JSF needs to be switched into the "current version" was highly controversial. Pretty much the entire EG voted against that, but eventually we could not get around the backwards compatibility requirements that the JCP sets for Java EE and the spec lead enforces.

Related

Is it possible to inject a bean to phaselistener when using JSF 2.3, tomcat with weld cdi implementation?

I want to inject a #SessionScoped and a #RequestScoped beans into my PhaseListener implementation, but I got NullPointerException.
I use tomcat with weld implementation to achieve CDI. I started to migrate JSF 2.2 to 2.3, so I changed to CDI from FacesContext.
Well I replaced #ManagedBean to #Named and any other things to must do during migration like:
- add beans XML to every modules
- add BeanManager to context XML
- delete bean declarations from faces-config.xml
- add SPI BeanManager as resource-env-ref to web.xml
How can I inject any bean to PhaseListener implementations?
#Named
#SessionScoped
public class MyHandler implements Serializable {
..}
#Named
#RequestScoped
public class MyController extends MyParentController<Example> {
..}
public class MyPhaseListener implements PhaseListener {
private MyHandler myHandler;
private MyController myController;
#Inject
public void setMyHandler(MyHandler myHandler) {
this.myHandler= myHandler;
}
#Inject
public void setMyController (MyController myController) {
this.myController= myController;
}
...
public void afterPhase(PhaseEvent event) {
myHandler.method()
}
myHandler injected bean is null in afterPhase method.
I put CDI configuration file beans.xml into folder META-INF instead of WEB-INF
In beans.xml I had to change bean-discovery-mode from "annotated" to "all".
I forgot to add a class with #FacesConfig(version = Version.JSF_2_3) annotation( to enable EL resolution for CDI beans).
Also forgot to change faces-config.xml version to 2.3
Fortunately I solved the problem... A few things I had to do:
I put beans.xml into META-INF/, but beans.xml has to be under
WEB-INF.
In beans.xml I had to change bean-discovery-mode from "annotated" to
"all".
I forgot to add a class with #FacesConfig(version = Version.JSF_2_3)
annotation( to enable EL resolution for CDI beans).
Also forgot to change faces-config.xml version to 2.3.

Instance null after injecting #SessionScoped CDI bean into a JSF #ManagedBean

I have :
- Repository Class:
#SessionScoped
public class EmployeeRepository {
#PersistenceContext
EntityManager entityManager;
public List<Employee> getEmployees(){
TypedQuery<Employee> qu = entityManager.createQuery("select * from Employee", Employee.class);
List<Employee> emp2 = qu.getResultList();
return emp2;
}
}
and
Managed Bean:
#ManagedBean(name = "helloWorldBean")
public class HelloWorldBean {
#Inject
private EmployeeRepository employeerepo;
public String getMsg() {
return "Hallo";
}
public String getEmployees() {
return String.valueOf(employeerepo.getEmployees().size());
}
}
and a JSF Page:
<h:head>
<title>JavaCodeGeeks</title>
</h:head>
<h:body>
- Message : <h:outputText value="#{helloWorldBean.msg}" />
- Employee count : <h:outputText value="#{helloWorldBean.employees}" />
</h:body>
</html>
I have an beans.xml in my META-INF Folder (src\META-INF) without special configurations:
<?xml version="1.0"?>
<beans xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/beans_1_1.xsd"
bean-discovery-mode="all" version="1.1">
</beans>
Problem:
Page throws nullpointer exception, because the EmployeeRepository is not injected in the HelloWorldBean.
What to do to be able to inject Instances of classes in my case ?
As you are using CDI, you should not be using #ManagedBean (which is a JSF annotation). While I have actually seen this working, most implementations will not allow you to inject a CDI bean into a classic JSF bean.
To allow for CDI injection in JSF beans, the CDI specification allows you to define JSF backing beans by specifying the #Named annotation in combination with a scope (#RequestScoped, #javax.faces.view.ViewScoped, #SessionScoped and #ApplicationScoped).
So in summary, the following piece of code should solve your problem,
#Named
#RequestScoped
public class HelloWorldBean {
#Inject
private EmployeeRepository employeerepo;
public String getMsg() {
return "Hallo";
}
public String getEmployees() {
return String.valueOf(employeerepo.getEmployees().size());
}
}
You can also read up further on the topic via some old Q/A's here on the site,
How to inject a CDI Bean in a ManagedBean?
#ManagedProperty does not work in a CDI managed bean
CDI beans injection

JSF access private/protected property of a super class

I am very new to JSF and this is the first project I work on (got a bit too lazy with jsp) so please forgive me if the question is trivial.
So I have a Super Class Device
#Entity
#Table(name = "Devices")
public class Device
{
protected bool Authorized
public bool isAuthorized()
{ return this.Authorized;}
public void setAuthorized(bool Authorized)
{ this.Authorized = Authorized;}
}
and a sub class SensorDevice that extends the Super Class Device
public class SensorDevice extends Device
{
// has its own properties which dont matter
}
and a Managed Bean UIDeviceManager
#ManagedBean(name = "DeviceManager")
#SessionScoped
public class UIDeviceManager
{
private List<SensorDevice> Pending;
// in constructor, Pending List gets populated with the devices requiring Authorization
}
and an xhtml page which contains a Table for the Pending Devices
<p:dataTable var="device" value="#{DeviceManager.pending}">
<p:column headerText="Device Authorization">
<h:form>
<p:inputSwitch
value="#{device.isAuthorized()}"
binding="#{AuthorizationInputSwitch}"
offLabel="UnAuthorized"
onLabel="Authorized">
<p:ajax
event="change"
listener="#{device.setAuthorized(AuthorizationInputSwitch.value)}" />
</p:inputSwitch>
</h:form>
</p:column>
Now unless the syntax in the xhtml is completely messed up (I tried my best there and would appreciate guidance), the function setAuthorized for that particular device instance should be called (even with the wrong input, but will sort that later by modifying the setter function), but that doesnt happen, the Ajax doesnt get called. Instead, the inputSwitch tries to update its "value property source" and attempts to look for a property isAuthorized() in the class SensorDevice which it fails to find.
Now I am aware that this could be easily solved by making the Boolean Authorized public in the super class but as you can see it is also a JPA entity that is persisted in a database to keep track of the devices, so the only option is to keep it protected.
So how do I update parameters of a Super class from a sub-class instance in a Managed Bean from a public function rather than direct access to the parameter itself (I thought JSF looked for the setters and getters but whatever)
Btw value="#{device.isAuthorized()}"works correctly but if I try the property directly it fails ( I guess its obvious at this point )
One last thing, if the approach/architecture is wrong, please advise on what is the correct layout to achieve this functionality. I am sure there is a standard way to integrate JSF and JPA without duplicating entities and wrappers
I think you must use field name in value attribute of InputSwitch component like this:
<p:inputSwitch
value="#{device.authorized}"
binding="#{AuthorizationInputSwitch}"
offLabel="UnAuthorized"
onLabel="Authorized">
Instead of:
<p:inputSwitch
value="#{device.isAuthorized()}"
binding="#{AuthorizationInputSwitch}"
offLabel="UnAuthorized"
onLabel="Authorized">
JSF will use isAuthorized and setAuthorized method (uses Java Beans standard convention to recognize getter and setter methods)
So i think you don't need the ajax part to call setter method.
To emphasize Mojtaba's answer, this is how you access properties in JSF:
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:head>
<title>Facelet Title</title>
</h:head>
<h:body>
<h:outputText value="#{myBean.entity.someBool}"/>
</h:body>
</html>
Managed bean:
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
#ManagedBean
#SessionScoped
public class MyBean {
private SomeEntity entity = new SomeEntity();
public SomeEntity getEntity() {
return entity;
}
}
Entity classes:
public class SomeEntity extends SomeParent {
}
public class SomeParent {
private boolean someBool = true;
public boolean isSomeBool() {
return someBool;
}
public void setSomeBool(boolean someBool) {
this.someBool = someBool;
}
}
JSF doesn't know or care that your objects are JPA entities, and standard inheritance and access rules apply.
See also
JavaBean conventions

How to inject a CDI Bean in a ManagedBean?

I want to inject a CDI Bean in a ManagedBean either with the annotation #Inject or #Produce. The CDI Bean which I use is:
#Named
#Startup
#ApplicationScoped
public class BaseBean {
private List<String> custs;
public List<String> getCusts() {
return custs;
}
public void setCusts(List<String> emps) {
this.custs = emps;
}
public BaseBean(){
}
#PostConstruct
void init() {
custs = new ArrayList<String>();
custs.add("Cust1");
custs.add("Cust3");
custs.add("Cust2");
custs.add("Cust4");
}
}
The ManagedBean, in which I want to inject the CDI Bean is:
#SessionScoped
#ManagedBean
public class Hello implements Serializable {
#Inject
private BaseBean dBean;
private static final long serialVersionUID = 1L;
private List<String> customers;
private List<String> customersSelect;
public Hello() {
}
#PostConstruct
void init() {
// dBean = new BaseBean();
customers = dBean.getCusts();
}
public List<String> getCustomers() {
return customers;
}
public List<String> getCustomersSelect() {
return customersSelect;
}
public void setCustomersSelect(List<String> customersSelect) {
this.customersSelect = customersSelect;
}
}
In the init function however, it throws NullPointerException. If I use the annotation #Produces instead of #Inject, the result is the same: NullPointerException. Is anything wrong with the CDI Bean (improper annotations)? Do I try to inject it with a wrong way? Does my code lack of something? How can I get it work? Here is the JSF code:
<h:form id ="f">
<h:selectManyCheckbox layout="pageDirection" border="1" value="#{hello.customersSelect}">
<f:selectItems value="#{hello.customers}"></f:selectItems>
</h:selectManyCheckbox><br />
<h:commandButton action="response.xhtml" value="Click me" />
</h:form>
PS: If I use a Stateless Bean as BaseBean and I inject it with the annotation #EJB, it works with no problem.
UPDATE: I have tried it with the annotations #SessionScoped (javax.enterprise.context.SessionScoped) and #Named on the Hello class. Although I do not receive a NullPointerException, the h:selectManyCheckbox is empty. moreover, it strikes me, that when I add the beans.xml file under META-INF folder, I receive a StartException, although the file is there supposed to be. I think my application lacks the proper configuration to be capable of Dependency Injection. What is likely to need additional configuration?
UPDATE 2: This error appears when I add the beans.xml file in the WEB-INF folder. The beans.xml file is empty, it contains only the line :
<?xml version="1.0" encoding="UTF-8"?>
The error is:
Services which failed to start: service jboss.deployment.unit."JSF1.war".PARSE: org.jboss.msc.service.StartException in service jboss.deployment.unit."JSF1.war".PARSE: Failed to process phase PARSE of deployment "JSF1.war"
12:51:11,482 ERROR [org.jboss.as.server.deployment.scanner] (DeploymentScanner-threads - 1) {"JBAS014653: Composite operation failed and was rolled back. Steps that failed:" => {"Operation step-2" => {"JBAS014671: Failed services" => {"jboss.deployment.unit.\"JSF1.war\".PARSE" => "org.jboss.msc.service.StartException in service jboss.deployment.unit.\"JSF1.war\".PARSE: Failed to process phase PARSE of deployment \"JSF1.war\""}}}}
What #patlov is suggesting will work if you use #Named on your CDI beans. However, if you're working in an environment that supports CDI, do not use #ManagedBean. Instead, use CDI all the way. See this answer and I'm sure you could find numerous other ones that strongly advise against what you're trying to do.
Just switch from javax.faces.bean.SessionScoped to javax.enterprise.context.SessionScoped and everything will magically work. What you may run into is the absense of #ViewScoped from CDI however, in which case use something like JBoss Seam or Apache Deltaspike that implement it for you. As an added benefit, they will also automatically replace all of the JSF scopes with CDI scopes automatically if you already have existing code written for JSF.
Update:
This should be the content of your beans.xml:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/beans_1_0.xsd">
</beans>
Make sure you have enabled CDI by putting a WEB-INF/beans.xml file in your application.
If you are using #ManagedBean use #ManagedProperty to inject properties:
#ManagedProperty(value = "#{baseBean}")
private BaseBean dBean;
// getter and setter

CDI interface-based bean in JSF

I'm having troubles working with CDI in JSF project. I cannot force CDI to inject interface-based bean into JSF file.
#Named
public class ClassBasedNamedBean {
public String getMessage() {
return "Class-based Hello World!";
}
}
#Named
public interface InterfaceBasedNamedBean {
public String getMessage();
}
public class InterfaceBasedNamedBeanImpl implements InterfaceBasedNamedBean {
#Override
public String getMessage() {
return "Interface-based Hello World!";
}
}
I can use both beans in WebServlet environment:
#WebServlet("/HelloServlet")
public class HelloServlet extends HttpServlet {
#Inject
private ClassBasedNamedBean classBasedNamedBean;
#Inject
private InterfaceBasedNamedBean interfaceBasedNamedBean;
protected void doGet(...) ... {
PrintWriter pw = response.getWriter();
pw.println("classBasedNamedBean: " + classBasedNamedBean.getMessage());
pw.println("interfaceBasedNamedBean: " + interfaceBasedNamedBean.getMessage());
// Output:
// classBasedNamedBean: Class-based Hello World!
// interfaceBasedNamedBean: Interface-based Hello World!
}
}
But interfaceBasedNamedBean is not available in JSF page:
<p>ClassBasedNamedBean: #{classBasedNamedBean.message}</p>
<p>InterfaceBasedNamedBean: #{interfaceBasedNamedBean.message}</p>
Output:
<p>ClassBasedNamedBean: Class-based Hello World!</p>
<p>InterfaceBasedNamedBean: </p>
How could I fix this issue? Does JSF require some explicit configuration for interfaceBasedNamedBean?
As my best guess:
I don't think that this is mentioned in the spec, but I'm pretty sure that #Named is not intended to be used on interfaces.
After all, it's just a matching between a type and an EL-name - and it seems as if the EL resolver can't find anything (concrete) under the name of the interface.
So, try annotating the implementation, not the interface - this should work. If you need to be flexible with various implementations of the same bean type - inject it in a controller bean and make that bean accessible.
You set javax.enterprise.inject.spi.BeanManager as your BeanManager?
What happens if you add #Named("InterfaceBasedNamedBean") to your Class Definition and remove the annotation from the interface? For what reason are you using the annotations anyways? CDI is not requiring them in contrast to spring.
Have you tried using a producer method?
Try adding scope to your bean with #RequestScoped, for example. From Weld docs:
The #Named annotation is not what makes the class a bean. Most classes in a bean archive are already recognized as beans. The #Named annotation just makes it possible to reference the bean from the EL, most commonly from a JSF view.
CDI defines #Named as a String-based qualifier. A qualifier's purpose is to distinguish which implementation to use at the injection point. The #Named's javadoc gives an example:
public class Car {
#Inject #Named("driver") Seat driverSeat;
#Inject #Named("passenger") Seat passengerSeat;
...
}
Thus #Named must annotate a specific implementation.
#Named as a way to use CDI beans in JSF views can be seen as a secondary function. #Named is not "#Inject for JSF" as it may seem to be.

Resources