开发者

Java jsf beans - Nullpointer exception

For school I'm making this website which is a look-a-like of twitter. Now I have this nullpointer exception for over 2 days now. I would like some help on the following error:

java.lang.NullPointerException

java.lang.NullPointerException at javassist.util.proxy.RuntimeSupport$DefaultMethodHandler.invoke(RuntimeSupport.java:37) at org.javassist.tmp.java.lang.Object_$$_javassist_587.findAll(Object_$$_javassist_587.java) at bean.KwetterBean.Followers(KwetterBean.java:218) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:597) at org.jboss.weld.util.reflection.SecureReflections$13.work(SecureReflections.java:304) at org.jboss.weld.util.reflection.SecureReflectionAccess.run(SecureReflectionAccess.java:54) at org.jboss.weld.util.reflection.SecureReflectionAccess.runAsInvocation(SecureReflectionAccess.java:163) at org.jboss.weld.util.reflection.SecureReflections.invoke(SecureReflections.java:298) at org.jboss.weld.bean.proxy.ClientProxyMethodHandler.invoke(ClientProxyMethodHandler.java:113) at org.jboss.weld.util.CleanableMethodHandler.invoke(CleanableMethodHandler.java:43) at bean.KwetterBean_$$_javassist_593.Followers(KwetterBean_$$_javassist_593.java) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:597) at javax.el.BeanELResolver.invokeMethod(BeanELResolver.java:737) at javax.el.BeanELResolver.invoke(BeanELResolver.java:467) at javax.el.CompositeELResolver.invoke(CompositeELResolver.java:246) at com.sun.el.parser.AstValue.getValue(AstValue.java:111) at com.sun.el.parser.AstValue.getValue(AstValue.java:163) at com.sun.el.ValueExpressionImpl.getValue(ValueExpressionImpl.java:219) at org.jboss.weld.el.WeldValueExpression.getValue(WeldValueExpression.java:71) at com.sun.faces.facelets.el.ELText$ELTextVariable.writeText(ELText.java:217) at com.sun.faces.facelets.compiler.TextInstruction.write(TextInstruction.java:78) at com.sun.faces.facelets.compiler.UIInstructions.encodeBegin(UIInstructions.java:75) at com.sun.faces.facelets.compiler.UILeaf.encodeAll(UILeaf.java:176) at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1616) at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1616) at com.sun.faces.application.view.FaceletViewHandlingStrategy.renderView(FaceletViewHandlingStrategy.java:380) at com.sun.faces.application.view.MultiViewHandler.renderView(MultiViewHandler.java:126) at javax.faces.application.ViewHandlerWrapper.renderView(ViewHandlerWrapper.java:273) at com.sun.faces.lifecycle.RenderResponsePhase.execute(RenderResponsePhase.java:127) at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101) at com.sun.faces.lifecycle.LifecycleImpl.render(LifecycleImpl.java:139) at javax.faces.webapp.FacesServlet.service(FacesServlet.java:313) at org.apache.catalina.core.StandardWrapper.service(StandardWrapper.java:1523) at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:279) at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:188) at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:641) at com.sun.enterprise.web.WebPipeline.invoke(WebPipeline.java:97) at com.sun.enterprise.web.PESessionLockingStandardPipeline.invoke(PESessionLockingStandardPipeline.java:85) at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:185) at org.apache.catalina.connector.CoyoteAdapter.doService(CoyoteAdapter.java:325) at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:226) at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:165) at com.sun.grizzly.http.ProcessorTask.invokeAdapter(ProcessorTask.java:791) at com.sun.grizzly.http.ProcessorTask.doProcess(ProcessorTask.java:693) at com.sun.grizzly.http.ProcessorTask.process(ProcessorTask.java:954) at com.sun.grizzly.http.DefaultProtocolFilter.execute(DefaultProtocolFilter.java:170) at com.sun.grizzly.DefaultProtocolChain.executeProtocolFilter(DefaultProtocolChain.java:135) at com.sun.grizzly.DefaultProtocolChain.execute(DefaultProtocolChain.java:102) at com.sun.grizzly.DefaultProtocolChain.execute(DefaultProtocolChain.java:88) at com.sun.grizzly.http.HttpProtocolChain.execute(HttpProtocolChain.java:76) at com.sun.grizzly.ProtocolChainContextTask.doCall(ProtocolChainContextTask.java:53) at com.sun.grizzly.SelectionKeyContextTask.call(SelectionKeyContextTask.java:57) at com.sun.grizzly.ContextTask.run(ContextTask.java:69) at com.sun.grizzly.util.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:330) at com.sun.grizzly.util.AbstractThreadPool$Worker.run(AbstractThreadPool.java:309) at java.lang.Thread.run(Thread.java:619)

