Skip to Main Content

Java EE (Java Enterprise Edition) General Discussion

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

Can't Instantiate Class Get Null Pointer Exception

843844Aug 16 2007 — edited Aug 20 2007
When I try to instantiate my AuthTools class, which is a backing bean, I get a null pointer exception.

It errors when it tries to create a user info object (Which is the three lines of code in the constructor which are // commented out).

Below are the files I think are relavent. I know its quite a bit of code but I've been stuck on this for two days and really need to move past it in the project.

========== AuthTools Backing Bean ==========
package com.stryker.cmf.helpers;

import javax.ejb.EJB;
import javax.faces.component.UIInput;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;

import com.stryker.cmf.accountmgrbean.AccountMgr;
import com.stryker.cmf.accountmgrbean.AccountMgrException;
import com.stryker.cmf.accountmgrbean.UserInfo;



public class AuthTools extends UIInput {
	private String loggedIn, isDoctor, isAdmin, isUser, isAcctMgr, isSales, isInHouse, firstName, lastName;
	
	@EJB AccountMgr userMgr;
	@EJB UserInfo user;

	public AuthTools()  {
		System.out.print("*");
		try {
			System.out.print("*");
			FacesContext facesContext = FacesContext.getCurrentInstance();
			System.out.print("*");
			ExternalContext externalContext = facesContext.getExternalContext();
			System.out.print("*");
			loggedIn = ((externalContext.getUserPrincipal() != null) ? "true" : "false");
			System.out.print("*");
			if (loggedIn == "true") {
				System.out.print("+!+");
				//user = userMgr.getInfo(externalContext.getUserPrincipal().getName());
				System.out.print("+!+" + externalContext.getUserPrincipal().getName() + "+!+");
				//lastName = user.getLastname();
				System.out.print("+");
				//firstName = user.getFirstname();
				System.out.print("+");
			}
			System.out.print("*");
			if (firstName == null) firstName = "Unknown";
			System.out.print("*");
			if (lastName == null) lastName = "User";
			System.out.print("*");
			isDoctor = (externalContext.isUserInRole("doctor") ? "true" : "false");
			System.out.print("*");
			isAdmin = (externalContext.isUserInRole("admin") ? "true" : "false");
			System.out.print("*");
			isUser = (externalContext.isUserInRole("users") ? "true" : "false");
			System.out.print("*");
			isAcctMgr = (externalContext.isUserInRole("acctmgr") ? "true" : "false");
			System.out.print("*");
			isSales = (externalContext.isUserInRole("sales") ? "true" : "false");
			System.out.print("*");
			isInHouse = (externalContext.isUserInRole("inhouse") ? "true" : "false");
			System.out.print("*");
			System.out.println("****************" + firstName + " " + lastName);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	public String getLoggedIn() {
		return loggedIn;
	}
	public String getIsDoctor() {
		return isDoctor;
	}
	public String getIsAdmin() {
		return isAdmin;
	}
	public String getFirstName() {
		return firstName;
	}

	public String getLastName() {
		return lastName;
	}

	public String getIsUser() {
		return isUser;
	}
	public String getIsAcctMgr() {
		return isAcctMgr;
	}
	public String getIsSales() {
		return isSales;
	}
	public String getIsInHouse() {
		return isInHouse;
	}
}
========== UserInfo Session Bean ==========
package com.stryker.cmf.accountmgrbean;

import javax.annotation.PostConstruct;
import javax.ejb.Stateless;

@Stateless
public class UserInfoBean implements UserInfo {
	private String username;
	private String groupname;
	private String firstname;
	private String lastname;
	private String title;
	private String phone;
	private String extension;
	private String email;
	
	@PostConstruct
	public void initialize() {
		username = " ";
		groupname = " ";
		firstname = " ";
		lastname = " ";
		title = " ";
		phone = " ";
		extension = " ";
		email = " ";
	}
	
	public String getUsername() {
		return username;
	}
	public void setUsername(String username) {
		this.username = username;
	}
	public String getGroupname() {
		return groupname;
	}
	public void setGroupname(String groupname) {
		this.groupname = groupname;
	}
	public String getFirstname() {
		return firstname;
	}
	public void setFirstname(String firstname) {
		this.firstname = firstname;
	}
	public String getLastname() {
		return lastname;
	}
	public void setLastname(String lastname) {
		this.lastname = lastname;
	}
	public String getTitle() {
		return title;
	}
	public void setTitle(String title) {
		this.title = title;
	}
	public String getPhone() {
		return phone;
	}
	public void setPhone(String phone) {
		this.phone = phone;
	}
	public String getExtension() {
		return extension;
	}
	public void setExtension(String extension) {
		this.extension = extension;
	}
	public String getEmail() {
		return email;
	}
	public void setEmail(String email) {
		this.email = email;
	}
}
========= UserManager Bean ==========
package com.stryker.cmf.accountmgrbean;

import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Random;

import javax.ejb.EJB;
import javax.ejb.Stateless;

import com.stryker.cmf.cimailer.CIMailer;
import com.stryker.cmf.cimailer.CIMailerException;
/**
 * 
 * @author tony.mattas
 *
 */
@Stateless
public class AccountMgrBean implements AccountMgr {
	@EJB UsersFacadeLocal userfacade;
	@EJB CIMailer mailer;
	@EJB UserInfo info;
	
	public void addUser(String username, String firstname, String lastname, String title, String phone, String extension, String email) throws AccountMgrException  {
		String password = randomPassword();
		Users user = userfacade.findById(username);
		if (user != null) { 
			throw new AccountMgrException("The Account " + user.getUsername() + "already exists.");
		}
		user = new Users();
		user.setUsername(username);
		user.setGroupname("users");
		user.setFirstname(firstname);
		user.setLastname(lastname);
		user.setTitle(title);
		user.setPhone(phone);
		user.setExtension(extension);
		user.setEmail(email);
		user.setDisabled(0);
		user.setNumfails(0);
		try {
			System.out.println("Trying to e-mail");
			user.setPassword(hash(password));
			userfacade.save(user);
			mailer.addRecipient(email);
			mailer.setSubject("Stryker CranioMaxilloFacial Login Information");
			mailer.setSender("CIAdministrators@stryker.com", "Stryker CranioMaxilloFacial");
			mailer.setMessage("Dear User,\n\n" +
					"Welcome to the Stryker CranioMaxilloFacial custom implant site. This e-mail contains your registration information " +
					"along with a temporary username and password. \n\n" +
					"Username: " + username + "\n" +
					"Password: " + password + "\n\n" +
					"You will be asked to change this password on first login, however please note that you will not be allowed " +
					"to log in until your registration request is processed by a Stryker CranioMaxilloFacial representative. " +
					"You will receive a second e-mail when this process is completed.\n\n" +
					"The above username and password is for the following person:\n\n" +
					user.getFirstname() + " " + user.getLastname() + "\n" +
					"(" + user.getPhone().substring(0, 3) + ") " + user.getPhone().substring(3, 6) + "-" + 
					user.getPhone().substring(6, 10) + " " + user.getExtension() + "\n" +
					user.getEmail() + "\n\n" + 
					" If this is not you please delete this e-mail and immediately contact 1+ (269) 324-5346.");

			mailer.sendMessage();
		} catch (NoSuchAlgorithmException e1) {
			throw new AccountMgrException("MD5 Algorithm Does Not Exist.", e1);
		} catch (RuntimeException e) {
			throw new AccountMgrException("Unable to Commit Data.", e);
		} catch (CIMailerException e) {
			throw new AccountMgrException("Unable to mail password.", e); 
		}
	}
	
	/**
	 * Generates a MD5 Hash
	 * @param password Plain text password
	 * @return Hashed Password
	 * @throws NoSuchAlgorithmException 
	 * @throws NoSuchAlgorithmException
	 */
	private String hash(String password) throws NoSuchAlgorithmException {
		/* String to return */
		String hashed = null;
		BigInteger hash;
		try {
			/* Hashing algorithm */
			MessageDigest md5 = MessageDigest.getInstance("MD5");
			md5.update(password.getBytes());
			hash = new BigInteger(1, md5.digest());
			hashed = hash.toString(16);
			/* Acount for varying string lengths */
			if (hashed.length() < 32) {
				hashed = 0 + hashed;
			}
		} catch (NoSuchAlgorithmException e) {
			/* Throw up to parent */
			throw e;
		}
		return hashed;
	}

	/**
	 * Generates a random password
	 * @return The new Random password
	 */
	private String randomPassword() {
		char[] allowedChars = "abcdefghijklmnopqrstuvqxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890".toCharArray();
		Random randNumberGen = new Random();
		StringBuffer password = new StringBuffer();
		int randNumber;
		for (int i=0; i<10; i++) {
			randNumber = (randNumberGen.nextInt(61));
			password.append(allowedChars[randNumber]);
		}
		return password.toString();
	}
	
	public void setGroup(String user, String group) throws AccountMgrException {
		Users username = new Users();
		username = userfacade.findById(user);
		// Check to see if the user exists.
		if (username == null) {
			throw new AccountMgrException("User " + user + " Does Not Exist.");
		}
		else {
			//Edit group
			username.setGroupname(group);
			try {
				userfacade.update(username);
			} catch (RuntimeException e) {
				throw new AccountMgrException("Unable to Commit Data.", e);
			}	
		}
	}
	
	public void setPassword(String username, String password) throws AccountMgrException {
		Users user = new Users();
		user = userfacade.findById(username);
		// Check to see if the user exists.
		if (user == null) {
			throw new AccountMgrException("User " + username + " Does Not Exist.");
		}
		else {
			//Edit group
			try {
				user.setPassword(hash(password));
				userfacade.update(user);
			} catch (RuntimeException e) {
				throw new AccountMgrException("Unable to Commit Data.", e);
			} catch (NoSuchAlgorithmException e) {
				throw new AccountMgrException("MD5 Algorithm Does Not Exist.", e);
			}
		}
	}
	
	public void newPassword(String username) throws AccountMgrException {
		setPassword(username, randomPassword());
	}
	
	public void setInfo(String username, String firstname, String lastname, String title, String phone, String extension, String email) throws AccountMgrException {
		Users user = userfacade.findById(username);
		if (user == null) { 
			throw new AccountMgrException("The Account " + user.getUsername() + "does not exist.");
		}
		user.setUsername(username);
		user.setGroupname("users");
		user.setFirstname(firstname);
		user.setLastname(lastname);
		user.setTitle(title);
		user.setPhone(phone);
		user.setExtension(extension);
		user.setEmail(email);
		try {
			userfacade.save(user);
		} catch (RuntimeException e) {
			throw new AccountMgrException("Unable to Commit Data.", e);
		} 
	}
	
	public void setInfo(UserInfo user) throws AccountMgrException {
		setInfo(user.getUsername(), user.getFirstname(), user.getLastname(), user.getTitle(), user.getPhone(), user.getExtension(), user.getEmail());
	}
	
	public UserInfo getInfo(String username) throws AccountMgrException {
		System.out.println("*************Looking up: " + username);
		Users user = userfacade.findById(username);
		if (user == null) { 
			throw new AccountMgrException("The Account " + user.getUsername() + "does not exist.");
		}
		info.setUsername(user.getUsername());
		info.setGroupname(user.getGroupname());
		info.setFirstname(user.getFirstname());
		info.setLastname(user.getLastname());
		info.setTitle(user.getTitle());
		info.setPhone(user.getPhone());
		info.setExtension(user.getExtension());
		info.setEmail(user.getEmail());
		return info;
		}

}
==========The Faces page==========
<?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:ui="http://java.sun.com/jsf/facelets"
	xmlns:h="http://java.sun.com/jsf/html"
	xmlns:f="http://java.sun.com/jsf/core" xml:lang="en" lang="en">
		<ui:composition template="/templates/template.xhtml">
	<head>
		<title>My XHTML Page</title>
		<meta http-equiv="keywords" content="enter,your,keywords,here" />
		<meta http-equiv="description"
			content="A short description of this page." />
		<meta http-equiv="content-type" content="text/html; charset=UTF-8" />

		<!--<link rel="stylesheet" type="text/css" href="styles.css">-->
	</head>
		<body>



			<ui:define name="title">
			Welcome
		</ui:define>
			<ui:define name="body">
			Hello�<h:outputText value="#{AuthTools.firstName}"></h:outputText>�
				<h:outputText value="#{AuthTools.lastName}"></h:outputText>, welcome back to Custom Implants!
			<p style="width: 100%; text-align: center;">
					<h:graphicImage url="../media/main.png"></h:graphicImage>

					<h:dataTable border="1" width="80%">
						<column id="date"> <facet name="header"> <outputText
							value="column1" /> </facet> </column>
						<column id="news"> <facet name="header"> <outputText
							value="column2" /> </facet> </column>
					</h:dataTable>
			</p>
			</ui:define>
		</body>
	</ui:composition>
</html>
=========faces_config.xml=========
<?xml version='1.0' encoding='UTF-8'?>

<faces-config 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-facesconfig_1_2.xsd"
	version="1.2">

	<application>
		<view-handler>com.sun.facelets.FaceletViewHandler</view-handler>
	</application>
	<managed-bean>
		<managed-bean-name>Register</managed-bean-name>
		<managed-bean-class>
			com.stryker.cmf.admin.Register
		</managed-bean-class>
		<managed-bean-scope>request</managed-bean-scope>
	</managed-bean>
	<managed-bean>
		<managed-bean-name>AuthTools</managed-bean-name>
		<managed-bean-class>
			com.stryker.cmf.helpers.AuthTools
		</managed-bean-class>
		<managed-bean-scope>request</managed-bean-scope>
	</managed-bean>

	<navigation-rule>



		<navigation-case>
			<description>Redirects a user to login</description>
			<from-outcome>login</from-outcome>

			<to-view-id>/users/userhome.xhtml</to-view-id>
			<redirect />
		</navigation-case>
		<navigation-case>
			<description>
				Redirects user to change password form
			</description>
			<from-outcome>chgpasswd</from-outcome>

			<to-view-id>/users/password.xhtml</to-view-id>
			<redirect />
		</navigation-case>
		<navigation-case>
			<description>
				Allows users to register a new account.
			</description>
			<from-outcome>register</from-outcome>

			<to-view-id>/system/register.xhtml</to-view-id>
			<redirect />
		</navigation-case>
		<navigation-case>
			<description>Site management console</description>
			<from-outcome>console</from-outcome>
			<to-view-id>/admin/console.xhtml</to-view-id>
			<redirect></redirect>
		</navigation-case>
	</navigation-rule>
	<navigation-rule>
		<from-view-id>/admin/console.xhtml</from-view-id>
		<navigation-case>
			<description>See all users on site.</description>
			<from-outcome>seeuser</from-outcome>

			<to-view-id>/admin/users.xhtml</to-view-id>
			<redirect />
		</navigation-case>
	</navigation-rule>
</faces-config>
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Sep 17 2007
Added on Aug 16 2007
19 comments
1,190 views