0

here is the code for my jsf managed bean:

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.sql.Blob;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import javax.activation.MimetypesFileTypeMap;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.validator.ValidatorException;
import javax.imageio.ImageIO;
import javax.persistence.Transient;
import javax.servlet.http.Part;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;

/**
 *
 * @author ADITYA
 */
@ManagedBean
@SessionScoped
public class entersite {
String link,location;
int code,noot;
@Transient
Part file;

    public Part getFile() {
        return file;
    }

    public void setFile(Part file) {
        this.file = file;
    }

    public int getNoot() {
        return noot;
    }

    public void setNoot(int noot) {
        this.noot = noot;
    }
byte[] image;

    public byte[] getImage() {
        return image;
    }

    public void setImage(byte[] image) {
        this.image = image;
    }

    public String getLink() {
        return link;
    }

    public void setLink(String link) {
        this.link = link;
    }

    public String getLocation() {
        return location;
    }

    public void setLocation(String location) {
        this.location = location;
    }

    public int getCode() {
        return code;
    }

    public void setCode(int code) {
        this.code = code;
    }




    public entersite() {
    }
    public boolean ver()
    {
    boolean d=false;
    Session s1=new Configuration().configure("hibernate.cfg.xml")  
                        .buildSessionFactory().openSession();  
    Transaction tx=s1.beginTransaction();
    int cd1=this.getCode();
    Query q1=s1.createQuery("from site.entersite where CODE=:var");
    q1.setInteger("var",cd1);
    tx.commit();
    List<entersite> lst=new ArrayList<>();
    for(Iterator itr=q1.iterate();itr.hasNext();)
    {
    entersite es1=(entersite)itr.next();
    if(es1.getCode()==cd1)
        d=true;
    }
    return d;
    }

    public String saving() throws Exception
    {
        if(ver()==true)
            return "err1";
        else
        {
        InputStream is1;        
        is1=file.getInputStream();
        byte[] buffer = new byte[(int)file.getSize()];
    int bytesRead;
    ByteArrayOutputStream output = new ByteArrayOutputStream();
    while ((bytesRead = is1.read(buffer)) != -1)
    {
        output.write(buffer, 0, bytesRead);
    }
    Session s1=new Configuration().configure("hibernate.cfg.xml")  
                        .buildSessionFactory().openSession();  
    Transaction tx=s1.beginTransaction();        
    entersite es=new entersite();
    es.setCode(this.getCode());
    es.setLink(this.getLink());
    es.setLocation(this.getLocation());
    es.setNoot(this.getNoot());
    es.setImage(output.toByteArray());
    s1.save(es);
    tx.commit();
    return "admin41";
        }
    }
    /*
    public File convertFile(Part file) throws IllegalStateException, IOException 
{
    InputStream is1;        
        is1=file.getInputStream();
        byte[] buffer = new byte[(int)file.getSize()];
    int bytesRead;
    ByteArrayOutputStream output = new ByteArrayOutputStream();
    while ((bytesRead = is1.read(buffer)) != -1)
    {
        output.write(buffer, 0, bytesRead);
    }
        File convFile = new File(file.getName());
    convFile.createNewFile(); 
    FileOutputStream fos = new FileOutputStream(convFile); 
    fos.write(output.toByteArray());
    fos.close(); 
    return convFile;
}
    */
    public void validateFile(FacesContext fc,UIComponent uc,Object value) throws Exception
    {
        Part file1=(Part)value;

        if(file1.getName()!=null)        
        {
    try(InputStream input = file1.getInputStream())
    {

        ImageIO.read(input).toString();
        // It's an image (only BMP, GIF, JPG and PNG are recognized).
    } catch (Exception e) {
        // It's not an image.
        throw new ValidatorException(new FacesMessage("please select image file only"));
    }    
        }
    /*
    File f = (File)convertFile(file1);
        String mimetype= new MimetypesFileTypeMap().getContentType(f);
        String type = mimetype.split("/")[0];
        if(type.equalsIgnoreCase("image")) {
    } else {
            throw new ValidatorException(new FacesMessage("please select image file only!"));
    }
            */

}
    public String move2()
    {
    return "adminmenu";
    }

}