Now the classes involved:

KwetterBean.java

/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package bean;

import domain.*; import java.io.Serializable; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.Date; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import javax.ejb.EJB; import javax.enterprise.context.SessionScoped; import javax.inject.Named;

import javax.faces.bean.ManagedBean;

import javax.faces.context.FacesContext; import javax.faces.event.AjaxBehaviorEvent; import javax.inject.Inject;

import service.IUserService;

/** * * @author Julian */ @Named @ManagedBean @SessionScoped public class KwetterBean implements Serializable {

// DATA
@Inject    private IUserService uService;
private User user;
private String newTweet;
private int newTweetLength;
private String twitterFilter;
private String trend = "";

// PROPERTIES
public int getnewTweetLength() {
    return newTweetLength;
}

public User getUser() {
    if (user == null) {
        //user = new User("test", "test", "test");
        user = uService.find(0);
    }
    return user;
}

public String getNewTweet() {
    return newTweet;
}

public void setNewTweet(String newTweet) {
    this.newTweet = newTweet;
}

public void LimitTweetLength(AjaxBehaviorEvent

event) { newTweetLength = newTweet.length(); }

public String getTwitterFilter() {
    return twitterFilter;
}

public void setTwitterFilter(String twitterFilter)

{ this.twitterFilter = twitterFilter; }

public Collection<Tweet> getMentioned() {
    List<Tweet> tweets = new ArrayList<Tweet>();
    for (User u : uService.findAll()) {
        for (Tweet t : u.getTweets()) {
            String[] words = t.getTweet().split(" ");
            for (String word : words) {
                if (word.equals("@" + user.getName())) {
                    tweets.add(t);
                }
            }
        }
    }
    // Custom comparator
    Collections.sort(tweets, new Comparator() {

        @Override
        public int compare(Object o1, Object o2) {
            Tweet p1 = (Tweet) o1;
            Tweet p2 = (Tweet) o2;
            return p2.getDatum().compareTo(p1.getDatum());
        }
    });
    return tweets;
}

public void setTrend(String trend)
{
    this.trend = trend;
}

public Collection<Tweet> getTrendTimeLine() {
    List<Tweet> trendTweets = new ArrayList<Tweet>();
    for (User u : uService.findAll()) {
        for (Tweet t : u.getTweets()) {
            String[] words = t.getTweet().split(" ");
            for (String word : words) {
                if(word.equals(trend))
                    trendTweets.add(t);
            }
        }
    }
    // Custom comparator
    Collections.sort(trendTweets, new Comparator() {

        @Override
        public int compare(Object o1, Object o2) {
            Tweet p1 = (Tweet) o1;
            Tweet p2 = (Tweet) o2;
            return p2.getDatum().compareTo(p1.getDatum());
        }
    });
    return trendTweets;
}

public List<String> getTrends() {
    List<String> templist = new ArrayList<String>();
    HashMap<String, Integer> trends = new HashMap<String,

Integer>(); for (User u : uService.findAll()) { for (Tweet t : u.getTweets()) { String[] words = t.getTweet().split(" "); for (String word : words) { if (word.startsWith("#")) { if (trends.containsKey(word)) { trends.put(word, trends.get(word) + 1); } else { trends.put(word, 1); } } } } } trends = (HashMap) sortByValue(trends); Iterator testiter = trends.keySet().iterator(); while (testiter.hasNext()) { templist.add((String) testiter.next()); } if(templist.size() < 5) return templist;

    return templist.subList(0, 5);
}

public Collection<Tweet> getTimelineTweets() {
    if(!trend.isEmpty())
        return getTrendTimeLine();
    List<Tweet> tweets = new ArrayList<Tweet>();
    tweets.addAll(user.getTweets());
    for (User following : user.getFollowing()) {
        tweets.addAll(following.getTweets());
    }

    if (twitterFilter != null && twitterFilter.length() > 0) {
        Collection<Tweet> filteredTweets = new

ArrayList(); for (Tweet t : tweets) { if (t.getTweet().indexOf(twitterFilter) > -1) { filteredTweets.add(t); } } return filteredTweets; } // Custom comparator Collections.sort(tweets, new Comparator() {

        @Override
        public int compare(Object o1, Object o2) {
            Tweet p1 = (Tweet) o1;
            Tweet p2 = (Tweet) o2;
            return p2.getDatum().compareTo(p1.getDatum());
        }
    });
    return tweets;
}

