One thing standing out is, you are not using container-managed
persistence context. It could've caused interference between different
contexts. I suggest change to use a consistent, container-managed
persistence context by using injection or lookup.
-cheng
On 4/8/11 3:17 PM, Jose Alvarez de Lara wrote:
> Hi,
> I am trying a web app that implements some EJB 3.1 calling showing the
> results in JSP files.
> And I am finding a strange issue that is some times the EJBs return a
> result set and other times
> return an EJBException. To call the EJBs I use a controller Servlet
> that dispatches to the JSP files.
> Here is the code of the EJBs,
> @Stateless
> @LocalBean
> public class CallStoredProcedure implements java.io.Serializable {
>
> private static final long serialVersionUID = 1L;
>
> /**
> * Default constructor.
> */
> public CallStoredProcedure() {
> // TODO Auto-generated constructor stub
> }
>
> @SuppressWarnings("unchecked")
> public List<Country> getCountriesSP(BigDecimal region)
> throws Exception {
> final Logger logger = Logger.getLogger("CallStoredProcedure");
>
> EntityManagerFactory emf =
> Persistence.createEntityManagerFactory("JPACallingOracleStoredProcedure-jpa");
> EntityManager em = emf.createEntityManager();
> try {
> EntityTransaction entr = em.getTransaction();
> entr.begin();
> JpaEntityManager jpaEntityManager = JpaHelper.getEntityManager(em);
> Session session = jpaEntityManager.getActiveSession();
> StoredProcedureCall call = new StoredProcedureCall();
> call.setProcedureName("HR.RECORD_SET.COUNTRIES_LIST");
> call.addNamedArgumentValue("P_REGION", region);
> call.useNamedCursorOutputAsResultSet("P_RESULTSET");
>
>
> ObjectLevelReadQuery query = new ReadAllQuery(Country.class);
> query.addArgument("P_REGION");
> query.setCall(call);
>
> List<BigDecimal> queryArgs = new ArrayList<BigDecimal>();
> queryArgs.add(region);
>
> return (List<Country>) session.executeQuery(query, queryArgs);
> } catch (Exception ex) {
> logger.severe("ERROR: " + ex.getMessage());
> throw ex;
> } finally {
> em.close();
> }
> }
>
> }
> that calls an Oracle Stored Procedure
> And the following one,
> @Stateless
> @LocalBean
> public class RegionsFacade implements java.io.Serializable {
> private static final long serialVersionUID = 1L;
>
> /**
> * Default constructor.
> */
> public RegionsFacade() {
> // TODO Auto-generated constructor stub
> }
>
> public HashMap<String, List<String>> findAll()
> throws EJBException {
>
> EntityManagerFactory emf =
> Persistence.createEntityManagerFactory("JPACallingOracleStoredProcedure-jpa");
> EntityManager em = emf.createEntityManager();
>
> HashMap<String, List<String>> hashMap = new HashMap<String,
> List<String>>();
>
> try {
> javax.persistence.criteria.CriteriaQuery<Country> cq1 =
> em.getCriteriaBuilder().createQuery(Country.class);
> cq1.select(cq1.from(Country.class));
> List<Country> listCountries = (List<Country>)
> em.createQuery(cq1).getResultList();
>
> javax.persistence.criteria.CriteriaQuery<Region> cq2 =
> em.getCriteriaBuilder().createQuery(Region.class);
> cq2.select(cq2.from(Region.class));
> List<Region> allRegions = (List<Region>)
> em.createQuery(cq2).getResultList();
>
> for(Region r: allRegions){
> List<String> myList = new ArrayList<String>();
> BigDecimal myRegionId = new BigDecimal(r.getRegionId());
> for(Country c: listCountries){
> if((c.getRegionId()).equals(myRegionId)){
> myList.add(c.getCountryName());
> }
> }
> hashMap.put(r.getRegionName(), myList);
> }
> } catch(EJBException ex) {
> throw ex;
> } finally {
> em.close();
> }
>
> return hashMap;
> }
>
> public HashMap<BigDecimal, String> findAllRegions()
> throws EJBException {
>
> EntityManagerFactory emf =
> Persistence.createEntityManagerFactory("JPACallingOracleStoredProcedure-jpa");
> EntityManager em = emf.createEntityManager();
>
> HashMap<BigDecimal, String> hashMap = new HashMap<BigDecimal,
> String>();
>
> try {
> javax.persistence.criteria.CriteriaQuery<Region> cq =
> em.getCriteriaBuilder().createQuery(Region.class);
> cq.select(cq.from(Region.class));
> List<Region> list = (List<Region>)
> em.createQuery(cq).getResultList();
>
> for(Region r: list){
> hashMap.put(new BigDecimal(r.getRegionId()), r.getRegionName());
> }
> } catch (EJBException ex){
> throw ex;
> } finally {
> em.close();
> }
>
> return hashMap;
> }
> }
> that uses CriteriaQuery
> Here is one of the exceptions they throw when do not work,
> javax.ejb.EJBException
> at
> com.sun.ejb.containers.BaseContainer.processSystemException(BaseContainer.java:5194)
> at
> com.sun.ejb.containers.BaseContainer.completeNewTx(BaseContainer.java:5092)
> at
> com.sun.ejb.containers.BaseContainer.postInvokeTx(BaseContainer.java:4880)
> at
> com.sun.ejb.containers.BaseContainer.postInvoke(BaseContainer.java:2039)
> at
> com.sun.ejb.containers.BaseContainer.postInvoke(BaseContainer.java:1990)
> at
> com.sun.ejb.containers.EJBLocalObjectInvocationHandler.invoke(EJBLocalObjectInvocationHandler.java:222)
> at
> com.sun.ejb.containers.EJBLocalObjectInvocationHandlerDelegate.invoke(EJBLocalObjectInvocationHandlerDelegate.java:88)
> at $Proxy241.findAll(Unknown Source)
> at
> ejb.__EJB31_Generated__RegionsFacade__Intf____Bean__.findAll(Unknown
> Source)
> at controller.SPOutputServlet.doWork(SPOutputServlet.java:153)
> at controller.SPOutputServlet.doPost(SPOutputServlet.java:57)
> at javax.servlet.http.HttpServlet.service(HttpServlet.java:755)
> at javax.servlet.http.HttpServlet.service(HttpServlet.java:848)
> at
> org.apache.catalina.core.StandardWrapper.service(StandardWrapper.java:1534)
> at
> org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:281)
> 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:326)
> at
> org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:227)
> at
> com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:228)
> at
> com.sun.grizzly.http.ProcessorTask.invokeAdapter(ProcessorTask.java:822)
> at com.sun.grizzly.http.ProcessorTask.doProcess(ProcessorTask.java:719)
> at com.sun.grizzly.http.ProcessorTask.process(ProcessorTask.java:1013)
> 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:619)
> Caused by: java.lang.IllegalArgumentException: The type [null] is not
> the expected [EntityType] for the key class [class entity.Region].
> at
> org.eclipse.persistence.internal.jpa.metamodel.MetamodelImpl.entity(MetamodelImpl.java:160)
> at
> org.eclipse.persistence.internal.jpa.querydef.AbstractQueryImpl.from(AbstractQueryImpl.java:97)
> at ejb.RegionsFacade.findAll(RegionsFacade.java:49)
> at sun.reflect.GeneratedMethodAccessor110.invoke(Unknown Source)
> at
> sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
> at java.lang.reflect.Method.invoke(Method.java:597)
> at
> org.glassfish.ejb.security.application.EJBSecurityManager.runMethod(EJBSecurityManager.java:1052)
> at
> org.glassfish.ejb.security.application.EJBSecurityManager.invoke(EJBSecurityManager.java:1124)
> at
> com.sun.ejb.containers.BaseContainer.invokeBeanMethod(BaseContainer.java:5367)
> at com.sun.ejb.EjbInvocation.invokeBeanMethod(EjbInvocation.java:619)
> at
> com.sun.ejb.containers.interceptors.AroundInvokeChainImpl.invokeNext(InterceptorManager.java:801)
> at com.sun.ejb.EjbInvocation.proceed(EjbInvocation.java:571)
> at
> com.sun.ejb.containers.interceptors.SystemInterceptorProxy.doAround(SystemInterceptorProxy.java:162)
> at
> com.sun.ejb.containers.interceptors.SystemInterceptorProxy.aroundInvoke(SystemInterceptorProxy.java:144)
> at sun.reflect.GeneratedMethodAccessor108.invoke(Unknown Source)
> at
> sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
> at java.lang.reflect.Method.invoke(Method.java:597)
> at
> com.sun.ejb.containers.interceptors.AroundInvokeInterceptor.intercept(InterceptorManager.java:862)
> at
> com.sun.ejb.containers.interceptors.AroundInvokeChainImpl.invokeNext(InterceptorManager.java:801)
> at
> com.sun.ejb.containers.interceptors.InterceptorManager.intercept(InterceptorManager.java:371)
> at
> com.sun.ejb.containers.BaseContainer.__intercept(BaseContainer.java:5339)
> at
> com.sun.ejb.containers.BaseContainer.intercept(BaseContainer.java:5327)
> at
> com.sun.ejb.containers.EJBLocalObjectInvocationHandler.invoke(EJBLocalObjectInvocationHandler.java:214)
> ... 32 more
> And this is the controller Servlet,
> //_at_WebServlet(name="SPOutputServlet", urlPatterns={"/SPOutputServlet"})
> public class SPOutputServlet extends HttpServlet {
> private static final long serialVersionUID = 1L;
> final Logger logger = Logger.getLogger("SPOutputServlet");
>
> @EJB CallStoredProcedure callSP;
> @EJB RegionsFacade regionsFacade;
> /**
> * @see HttpServlet#HttpServlet()
> */
> public SPOutputServlet() {
> super();
> // TODO Auto-generated constructor stub
> }
> /**
> * @see HttpServlet#doGet(HttpServletRequest request,
> HttpServletResponse response)
> */
> protected void doGet(HttpServletRequest request, HttpServletResponse
> response) throws ServletException, IOException {
> // TODO Auto-generated method stub
> doWork(request, response);
> }
> /**
> * @see HttpServlet#doPost(HttpServletRequest request,
> HttpServletResponse response)
> */
> protected void doPost(HttpServletRequest request, HttpServletResponse
> response) throws ServletException, IOException {
> // TODO Auto-generated method stub
> doWork(request, response);
> }
>
> @SuppressWarnings({ "unused", "static-access" })
> protected void doWork(HttpServletRequest request, HttpServletResponse
> response) throws ServletException, IOException {
> // TODO Auto-generated method stub
>
> String allRegions = (String) request.getParameter("allregions");
> String showModal = (String) request.getParameter("showmodal");
>
> if(allRegions.equals("0")) {
>
> if(showModal.equals("0")){
>
> HashMap<BigDecimal, String> hashMap = new HashMap<BigDecimal,
> String>();
> try {
> hashMap = regionsFacade.findAllRegions();
> } catch (Exception e) {
> // TODO Auto-generated catch block
> logger.severe("ERROR CALLING EJB: " + e.getMessage());
>
> request.setAttribute("exception", e);
> request.getRequestDispatcher("/error.jsp").forward(request,
> response);
> }
>
> request.setAttribute("regions", hashMap);
> request.getRequestDispatcher("/oneregion.jsp").forward(request,
> response);
>
> } else if(showModal.equals("1")) {
>
> String strRegion = (String) request.getParameter("region");
>
> if(strRegion != null) {
>
> BigDecimal region = new BigDecimal(Long.parseLong((String)
> request.getParameter("region")));
>
> List<Country> list = new ArrayList<Country>();
> try {
> list = callSP.getCountriesSP(region);
> } catch (Exception e) {
> // TODO Auto-generated catch block
> logger.severe("ERROR CALLING EJB: " + e.getMessage());
>
> request.setAttribute("exception", e);
> request.getRequestDispatcher("/error.jsp").forward(request,
> response);
> }
>
> ServletOutputStream out = response.getOutputStream();
>
> out.println("<html>");
> out.println("<head>");
> out.println("<title>SPOutputServlet</title>");
> out.println("<link href='./css/default.css' rel='stylesheet'
> type='text/css' />");
> out.println("<script language='javascript'>");
> out.println("function goToIndex(){window.location='index.jsp';}");
> out.println("function showModal(){");
> out.println("var countries = new Array(");
> int i = 0;
> for(Country c: list){
> if(i == list.size() - 1)
> out.println("new Array('" + c.getCountryName() + "', '" +
> c.getCountryId() + "'));");
> else
> out.println("new Array('" + c.getCountryName() + "', '" +
> c.getCountryId() + "'), ");
> i++;
> }
> out.println("var answer1 = window.showModalDialog('modal.html',
> countries, " +
> "'dialogWidth:300px; dialogHeight:200px; center:yes');");
> out.println("}");
> out.println("</script>");
> out.println("</head>");
> out.println("<body>");
> out.println("<table align='center'>");
> int k=0;
> for(Country c: list){
> out.println("<tr class='tr" + (k % 2) + "'>");
> out.println("<td class='col0'>" + c.getCountryName() + "</td>" +
> "<td class='col1'>" + c.getCountryId() + "</td>");
> out.println("</tr>");
> k++;
> }
> out.println("</table>");
> out.println("<br/>");
> out.println("<form>");
> out.println("<table align='center'>");
> out.println("<tr class='tr" + (k % 2) + "'><td
> class='col0'><input id='idIndex' type='button' value='Go to Index'
> onclick='javascript:goToIndex();'/></td>" +
> "<td class='col1'><input id='idModal' type='button'
> value='Open Modal' onclick='javascript:showModal();'/></td></tr>");
> out.println("</table>");
> out.println("</form>");
> out.println("</body>");
> out.println("</html>");
>
> }
> }
> } else if(allRegions.equals("1")){
>
> HashMap<String, List<String>> hashMap = new HashMap<String,
> List<String>>();
> try {
> hashMap = regionsFacade.findAll();
> } catch (Exception e) {
> // TODO Auto-generated catch block
> logger.severe("ERROR CALLING EJB: " + e.getMessage());
>
> request.setAttribute("exception", e);
> request.getRequestDispatcher("/error.jsp").forward(request, response);
> }
>
> int max = hashMap.size();
> Set<String> set = hashMap.keySet();
> for(String region: set)
> max += ((List<String>) hashMap.get(region)).size();
>
> List<String> countries = new ArrayList<String>();
> if(showModal.equals("1")){
> for(int h=1; h<=max; h++){
> String country = (String) request.getParameter("f_" + h);
> if(country != null){
> if(!hashMap.containsKey(country))
> countries.add(country);
> }
> }
> }
>
> request.setAttribute("showmodal", showModal);
> request.setAttribute("countries", countries);
> request.setAttribute("hashMap", hashMap);
> request.getRequestDispatcher("/allregions.jsp").forward(request,
> response);
> }
> }
> }
> Why is this happening?