0

I am trying to fileupload component of Primefaces 3.0 based on the example given in the demo. I have also added commons-fileupload-1.2.2.jar and commons-io-2.0.1.jar along with primefaces-3.1.jar file.

I run the uploader I get a java.lang.NullPointerException could anyone please help me with this problem, I have searched the internet extensively and cannot find a solution that works.

I am using NetBeans 7.2.1 and GlassFish to deploy.

My Codes : XHTML :

<h:form id="frm" enctype="multipart/form-data">  
        <table>
            <tr><td><div style="height:300px;"><img src="images/adcar.jpg" style="top:0px;"/>
                    </div>
                    </td>
                <td>
                    <h:form id="img" enctype="multipart/form-data">
 <div style=" -moz-border-radius:15px;  border:1px solid;  width:600px; border-color:#930303;">
    <br></br>
        <p:panel style="border:none;">
         <p:messages></p:messages>
        </p:panel>
        <h:panelGrid columns="2">
           <h:outputText value="Nom Projet :"/>
           <h:inputText id="Nom" value="#{ajoutprjt.nomProjet}" />
           <h:outputText value="Ref Projet :"></h:outputText><h:inputText value="#{ajoutprjt.idProjet}" />
           <h:outputText value="Date de Début :"></h:outputText><h:inputText value="#{ajoutprjt.dateDeb}" />
           <h:outputText value="Date de Fin :"></h:outputText><h:inputText value="#{ajoutprjt.dateFin}" />
           <h:outputText value="Chef  :"></h:outputText>
           <h:selectOneMenu value="#{ajoutprjt.idChef}">
               <f:selectItem itemValue="#{null}" itemLabel="-- select one --" />
               <f:selectItems value="#{ajoutprjt.tdata}" var="cmd" 
                                             itemValue="#{cmd.id}" itemLabel="#{cmd.id} #{cmd.nom} #{cmd.prenom}" />
           </h:selectOneMenu>
           Documents : <p:fileUpload value="#{ajoutprjt.file}" id="fileupload"   mode="simple"></p:fileUpload>
           <h:outputText></h:outputText><p:panel style="border: none;"><p:commandButton value="Ajouter" action="#{ajoutprjt.ajoutP}" ajax="false"></p:commandButton><p:commandButton value="Annuler" action="#{ajoutprjt.annuleraj}" ajax="false"></p:commandButton></p:panel>
       </h:panelGrid>
         </div>
                    </h:form>
     </td></tr>  </table>
        </h:form>[/code]

my Bean :

package beans;

import com.persistence.Compte;
import com.persistence.Projets;
import com.persistence.geoUtil;
import java.io.File;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Logger;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import javax.faces.context.FacesContext;
import javax.faces.model.DataModel;
import javax.faces.model.ListDataModel;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.primefaces.model.UploadedFile;
/**
 *
 * @author  SA
 */
@ManagedBean
@RequestScoped
public class ajoutprjt implements Serializable{

     private String idpro;
     private String IdProjet;
     private String NomProjet;
     private String DateDeb;
     private String DateFin;
     private String nomimg;
     private UploadedFile file;  
     private String IdChef;
     private DataModel<Compte> tdata ;

       public ajoutprjt(){

                        }
      // getters et Setters 

    ...

    public UploadedFile getFile() {
        System.out.println("Je suis sous GetFile: " );
        return file;
    }

    public void setFile(UploadedFile file) {
        System.out.println("je Suis Sous SetFile : ");
        this.file = file;
    }