here is my jsf file:

<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:h="http://xmlns.jcp.org/jsf/html"
      xmlns:ui="http://xmlns.jcp.org/jsf/facelets">
    <h:head>
        <title>Facelet Title</title>
    </h:head>
    <h:body>
        <ui:composition template="mytemp1_2.xhtml">
            <ui:define name="content">
                <table>
                    <tr><td> <a  href="/Last_project_work_1_1/faces/admin/admin2.xhtml">Enter new admin</a></td><td><a href="/Last_project_work_1_1/faces/admin/admin4.xhtml">Enter new site</a></td></tr>
                        <tr><td><a href="Last_project_work_1_1/faces/admin/addtheater.xhtml">Add Theater</a></td><td><a href="Last_project_work_1_1/faces/admin/deletesite.xhtml">Delete A Site</a></td></tr>
                        <tr><td><a href="listall.jsp">List all sites</a></td><td> <a href="Last_project_work_1_1/faces/admin/editdetails.xhtml">Edit Site Details</a></td></tr>
                </table>
            </ui:define>
        </ui:composition>        
    </h:body>
</html>

here is my stack trace:

java.lang.NullPointerException
    at site.entersite.validateFile(entersite.java:172)
    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:497)
    at com.sun.el.parser.AstValue.invoke(AstValue.java:289)
    at com.sun.el.MethodExpressionImpl.invoke(MethodExpressionImpl.java:304)
    at com.sun.faces.facelets.el.TagMethodExpression.invoke(TagMethodExpression.java:105)
    at javax.faces.validator.MethodExpressionValidator.validate(MethodExpressionValidator.java:106)
    at javax.faces.component.UIInput.validateValue(UIInput.java:1164)
    at javax.faces.component.UIInput.validate(UIInput.java:982)
    at javax.faces.component.UIInput.executeValidate(UIInput.java:1248)
    at javax.faces.component.UIInput.processValidators(UIInput.java:712)
    at javax.faces.component.UIForm.processValidators(UIForm.java:253)
    at javax.faces.component.UIComponentBase.processValidators(UIComponentBase.java:1258)
    at javax.faces.component.UIComponentBase.processValidators(UIComponentBase.java:1258)
    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:646)
    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)

Now when i click on back commandButton with value back the control is supposed to go to adminmenu.xhtml but instead it gives the above null pointer exception.This happens when i leave the form fields empty. i have tried the silly small tricks to avoid npe but in vain please help me figure out the problem. thanks in advance...

Tiny
  • 27,221
  • 105
  • 339
  • 599
adibro500
  • 171
  • 2
  • 10
  • I wouldn't say there are really "tricks" to avoid NPE. NPEs indicate that there is a bigger bug in your code or you understanding of how things work. You should be able to write some code to find out _exactly_ which variable is null in your `validateFile` method. Then, try to understand why it's null. If you can't figure it out, come ask for help. – DavidS Feb 12 '16 at 21:00
  • Sounds like your validator is getting a null for `value` and you are not protecting against that. When posting a stack trace ***ALWAYS*** identify the line in your code mentioned in the trace. In this case it's `site.entersite.validateFile(entersite.java:172)` but we don't know which line is #172. – Jim Garrison Feb 12 '16 at 21:00
  • Once you're capable to ask "why is variable X null?" instead of "why do I get a NullPointerException?", feel free to ask a new question along with the concrete functional requirement. Exceptions of java.lang package coming from own code are at least not a JSF related problem. – BalusC Feb 12 '16 at 21:06
  • The exception occurs here:if(file1.getName()!=null) – adibro500 Feb 12 '16 at 21:06
  • If that is true, there is (almost) only one possibility: `file1` is null. – DavidS Feb 12 '16 at 22:28
  • problem solved i just included the boolean check:if(value!=null){} to validator method and excuse me for the duplicate question – adibro500 Feb 18 '16 at 14:53

0 Answers0