// METHODS
public void setUser(String name) {
    List<User> temp = uService.findAll();
    for (User u : temp) {
        if (u.getName().equals(name)) {
            this.user = u;
        }
    }
}

public void submitTweet() {
    if (newTweet != null && newTweet.length() > 0) {
        Tweet tweet = new Tweet(newTweet, new Date(), "PC");
        user.addTweet(newTweet);
        newTweet = "";
        newTweetLength = 0;
    }
}

public Collection<User> Followers(User user) {
    List<User> tempUserList = new ArrayList<User>();
    Iterator<User> iterator = uService.findAll().iterator();
    while (iterator.hasNext()) {
        User tempUser = iterator.next();
        if (tempUser.getFollowing().contains(user))

{ tempUserList.add(tempUser); } } return tempUserList; }

public String viewUser(User user) {
    trend = "";
    this.user = user;
    return "index.xhtml";
}

public List<String> getAllUsers() {
    List<String> tempUserList = new ArrayList<String>();
    Iterator<User> iterator = uService.findAll().iterator();
    while (iterator.hasNext()) {
        tempUserList.add(iterator.next().getName());
    }
    return tempUserList;
}

public String Login() {
    return "login.xhtml";
}

public String Logout() {
    return "index.xhtml";
}

private static Map sortByValue(Map map) {
    List list = new LinkedList(map.entrySet());
    Collections.sort(list, new Comparator() {

        @Override
        public int compare(Object o1, Object o2) {
            return ((Comparable) ((Map.Entry)

(o2)).getValue()).compareTo(((Map.Entry) (o1)).getValue()); } });

    Map result = new LinkedHashMap();
    for (Iterator it = list.iterator(); it.hasNext();) {
        Map.Entry entry = (Map.Entry) it.next();
        result.put(entry.getKey(), entry.getValue());
    }
    return result;
} }

UserServiceJPA.java

/* * To change this template, choose Tools | Templates * and open the template in the editor. */

package service;

import domain.User; import java.util.ArrayList; import java.util.List; import javax.ejb.Stateful; import javax.enterprise.inject.Alternative; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import javax.persistence.TypedQuery;