  public void ajoutP(){
    //  String p=Integer.toString(puis);
     System.out.println("Ajout Projet de ref : " +IdProjet);
     System.out.println("Ajout Projet de Idchef est  : " +IdChef);
     System.out.println("file a ajouter e  : " +this.getFile().getSize());
     if(IdProjet.equals("")==false && NomProjet.equals("")==false  && DateDeb.equals("")==false && DateFin.equals("")==false && IdChef.equals("")==false){

           try{
        Session se=geoUtil.getSessionFactory().getCurrentSession();
        Transaction tr=se.beginTransaction();
        Query q = se.createQuery("SELECT p from Projets p where IdProjet = :rf");
           q.setParameter("rf", IdProjet);     
           List<Object[]> list = (List<Object[]>) q.list();
           if(list.size() == 0){

         Projets p =new Projets();

         p.setNomProjet(NomProjet);
         p.setIdProjet(IdProjet);
         p.setDateDeb(DateDeb);
         p.setDateFin(DateFin);
         p.setIdChef(IdChef);
         // UploadedFile file = event.getFile();
          if(this.getFile()!= null) {  
                 String fileName = file.getFileName();
                 byte[] fileBytes = file.getContents();
                 p.setNomimg(fileName);
                 p.setImg(fileBytes);}
             else{
                      p.setNomimg("Pas de fichier");
                      String s = "a";
                      byte[] a = s.getBytes();      
                      p.setImg(a); 
                         }  
            se.persist(p);
            tr.commit();

         context.addMessage(null,new FacesMessage(FacesMessage.SEVERITY_INFO,"Projet ajouté avec succes","Compte chef ajouté avec succes"));
     this.setNomProjet("");
         this.setIdProjet("");
         this.setDateDeb("");
         this.setDateFin("");
         this.setIdChef("");

           }else{
               context.addMessage(null,new FacesMessage(FacesMessage.SEVERITY_ERROR,"Attention:Projet déjas existe","Attention"));
           }
           }
           catch(Exception e1){
               e1.printStackTrace();
       context.addMessage(null,new FacesMessage(FacesMessage.SEVERITY_ERROR,"Attention:Erreur d'insertion","Attention"));
           }
          }
       else{
         context.addMessage(null,new FacesMessage(FacesMessage.SEVERITY_WARN,"Attention Tous les champs doivent etre  remplis!!","Attention"));
       }

   }
}

