Skip to main content

EJB 3.0 NullPointerException wiht Dependency Injection

9 replies [Last post]
loopman
Offline
Joined: 2008-02-17

Hello every one,

i try (since several days) to develop some basics Javaee Enterprise Applications using NetBeans 6.0 and EJB 3.0 specially the dependency injection features. Unfortunely, the injection don't work, so that i always get a NullPointerException. Even when i try just to deploy sun delivered samples in Glassfish for instance, then i always have the same problem.

Here ist a code sample:

--

package confirmer.client;

import confirmer.ejb.Confirmer;
import javax.ejb.EJB;

/**
*
* @author ie139813
*/
public class ConfirmerClient {
@EJB
private static Confirmer confirmer;

/** Creates a new instance of ConfirmerClient */
public ConfirmerClient() {
}

/**
* @param args the command line arguments
*/
public static void main(String[] args) {
String recipient = null;

if (args.length == 1) {
recipient = args[0];
} else {
recipient = "pig.bodine@example.com";
}

try {
confirmer.sendNotice(recipient);
System.out.println("Message sent to " + recipient + ".");
System.exit(0);
} catch (Exception ex) {
ex.printStackTrace();
}
}
}

---

The Confirmer class is a stateless session Bean Interface. There is an implementing Class named ConfirmerBean in the Enterprise Application.

Please, could somebody help me? I would be very greatful.

Cheers.
loopman

Reply viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.
af25
Offline
Joined: 2010-09-25

Here is a very usefull link, explaining how to create and acces a simple ejb from an application client or from a web module: http://javahowto.blogspot.com/2007/07/simple-ejb-3-servlet-application.html
- This is a simple EJB 3 app that is written, deployed and run from command line and vim, with no IDE, no ant, no maven, no admin console. The target appserver is glassfish.

af25
Offline
Joined: 2010-09-25

If you have a web.xml, check that is version 2.5 or newer. Annotations in the servlet are ignored if the web.xml is version 2.4 or older.
exp:


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_2_5.xsd">

..........

gluk
Offline
Joined: 2009-04-20

The solution for most of the Java related errors can be found at this site: http://iderror.com/category/errors/java/

eve2
Offline
Joined: 2007-01-05

My problem above has been resolve. I simplified my application by testing it with a simple client like the ones in the JEE 5 tutorial. it works fine.

eve

mtbittle
Offline
Joined: 2008-03-18

Is the client part of your EAR file? By that I mean, is the EJB and the client application inside the same Enterprise application?

Secondly, What interface are you accessing of the Confirmer? You have to reference either a local or remote interface of the session bean.
Should look like this:

@EJB
private static ConfirmerLocal confirmerLocal;

Is that any help? Try using NetBeans' functionality by right clicking in your ConfirmerClient code somewhere and choosing 'Enterprise Resources' then 'Call EJB', and choose the local or remote interface of the Confirmer Bean.

mtbittle
Offline
Joined: 2008-03-18

Also, to use dependency injection, the client application must be an 'Application Client Module' and not just a Java class.

loopman
Offline
Joined: 2008-02-17

Hello and thank you very much for your reply.
The client application is actualy an 'Application Client Module' and is part of the Enterprise ear. But It still doesn't. Do you have any experience with dependency injection using NetBeans IDE? Like i said, i just pick up a sun delivered sample and build it in NetBeans without touching anything in the code, but it doesn't work.

I send you also the Bean Interface with its implementation:

/**
* This is the business interface for Confirmer enterprise bean.
*/
@Remote
public interface Confirmer {
void sendNotice(String recipient);
}

---

@Stateless
public class ConfirmerBean implements Confirmer {
private static final String mailer = "JavaMailer";
private static Logger logger = Logger.getLogger(
"confirmer.ejb.ConfirmerBean");
@Resource(name = "mail/myMailSession")
private Session session;

/** Creates a new instance of ConfirmerBean */
public ConfirmerBean() {
}

public void sendNotice(String recipient) {
try {
Message message = new MimeMessage(session);
message.setFrom();
message.setRecipients(
Message.RecipientType.TO,
InternetAddress.parse(recipient, false));
message.setSubject("Test Message from ConfirmerBean");

DateFormat dateFormatter = DateFormat.getDateTimeInstance(
DateFormat.LONG,
DateFormat.SHORT);
Date timeStamp = new Date();

String messageText = "Thank you for your order." + '\n'
+ "We received your order on "
+ dateFormatter.format(timeStamp) + ".";
message.setText(messageText);
message.setHeader("X-Mailer", mailer);
message.setSentDate(timeStamp);

// Send message
Transport.send(message);

logger.info("Mail sent to " + recipient + ".");
} catch (MessagingException ex) {
ex.printStackTrace();
logger.info("Error in ConfirmerBean for " + recipient);
}
}
}
---

