8 Replies Latest reply on Mar 14, 2010 9:06 AM by Nicklas Karlsson

    weld: inject entity manager in tomcat app

    fiorenzo pizza Newbie

      Hi,


      i'm working to a jsf application in tomcat with weld extension
      (starting from this: http://seamframework.org/Documentation/WeldAndJPARunningInTomcat).


      All works correctly, the em is injected in all managed beans.
      I want use a custom resolver to load some facelets components from database.


      Starting from this http://seamframework.org/Community/HowToDisplayAnXMLFileTransformedByXSLSSFileWithSeam ,


      I wrote my CustomResolver, and briefly:


      resourceUrl = new URL(null, resource, new DBStreamHandlerFactory().createURLStreamHandler("db"));
      
      DBStreamHandlerFactory --->  DBProtocolHandler ---> DBURLConnection.
      


      I want inject my entitymanager in DBURLConnection class:


      public class DBURLConnection extends URLConnection {
      
              @Inject
              EntityManager em;
      
              private String form;
              private String content = null;
              private Page currentPage;
      
              public DBURLConnection(URL u) {
                      super(u);
              }
      
              @Override
              public synchronized InputStream getInputStream() throws IOException {
      
                      if (!connected)
                              connect();
                      if (content != null) {
                              return IOUtils.toInputStream(content);
                      } else {
                              return null;
                      }
      
              }
      
              public String getContentType() {
                      return "text/html";
              }
      
              public synchronized void connect() throws IOException {
                      if (!connected) {
                     try {
                                this.form = url.getFile().substring(url.getFile().indexOf("/") + 1);
                                System.out.println("form: " + this.form);
                                this.currentPage= (Page) em.find(Page.class, this.form);
                          this.content = this.currentPage.getContent();
                     } catch (Exception e){
                          content = "<ui:composition "
                                              + " xmlns=\"http://www.w3.org/1999/xhtml\" "
                                              + " xmlns:ui=\"http://java.sun.com/jsf/facelets\" "
                                              + " xmlns:c=\"http://java.sun.com/jstl/core\" "
                                              + " xmlns:f=\"http://java.sun.com/jsf/core\" "
                                              + " xmlns:h=\"http://java.sun.com/jsf/html\"> "
                                              + " <h:outputText value=\"#{bookFactory.text2}\" />"
                                              + " </ui:composition>";
                     }
                              this.connected = true;
                      }
              }
      
              @Override
              public long getExpiration() {
                      return -1l;
              }
      
              @Override
              public long getLastModified() {
                      return -1l;
              }
      }
      



      But the em is null.
      Also if i inject some beans, it's always null.


      Some help??



      Thank's in advance.


      Fiorenzo

        • 1. Re: weld: inject entity manager in tomcat app
          Nicklas Karlsson Master

          You must obtain DBURLConnection from the manager, any usage of new DBURLConnection() will result in nothing injected.

          • 3. Re: weld: inject entity manager in tomcat app
            fiorenzo pizza Newbie

            ou must obtain DBURLConnection from the manager, any usage of new DBURLConnection() will result in nothing injected.


            I used weld manager but my managed bean is alway not usable.



            public static PagesHandler getPageHandler() {
            
                      PagesHandler pagesHandler = null;
                      try {
                           FacesContext facesContext = FacesContext.getCurrentInstance();
                           ServletContext servletContext = (ServletContext) facesContext
                                     .getExternalContext().getContext();
                           WeldManager beanManager = (WeldManager) ServletHelper
                                     .getModuleBeanManager(servletContext);
                           Map<String, Object> mappa = FacesContext.getCurrentInstance()
                                     .getExternalContext().getApplicationMap();
            
                           Bean phBean = beanManager.getBeans(PagesHandler.class).iterator()
                                     .next();
                           pagesHandler = (PagesHandler) phBean.create(beanManager
                                     .createCreationalContext(phBean));
            
                      } catch (Exception e) {
                           e.printStackTrace();
                      }
                      return pagesHandler;
                 }





            And this is my PageHandler:



            package weld.view;
            
            import java.io.Serializable;
            
            import javax.enterprise.context.SessionScoped;
            import javax.inject.Inject;
            import javax.inject.Named;
            import javax.persistence.EntityManager;
            
            import org.seamframework.tx.Transactional;
            
            import weld.model.Page;
            import weld.view.utils.PagesUtils;
            
            @Named
            @SessionScoped
            public class PagesHandler implements Serializable {
            
                 private String page = "index";
                 private Page currentPage;
                 @Inject
                 EntityManager em;
            
                 PagesHandler() {
                      System.out.println("create new PH");
                 }
            
                 @SuppressWarnings( { "unchecked" })
                 @Transactional
                 public void createPage(String title, String description, String content) {
                      Page page = new Page();
                      page.setTitle(title);
                      page.setDescription(description);
                      page.setId(PagesUtils.createPageId(page.getTitle()));
                      page.setContent(content);
                      em.persist(page);
                 }
            
            
                 @SuppressWarnings( { "unchecked" })
                 @Transactional
                 public void findPage() {
                      try {
                           this.currentPage = em.find(Page.class, getPage());
            
                      } catch (Exception e) {
                           e.printStackTrace();
                      }
                      if (this.currentPage == null)
                           this.currentPage = em.find(Page.class, PagesUtils
                                     .createPageId("Home Page"));
            
                 }
            
                 public String getPage() {
                      return page;
                 }
            
                 public void setPage(String page) {
                      this.currentPage = null;
                      this.page = page;
                 }
            
                 public Page getCurrentPage() {
                      if (this.currentPage == null)
                           findPage();
                      return currentPage;
                 }
            
                 public void setCurrentPage(Page currentPage) {
                      this.currentPage = currentPage;
                 }
            
                 public Page findPage(String pageName) {
                      try {
                           return em.find(Page.class, getPage());
                      } catch (Exception e) {
                           // TODO: handle exception
                      }
                      return null;
                 }
            
            }




            Also if i use the FacesContext, my managed bean is always unusable:



            public static Object getManagedBean(String name) {
                      FacesContext fc = FacesContext.getCurrentInstance();
                      if (fc == null) {
                           System.out.println("Ops!");
                      }
                      return fc.getApplication().getELResolver().getValue(fc.getELContext(),
                                null, name);
            }




            Can someone give me a piece of code to retrieve some beans in all class where CDI
            injection is not usable??


            I use weld 1.0-SP1!


            thank's in advance


            Fiorenzo



            • 4. Re: weld: inject entity manager in tomcat app
              Nicklas Karlsson Master

              Use 1.0.1-Final, it's easier to sort out issues


              Obtain the BeanManager from JNDI. See section 18.3 in the RefGiude on Tomcat usage

              • 5. Re: weld: inject entity manager in tomcat app
                fiorenzo pizza Newbie

                ok,


                some progress...


                Using the last version of weld, context.xml (like ref guide),



                Context initCtx = new InitialContext();
                Context envCtx = (Context) initCtx.lookup("java:comp/env");
                BeanManager beanManager = (BeanManager) envCtx.lookup("BeanManager");
                Bean phBean = beanManager.getBeans(PagesHandler.class).iterator().next();
                pagesHandler = (PagesHandler) phBean.create(beanManager.createCreationalContext(phBean));



                But my pageHandler is not the sessionScoped object, but it's a new instance, and without em injected.


                bye


                Fiorenzo

                • 6. Re: weld: inject entity manager in tomcat app
                  Nicklas Karlsson Master
                    Bean phBean = (Bean) beanManager.getBeans(PagesHandler.class).iterator().next();
                    CreationalContext cc = beanManager.createCreationalContext(phBean);
                    PagesHandler ph = (PagesHandler) beanManager.getReference(phBean, PagesHandler.class, cc);
                  

                  • 7. Re: weld: inject entity manager in tomcat app
                    fiorenzo pizza Newbie

                    Very good!!
                    It works!


                    Thanks Nicklas for the valuable and quick answers!


                    In some future weld release, do you think we will can @Inject in all classes?


                    Thank's a lot of your support!


                    Fiorenzo

                    • 8. Re: weld: inject entity manager in tomcat app
                      Nicklas Karlsson Master

                      Hopefully, one day, all server initiated classes (PhaseListeners etc) will be obtained by CDI resolution and injectable but that is more of a platform issue.