This is my web.xml file :

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0" 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/web-app_3_0.xsd">
    <context-param>
        <param-name>javax.faces.PROJECT_STAGE</param-name>
        <param-value>Development</param-value>
    </context-param>
    <context-param>
        <param-name>primefaces.THEME</param-name>
        <param-value>aristo</param-value>
    </context-param>
    <servlet>
        <servlet-name>Faces Servlet</servlet-name>
        <servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>Faces Servlet</servlet-name>
        <url-pattern>*.xhtml</url-pattern>
        <url-pattern>/faces/*</url-pattern>
    </servlet-mapping>
    <session-config>
        <session-timeout>
            30
        </session-timeout>
    </session-config>
    <welcome-file-list>
        <welcome-file>faces/auth.xhtml</welcome-file>
    </welcome-file-list>
    <resource-ref>
        <description>Base de données pour app Ontologie
Projet master Pro</description>
        <res-ref-name>jdbc/gcn</res-ref-name>
        <res-type>javax.sql.DataSource</res-type>
        <res-auth>Container</res-auth>
        <res-sharing-scope>Shareable</res-sharing-scope>
    </resource-ref>
        <filter>
         <filter-name>PrimeFaces FileUpload Filter</filter-name>
        <filter-class>
                org.primefaces.webapp.filter.FileUploadFilter
         </filter-class>
        </filter>
        <filter-mapping>
            <filter-name>PrimeFaces FileUpload Filter</filter-name>
             <servlet-name>Faces Servlet</servlet-name>
                 <dispatcher>FORWARD</dispatcher>
        </filter-mapping>
</web-app>

Any help would be greatly appreciated. Here is the stack trace:

javax.faces.el.EvaluationException: java.lang.NullPointerException
    at javax.faces.component.MethodBindingMethodExpressionAdapter.invoke(MethodBindingMethodExpressionAdapter.java:102)
    at com.sun.faces.application.ActionListenerImpl.processAction(ActionListenerImpl.java:102)
    at javax.faces.component.UICommand.broadcast(UICommand.java:315)
    at javax.faces.component.UIViewRoot.broadcastEvents(UIViewRoot.java:794)
    at javax.faces.component.UIViewRoot.processApplication(UIViewRoot.java:1259)
    at com.sun.faces.lifecycle.InvokeApplicationPhase.execute(InvokeApplicationPhase.java:81)
    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:1550)
    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 org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:161)
    at org.apache.catalina.connector.CoyoteAdapter.doService(CoyoteAdapter.java:331)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:231)
    at com.sun.enterprise.v3.services.impl.ContainerMapper$AdapterCallable.call(ContainerMapper.java:317)
    at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:195)
    at com.sun.grizzly.http.ProcessorTask.invokeAdapter(ProcessorTask.java:860)
    at com.sun.grizzly.http.ProcessorTask.doProcess(ProcessorTask.java:757)
    at com.sun.grizzly.http.ProcessorTask.process(ProcessorTask.java:1056)
    at com.sun.grizzly.http.DefaultProtocolFilter.execute(DefaultProtocolFilter.java:229)
    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:722)
Caused by: java.lang.NullPointerException
    at beans.ajoutprjt.ajoutP(ajoutprjt.java:176)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:601)
    at com.sun.el.parser.AstValue.invoke(AstValue.java:254)
    at com.sun.el.MethodExpressionImpl.invoke(MethodExpressionImpl.java:302)
    at com.sun.faces.facelets.el.TagMethodExpression.invoke(TagMethodExpression.java:105)
    at javax.faces.component.MethodBindingMethodExpressionAdapter.invoke(MethodBindingMethodExpressionAdapter.java:88)
    ... 32 more
Luiggi Mendoza
  • 85,076
  • 16
  • 154
  • 332
user2420469
  • 91
  • 3
  • 14
  • possible duplicate of [How to use PrimeFaces p:fileUpload?](http://stackoverflow.com/a/8880083/) – BalusC Jun 23 '13 at 18:41

3 Answers3

1

I don't understand how you can use this method "ajoutP" on "actionListener" like follow "actionListener="#{ajoutprjt.ajoutP}" so that you have a parameter in the method "ajoutP(FileUploadEvent event)". that generate the following Error «javax.el.MethodNotFoundException»

0

You seem to have a lot of stuff on that page. Here is how I would approach debugging this:

  • Download all the dependencies if you have not already done so (if you did then double check your work). here is the link/source for dependencies

enter image description here

  • Use this example from PrimeFace website to just create a separate fileuploadController and view page just like what they have at this link

  • Try to make the above step working first, once you have that working then start adding those elements slowly to your existing current JSF page and controller and change to accommodate your requirements (start from scratch though and not with what you have already modified and posted on this page).

Just one thing I noticed:

  • I see you have nested enctype="multipart/form-data" this maybe one of the contributing factors of being null is you have too many of these in one page and your controller is only getting one of them but this is just a educated observation which you may want to debug and look into before going through all the trouble/steps I listed out for you above.
Community
  • 1
  • 1
grepit
  • 21,260
  • 6
  • 105
  • 81
-1

In xhtml page Use actionListener instead of action as like

<p:commandButton value="Ajouter" actionListener="#{ajoutprjt.ajoutP}"
 ajax="false"></p:commandButton>

And change the ManagedBean ajoutP() method as

public void ajoutP(FileUploadEvent event){

        OutputStream out=null;
        InputStream fileContent=null;
        try{
            UploadedFile uploadedFile= event.getFile();
            out= new FileOutputStream(new 
                           File("D:/")+uploadedFile.getFileName());
            fileContent= uploadedFile.getInputstream();
            int read=0;
            final byte[] bytes= new byte[1024];
            while((read= fileContent.read(bytes))!=-1){
               out.write(bytes,0,read); 
            }
        }
        catch(FileNotFoundException fnfe){

        }
        catch(IOException ioex){

        }
}
Masudul
  • 21,823
  • 5
  • 43
  • 58