I did some coding : converter, dropdown list, List, ...
I get a NullPointerException though I am sure that ALL USED OBJECT have been initialized.
Below are the new edited beens ans jsf (the converter is in the Fil_M_B bean and M_B stands for Managed Bean)
Could you please help me figure out whats going wrong now ?
Fil_M_B bean
#Named(value = "fil_M_B")
#SessionScoped
public class Fil_M_B implements Serializable {
#EJB
private FiliereFacadeLocal filiereFacade;
public FiliereFacadeLocal getFiliereFacade() {
return filiereFacade;
}
private List<Filiere> list_fil;
public List<Filiere> getList_fil() {
return list_fil;
}
#PostConstruct
public void list(){
list_fil = filiereFacade.findAll();
}
// NOW THE CONVERTER
#FacesConverter(forClass = Filiere.class)
public static class FiliereControllerConverter implements Converter {
#Override
public Object getAsObject(FacesContext facesContext, UIComponent component, String value) {
if (value == null || value.length() == 0) {
return null;
}
Fil_M_B controller = (Fil_M_B) facesContext.getApplication().getELResolver().
getValue(facesContext.getELContext(), null, "Fil_M_B");
return controller.filiereFacade.find(getKey(value));
}
java.lang.String getKey(String value) {
java.lang.String key;
key = value;
return key;
}
String getStringKey(java.lang.String value) {
StringBuilder sb = new StringBuilder();
sb.append(value);
return sb.toString();
}
#Override
public String getAsString(FacesContext facesContext, UIComponent component, Object object) {
if (object == null) {
return null;
}
if (object instanceof Filiere) {
Filiere o = (Filiere) object;
return getStringKey(o.getNomFiliere());
} else {
throw new IllegalArgumentException("object " + object + " is of type " + object.getClass().getName() + "; expected type: " + Filiere.class.getName());
}
}
}
/**
* Creates a new instance of Fil_M_B
*/
public Fil_M_B() {
}
Spec_M_B
#Named(value = "spec_M_B")
#SessionScoped
public class Spec_M_B implements Serializable{
#EJB
private SpecialiteFacadeLocal specialiteFacade;
Specialite spec = new Specialite();
public Specialite getSpec() {
return spec;
}
public void setSpec(Specialite spec) {
this.spec = spec;
}
public void ADD(){
specialiteFacade.create(spec);
}
/**
* Creates a new instance of Spec_M_B
*/
public Spec_M_B() {
}
}
Jsf page
<f:view>
<h:form>
<h:panelGrid columns="2">
<h:outputLabel value="Specialite" for="nomSpec" />
<h:inputText id="nomSpec" value="#{spec_M_B.spec.nomSpec}" title="Nom Specialite" required="true" requiredMessage="Required!"/>
<h:outputLabel value="Filiere" for="nomFiliere" />
<h:selectOneMenu id="nomFiliere" value="#{spec_M_B.spec.nomFiliere}" title="Nom Filiere" required="true" requiredMessage="Required !">
<f:selectItems value="#{fil_M_B.list_fil}"/>
</h:selectOneMenu>
</h:panelGrid>
<h:commandButton value="ADD" action="#{spec_M_B.ADD()}"/>
</h:form>
</f:view>
Could you please help me figure out whats going wrong ?
Stack trace Below is the stack trace I I see in my browser afetr clicking the ADD button
java.lang.NullPointerException
at TEST_3.Fil_M_B.access$000(Fil_M_B.java:27)
at TEST_3.Fil_M_B$FiliereControllerConverter.getAsObject(Fil_M_B.java:59)
at com.sun.faces.renderkit.html_basic.HtmlBasicInputRenderer.getConvertedValue(HtmlBasicInputRenderer.java:171)
at com.sun.faces.renderkit.html_basic.MenuRenderer.convertSelectOneValue(MenuRenderer.java:201)
at com.sun.faces.renderkit.html_basic.MenuRenderer.getConvertedValue(MenuRenderer.java:318)
at javax.faces.component.UIInput.getConvertedValue(UIInput.java:1045)
at javax.faces.component.UIInput.validate(UIInput.java:975)
at javax.faces.component.UIInput.executeValidate(UIInput.java:1248)
at javax.faces.component.UIInput.processValidators(UIInput.java:712)
at javax.faces.component.UIComponentBase.processValidators(UIComponentBase.java:1261)
at javax.faces.component.UIForm.processValidators(UIForm.java:253)
at javax.faces.component.UIComponentBase.processValidators(UIComponentBase.java:1261)
at javax.faces.component.UIComponentBase.processValidators(UIComponentBase.java:1261)
at javax.faces.component.UIViewRoot.processValidators(UIViewRoot.java:1195)
at com.sun.faces.lifecycle.ProcessValidationsPhase.execute(ProcessValidationsPhase.java:76)
at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)
at com.sun.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:198)
at javax.faces.webapp.FacesServlet.service(FacesServlet.java:658)
at org.apache.catalina.core.StandardWrapper.service(StandardWrapper.java:1682)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:318)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:160)
at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:734)
at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:673)
at com.sun.enterprise.web.WebPipeline.invoke(WebPipeline.java:99)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:174)
at org.apache.catalina.connector.CoyoteAdapter.doService(CoyoteAdapter.java:416)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:283)
at com.sun.enterprise.v3.services.impl.ContainerMapper$HttpHandlerCallable.call(ContainerMapper.java:459)
at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:167)
at org.glassfish.grizzly.http.server.HttpHandler.runService(HttpHandler.java:206)
at org.glassfish.grizzly.http.server.HttpHandler.doHandle(HttpHandler.java:180)
at org.glassfish.grizzly.http.server.HttpServerFilter.handleRead(HttpServerFilter.java:235)
at org.glassfish.grizzly.filterchain.ExecutorResolver$9.execute(ExecutorResolver.java:119)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeFilter(DefaultFilterChain.java:283)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeChainPart(DefaultFilterChain.java:200)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.execute(DefaultFilterChain.java:132)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.process(DefaultFilterChain.java:111)
at org.glassfish.grizzly.ProcessorExecutor.execute(ProcessorExecutor.java:77)
at org.glassfish.grizzly.nio.transport.TCPNIOTransport.fireIOEvent(TCPNIOTransport.java:536)
at org.glassfish.grizzly.strategies.AbstractIOStrategy.fireIOEvent(AbstractIOStrategy.java:112)
at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.run0(WorkerThreadIOStrategy.java:117)
at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.access$100(WorkerThreadIOStrategy.java:56)
at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy$WorkerThreadRunnable.run(WorkerThreadIOStrategy.java:137)
at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:591)
at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.run(AbstractThreadPool.java:571)
at java.lang.Thread.run(Thread.java:745)
Related
im new on java programing im trying to complete this methods where with an array of id , find the prices of the products and them i save it in the db.
Im having two errors:
1st the method obtenerPrecios don´t return the string with all the values in it ( the query doesnt work).
2nd the method confirmarVentadon´t go through array list and broke at the second element.
Here is my code, I will appreciate all the help.
package Controladores;
import Modelos.HibernateUtil;
import Modelos.Productos;
import Modelos.Venta;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Random;
import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
#Controller
#RequestMapping("/venta.htm")
public class CVentas {
#RequestMapping(method=RequestMethod.GET)
public ModelAndView getProduct (){
ModelAndView mv = new ModelAndView ("vVentas");
String out = "Productos";
try{
Session session=HibernateUtil.getSessionFactory().openSession();
session.beginTransaction();
List result = session.createQuery("from Productos").list();
mv.addObject("product", result);
session.getTransaction().commit();
session.close();
}catch(Exception e){
e.printStackTrace();
}
mv.addObject("message", out);
return mv;
}
private static java.sql.Date getCurrentDate() {
java.util.Date today = new java.util.Date();
return new java.sql.Date(today.getTime());
}
private Integer generarID(){
int x = new Random().nextInt(10 + 1);
int y = new Random().nextInt(7 + 1);
int z = new Random().nextInt(9 + 1);
int uniqueID =((x + y) *z) + x + y ;
return uniqueID;
}
private String obtenerPrecios (String ids) {
System.out.println("ids parametro: :" + ids);
try{
Session session=HibernateUtil.getSessionFactory().openSession();
session.beginTransaction();
List<String> listaIds = new ArrayList<String>();
System.out.println("ids lista: :" + listaIds);
listaIds = Arrays.asList(ids);
System.out.println("listaIds :" + listaIds);
List result = session.createQuery("SELECT p.precioUnidad FROM Productos p WHERE p.id IN (:ids)").setParameter("ids", listaIds).list();
session.getTransaction().commit();
session.close();
System.out.println("precios :" + result);
//listaIds.toString();
System.out.println("lista a string :" + result.toString());
return result.toString();
}catch(Exception e){
e.printStackTrace();
return "error";
}
}
#RequestMapping ( method = RequestMethod.POST )
public String confirmarVenta (#RequestParam(value = "check", required = true) String checkboxValores, Model model){
System.out.println(checkboxValores +": String con ids");
try{
Session session=HibernateUtil.getSessionFactory().openSession();
session.beginTransaction();
Venta vnt = new Venta();
Productos prdcts = new Productos();
int idVenta = generarID();
// List ids = Arrays.asList(checkboxValores);
System.out.println(checkboxValores +": Array con ids");
// List result = session.createQuery("from Productos where id=" + ids).list();
// System.out.println(result + "result");
for( int i=0; i < checkboxValores.length(); i++){
System.out.println("ids :" + checkboxValores );
int idP;
String precioQ;
idP = Character.getNumericValue(checkboxValores.charAt(i));
precioQ = obtenerPrecios (checkboxValores);
System.out.println(idP + ": id aguardar dentro del for");
vnt.setFechaVenta(getCurrentDate());
System.out.println(idVenta + ": id venta");
vnt.setIdVenta(idVenta);
System.out.println(precioQ.charAt(i) + ": precio");
vnt.setMonto(precioQ.charAt(i));
vnt.setIdProducto(idP);
//vnt.setIdUsuario(id); pasar por url el id del empleado y pasarlo como parametro.
session.save(vnt);
model.addAttribute(vnt);
session.getTransaction().commit();
}
session.close();
return "transicionVenta";
}catch(Exception e){
e.printStackTrace();
return"error";
}
}
}
And here i post the logs of the S.O.P:
Información: 2: id aguardar dentro del for
Información: 130: id venta
Información: e: precio
Información: ids :2,4
Información: ids parametro: :2,4
Información: ids lista: :[]
Información: listaIds :[2,4]
Grave: java.lang.ClassCastException: java.util.Arrays$ArrayList cannot be cast to java.lang.Integer
at org.hibernate.type.descriptor.java.IntegerTypeDescriptor.unwrap(IntegerTypeDescriptor.java:36)
at org.hibernate.type.descriptor.sql.IntegerTypeDescriptor$1.doBind(IntegerTypeDescriptor.java:64)
at org.hibernate.type.descriptor.sql.BasicBinder.bind(BasicBinder.java:90)
at org.hibernate.type.AbstractStandardBasicType.nullSafeSet(AbstractStandardBasicType.java:282)
at org.hibernate.type.AbstractStandardBasicType.nullSafeSet(AbstractStandardBasicType.java:277)
at org.hibernate.param.NamedParameterSpecification.bind(NamedParameterSpecification.java:67)
at org.hibernate.loader.hql.QueryLoader.bindParameterValues(QueryLoader.java:613)
at org.hibernate.loader.Loader.prepareQueryStatement(Loader.java:1900)
at org.hibernate.loader.Loader.executeQueryStatement(Loader.java:1861)
at org.hibernate.loader.Loader.executeQueryStatement(Loader.java:1838)
at org.hibernate.loader.Loader.doQuery(Loader.java:909)
at org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:354)
at org.hibernate.loader.Loader.doList(Loader.java:2551)
at org.hibernate.loader.Loader.doList(Loader.java:2537)
at org.hibernate.loader.Loader.listIgnoreQueryCache(Loader.java:2367)
at org.hibernate.loader.Loader.list(Loader.java:2362)
at org.hibernate.loader.hql.QueryLoader.list(QueryLoader.java:496)
at org.hibernate.hql.internal.ast.QueryTranslatorImpl.list(QueryTranslatorImpl.java:387)
at org.hibernate.engine.query.spi.HQLQueryPlan.performList(HQLQueryPlan.java:229)
at org.hibernate.internal.SessionImpl.list(SessionImpl.java:1260)
at org.hibernate.internal.QueryImpl.list(QueryImpl.java:103)
at Controladores.CVentas.obtenerPrecios(CVentas.java:83)
at Controladores.CVentas.confirmarVenta(CVentas.java:127)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.springframework.web.bind.annotation.support.HandlerMethodInvoker.invokeHandlerMethod(HandlerMethodInvoker.java:175)
at org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.invokeHandlerMethod(AnnotationMethodHandlerAdapter.java:446)
at org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.handle(AnnotationMethodHandlerAdapter.java:434)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:945)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:876)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:961)
at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:863)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:707)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:837)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:790)
at org.apache.catalina.core.StandardWrapper.service(StandardWrapper.java:1682)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:344)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:214)
at org.glassfish.tyrus.servlet.TyrusServletFilter.doFilter(TyrusServletFilter.java:305)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:256)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:214)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:316)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:160)
at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:734)
at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:673)
at com.sun.enterprise.web.WebPipeline.invoke(WebPipeline.java:99)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:174)
at org.apache.catalina.connector.CoyoteAdapter.doService(CoyoteAdapter.java:416)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:283)
at com.sun.enterprise.v3.services.impl.ContainerMapper$HttpHandlerCallable.call(ContainerMapper.java:459)
at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:167)
at org.glassfish.grizzly.http.server.HttpHandler.runService(HttpHandler.java:206)
at org.glassfish.grizzly.http.server.HttpHandler.doHandle(HttpHandler.java:180)
at org.glassfish.grizzly.http.server.HttpServerFilter.handleRead(HttpServerFilter.java:235)
at org.glassfish.grizzly.filterchain.ExecutorResolver$9.execute(ExecutorResolver.java:119)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeFilter(DefaultFilterChain.java:283)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeChainPart(DefaultFilterChain.java:200)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.execute(DefaultFilterChain.java:132)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.process(DefaultFilterChain.java:111)
at org.glassfish.grizzly.ProcessorExecutor.execute(ProcessorExecutor.java:77)
at org.glassfish.grizzly.nio.transport.TCPNIOTransport.fireIOEvent(TCPNIOTransport.java:536)
at org.glassfish.grizzly.strategies.AbstractIOStrategy.fireIOEvent(AbstractIOStrategy.java:112)
at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.run0(WorkerThreadIOStrategy.java:117)
at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.access$100(WorkerThreadIOStrategy.java:56)
at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy$WorkerThreadRunnable.run(WorkerThreadIOStrategy.java:137)
at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:591)
at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.run(AbstractThreadPool.java:571)
at java.lang.Thread.run(Thread.java:745)
Grave: org.hibernate.TransactionException: Transaction not successfully started
at org.hibernate.engine.transaction.spi.AbstractTransactionImpl.commit(AbstractTransactionImpl.java:172)
at Controladores.CVentas.confirmarVenta(CVentas.java:142)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.springframework.web.bind.annotation.support.HandlerMethodInvoker.invokeHandlerMethod(HandlerMethodInvoker.java:175)
at org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.invokeHandlerMethod(AnnotationMethodHandlerAdapter.java:446)
at org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.handle(AnnotationMethodHandlerAdapter.java:434)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:945)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:876)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:961)
at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:863)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:707)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:837)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:790)
at org.apache.catalina.core.StandardWrapper.service(StandardWrapper.java:1682)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:344)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:214)
at org.glassfish.tyrus.servlet.TyrusServletFilter.doFilter(TyrusServletFilter.java:305)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:256)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:214)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:316)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:160)
at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:734)
at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:673)
at com.sun.enterprise.web.WebPipeline.invoke(WebPipeline.java:99)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:174)
at org.apache.catalina.connector.CoyoteAdapter.doService(CoyoteAdapter.java:416)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:283)
at com.sun.enterprise.v3.services.impl.ContainerMapper$HttpHandlerCallable.call(ContainerMapper.java:459)
at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:167)
at org.glassfish.grizzly.http.server.HttpHandler.runService(HttpHandler.java:206)
at org.glassfish.grizzly.http.server.HttpHandler.doHandle(HttpHandler.java:180)
at org.glassfish.grizzly.http.server.HttpServerFilter.handleRead(HttpServerFilter.java:235)
at org.glassfish.grizzly.filterchain.ExecutorResolver$9.execute(ExecutorResolver.java:119)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeFilter(DefaultFilterChain.java:283)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeChainPart(DefaultFilterChain.java:200)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.execute(DefaultFilterChain.java:132)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.process(DefaultFilterChain.java:111)
at org.glassfish.grizzly.ProcessorExecutor.execute(ProcessorExecutor.java:77)
at org.glassfish.grizzly.nio.transport.TCPNIOTransport.fireIOEvent(TCPNIOTransport.java:536)
at org.glassfish.grizzly.strategies.AbstractIOStrategy.fireIOEvent(AbstractIOStrategy.java:112)
at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.run0(WorkerThreadIOStrategy.java:117)
at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.access$100(WorkerThreadIOStrategy.java:56)
at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy$WorkerThreadRunnable.run(WorkerThreadIOStrategy.java:137)
at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:591)
at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.run(AbstractThreadPool.java:571)
at java.lang.Thread.run(Thread.java:745)
Información: -1: id aguardar dentro del for
Información: 130: id venta
Información: r: precio
You pass identifiers as String. First, if you want to create a list of ids, you could do something like this:
List<String> idsList = Arrays.asList(ids.split(","));
And then you could convert the list of String to list of Integers:
List<Integer> iList = idsList.stream().map(Integer::valueOf).collect(Collectors.toList());
And pass to query as a parameter
you have to use SetParamtereList method , you see some detail in this link
https://stackoverflow.com/a/14296425/1838804
Please be patient as this is my first time learning about how to use web services.
I am trying to build a simple system that when given a parameter (String id), the web service returns a JSON object. I am somewhat following this codebase as a guide https://o7planning.org/en/11207/simple-crud-example-with-java-restful-web-service
Problem: When I run the service and go the URL http://localhost:8080/RESTfulServiceLIT_war_exploded/users/{id}, I receive a NullPointer exception in the glassfish log. It should simply display the JSON object relative to the user object returned from the id.
Here is the UserDAO class code
import java.util.*;
public class UserDAO {
private static final Map<String, User> userMap = new HashMap<String, User>();
static {
initUsers();
}
private static void initUsers() {
User u1 = new User("K1", "Student 1", "Student");
User u2 = new User("K2", "Student 2", "Student");
User u3 = new User("K3", "Student 3", "Student");
User u4 = new User("S1", "Staff 1", "Staff");
User u5 = new User("S2", "Staff 2", "Staff");
User u6 = new User("S3", "Staff 3", "Staff");
userMap.put(u1.getId(), u1);
userMap.put(u2.getId(), u2);
userMap.put(u3.getId(), u3);
userMap.put(u4.getId(), u4);
userMap.put(u5.getId(), u5);
userMap.put(u6.getId(), u6);
}
public static User getUser(String id) {
return userMap.get(id);
}
public static List<User> getAllUsers() {
Collection<User> c = userMap.values();
List<User> list = new ArrayList<User>();
list.addAll(c);
return list;
}
List<User> list;
}
Here is the Main class that has the rest service
import javax.print.attribute.standard.Media;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import java.util.ArrayList;
import java.util.List;
import javax.ws.rs.core.MediaType;
// The Java class will be hosted at the URI path "/helloworld"
#Path("/users")
public class Main {
#GET
#Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
#Path("/{id}")
public User getUser(#PathParam("id") String id) {
return UserDAO.getUser(id);
}
// #GET
// #Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
// #Path{"/all"}
// public List<User> getUsers_JSON(){
// List<User> listOfUsers = UserDAO.getAllUsers();
// return listOfUsers;
// }
}
Here is the server log
[2018-05-22T20:09:17.937+0100] [glassfish 4.1] [WARNING] [] [javax.enterprise.web] [tid: _ThreadID=35 _ThreadName=http-listener-1(3)] [timeMillis: 1527016157937] [levelValue: 900] [[
StandardWrapperValve[MyApplication]: Servlet.service() for servlet MyApplication threw exception
java.lang.NullPointerException
at org.eclipse.persistence.jaxb.rs.MOXyJsonProvider.writeTo(MOXyJsonProvider.java:944)
at org.glassfish.jersey.message.internal.WriterInterceptorExecutor$TerminalWriterInterceptor.invokeWriteTo(WriterInterceptorExecutor.java:265)
at org.glassfish.jersey.message.internal.WriterInterceptorExecutor$TerminalWriterInterceptor.aroundWriteTo(WriterInterceptorExecutor.java:250)
at org.glassfish.jersey.message.internal.WriterInterceptorExecutor.proceed(WriterInterceptorExecutor.java:162)
at org.glassfish.jersey.server.internal.JsonWithPaddingInterceptor.aroundWriteTo(JsonWithPaddingInterceptor.java:106)
at org.glassfish.jersey.message.internal.WriterInterceptorExecutor.proceed(WriterInterceptorExecutor.java:162)
at org.glassfish.jersey.server.internal.MappableExceptionWrapperInterceptor.aroundWriteTo(MappableExceptionWrapperInterceptor.java:86)
at org.glassfish.jersey.message.internal.WriterInterceptorExecutor.proceed(WriterInterceptorExecutor.java:162)
at org.glassfish.jersey.message.internal.MessageBodyFactory.writeTo(MessageBodyFactory.java:1130)
at org.glassfish.jersey.server.ServerRuntime$Responder.writeResponse(ServerRuntime.java:683)
at org.glassfish.jersey.server.ServerRuntime$Responder.processResponse(ServerRuntime.java:424)
at org.glassfish.jersey.server.ServerRuntime$Responder.process(ServerRuntime.java:414)
at org.glassfish.jersey.server.ServerRuntime$2.run(ServerRuntime.java:312)
at org.glassfish.jersey.internal.Errors$1.call(Errors.java:271)
at org.glassfish.jersey.internal.Errors$1.call(Errors.java:267)
at org.glassfish.jersey.internal.Errors.process(Errors.java:315)
at org.glassfish.jersey.internal.Errors.process(Errors.java:297)
at org.glassfish.jersey.internal.Errors.process(Errors.java:267)
at org.glassfish.jersey.process.internal.RequestScope.runInScope(RequestScope.java:317)
at org.glassfish.jersey.server.ServerRuntime.process(ServerRuntime.java:292)
at org.glassfish.jersey.server.ApplicationHandler.handle(ApplicationHandler.java:1139)
at org.glassfish.jersey.servlet.WebComponent.service(WebComponent.java:460)
at org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:386)
at org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:334)
at org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:221)
at org.apache.catalina.core.StandardWrapper.service(StandardWrapper.java:1682)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:318)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:160)
at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:734)
at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:673)
at com.sun.enterprise.web.WebPipeline.invoke(WebPipeline.java:99)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:174)
at org.apache.catalina.connector.CoyoteAdapter.doService(CoyoteAdapter.java:416)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:283)
at com.sun.enterprise.v3.services.impl.ContainerMapper$HttpHandlerCallable.call(ContainerMapper.java:459)
at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:167)
at org.glassfish.grizzly.http.server.HttpHandler.runService(HttpHandler.java:206)
at org.glassfish.grizzly.http.server.HttpHandler.doHandle(HttpHandler.java:180)
at org.glassfish.grizzly.http.server.HttpServerFilter.handleRead(HttpServerFilter.java:235)
at org.glassfish.grizzly.filterchain.ExecutorResolver$9.execute(ExecutorResolver.java:119)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeFilter(DefaultFilterChain.java:283)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeChainPart(DefaultFilterChain.java:200)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.execute(DefaultFilterChain.java:132)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.process(DefaultFilterChain.java:111)
at org.glassfish.grizzly.ProcessorExecutor.execute(ProcessorExecutor.java:77)
at org.glassfish.grizzly.nio.transport.TCPNIOTransport.fireIOEvent(TCPNIOTransport.java:536)
at org.glassfish.grizzly.strategies.AbstractIOStrategy.fireIOEvent(AbstractIOStrategy.java:112)
at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.run0(WorkerThreadIOStrategy.java:117)
at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.access$100(WorkerThreadIOStrategy.java:56)
at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy$WorkerThreadRunnable.run(WorkerThreadIOStrategy.java:137)
at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:591)
at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.run(AbstractThreadPool.java:571)
at java.lang.Thread.run(Thread.java:748)
]]
User class
public class User {
private String id;
private String name;
private String type;
User(){}
User(String id, String name, String type){
this.setId(id);
this.setName(name);
this.setType(type);
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
}
The URL:
http://localhost:8080/RESTfulServiceLIT_war_exploded/users/{id}
is a path specification used by Jersey to state how you can access data. If you simply typed that string into your web browser, then you will get a NullPointerException.
What happens when you type:
http://localhost:8080/RESTfulServiceLIT_war_exploded/users/K1
?
I resolved the same issue today. Issue came when you called bean method in rest api.
so create beans.xml file in WEB-INF folder
include the following
<?xml version="1.0" encoding="UTF-8"?>
<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_2_0.xsd"
bean-discovery-mode="all">
</beans>
I wanted to list all countries to fetch all the respective state and currency.
ConfFacade.java
public Result<List<Country>> listCountries() {
try {
String HQL = "SELECT DISTINCT o FROM Ocountry o LEFT JOIN FETCH o.ostate, o.ocurrency";
List<Country> list = em.createQuery(HQL).getResultList();
return new Result(Status.SUCCESS, list);
} catch(Exception e) {
e.printStackTrace();
return new Result<>(Status.ERROR, Exception.GENERAL, e.getMessage());
}
}
ConfFacadeLocal.java
public interface ConfFacadeLocal {
public Result<List<Country>> listCountries();
}
This is the jsp that I use and code it:
listCountries.jsp
<%
try {
InitialContext ctx = new InitialContext();
ConfFacadeLocal confFacadeLocal = (ConfFacadeLocal)ctx.lookup("java:comp/env/tomin");
Result<List<Country>> result = confFacadeLocal.listCountries();
if(result.isUnsuccessful()) {
throw new Exception(result.getErrMsg());
}
List<Country> countryList = result.getObject();
if(countryList == null) {
throw new Exception("Error.");
}
out.print("OK");
%>
<table border="1" align="center" style="width:50%">
<thead>
<tr>
<th>country code</th>
<th>currency code</th>
<th>state id</th>
<th>state description</th>
</tr>
</thead>
<tbody><%
for (Ocountry country : countryList){ %>
<tr>
<td><%=country.getOccode()%></td>
<td><%=country.getOcurrency().getOcucode()%></td>
<td><%=country.getOstate().getOsid()%></td>
<td><%=country.getOstate().getOsdesc()%></td>
</tr><%
}
} catch (Exception e) {
e.printStackTrace();
out.print("Error: " + e.getMessage());
} %>
</tbody>
</table>
Here is the error that I get:
cannot find symbol
symbol: method getOstate()
location: variable country of type com.ejb.entities.conf.Country
PWC6197: An error occurred at line: 42 in the jsp file: /country/listCountries.jsp
PWC6199: Generated servlet error:
cannot find symbol
symbol: method getOstate()
location: variable country of type com.ejb.entities.conf.Country
at org.apache.jasper.compiler.DefaultErrorHandler.javacError(DefaultErrorHandler.java:129)
at org.apache.jasper.compiler.ErrorDispatcher.javacError(ErrorDispatcher.java:299)
at org.apache.jasper.compiler.Compiler.generateClass(Compiler.java:392)
at org.apache.jasper.compiler.Compiler.compile(Compiler.java:453)
at org.apache.jasper.JspCompilationContext.compile(JspCompilationContext.java:625)
at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:375)
at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:473)
at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:377)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:790)
at org.apache.catalina.core.StandardWrapper.service(StandardWrapper.java:1682)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:318)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:160)
at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:734)
at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:673)
at com.sun.enterprise.web.WebPipeline.invoke(WebPipeline.java:99)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:174)
at org.apache.catalina.connector.CoyoteAdapter.doService(CoyoteAdapter.java:415)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:282)
at com.sun.enterprise.v3.services.impl.ContainerMapper$HttpHandlerCallable.call(ContainerMapper.java:459)
at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:167)
at org.glassfish.grizzly.http.server.HttpHandler.runService(HttpHandler.java:201)
at org.glassfish.grizzly.http.server.HttpHandler.doHandle(HttpHandler.java:175)
at org.glassfish.grizzly.http.server.HttpServerFilter.handleRead(HttpServerFilter.java:235)
at org.glassfish.grizzly.filterchain.ExecutorResolver$9.execute(ExecutorResolver.java:119)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeFilter(DefaultFilterChain.java:284)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeChainPart(DefaultFilterChain.java:201)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.execute(DefaultFilterChain.java:133)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.process(DefaultFilterChain.java:112)
at org.glassfish.grizzly.ProcessorExecutor.execute(ProcessorExecutor.java:77)
at org.glassfish.grizzly.nio.transport.TCPNIOTransport.fireIOEvent(TCPNIOTransport.java:561)
at org.glassfish.grizzly.strategies.AbstractIOStrategy.fireIOEvent(AbstractIOStrategy.java:112)
at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.run0(WorkerThreadIOStrategy.java:117)
at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.access$100(WorkerThreadIOStrategy.java:56)
at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy$WorkerThreadRunnable.run(WorkerThreadIOStrategy.java:137)
at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:565)
at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.run(AbstractThreadPool.java:545)
at java.lang.Thread.run(Thread.java:745)
Can anyone help to fix it?
From your JSP error logs, I guess you missed to declare the #listCountries method to the ConfFacadeLocal bean interface.
Adding the needed method declaration to the interface should resolve the issue:
public interface ConfFacadeLocal {
// other API methods ...
public Result<List<Country>> listCountries();
}
There (line 41):
<td><%=currency.getOcucode()%></td>
you are using the currency variable, which has not been declared.
It seems that currency is an attribute of the 'Country' class in you program, so maybe you should write instead
<td><%=country.getCurrency().getOcucode()%></td>
You have the same problem with the 'state' variable.
kindly help me out with this NullPointerException error i am getting while trying to use the remove(T entity) method in JPA
Here is my code
ControllerServlet
}else if (userPath.equals("/confirm_delete")){
String userid = request.getParameter("userToDelete");
int usrId = Integer.valueOf(userid);
SystemusersFacade usertoDelete = new SystemusersFacade();
Systemusers user = new Systemusers();
user = systemusersFacade.find(usrId);
usertoDelete.remove(user);
userPath ="/view_users";
SystemusersFacade extends AbstractFacade that contains the remove(T entity) method)
remove(T entity) method
public void remove(T entity) {
System.out.println(entity);
getEntityManager().remove(getEntityManager().merge(entity));
}
Below is the NullPointerException i am getting
Info: theBankingGuide was successfully deployed in 13,022 milliseconds.
Info: WebModule[null] ServletContext.log():ControllerServlet:
Info: entity.Systemusers[ userId=1 ]
Warning: StandardWrapperValve[ControllerServlet]: Servlet.service() for servlet ControllerServlet threw exception
java.lang.NullPointerException
at session.AbstractFacade.remove(AbstractFacade.java:35)
at controller.ControllerServlet.doPost(ControllerServlet.java:212)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:707)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:790)
at org.apache.catalina.core.StandardWrapper.service(StandardWrapper.java:1682)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:344)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:214)
at org.glassfish.tyrus.servlet.TyrusServletFilter.doFilter(TyrusServletFilter.java:295)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:256)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:214)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:316)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:160)
at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:734)
at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:673)
at com.sun.enterprise.web.WebPipeline.invoke(WebPipeline.java:99)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:174)
at org.apache.catalina.connector.CoyoteAdapter.doService(CoyoteAdapter.java:415)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:282)
at com.sun.enterprise.v3.services.impl.ContainerMapper$HttpHandlerCallable.call(ContainerMapper.java:459)
at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:167)
at org.glassfish.grizzly.http.server.HttpHandler.runService(HttpHandler.java:201)
at org.glassfish.grizzly.http.server.HttpHandler.doHandle(HttpHandler.java:175)
at org.glassfish.grizzly.http.server.HttpServerFilter.handleRead(HttpServerFilter.java:235)
at org.glassfish.grizzly.filterchain.ExecutorResolver$9.execute(ExecutorResolver.java:119)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeFilter(DefaultFilterChain.java:284)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeChainPart(DefaultFilterChain.java:201)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.execute(DefaultFilterChain.java:133)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.process(DefaultFilterChain.java:112)
at org.glassfish.grizzly.ProcessorExecutor.execute(ProcessorExecutor.java:77)
at org.glassfish.grizzly.nio.transport.TCPNIOTransport.fireIOEvent(TCPNIOTransport.java:561)
at org.glassfish.grizzly.strategies.AbstractIOStrategy.fireIOEvent(AbstractIOStrategy.java:112)
at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.run0(WorkerThreadIOStrategy.java:117)
at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.access$100(WorkerThreadIOStrategy.java:56)
at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy$WorkerThreadRunnable.run(WorkerThreadIOStrategy.java:137)
at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:565)
at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.run(AbstractThreadPool.java:545)
at java.lang.Thread.run(Thread.java:745)
I am sure that the entity is not passed as a null because when i use a System.out.Print, it gives me a value as you see in the log above
Info: entity.Systemusers[ userId=1 ]
I have also checked the debugger and the entity variable exits with the following parameters
entity Systemusers #1232
Static
_persistence_cacheKey HardCacheWeakIdentityMap$ReferenceCacheKey #1280
_persistence_fetchGroup null
_persistence_href null
_persistence_listener AttributeChangeListener #1281
_persistence_primaryKey Integer ObjectFieldVariable _persistence_primaryKey
_persistence_relationshipInfo null
_persistence_session null
_persistence_shouldRefreshFetchGroup boolean false
adsCollection IndirectList size = 0
mmtransinfoCollection IndirectList size = 0
securitiesinfoCollection IndirectList size = 0
systemUsersTime Date 02-Jan-2015 20:09:52
userEmail String jonahkayizzi#gmail.com
userId Integer 1
userName String "Jonah"
userPassword String "0xgl#kylZ"
userType String "Manager"
I also tried creating my custome delete function in the SystemusersFacade and i got the same error.
Please help out
EDIT
package session;
import entity.Systemusers;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
/**
*
* #author Jonah
*/
#Stateless
public class SystemusersFacade extends AbstractFacade<Systemusers> {
#PersistenceContext(unitName = "theBankingGuidePU")
private EntityManager em;
#Override
protected EntityManager getEntityManager() {
return em;
}
public SystemusersFacade() {
super(Systemusers.class);
}
}
package session;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.Query;
public abstract class AbstractFacade<T> {
private Class<T> entityClass;
public AbstractFacade(Class<T> entityClass) {
this.entityClass = entityClass;
}
protected abstract EntityManager getEntityManager();
public void remove(T entity) {
System.out.println(entity);
getEntityManager().remove(getEntityManager().merge(entity));
}
}
SystemusersFacade usertoDelete = new SystemusersFacade() is your problem (ignoring strange name, maybe a copy/paste error). Since you instantiate it using new, you are bypassing container management so the annotations are not processed. You need to inject the bean into the class that uses it. Use something like this
#EJB
private SystemusersFacade systemusersFacade;
...
String userid = request.getParameter("userToDelete");
int usrId = Integer.valueOf(userid);
Systemusers user = systemusersFacade.find(usrId);
systemusersFacade.remove(user);
This question already has answers here:
How to inject #EJB, #PersistenceContext, #Inject, #Autowired, etc in #FacesConverter?
(5 answers)
Closed 7 years ago.
I'm using netbean 7.0.1, glassfish 3.1, primefaces 2.2.1.
This is view
<ui:define name="content">
<h:form enctype="multipart/form-data">
<p:wizard>
<p:tab title="Tab 01">
<p:panel header="This is tab 01">
<h:messages errorStyle="color:red"/>
<h:panelGrid>
<h:selectOneMenu value="#{sellerController.currentCity}">
<f:selectItems value="#{cityController.listCity}" var="obj" itemLabel="#{obj.name}" itemValue="#{obj}"/>
</h:selectOneMenu>
</h:panelGrid>
</p:panel>
</p:tab>
<p:tab title="Tab 02">
<p:panel header="This is tab 02">
<h:panelGrid>
<p:commandButton value="Save" action="#{sellerController.addProperty()}"/>
</h:panelGrid>
</p:panel>
</p:tab>
</p:wizard>
</h:form>
</ui:define>
also try with
<h:selectOneMenu value="#{sellerController.currentCity}">
<f:selectItems value="#{cityController.itemsAvailableSelectOne}"/>
</h:selectOneMenu>
When i click next button on tab 01 and save button on tab 02, sellerController.currentCity return null value. Save button still call : "addProperty()". I got this error
INFO: java.lang.NullPointerException
java.lang.NullPointerException
at my.controller.CityController$CityControllerConverter.getAsObject(CityController.java:67)
at com.sun.faces.renderkit.html_basic.HtmlBasicInputRenderer.getConvertedValue(HtmlBasicInputRenderer.java:171)
at com.sun.faces.renderkit.html_basic.MenuRenderer.convertSelectOneValue(MenuRenderer.java:202)
at com.sun.faces.renderkit.html_basic.MenuRenderer.getConvertedValue(MenuRenderer.java:319)
at javax.faces.component.UIInput.getConvertedValue(UIInput.java:1030)
at javax.faces.component.UIInput.validate(UIInput.java:960)
at javax.faces.component.UIInput.executeValidate(UIInput.java:1233)
at javax.faces.component.UIInput.processValidators(UIInput.java:698)
at javax.faces.component.UIComponentBase.processValidators(UIComponentBase.java:1214)
at javax.faces.component.UIComponentBase.processValidators(UIComponentBase.java:1214)
at javax.faces.component.UIComponentBase.processValidators(UIComponentBase.java:1214)
at org.primefaces.component.wizard.Wizard.processValidators(Wizard.java:216)
at com.sun.faces.context.PartialViewContextImpl$PhaseAwareVisitCallback.visit(PartialViewContextImpl.java:508)
at com.sun.faces.component.visit.PartialVisitContext.invokeVisitCallback(PartialVisitContext.java:183)
at javax.faces.component.UIComponent.visitTree(UIComponent.java:1589)
at javax.faces.component.UIComponent.visitTree(UIComponent.java:1600)
at javax.faces.component.UIForm.visitTree(UIForm.java:344)
at javax.faces.component.UIComponent.visitTree(UIComponent.java:1600)
at javax.faces.component.UIComponent.visitTree(UIComponent.java:1600)
at com.sun.faces.context.PartialViewContextImpl.processComponents(PartialViewContextImpl.java:376)
at com.sun.faces.context.PartialViewContextImpl.processPartial(PartialViewContextImpl.java:252)
at javax.faces.context.PartialViewContextWrapper.processPartial(PartialViewContextWrapper.java:183)
at javax.faces.component.UIViewRoot.processValidators(UIViewRoot.java:1170)
at com.sun.faces.lifecycle.ProcessValidationsPhase.execute(ProcessValidationsPhase.java:76)
at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)
at com.sun.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:118)
at javax.faces.webapp.FacesServlet.service(FacesServlet.java:593)
at org.apache.catalina.core.StandardWrapper.service(StandardWrapper.java:1539)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:343)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:217)
at org.primefaces.webapp.filter.FileUploadFilter.doFilter(FileUploadFilter.java:79)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:256)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:217)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:279)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:175)
at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:655)
at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:595)
at com.sun.enterprise.web.WebPipeline.invoke(WebPipeline.java:98)
at com.sun.enterprise.web.PESessionLockingStandardPipeline.invoke(PESessionLockingStandardPipeline.java:91)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:162)
at org.apache.catalina.connector.CoyoteAdapter.doService(CoyoteAdapter.java:330)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:231)
at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:174)
at com.sun.grizzly.http.ProcessorTask.invokeAdapter(ProcessorTask.java:828)
at com.sun.grizzly.http.ProcessorTask.doProcess(ProcessorTask.java:725)
at com.sun.grizzly.http.ProcessorTask.process(ProcessorTask.java:1019)
at com.sun.grizzly.http.DefaultProtocolFilter.execute(DefaultProtocolFilter.java:225)
at com.sun.grizzly.DefaultProtocolChain.executeProtocolFilter(DefaultProtocolChain.java:137)
at com.sun.grizzly.DefaultProtocolChain.execute(DefaultProtocolChain.java:104)
at com.sun.grizzly.DefaultProtocolChain.execute(DefaultProtocolChain.java:90)
at com.sun.grizzly.http.HttpProtocolChain.execute(HttpProtocolChain.java:79)
at com.sun.grizzly.ProtocolChainContextTask.doCall(ProtocolChainContextTask.java:54)
at com.sun.grizzly.SelectionKeyContextTask.call(SelectionKeyContextTask.java:59)
at com.sun.grizzly.ContextTask.run(ContextTask.java:71)
at com.sun.grizzly.util.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:532)
at com.sun.grizzly.util.AbstractThreadPool$Worker.run(AbstractThreadPool.java:513)
at java.lang.Thread.run(Thread.java:662)
i have two controller, this is CityController :
#Named(value = "cityController")
#SessionScoped
public class CityController implements Serializable {
#EJB
CityModel cityModel;
List<City> listCity;
/** Creates a new instance of CityController */
public CityController() {
}
public List<City> getListCity(){
if (listCity==null) {
listCity = new ArrayList<City>();
listCity = cityModel.findAll();
}
return listCity;
}
public SelectItem[] getItemsAvailableSelectMany() {
return JsfUtil.getSelectItems(cityModel.findAll(), false);
}
public SelectItem[] getItemsAvailableSelectOne() {
return JsfUtil.getSelectItems(cityModel.findAll(), true);
}
#FacesConverter(forClass = City.class)
public static class CityControllerConverter implements Converter {
#Override
public Object getAsObject(FacesContext facesContext, UIComponent component, String value) {
if (value == null || value.length() == 0) {
return "";
}
CityController controller = (CityController) facesContext.getApplication().getELResolver().
getValue(facesContext.getELContext(), null, "customerController");
return controller.cityModel.find(getKey(value));
}
java.lang.Integer getKey(String value) {
java.lang.Integer key;
key = Integer.valueOf(value);
return key;
}
String getStringKey(java.lang.Integer value) {
StringBuffer sb = new StringBuffer();
sb.append(value);
return sb.toString();
}
#Override
public String getAsString(FacesContext facesContext, UIComponent component, Object object) {
if (object == null) {
return null;
}
if (object instanceof City) {
City o = (City) object;
return getStringKey(o.getId());
} else {
throw new IllegalArgumentException("object " + object + " is of type " + object.getClass().getName() + "; expected type: " + CityController.class.getName());
}
}
}
}
This is SellerController
#Named(value = "sellerController")
#SessionScoped
public class SellerController implements Serializable {
#EJB
CityModel cityModel;
private City currentCity;
/** Creates a new instance of SellerController */
public SellerController() {
}
public City getCurrentCity() {
if (currentCity==null) {
currentCity = new City();
}
return currentCity;
}
public void setCurrentCity(City currentCity) {
this.currentCity = currentCity;
}
public void addProperty(){
System.out.println("Call from Save button ?? ");
}
}
This is JsfUtil class
public class JsfUtil {
public static SelectItem[] getSelectItems(List<?> entities, boolean selectOne) {
int size = selectOne ? entities.size() + 1 : entities.size();
SelectItem[] items = new SelectItem[size];
int i = 0;
if (selectOne) {
items[0] = new SelectItem("", "---");
i++;
}
for (Object x : entities) {
items[i++] = new SelectItem(x, x.toString());
}
return items;
}
}
Because of CityController. when i use
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
#ManagedBean(name = "cityController")
#SessionScoped
It's work !
Considering this "cityController"-
#Named(value = "cityController")
#SessionScoped
public class CityController implements Serializable {
Is "customerController" right in the following -
CityController controller = (CityController) facesContext.getApplication().getELResolver().getValue(facesContext.getELContext(), null, "customerController");
Change it to "cityController" as follows -
FacesContext fc = FacesContext.getCurrentInstance();
ELResolver elr = fc.getApplication().getELResolver();
ELContext elc = fc.getELContext();
CityController cc = (CityController) elr.getValue(elc, null, "cityController");
I think your cityModel is NULL. Is your EJB injection configured right?