/** * * @author Julian */ @Stateful @Alternative public class UserServiceJPA implements IUserService {

@PersistenceContext(unitName="Kwetter")
private EntityManager em;

@Override
public int count() {
    throw new UnsupportedOperationException("Not

supported yet."); }

public UserServiceJPA() {

    initUsers();
}

public void initUsers(){
    User u1 = new User("Hans","http","geboren 1");
    User u2 = new User("Frank","httpF","geboren 2");
    User u3 = new User("Tom","httpT","geboren 3");
    User u4 = new User("Sjaak","httpS","geboren 4");

    this.create(u1);
    this.create(u2);
    this.create(u3);
    this.create(u4);
}

@Override
public void create(User user) {
    em.persist(user);
}

@Override
public void edit(User user) {
    User user2 = new User();
    user2 = em.find(User.class, user.getId());
    user2.setFollowing(user.getFollowing());
    user2.setTweets(user.getTweets());
}

@Override
public User find(int id) {
    User user1 = new User();        
    user1 = em.find(User.class, (long)id);
    return user1;
}

@Override
public List<User> findAll() {
    List<User> users = new ArrayList();

    TypedQuery<User> query = em.createQuery("select u From User u",

User.class); for (User user1 : query.getResultList()) { users.add(user1); }

    return users;
}

@Override
public void remove(User user) {
    em.remove(user);
}

}

In this above class I only use the init once so the users are in the database but it wont create the users in the database, it does make the tables though.

I hope somebody can show me where the error is made because I really have no idea of what is going wrong.

Thanks in advance.

New error:

org.jboss.weld.exceptions.CreationException: WELD-000079 Could not find the EJB in JNDI: class org.javassist.tmp.java.io.Serializable_$$_javassist_633 at org.jboss.weld.bean.SessionBean.create(SessionBean.java:315) at org.jboss.weld.context.DependentContext.get(DependentContext.java:62) at org.jboss.weld.manager.BeanManagerImpl.getReference(BeanManagerImpl.java:709) at org.jboss.weld.manager.BeanManagerImpl.getReference(BeanManagerImpl.java:771) at org.jboss.weld.manager.BeanManagerImpl.getInjectableReference(BeanManagerImpl.java:794) at org.jboss.weld.injection.FieldInjectionPoint.inject(FieldInjectionPoint.java:108) at org.jboss.weld.util.Beans.injectBoundFields(Beans.java:790) at org.jboss.weld.util.Beans.injectFieldsAndInitializers(Beans.java:802) at org.jboss.weld.bean.ManagedBean$ManagedBeanInjectionTarget$1$1.proceed(ManagedBean.java:177) at org.glassfish.weld.services.InjectionServicesImpl.aroundInject(InjectionServicesImpl.java:130) at org.jboss.weld.injection.Injectio开发者_开发知识库nContextImpl.run(InjectionContextImpl.java:47) at org.jboss.weld.bean.ManagedBean$ManagedBeanInjectionTarget$1.work(ManagedBean.java:171) at org.jboss.weld.bean.ManagedBean$FixInjectionPoint.run(ManagedBean.java:142) at org.jboss.weld.bean.ManagedBean$ManagedBeanInjectionTarget.inject(ManagedBean.java:165) at org.jboss.weld.bean.ManagedBean.create(ManagedBean.java:332) at org.jboss.weld.context.AbstractMapContext.get(AbstractMapContext.java:112) at org.jboss.weld.bean.proxy.ClientProxyMethodHandler.getProxiedInstance(ClientProxyMethodHandler.java:143) at org.jboss.weld.bean.proxy.ClientProxyMethodHandler.invoke(ClientProxyMethodHandler.java:100) at org.jboss.weld.util.CleanableMethodHandler.invoke(CleanableMethodHandler.java:43) at bean.KwetterBean_$$_javassist_644.getUser(KwetterBean_$$_javassist_644.java) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:597) at javax.el.BeanELResolver.getValue(BeanELResolver.java:302) at javax.el.CompositeELResolver.getValue(CompositeELResolver.java:175) at com.sun.faces.el.FacesCompositeELResolver.getValue(FacesCompositeELResolver.java:72) at com.sun.el.parser.AstValue.getValue(AstValue.java:116) at com.sun.el.parser.AstValue.getValue(AstValue.java:163) at com.sun.el.ValueExpressionImpl.getValue(ValueExpressionImpl.java:219) at org.jboss.weld.el.WeldValueExpression.getValue(WeldValueExpression.java:71) at com.sun.faces.facelets.el.ELText$ELTextVariable.writeText(ELText.java:217) at com.sun.faces.facelets.el.ELText$ELTextComposite.writeText(ELText.java:141) at com.sun.faces.facelets.compiler.TextInstruction.write(TextInstruction.java:78) at com.sun.faces.facelets.compiler.UIInstructions.encodeBegin(UIInstructions.java:75) at com.sun.faces.facelets.compiler.UILeaf.encodeAll(UILeaf.java:176) at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1616) at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1616) at com.sun.faces.application.view.FaceletViewHandlingStrategy.renderView(FaceletViewHandlingStrategy.java:380) at com.sun.faces.application.view.MultiViewHandler.renderView(MultiViewHandler.java:126) at javax.faces.application.ViewHandlerWrapper.renderView(ViewHandlerWrapper.java:273) at com.sun.faces.lifecycle.RenderResponsePhase.execute(RenderResponsePhase.java:127) at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101) at com.sun.faces.lifecycle.LifecycleImpl.render(LifecycleImpl.java:139) at javax.faces.webapp.FacesServlet.service(FacesServlet.java:313) at org.apache.catalina.core.StandardWrapper.service(StandardWrapper.java:1523) at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:279) at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:188) at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:641) at com.sun.enterprise.web.WebPipeline.invoke(WebPipeline.java:97) at com.sun.enterprise.web.PESessionLockingStandardPipeline.invoke(PESessionLockingStandardPipeline.java:85) at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:185) at org.apache.catalina.connector.CoyoteAdapter.doService(CoyoteAdapter.java:325) at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:226) at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:165) at com.sun.grizzly.http.ProcessorTask.invokeAdapter(ProcessorTask.java:791) at com.sun.grizzly.http.ProcessorTask.doProcess(ProcessorTask.java:693) at com.sun.grizzly.http.ProcessorTask.process(ProcessorTask.java:954) at com.sun.grizzly.http.DefaultProtocolFilter.execute(DefaultProtocolFilter.java:170) at com.sun.grizzly.DefaultProtocolChain.executeProtocolFilter(DefaultProtocolChain.java:135) at com.sun.grizzly.DefaultProtocolChain.execute(DefaultProtocolChain.java:102) at com.sun.grizzly.DefaultProtocolChain.execute(DefaultProtocolChain.java:88) at com.sun.grizzly.http.HttpProtocolChain.execute(HttpProtocolChain.java:76) at com.sun.grizzly.ProtocolChainContextTask.doCall(ProtocolChainContextTask.java:53) at com.sun.grizzly.SelectionKeyContextTask.call(SelectionKeyContextTask.java:57) at com.sun.grizzly.ContextTask.run(ContextTask.java:69) at com.sun.grizzly.util.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:330) at com.sun.grizzly.util.AbstractThreadPool$Worker.run(AbstractThreadPool.java:309) at java.lang.Thread.run(Thread.java:619) Caused by: java.lang.IllegalStateException: Error resolving session object reference for ejb name class service.UserServiceJPA and jndi name java:global/Kwetter_-_Julian/UserServiceJPA!service.IUserService at org.glassfish.weld.services.EjbServicesImpl.resolveEjb(EjbServicesImpl.java:117) at org.jboss.weld.bean.SessionBean.createReference(SessionBean.java:422) at org.jboss.weld.bean.proxy.EnterpriseBeanProxyMethodHandler.(EnterpriseBeanProxyMethodHandler.java:76) at org.jboss.weld.bean.SessionBean.create(SessionBean.java:298) ... 68 more Caused by: javax.naming.CommunicationException: Communication exception for SerialContext [Root exception is java.lang.reflect.UndeclaredThrowableException] at com.sun.enterprise.naming.impl.SerialContext.lookup(SerialContext.java:461) at javax.naming.InitialContext.lookup(InitialContext.java:392) at javax.naming.InitialContext.lookup(InitialContext.java:392) at org.glassfish.weld.services.EjbServicesImpl.resolveEjb(EjbServicesImpl.java:110) ... 71 more Caused by: java.lang.reflect.UndeclaredThrowableException at $Proxy223.create(Unknown Source) at com.sun.ejb.containers.JavaGlobalJndiNamingObjectProxy.create(JavaGlobalJndiNamingObjectProxy.java:61) at com.sun.enterprise.naming.impl.SerialContext.lookup(SerialContext.java:432) ... 74 more Caused by: javax.ejb.CreateException: ERROR creating stateful SessionBean at com.sun.ejb.containers.StatefulSessionContainer.createEJBLocalBusinessObjectImpl(StatefulSessionContainer.java:553) at com.sun.ejb.containers.BaseContainer.createEJBLocalBusinessObjectImpl(BaseContainer.java:2425) at com.sun.ejb.containers.EJBLocalHomeImpl.createEJBLocalBusinessObjectImpl(EJBLocalHomeImpl.java:113) at com.sun.ejb.containers.EJBLocalHomeInvocationHandler.invoke(EJBLocalHomeInvocationHandler.java:153) ... 77 more Caused by: java.lang.NullPointerException at service.UserServiceJPA.create(UserServiceJPA.java:52) at service.UserServiceJPA.initUsers(UserServiceJPA.java:44) at service.UserServiceJPA.(UserServiceJPA.java:35) at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:39) at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:27) at java.lang.reflect.Constructor.newInstance(Constructor.java:513) at java.lang.Class.newInstance0(Class.java:355) at java.lang.Class.newInstance(Class.java:308) at com.sun.ejb.containers.StatefulSessionContainer._constructEJBInstance(StatefulSessionContainer.java:569) at com.sun.ejb.containers.BaseContainer.createEjbInstanceAndContext(BaseContainer.java:1616) at com.sun.ejb.containers.StatefulSessionContainer.createBeanInstance(StatefulSessionContainer.java:581) at com.sun.ejb.containers.StatefulSessionContainer.createEJBLocalBusinessObjectImpl(StatefulSessionContainer.java:534) ... 80 more


bean.KwetterBean.Followers(KwetterBean.java:218 seems to be the place you should look at.

Probably user.getFollowing() is returning null and calling contains() on it makes it bomb.

I think you should connect with a debugger, set this to stop on NPE and just see where it stops. This will allow you to inspect the variables and get a fix quicker than waiting for answers here.


Try using @EJB instead of @Inject for the service Dependency injection

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