King Regards

mtbittle
Offline
Joined: 2008-03-18

The only thing I can think of is that you may not have set up the resource ("mail/session") correctly for sending the MIME message. I haven't done anything with sending MIME messages, but with the resource may need to be defined in the app server. have you tried that? Make sure you're setting up the message correctly too.

eve2
Offline
Joined: 2007-01-05

hello everyone,

I have the exact same problem. I'm looking for a solution. See below:

package machinedetails2;

import javax.ejb.Remote;
import java.util.List;

/**
* This is the business interface for Usersbean enterprise bean.
*/

//decoding interface definetion
//the converter requires this annotation,
//which says client will be accessing this remotely
@Remote
public interface UsersRemote{

//For entering new user into the DB
public void createUser();

//public Usersent(String userid, String Firstname, String Surname, String Password );

//public Usersent getUserlogindet(String firstname);

/**
* call the Usersent contructor, using the getUserlogindet
* defined in remote interface, retrive the user's details after
* login
*/

machinedetails2.Usersent getUserlogindet(String userid, String Password);

machinedetails2.Usersent getUserlogindet(String userid);

machinedetails2.Usersent searchbyusername(String userid);

void createUser(String userid, String firstname, String surname, String password);

}

appication client:

/*
* UsersClient.java
*

*/

package machineappclit2;

import machinedetails2.*;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
import javax.naming.InitialContext;
import java.awt.BorderLayout;
//import productdetails.details.Users;
import javax.ejb.EJB;

/**
*
* @author eve.pokua
*/
public class UsersClient extends javax.swing.JFrame {

JLabel northlab, useridlab, fnamelab, snamelab, userpwdlab;
JTextField useridtxt, fnametxt, snametxt, userpwdtxt;
JPanel jpcen, northpanel;
JButton saveNewuserdetails;

//make a reference to the Users enterprise bean instance
@EJB
private static UsersRemote users;
/** Creates new form UsersClient */
public UsersClient() {
JFrame frame = new JFrame("New User Application Client");
northpanel= new JPanel();
jpcen=new JPanel();
northlab=new JLabel("Enter new user's details below and click the 'Save Details' button below");
useridlab =new JLabel("User ID");
useridtxt =new JTextField("asdfgad");
fnamelab=new JLabel("User's first Name");
fnametxt=new JTextField("fsdfa");
snamelab=new JLabel("User's Surname");
snametxt=new JTextField("asdfa");
userpwdlab=new JLabel("User's password");
userpwdtxt=new JTextField("fasdfasdf");
saveNewuserdetails=new JButton("Save details");
northpanel.add(northlab);
jpcen.add(useridlab);
jpcen.add(useridtxt);
jpcen.add(fnamelab);
jpcen.add(fnametxt);
jpcen.add(snamelab);
jpcen.add(snametxt);
jpcen.add(userpwdlab);
jpcen.add(userpwdtxt);
jpcen.add(saveNewuserdetails);
saveNewuserdetails.addActionListener(new SaveNewuserdetlistener());

jpcen.setLayout(new BoxLayout(jpcen, BoxLayout.PAGE_AXIS));
jpcen.setBorder(BorderFactory.createEmptyBorder(20,20,5,5));

frame.getContentPane().add(northpanel, BorderLayout.NORTH);
frame.getContentPane().add(jpcen, BorderLayout.CENTER);
frame.pack();
frame.setVisible(true);
//initComponents();
}

/**
* @param args the command line arguments
*/
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
//new UsersClient().setVisible(true);
//run an instance of UsersClient class
UsersClient usersClient=new UsersClient();
//try{
//get access to the JNDI
//InitialContext ctx=new InitialContext();

//UsersbeanRemote users=(UsersbeanRemote)ctx.lookup("UsersbeanJNDI");
// Machinesrem sebean=(Machinesrem)ctx.lookup("jdbc/PRODUCTDETAILS");
//users.createUser();
//users.createUser();
//serialname, computname, it3, it4, it5);

//System.out.println(serialname + computname + it3 + it4 +it5);

//}
//catch(Exception ex){
//System.err.println("Caught an exception: data not inserted into dbases");
//ex.printStackTrace();}
//}

}
});
}

// Variables declaration - do not modify
// End of variables declaration

private class SaveNewuserdetlistener implements ActionListener{
public void actionPerformed(ActionEvent e){

String userid=useridtxt.getText();
String fname=fnametxt.getText();
String sname=snametxt.getText();
String userpwd=userpwdtxt.getText();
try{

//InitialContext ctx=new InitialContext();
//UsersRemote users=(UsersRemote)ctx.lookup("UsersbJNDI");

users.createUser(userid,fname,sname,userpwd);
System.out.println("Created new user details " + userid + " " + fname + " " + sname + " " + userpwd);
}catch(Exception ex){
System.err.println("Can not insert data into DB");
ex.printStackTrace();
}

}
}
}

Entity:

package machinedetails2;

import machinedetails2.*;

import java.io.Serializable;
import java.util.Collection;
import java.util.List;
//import java.util.Collection;
//import java.util.Collection;
//import java.util.List;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.EntityManager;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.OneToMany;
//import javax.persistence.JoinColumn;
//import javax.persistence.JoinTable;
//import javax.persistence.ManyToOne;

//import javax.persistence.OneToMany;

import javax.persistence.Table;
//import machinedetails.Machineent;

/**
* Entity class Usersent
*
* @author eve.pokua
*/
@Entity
@Table(name="USERS")
//@NamedQueries({
//@NamedQuery(name = "Machinedetail2.Usersent.findMachinebyuser",query = "SELECT m, us FROM Usersent us, Machineent m WHERE us.UserID=:UserID AND us.UserID=m.UserID") })
//"SELECT m, us.UserID, us.Firstname, us.Surname FROM Machineent m, Usersent us WHERE us.UserID=:UserID") })
public class Usersent implements Serializable {

// @ManyToOne
//private Machineent machineent;

//@OneToOne(mappedBy = "usersent")
// private Machineent machinePCNM;

//@Id
//@GeneratedValue(strategy = GenerationType.AUTO)
//private Long id;

@Id
@Column(name="USERID", nullable=false, length=8)
private String userID;
@Column(name="FIRSTNAME", nullable=true, length=60)
private String firstname;
@Column(name="SURNAME", nullable=true, length=80)
private String surname;
@Column(name="PASSWORD", nullable=true, leng

........}

stateful bean:

package machinedetails2;

import machinedetails2.*;

import javax.ejb.EJBException;

import javax.ejb.Stateful;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

/**
*
* @author eve.pokua
*/
@Stateful
//@Stateful(name="usersb", mappedName="UsersbJNDI")
public class UsersBean implements UsersRemote {

//refer to the persistence unit with a persistenceContext
@PersistenceContext(name="MACHINEDETAILS2-ejbPU2")
EntityManager em;
/** Creates a new instance of UsersbeanBean */
public UsersBean() {
}

public void createUser() {
try{
Usersent userent = new Usersent();
userent.setUserid("dsfgwer");
userent.setFirstname("asdfasdgf");
userent.setSurname("sdfasdfasdf");
userent.setPassword("uqwer");
em.persist(userent);
//}
} catch (Exception ex) {
System.err.println("Caught an exception: data not inserted into db");
throw new EJBException(ex);

}

}
public void createUser(String userid, String firstname, String surname, String password) {
try{
Usersent usersent= new Usersent();
//(userid, Firstname,Surname,Password );
usersent.setUserid(userid);
usersent.setFirstname(firstname);
usersent.setSurname(surname);
usersent.setPassword(password);
em.persist(usersent);
}catch(Exception ex){
System.err.print("can not insert new user details into the DB");
ex.printStackTrace();
}

}

so why is it that the JEE 5 tutorial works but when we create our own it does not work?

Please help.

eve