NullPointerException when attempting to login JSF Web Application - jsf

first time poster so apologies for any mistakes. I have a web application connected to an Oracle database and don't understand why I am getting the NPE when trying to login:
StackTrace:
It points to this method in my login bean:
public String checkCredentials() {
String outcome = "";
User user = userHandler.findUserByUsername(username); <---NullPointerException
if (username.equals(user.getUserName())
&& password.equals(user.getPassword())) {
//clearFields();
switch (user.getUserType()) {
case "Super":
outcome = "Super";
break;
case "Admin":
outcome = "Admin";
break;
case "Teacher":
outcome = "Teacher";
break;
case "Parent":
outcome = "Parent";
break;
case "Student":
outcome = "Student";
break;
}
}
if (outcome.isEmpty()) {
clearFields();
FacesMessage msg = new FacesMessage("Username and/or password not recognised.");
FacesContext.getCurrentInstance().addMessage(null, msg);
}
return outcome;
}
I have tested the following method in the handler to ensure the SQL pulls the correct info:
public User findUserByUsername(String username) {
User u = null;
DatabaseConnection con = ConnectionManager.getInstance().getConnection();
con.prepareStatement(FIND_USER_BY_USERNAME);
con.setStatementParameter(1, username);
if (con.executePreparedStatement()) {
u = prepareUser(con.getResultSet());
}
con.close();
return u;
}
private User prepareUser(ResultSet rs) {
User u = null;
try {
if (rs.next()) {
u = new User(rs.getInt("UserId"),
rs.getString("fName"),
rs.getString("lName"),
rs.getString("userName"),
rs.getString("password"),
rs.getString("userType"),
rs.getInt("schoolID"));
}
} catch (SQLException sqle) {
sqle.getMessage();
}
return u;
}
Here is my login xhtml:
<h:body>
<ui:composition template="/template.xhtml">
<ui:define name="content">
<h2>Login</h2>
<h:messages class="error" />
<h:form>
<p>Username:
<h:inputText id="username"
maxlength="12"
required="true"
requiredMessage="Please enter your username"
title="Your username: "
value="#{login.username}" />
</p>
<p>Password:
<h:inputSecret id="password"
maxlength="15"
required="true"
requiredMessage="Please enter your password"
title="Your password: "
value="#{login.password}" />
</p>
<p>
<h:commandButton type="submit" value="Log-in" action="#{login.checkCredentials()}"/>
<h:commandButton type="reset" value="Reset" />
</p>
</h:form>
</ui:define>
</ui:composition>
</h:body>
The username that is used where the NPE points is set by the user in the form, the username and password exist in my database and the SQL string 'FIND_USER_BY_USERNAME' pulls the correct user when tested separate. Would really appreciate a point in the right direction.
edit:
Login_UI:
package Beans;
import ActiveRecord.User;
import ActiveRecord.UserHandler;
import java.io.Serializable;
import javax.inject.Named;
import javax.enterprise.context.SessionScoped;
import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
#Named(value = "login")
#SessionScoped
public class Login_UI implements Serializable {
private String username;
private String password;
private String userType;
private final transient UserHandler userHandler;
public Login_UI() {
clearFields();
userHandler = new UserHandler();
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getUserType() {
return userType;
}
public void setUserType(String userType) {
this.userType = userType;
}
public void clearFields() {
username = "";
password = "";
}
public String checkCredentials() {
String outcome = "";
User user = userHandler.findUserByUsername(username);
if (username.equals(user.getUserName())
&& password.equals(user.getPassword())) {
//clearFields();
switch (user.getUserType()) {
case "Super":
outcome = "Super";
break;
case "Admin":
outcome = "Admin";
break;
case "Teacher":
outcome = "Teacher";
break;
case "Parent":
outcome = "Parent";
break;
case "Student":
outcome = "Student";
break;
}
}
if (outcome.isEmpty()) {
clearFields();
FacesMessage msg = new FacesMessage("Username and/or password not recognised.");
FacesContext.getCurrentInstance().addMessage(null, msg);
}
return outcome;
}
}
userHandler:
package ActiveRecord;
import Database.ConnectionManager;
import Database.DatabaseConnection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
public class UserHandler {
private static final String FIND_USER_BY_USERNAME = "SELECT userID, fName, lName, "
+ "username, password, usertype, FK1_schoolID FROM UserInformation "
+ "WHERE UserName = ?";
private static final String FIND_USER_BY_ID = "SELECT fName, lName, userName, "
+ "password, userType, FK1_schoolID FROM UserInformation "
+ "WHERE userID = ?";
private static final String FIND_USER_BY_FNAME = "SELECT * FROM UserInformation "
+ "WHERE fName = ? "
+ "ORDER BY userID";
private static final String FIND_USER_BY_LNAME = "SELECT * FROM UserInformation "
+ "WHERE lName = ? "
+ "ORDER BY userID";
private static final String FIND_ALL_USERS = "SELECT * FROM UserInformation "
+ "ORDER BY userID";
private static final String FIND_STUDENT_BY_ID = "SELECT StudentID, yearGroup, "
+ "overallMarks, FK2_UserID FROM Student WHERE StudentID = ? ";
private static final String FIND_STUDENT_BY_YEARGROUP = "SELECT StudentID, yearGroup, "
+ "overallMarks, FK2_UserID FROM Student WHERE yearGroup = ? "
+ "ORDER BY studentID";
private static final String FIND_ALL_STUDENTS = "SELECT * FROM Student "
+ "LEFT JOIN UserInformation ON Student.FK2_UserId = UserInformation.UserId "
+ "ORDER BY Student.studentId";
private User prepareUser(ResultSet rs) {
User u = null;
try {
if (rs.next()) {
u = new User(rs.getInt("UserId"),
rs.getString("fName"),
rs.getString("lName"),
rs.getString("userName"),
rs.getString("password"),
rs.getString("userType"),
rs.getInt("schoolID"));
System.out.println("Test: prepUser");
}
} catch (SQLException sqle) {
sqle.getMessage();
}
return u;
}
private ArrayList<User> prepareUsers(ResultSet rs) {
ArrayList<User> u = new ArrayList();
try {
while (rs.next()) {
u.add(new User(rs.getInt("UserId"),
rs.getString("fName"),
rs.getString("lName"),
rs.getString("userName"),
rs.getString("password"),
rs.getString("userType"),
rs.getInt("schoolID")));
}
} catch (SQLException sqle) {
sqle.getMessage();
}
return u;
}
private Student prepareStudent(ResultSet rs) {
Student s = null;
try {
if (rs.next()) {
s = new Student(rs.getInt("StudentId"),
rs.getInt("yearGroup"),
rs.getInt("overallMarks"),
rs.getInt("FK1_StudenttestID"),
rs.getInt("FK2_UserID"));
}
} catch (SQLException sqle) {
sqle.getMessage();
}
return s;
}
private ArrayList<Student> prepareStudents(ResultSet rs) {
ArrayList<Student> s = new ArrayList();
try {
while (rs.next()) {
s.add(new Student(rs.getInt("StudentId"),
rs.getInt("yearGroup"),
rs.getInt("overallMarks"),
rs.getInt("FK1_StudenttestID"),
rs.getInt("FK2_UserID")));
}
} catch (SQLException sqle) {
sqle.getMessage();
}
return s;
}
public User findUserById(int userId) {
User u = null;
DatabaseConnection con = ConnectionManager.getInstance().getConnection();
con.prepareStatement(FIND_USER_BY_ID);
con.setStatementParameter(1, userId);
if (con.executePreparedStatement()) {
u = prepareUser(con.getResultSet());
}
con.close();
return u;
}
public ArrayList<User> findUserByFirstName(String fName) {
ArrayList<User> u = null;
DatabaseConnection con = ConnectionManager.getInstance().getConnection();
con.prepareStatement(FIND_USER_BY_FNAME);
con.setStatementParameter(1, fName);
if (con.executePreparedStatement()) {
u = prepareUsers(con.getResultSet());
}
con.close();
return u;
}
public ArrayList<User> findUserByLastName(String lName) {
ArrayList<User> u = null;
DatabaseConnection con = ConnectionManager.getInstance().getConnection();
con.prepareStatement(FIND_USER_BY_LNAME);
con.setStatementParameter(1, lName);
if (con.executePreparedStatement()) {
u = prepareUsers(con.getResultSet());
}
con.close();
return u;
}
public User findUserByUsername(String username) {
User u = null;
DatabaseConnection con = ConnectionManager.getInstance().getConnection();
con.prepareStatement(FIND_USER_BY_USERNAME);
con.setStatementParameter(1, username);
if (con.executePreparedStatement()) {
u = prepareUser(con.getResultSet());
}
con.close();
return u;
}
public ArrayList<User> findAllUsers() {
ArrayList<User> u = null;
DatabaseConnection con = ConnectionManager.getInstance().getConnection();
con.prepareStatement(FIND_ALL_USERS);
if (con.executePreparedStatement()) {
u = prepareUsers(con.getResultSet());
}
con.close();
return u;
}
public Student findStudentById(int studentId) {
Student s = null;
DatabaseConnection con = ConnectionManager.getInstance().getConnection();
con.prepareStatement(FIND_STUDENT_BY_ID);
con.setStatementParameter(1, studentId);
if (con.executePreparedStatement()) {
s = prepareStudent(con.getResultSet());
}
con.close();
return s;
}
public ArrayList<Student> findStudentByYearGroup() {
ArrayList<Student> s = null;
DatabaseConnection con = ConnectionManager.getInstance().getConnection();
con.prepareStatement(FIND_STUDENT_BY_YEARGROUP);
if (con.executePreparedStatement()) {
s = prepareStudents(con.getResultSet());
}
con.close();
return s;
}
public ArrayList<Student> findAllStudents() {
ArrayList<Student> s = null;
DatabaseConnection con = ConnectionManager.getInstance().getConnection();
con.prepareStatement(FIND_ALL_STUDENTS);
if (con.executePreparedStatement()) {
s = prepareStudents(con.getResultSet());
}
con.close();
return s;
}
public boolean createUser(User u) {
boolean userCreated = false;
ArrayList<User> users = findAllUsers();
boolean found = false;
for (User x : users) {
if (x.getUserName().equals(u.getUserName())) {
found = true;
}
}
if (!found) {
try {
u.insert();
userCreated = true;
} catch (Exception e) {
e.getMessage();
}
}
return userCreated;
}
public boolean deleteUser(User u) {
boolean deleted = false;
if (u != null) {
try {
u.delete();
deleted = true;
} catch (Exception e) {
e.getMessage();
}
}
return deleted;
}
}
Apologies for all the edits, I have found the problem just not sure how to fix it, my singleton database connection should create a pool of 5 available connections DatabaseConnection con = ConnectionManager.getInstance().getConnection(); but during this call it returns a null connection
package Database;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class DatabaseConnection {
private static final String DATABASE_URL = "removed";
private final ConnectionManager connManager;
private Connection conn = null;
private PreparedStatement stmt = null;
private ResultSet rs = null;
private int updateCount = -1;
public DatabaseConnection(ConnectionManager connectionManager) throws SQLException {
connManager = connectionManager;
DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());
conn = DriverManager.getConnection(DATABASE_URL);
}
public void close() {
connManager.releaseConnection(this);
}
public boolean prepareStatement(String sql) {
boolean statementPrepared = false;
try {
stmt = conn.prepareStatement(sql);
statementPrepared = true;
} catch (SQLException sqle) {
sqle.getMessage();
}
return statementPrepared;
}
public boolean executePreparedStatement() {
boolean resultSetAvailable = false;
try {
resultSetAvailable = stmt.execute();
updateCount = stmt.getUpdateCount();
rs = stmt.getResultSet();
} catch (SQLException sqle) {
sqle.getMessage();
}
return resultSetAvailable;
}
public boolean setStatementParameter(int paramIndex, boolean paramValue) {
boolean paramSet = false;
if (stmt != null) {
try {
stmt.setBoolean(paramIndex, paramValue);
paramSet = true;
} catch (SQLException sqle) {
sqle.getMessage();
}
}
return paramSet;
}
public boolean setStatementParameter(int paramIndex, String paramValue) {
boolean paramSet = false;
if (stmt != null) {
try {
stmt.setString(paramIndex, paramValue);
paramSet = true;
} catch (SQLException sqle) {
sqle.getMessage();
}
}
return paramSet;
}
public boolean setStatementParameter(int paramIndex, int paramValue) {
boolean paramSet = false;
if (stmt != null) {
try {
stmt.setInt(paramIndex, paramValue);
paramSet = true;
} catch (SQLException sqle) {
sqle.getMessage();
}
}
return paramSet;
}
public int getUpdateCount() {
return updateCount;
}
public ResultSet getResultSet() {
return rs;
}
}
package Database;
import java.sql.SQLException;
import java.util.ArrayList;
public class ConnectionManager {
private static final ConnectionManager instance = new ConnectionManager();
private final ArrayList<DatabaseConnection> available;
private final ArrayList<DatabaseConnection> busy;
private ConnectionManager() {
available = new ArrayList();
busy = new ArrayList();
for (int i = 0; i < 5; i++) {
try {
available.add(new DatabaseConnection(this));
} catch (SQLException sqle) {
sqle.getMessage();
}
}
}
public static ConnectionManager getInstance() {
return instance;
}
public DatabaseConnection getConnection() {
DatabaseConnection connection = null;
synchronized (this) {
if (!available.isEmpty()) {
connection = available.remove(0); <---This gets skipped over as available is never added to
busy.add(connection);
}
}
return connection;
}
public void releaseConnection(DatabaseConnection connection) {
if (connection != null) {
synchronized (this) {
if (busy.remove(connection)) {
available.add(connection);
}
}
}
}
}

It seems that the error lies somewhere with your custom built connection pool. While it is tempting to create one yourself, it's not very simple because it can easily mess up the API, the transaction management, the pool auto-sizing when more connections than expected are needed. I would suggest that you use one of the libraries that are already there, and do the job perfectly, such as C3PO. After that, your ConnectionPool/CollectionManager singleton can be as simple as this:
public class ConnectionPool {
private static ComboPooledDataSource cpds;
private static class ConnectionPoolHolder {
private static final ConnectionPool INSTANCE = new ConnectionPool();
}
private ConnectionPool() {
cpds = new ComboPooledDataSource();
try {
cpds.setDriverClass(ServerConfig.JDBC_DRIVER_CLASS); //loads the jdbc driver
} catch (PropertyVetoException e) {
e.printStackTrace();
}
cpds.setJdbcUrl(ServerConfig.CONNECTION_STRING);
cpds.setUser(ServerConfig.DB_USER);
cpds.setPassword(ServerConfig.DB_PASS);
// the settings below are optional -- c3p0 can work with defaults
cpds.setMinPoolSize(ServerConfig.MIN_POOL_SIZE);
cpds.setAcquireIncrement(5);
cpds.setMaxPoolSize(ServerConfig.MAX_POOL_SIZE);
cpds.setTestConnectionOnCheckin(true);
cpds.setPreferredTestQuery("select 1");
cpds.setTestConnectionOnCheckout(true);
cpds.setIdleConnectionTestPeriod(9000);
}
public static ConnectionPool getInstance() {
return ConnectionPoolHolder.INSTANCE;
}
public Connection getConnection() {
try {
return cpds.getConnection();
} catch (SQLException e) {
e.printStackTrace();
}
return null;
}
}

Related

How should I create a session for newly entered user in JSF

I am developing a web application in JSF. My question is when user enter after authentication the data will be the same means if we have two employee the data display is the same how this problem is solved in program. I import the entity from database and jsf page from entity
This is new for me I am try in PHP but I don't know in JSF.
public EmplController() {
}
public Empl getSelected() {
return selected;
}
public void setSelected(Empl selected) {
this.selected = selected;
}
protected void setEmbeddableKeys() {
}
protected void initializeEmbeddableKey() {
}
private EmplFacade getFacade() {
return ejbFacade;
}
public Empl prepareCreate() {
selected = new Empl();
initializeEmbeddableKey();
return selected;
}
public void create() {
persist(PersistAction.CREATE, ResourceBundle.getBundle("/Bundle").getString("EmplCreated"));
if (!JsfUtil.isValidationFailed()) {
items = null; // Invalidate list of items to trigger re-query.
}
}
public void update() {
persist(PersistAction.UPDATE, ResourceBundle.getBundle("/Bundle").getString("EmplUpdated"));
}
public void destroy() {
persist(PersistAction.DELETE, ResourceBundle.getBundle("/Bundle").getString("EmplDeleted"));
if (!JsfUtil.isValidationFailed()) {
selected = null; // Remove selection
items = null; // Invalidate list of items to trigger re-query.
}
}
public List<Empl> getItems() {
if (items == null) {
items = getFacade().findAll();
}
return items;
}
private void persist(PersistAction persistAction, String successMessage) {
if (selected != null) {
setEmbeddableKeys();
try {
if (persistAction != PersistAction.DELETE) {
getFacade().edit(selected);
} else {
getFacade().remove(selected);
}
JsfUtil.addSuccessMessage(successMessage);
} catch (EJBException ex) {
String msg = "";
Throwable cause = ex.getCause();
if (cause != null) {
msg = cause.getLocalizedMessage();
}
if (msg.length() > 0) {
JsfUtil.addErrorMessage(msg);
} else {
JsfUtil.addErrorMessage(ex, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured"));
}
} catch (Exception ex) {
Logger.getLogger(this.getClass().getName()).log(Level.SEVERE, null, ex);
JsfUtil.addErrorMessage(ex, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured"));
}
}
}
public Empl getEmpl(java.lang.String id) {
return getFacade().find(id);
}
public List<Empl> getItemsAvailableSelectMany() {
return getFacade().findAll();
}
public List<Empl> getItemsAvailableSelectOne() {
return getFacade().findAll();
}
#FacesConverter(forClass = Empl.class)
public static class EmplControllerConverter implements Converter {
#Override
public Object getAsObject(FacesContext facesContext, UIComponent component, String value) {
if (value == null || value.length() == 0) {
return null;
}
EmplController controller = (EmplController) facesContext.getApplication().getELResolver().
getValue(facesContext.getELContext(), null, "emplController");
return controller.getEmpl(getKey(value));
}
java.lang.String getKey(String value) {
java.lang.String key;
key = value;
return key;
}
String getStringKey(java.lang.String value) {
StringBuilder sb = new StringBuilder();
sb.append(value);
return sb.toString();
}
#Override
public String getAsString(FacesContext facesContext, UIComponent component, Object object) {
if (object == null) {
return null;
}
if (object instanceof Empl) {
Empl o = (Empl) object;
return getStringKey(o.getUserName());
} else {
Logger.getLogger(this.getClass().getName()).log(Level.SEVERE, "object {0} is of type {1}; expected type: {2}", new Object[]{object, object.getClass().getName(), Empl.class.getName()});
return null;
}
}
}
private String username;
private String password;
private String role;
private String value;
public void setRole(String role) {
this.role = role;
}
public String getRole() {
return role;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassWord() {
return password;
}
public void setPassWord(String pass) {
this.password = pass;
}
public String LogInfo() {
System.out.println("" + username);
boolean log = ejbFacade.LogValidate(username, password, role);
System.out.println("" + log);
if (log==false) {
switch (role) {
case "admin":
value = "/faces/admin.xhtml?faces-redirect=true";
break;
case "employee":
value = "/faces/employee.xhtml?faces-redirect=true";
break;
case "director":
value = "/faces/director.xhtml?faces-redirect=true";
break;
case "manager":
value = "/faces/manager.xhtml?faces-redirect=true";
break;
case "simret":
value = "/faces/simret.xhtml?faces-redirect=true";
break;
case "driver":
value = "/faces/driver.xhtml?faces-redirect=true";
break;
case "store":
value = "/faces/store.xhtml?faces-redirect=true";
break;
}
} else {
return "/faces/record/List.xhtml?faces-redirect=true";
}
return value;
}
public String logout() {
HttpSession session = JsfUtil.getSession();
session.invalidate();
return "index";
}
I'm expecting when different employee is enter the data will be different but the data will be the same.

How to restrict CRUD functions for not logged users?

I followed this tutorial to do a CRUD application: https://www.youtube.com/watch?v=DFFKMq1kh-M&t=339s
Here is my ManagedBean for it:
package model_controller;
import com.sun.net.httpserver.HttpsServer;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.inject.Named;
import javax.enterprise.context.RequestScoped;
import javax.faces.context.FacesContext;
import javax.servlet.http.HttpServletRequest;
#Named(value = "studentManagedBean")
#RequestScoped
public class StudentManagedBean {
private int id, wiek;
private String nazwisko, email, adres;
public StudentManagedBean() {
}
public StudentManagedBean(int id, int wiek, String nazwisko, String email, String adres) {
//konstruktory
this.id = id;
this.wiek = wiek;
this.nazwisko = nazwisko;
this.email = email;
this.adres = adres;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getWiek() {
return wiek;
}
public void setWiek(int wiek) {
this.wiek = wiek;
}
public String getNazwisko() {
return nazwisko;
}
public void setNazwisko(String nazwisko) {
this.nazwisko = nazwisko;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getAdres() {
return adres;
}
public void setAdres(String adres) {
this.adres = adres;
}
//
public static Connection conn = null;
public static PreparedStatement pstmt = null;
public static ResultSet rs = null;
private String str = "";
//
public static Connection getConnection() {
try {
Class.forName("com.mysql.jdbc.Driver");
//Alt+enter
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/studenci?zeroDateTimeBehavior=convertToNull", "root", "");
} catch (ClassNotFoundException ex) {
Logger.getLogger(StudentManagedBean.class.getName()).log(Level.SEVERE, null, ex);
} catch (SQLException ex) {
Logger.getLogger(StudentManagedBean.class.getName()).log(Level.SEVERE, null, ex);
}
return conn;
}
public static void closeAll(Connection conn, PreparedStatement pstmt, ResultSet rs) {
if (conn != null) {
try {
conn.close();
} catch (SQLException ex) {
Logger.getLogger(StudentManagedBean.class.getName()).log(Level.SEVERE, null, ex);
}
}
if (pstmt != null) {
try {
pstmt.close();
} catch (SQLException ex) {
Logger.getLogger(StudentManagedBean.class.getName()).log(Level.SEVERE, null, ex);
}
}
if (rs != null) {
try {
rs.close();
} catch (SQLException ex) {
Logger.getLogger(StudentManagedBean.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
public ArrayList<StudentManagedBean> GetAllStudent() {
ArrayList<StudentManagedBean> arr = new ArrayList<>();
str = "SELECT s.id, s.nazwisko, s.wiek, s.adres, s.email FROM student s";
getConnection();
try {
pstmt = conn.prepareStatement(str);
rs = pstmt.executeQuery();
while (rs.next()) {
StudentManagedBean st = new StudentManagedBean();
st.setId(rs.getInt("id"));
st.setNazwisko(rs.getString("nazwisko"));
st.setWiek(rs.getInt("wiek"));
st.setAdres(rs.getString("adres"));
st.setEmail(rs.getString("email"));
//
arr.add(st);
}
} catch (SQLException ex) {
Logger.getLogger(StudentManagedBean.class.getName()).log(Level.SEVERE, null, ex);
} finally {
closeAll(conn, pstmt, rs);
}
return arr;
}
public void add() {
getConnection();
str = "insert into student(nazwisko, wiek, adres, email) values(?,?,?,?)";
try {
pstmt = conn.prepareStatement(str);
pstmt.setString(1, this.getNazwisko());
pstmt.setInt(2, this.getWiek());
pstmt.setString(3, this.getAdres());
pstmt.setString(4, this.getEmail());
int executeUpdate = pstmt.executeUpdate();
if (executeUpdate > 0) {
System.out.println("Zaktualizowano dane");
}
} catch (SQLException ex) {
Logger.getLogger(StudentManagedBean.class.getName()).log(Level.SEVERE, null, ex);
} finally {
closeAll(conn, pstmt, rs);
}
}
public void Edit() {
ArrayList<StudentManagedBean> arrList = GetAllStudent();
FacesContext fc = FacesContext.getCurrentInstance();
// Map<String,String> mapParam = fc.getExternalContext().getInitParameterMap();
// idStudent = mapParam.get("id");
int idStudent;
HttpServletRequest request = (HttpServletRequest) fc.getExternalContext().getRequest();
idStudent = Integer.parseInt(request.getParameter("id"));
//
for (StudentManagedBean studentManagedBean : arrList) {
if (studentManagedBean.getId() == idStudent) {
this.setId(studentManagedBean.getId());//błąd
this.setNazwisko(studentManagedBean.getNazwisko());
this.setWiek(studentManagedBean.getWiek());
this.setAdres(studentManagedBean.getAdres());
this.setEmail(studentManagedBean.getEmail());
}
}
setId(idStudent);
}
public void update() {
getConnection();
str = "update student set nazwisko=?, wiek=?, adres=?, email=? where id=?";
// Map<String,String> mapParam = fc.getExternalContext().getInitParameterMap();
// idStudent = mapParam.get("id");
FacesContext fc = FacesContext.getCurrentInstance();
HttpServletRequest request = (HttpServletRequest) fc.getExternalContext().getRequest();
int idStudent = Integer.parseInt(request.getParameter("id"));
try {
pstmt = conn.prepareStatement(str);
pstmt.setString(1, this.getNazwisko());
pstmt.setInt(2, this.getWiek());
pstmt.setString(3, this.getAdres());
pstmt.setString(4, this.getEmail());
pstmt.setInt(5, idStudent);
System.out.println(getNazwisko());
int executeUpdate = pstmt.executeUpdate();
if (executeUpdate > 0) {
System.out.println("Zaktualizowano dane");
}
} catch (SQLException ex) {
Logger.getLogger(StudentManagedBean.class.getName()).log(Level.SEVERE, null, ex);
} finally {
closeAll(conn, pstmt, rs);
}
}
public void delete() {
getConnection();
str = "DELETE FROM student where id=?";
FacesContext fc = FacesContext.getCurrentInstance();
HttpServletRequest request = (HttpServletRequest) fc.getExternalContext().getRequest();
int idStudent = Integer.parseInt(request.getParameter("id"));
try {
pstmt = conn.prepareStatement(str);
pstmt.setInt(1, idStudent);
int executeUpdate = pstmt.executeUpdate();
if (executeUpdate > 0) {
System.out.println("Usunięto dane");
}
} catch (SQLException ex) {
Logger.getLogger(StudentManagedBean.class.getName()).log(Level.SEVERE, null, ex);
} finally {
closeAll(conn, pstmt, rs);
}
}
}
It works pretty well, and I wanted to upgrade it - so everyone can see the data, but only logged in users can edit, add and delete records.
I found login tutorial: http://www.journaldev.com/7252/jsf-authentication-login-logout-database-example
How can I restrict edit, add and delete functions only for users that are logged in?
CRUD app is using RequestScope, login uses SessionScope, can i even use two different scopes in one app?
Should I use two different databases for login and students, or should I put it in one database, just two tables?
You can use the rendered attribute, which by default is set to true.
// Your form for inserting data to the database
<h:form rendered="#{studentManagedBean.isLoggedIn}">
...
</h:form>
// delete button
<h:commandButton action="#{studentManagedBean.delete()}"
rendered="#{studentManagedBean.isLoggedIn}" />
You have to add a variable and a method to your managedbean to check whether the user is logged in or not.
private boolean loggedIn;
// getter and setter
public boolean isLoggedIn(){
return loggedIn;
}

JSF Datamodel & JPA parent to leaves navigation. How to?

My web application is a CRUD web application based on JSF 2.0 / JPA using Java EE 5 and JDK 1.6. Running on Glassfish 3.1. The IDE is Netbeans 7.0. (I do not use EJB, nor CDI).
THE PROBLEM
What I can achieve now is perform CRUD on my entities. Which is fine. For each entity I have:
List.xhtml (LIsting all Datamodel items for that entity in datatable)
Create.xhtml (A form to create a new item)
View.xhtml (a form to view an item)
Edit.xhtml (a form to edit an item)
Structure
entities package: entities.
jpa.controllers package: JPA controllers (Javax persistence..).
jsf package: a managed bean for each entity (session Scoped).
But the main problem is parent-leaf navigation. I want my webapp to do the same thing as the Demo application Agile ScrumToys that comes along shipped with Netbeans 7.0. or the demo webapp from SpringFuse, otherwise :
E.G: When you display a list of WRITERS in a you have the last <h:column> where you put three <h:commandLink /> for editing, viewing and deleting the selected row.
What I intend to do is to add another in the same column that allows me to view a collection of child objects related to that selected row.
Hence, I want to show the list of BOOKS written by a given WRITER.
WRITER 1 ---------- * BOOK (one-to-many) relationship.
When the user clicks on the
<h:commandButton action="#{someManagedBean.showBooksForWriter}" value="#{i18n.listBooks}" /> it forwards him to the /book/List.xhtml (list of the selected WRITEr row should appear). And so on, from the book datatable, from a given row, I click on <h:commandLink action="#{someManagedBean.showReferencesForBook}" value="List of Book References"/> to get the list of references for the given book.
A given hint by #Matt was to use a method in the book managed bean:
public showBooksForWriter(Writer writer) {
// TODO: get the selected writer
// Get the list of books for the selected writer
return "/book/List"; // Outcome
}
And in the view :
<h:datatable value="#{writerController.items}" var="w">
.....
<h:column>
<h:commandButton action="#{bookController.showBooksForWriter(w}" value="Show Books For Writer"/>
</h:column>
....
</h:datatable>
But I could not figure how to (DataModel is driving mad). So if anyone could help! It would be very appreciated!
Below is my code
the WRITER entity:
package entities;
import javax.persistence.*; // other imports
#Entity
#Table(name = "WRITER")
#XmlRootElement
#NamedQueries({
#NamedQuery(name = "Writer.findAll", query = "SELECT w FROM Writer w"),
#NamedQuery(name = "Writer.findByWriterid", query = "SELECT w FROM Writer w WHERE w.writerid = :writerid"),
#NamedQuery(name = "Writer.findByName", query = "SELECT w FROM Writer w WHERE w.name = :name"),
#NamedQuery(name = "Writer.findBySurname", query = "SELECT w FROM Writer w WHERE w.surname = :surname"),
#NamedQuery(name = "Writer.findByMiddlename", query = "SELECT w FROM Writer w WHERE w.middlename = :middlename"),
#NamedQuery(name = "Writer.findByIsRewarded", query = "SELECT w FROM Writer w WHERE w.isRewarded = :isRewarded")})
public class Writer implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Basic(optional = false)
#NotNull
#Column(name = "writerid")
private Integer writerid;
#Size(max = 45)
#Column(name = "name")
private String name;
#Size(max = 45)
#Column(name = "surname")
private String surname;
#Size(max = 45)
#Column(name = "middlename")
private String middlename;
#Column(name = "isRewarded")
private Boolean isRewarded;
#ManyToMany(mappedBy = "writerList")
private List<Topic> topicList;
#OneToMany(cascade = CascadeType.ALL, mappedBy = "writer")
private List<Evaluation> evaluationList;
#OneToMany(cascade = CascadeType.ALL, mappedBy = "writer")
private List<Book> bookList;
public Writer() {
}
public Writer(Integer writerid) {
this.writerid = writerid;
}
public Integer getWriterid() {
return writerid;
}
public void setWriterid(Integer writerid) {
this.writerid = writerid;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSurname() {
return surname;
}
public void setSurname(String surname) {
this.surname = surname;
}
public String getMiddlename() {
return middlename;
}
public void setMiddlename(String middlename) {
this.middlename = middlename;
}
public Boolean getIsRewarded() {
return isRewarded;
}
public void setIsRewarded(Boolean isRewarded) {
this.isRewarded = isRewarded;
}
#XmlTransient
public List<Topic> getTopicList() {
return topicList;
}
public void setTopicList(List<Topic> topicList) {
this.topicList = topicList;
}
#XmlTransient
public List<Evaluation> getEvaluationList() {
return evaluationList;
}
public void setEvaluationList(List<Evaluation> evaluationList) {
this.evaluationList = evaluationList;
}
#XmlTransient
public List<Book> getBookList() {
return bookList;
}
public void setBookList(List<Book> bookList) {
this.bookList = bookList;
}
#Override
public int hashCode() {
int hash = 0;
hash += (writerid != null ? writerid.hashCode() : 0);
return hash;
}
#Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof Writer)) {
return false;
}
Writer other = (Writer) object;
if ((this.writerid == null && other.writerid != null) || (this.writerid != null && !this.writerid.equals(other.writerid))) {
return false;
}
return true;
}
#Override
public String toString() {
return getMiddlename();
}
}
The Writer MANAGED BEAN
package jsf;
import entities.Writer;
import jsf.util.JsfUtil;
import jsf.util.PaginationHelper;
import jpa.controllers.WriterJpaController;
import javax.faces.bean.ManagedBean;
// other imports here
#ManagedBean(name = "writerController")
#SessionScoped
public class WriterController implements Serializable {
#Resource
private UserTransaction utx = null;
#PersistenceUnit(unitName = "writerPU")
private EntityManagerFactory emf = null;
private Writer current;
private DataModel items = null;
private WriterJpaController jpaController = null;
private PaginationHelper pagination;
private int selectedItemIndex;
public WriterController() {
}
public Writer getSelected() {
if (current == null) {
current = new Writer();
selectedItemIndex = -1;
}
return current;
}
private WriterJpaController getJpaController() {
if (jpaController == null) {
jpaController = new WriterJpaController(utx, emf);
}
return jpaController;
}
public PaginationHelper getPagination() {
if (pagination == null) {
pagination = new PaginationHelper(10) {
#Override
public int getItemsCount() {
return getJpaController().getWriterCount();
}
#Override
public DataModel createPageDataModel() {
return new ListDataModel(getJpaController().findWriterEntities(getPageSize(), getPageFirstItem()));
}
};
}
return pagination;
}
public String prepareList() {
recreateModel();
return "List";
}
public String prepareView() {
current = (Writer) getItems().getRowData();
selectedItemIndex = pagination.getPageFirstItem() + getItems().getRowIndex();
return "View";
}
public String prepareCreate() {
current = new Writer();
selectedItemIndex = -1;
return "Create";
}
public String create() {
try {
getJpaController().create(current);
JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("WriterCreated"));
return prepareCreate();
} catch (Exception e) {
JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured"));
return null;
}
}
public String prepareEdit() {
current = (Writer) getItems().getRowData();
selectedItemIndex = pagination.getPageFirstItem() + getItems().getRowIndex();
return "Edit";
}
public String update() {
try {
getJpaController().edit(current);
JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("WriterUpdated"));
return "View";
} catch (Exception e) {
JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured"));
return null;
}
}
public String destroy() {
current = (Writer) getItems().getRowData();
selectedItemIndex = pagination.getPageFirstItem() + getItems().getRowIndex();
performDestroy();
recreateModel();
return "List";
}
public String destroyAndView() {
performDestroy();
recreateModel();
updateCurrentItem();
if (selectedItemIndex >= 0) {
return "View";
} else {
// all items were removed - go back to list
recreateModel();
return "List";
}
}
private void performDestroy() {
try {
getJpaController().destroy(current.getWriterid());
JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("WriterDeleted"));
} catch (Exception e) {
JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured"));
}
}
private void updateCurrentItem() {
int count = getJpaController().getWriterCount();
if (selectedItemIndex >= count) {
// selected index cannot be bigger than number of items:
selectedItemIndex = count - 1;
// go to previous page if last page disappeared:
if (pagination.getPageFirstItem() >= count) {
pagination.previousPage();
}
}
if (selectedItemIndex >= 0) {
current = getJpaController().findWriterEntities(1, selectedItemIndex).get(0);
}
}
public DataModel getItems() {
if (items == null) {
items = getPagination().createPageDataModel();
}
return items;
}
private void recreateModel() {
items = null;
}
public String next() {
getPagination().nextPage();
recreateModel();
return "List";
}
public String previous() {
getPagination().previousPage();
recreateModel();
return "List";
}
public SelectItem[] getItemsAvailableSelectMany() {
return JsfUtil.getSelectItems(getJpaController().findWriterEntities(), false);
}
public SelectItem[] getItemsAvailableSelectOne() {
return JsfUtil.getSelectItems(getJpaController().findWriterEntities(), true);
}
#FacesConverter(forClass = Writer.class)
public static class WriterControllerConverter implements Converter {
public Object getAsObject(FacesContext facesContext, UIComponent component, String value) {
if (value == null || value.length() == 0) {
return null;
}
WriterController controller = (WriterController) facesContext.getApplication().getELResolver().
getValue(facesContext.getELContext(), null, "writerController");
return controller.getJpaController().findWriter(getKey(value));
}
java.lang.Integer getKey(String value) {
java.lang.Integer key;
key = Integer.valueOf(value);
return key;
}
String getStringKey(java.lang.Integer value) {
StringBuffer sb = new StringBuffer();
sb.append(value);
return sb.toString();
}
public String getAsString(FacesContext facesContext, UIComponent component, Object object) {
if (object == null) {
return null;
}
if (object instanceof Writer) {
Writer o = (Writer) object;
return getStringKey(o.getWriterid());
} else {
throw new IllegalArgumentException("object " + object + " is of type " + object.getClass().getName() + "; expected type: " + WriterController.class.getName());
}
}
}
}
JSF Utility Class
package jsf.util;
import javax.faces.application.FacesMessage;
// Other imports here
public class JsfUtil {
public static SelectItem[] getSelectItems(List<?> entities, boolean selectOne) {
int size = selectOne ? entities.size() + 1 : entities.size();
SelectItem[] items = new SelectItem[size];
int i = 0;
if (selectOne) {
items[0] = new SelectItem("", "---");
i++;
}
for (Object x : entities) {
items[i++] = new SelectItem(x, x.toString());
}
return items;
}
public static void addErrorMessage(Exception ex, String defaultMsg) {
String msg = ex.getLocalizedMessage();
if (msg != null && msg.length() > 0) {
addErrorMessage(msg);
} else {
addErrorMessage(defaultMsg);
}
}
public static void addErrorMessages(List<String> messages) {
for (String message : messages) {
addErrorMessage(message);
}
}
public static void addErrorMessage(String msg) {
FacesMessage facesMsg = new FacesMessage(FacesMessage.SEVERITY_ERROR, msg, msg);
FacesContext.getCurrentInstance().addMessage(null, facesMsg);
}
public static void addSuccessMessage(String msg) {
FacesMessage facesMsg = new FacesMessage(FacesMessage.SEVERITY_INFO, msg, msg);
FacesContext.getCurrentInstance().addMessage("successInfo", facesMsg);
}
public static String getRequestParameter(String key) {
return FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap().get(key);
}
public static Object getObjectFromRequestParameter(String requestParameterName, Converter converter, UIComponent component) {
String theId = JsfUtil.getRequestParameter(requestParameterName);
return converter.getAsObject(FacesContext.getCurrentInstance(), component, theId);
}
}
JSF Pagination helper
package jsf.util;
import javax.faces.model.DataModel;
public abstract class PaginationHelper {
private int pageSize;
private int page;
public PaginationHelper(int pageSize) {
this.pageSize = pageSize;
}
public abstract int getItemsCount();
public abstract DataModel createPageDataModel();
public int getPageFirstItem() {
return page * pageSize;
}
public int getPageLastItem() {
int i = getPageFirstItem() + pageSize - 1;
int count = getItemsCount() - 1;
if (i > count) {
i = count;
}
if (i < 0) {
i = 0;
}
return i;
}
public boolean isHasNextPage() {
return (page + 1) * pageSize + 1 <= getItemsCount();
}
public void nextPage() {
if (isHasNextPage()) {
page++;
}
}
public boolean isHasPreviousPage() {
return page > 0;
}
public void previousPage() {
if (isHasPreviousPage()) {
page--;
}
}
public int getPageSize() {
return pageSize;
}
} // END of CLASS
The JPA Controller
package jpa.controllers;
import entities.Writer;
// other imports here
public class WriterJpaController implements Serializable {
public WriterJpaController(UserTransaction utx, EntityManagerFactory emf) {
this.utx = utx;
this.emf = emf;
}
private UserTransaction utx = null;
private EntityManagerFactory emf = null;
public EntityManager getEntityManager() {
return emf.createEntityManager();
}
public void create(Writer writer) throws RollbackFailureException, Exception {
if (writer.getTopicList() == null) {
writer.setTopicList(new ArrayList<Topic>());
}
if (writer.getEvaluationList() == null) {
writer.setEvaluationList(new ArrayList<Evaluation>());
}
if (writer.getBookList() == null) {
writer.setBookList(new ArrayList<Book>());
}
EntityManager em = null;
try {
utx.begin();
em = getEntityManager();
List<Topic> attachedTopicList = new ArrayList<Topic>();
for (Topic topicListTopicToAttach : writer.getTopicList()) {
topicListTopicToAttach = em.getReference(topicListTopicToAttach.getClass(), topicListTopicToAttach.getTopicname());
attachedTopicList.add(topicListTopicToAttach);
}
writer.setTopicList(attachedTopicList);
List<Evaluation> attachedEvaluationList = new ArrayList<Evaluation>();
for (Evaluation evaluationListEvaluationToAttach : writer.getEvaluationList()) {
evaluationListEvaluationToAttach = em.getReference(evaluationListEvaluationToAttach.getClass(), evaluationListEvaluationToAttach.getEvaluationPK());
attachedEvaluationList.add(evaluationListEvaluationToAttach);
}
writer.setEvaluationList(attachedEvaluationList);
List<Book> attachedBookList = new ArrayList<Book>();
for (Book bookListBookToAttach : writer.getBookList()) {
bookListBookToAttach = em.getReference(bookListBookToAttach.getClass(), bookListBookToAttach.getBookPK());
attachedBookList.add(bookListBookToAttach);
}
writer.setBookList(attachedBookList);
em.persist(writer);
for (Topic topicListTopic : writer.getTopicList()) {
topicListTopic.getWriterList().add(writer);
topicListTopic = em.merge(topicListTopic);
}
for (Evaluation evaluationListEvaluation : writer.getEvaluationList()) {
Writer oldWriterOfEvaluationListEvaluation = evaluationListEvaluation.getWriter();
evaluationListEvaluation.setWriter(writer);
evaluationListEvaluation = em.merge(evaluationListEvaluation);
if (oldWriterOfEvaluationListEvaluation != null) {
oldWriterOfEvaluationListEvaluation.getEvaluationList().remove(evaluationListEvaluation);
oldWriterOfEvaluationListEvaluation = em.merge(oldWriterOfEvaluationListEvaluation);
}
}
for (Book bookListBook : writer.getBookList()) {
Writer oldWriterOfBookListBook = bookListBook.getWriter();
bookListBook.setWriter(writer);
bookListBook = em.merge(bookListBook);
if (oldWriterOfBookListBook != null) {
oldWriterOfBookListBook.getBookList().remove(bookListBook);
oldWriterOfBookListBook = em.merge(oldWriterOfBookListBook);
}
}
utx.commit();
} catch (Exception ex) {
try {
utx.rollback();
} catch (Exception re) {
throw new RollbackFailureException("An error occurred attempting to roll back the transaction.", re);
}
throw ex;
} finally {
if (em != null) {
em.close();
}
}
}
public void edit(Writer writer) throws IllegalOrphanException, NonexistentEntityException, RollbackFailureException, Exception {
// remainder of code goes here
}
public void destroy(Integer id) throws IllegalOrphanException, NonexistentEntityException, RollbackFailureException, Exception {
// remainder of code goes here
}
public List<Writer> findWriterEntities() {
return findWriterEntities(true, -1, -1);
}
public List<Writer> findWriterEntities(int maxResults, int firstResult) {
return findWriterEntities(false, maxResults, firstResult);
}
private List<Writer> findWriterEntities(boolean all, int maxResults, int firstResult) {
EntityManager em = getEntityManager();
try {
CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
cq.select(cq.from(Writer.class));
Query q = em.createQuery(cq);
if (!all) {
q.setMaxResults(maxResults);
q.setFirstResult(firstResult);
}
return q.getResultList();
} finally {
em.close();
}
}
public Writer findWriter(Integer id) {
EntityManager em = getEntityManager();
try {
return em.find(Writer.class, id);
} finally {
em.close();
}
}
public int getWriterCount() {
EntityManager em = getEntityManager();
try {
CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
Root<Writer> rt = cq.from(Writer.class);
cq.select(em.getCriteriaBuilder().count(rt));
Query q = em.createQuery(cq);
return ((Long) q.getSingleResult()).intValue();
} finally {
em.close();
}
}
}

javax.bluetooth.BluetoothExeption: unable to swithc master

i want to write bluetooth base app for send and recive string between two device . i have problem . i send string from device A and device B recive it but when i try to send answer from device B to A i get this notifier :
javax.bluetooth.BluetoothExeption: unable to swithc master
it is becouse this part of code :
StreamConnection conn =(StreamConnection) Connector.open(connString);
now what should i do for slove this probleam ?
thanks
Client class :
import java.io.*;
import javax.bluetooth.*;
import javax.microedition.io.Connector;
import javax.microedition.io.StreamConnection;
import javax.microedition.lcdui.*;
class Client implements CommandListener, Runnable {
Display display;
String msg;
Midlet midlet;
Form frm;
Command cmdBack = new Command("Back", Command.BACK, 1);
LocalDevice local = null;
DiscoveryAgent agent = null;
Thread thread;
StreamConnection conn = null;
OutputStream out = null;
public Client(String string, Midlet midlet, Display display) {
this.display = display;
this.midlet = midlet;
this.msg = string;
frm = new Form("Send Form");
frm.addCommand(cmdBack);
frm.setCommandListener(this);
thread = new Thread(this);
thread.start();
display.setCurrent(frm);
}
private void doDiscovery() {
try {
local = LocalDevice.getLocalDevice();
agent = local.getDiscoveryAgent();
String connString = agent.selectService(new UUID("86b4d249fb8844d6a756ec265dd1f6a3", false), ServiceRecord.NOAUTHENTICATE_NOENCRYPT, true);
if (connString != null) {
try {
conn = (StreamConnection) Connector.open(connString);
} catch (IOException ex) {
frm.append(ex.toString() + "1");
}
try {
out = conn.openOutputStream();
} catch (IOException ex) {
frm.append(ex.toString() + "2");
}
try {
out.write(msg.getBytes());
} catch (IOException ex) {
frm.append(ex.toString() + "3");
}
try {
out.close();
} catch (IOException ex) {
frm.append(ex.toString() + "4");
}
try {
conn.close();
} catch (IOException ex) {
frm.append(ex.toString() + "5");
}
System.out.println("Message sent currectly");
} else {
frm.append("connString == null");
}
} catch (BluetoothStateException ex) {
frm.append(ex.toString() + "6");
}
}
public void commandAction(Command c, Displayable d) {
if (c == cmdBack) {
display.setCurrent(midlet.tb);
}
}
public void run() {
doDiscovery();
}
}
Server Class :
import java.io.*;
import javax.bluetooth.*;
import javax.microedition.io.Connector;
import javax.microedition.io.StreamConnection;
import javax.microedition.io.StreamConnectionNotifier;
import javax.microedition.lcdui.*;
class Server implements Runnable {
Display display;
String msg;
Midlet midlet;
Thread thread;
private boolean endRecive = false;
public Server(Midlet midlet, Display display) {
this.display = display;
this.midlet = midlet;
thread = new Thread(this);
thread.start();
}
private void recive() {
try {
LocalDevice local = LocalDevice.getLocalDevice();
if (!local.setDiscoverable(DiscoveryAgent.GIAC)) {
midlet.tb.setString("Failed to change to the discoverable mode");
return;
}
StreamConnectionNotifier notifier = (StreamConnectionNotifier) Connector.open("btspp://localhost:" + "86b4d249fb8844d6a756ec265dd1f6a3");
StreamConnection conn = notifier.acceptAndOpen();
InputStream in = conn.openInputStream();
ByteArrayOutputStream out = new ByteArrayOutputStream();
int data;
while ((data = in.read()) != -1) {
out.write(data);
}
midlet.tb.delete(0, midlet.tb.size());
midlet.tb.setString(out.toString());
in.close();
conn.close();
notifier.close();
endRecive = true;
thread.interrupt();
} catch (Exception ex) {
System.out.println(ex.toString());
}
}
public void run() {
while (endRecive != true) {
try {
Thread.sleep(100);
} catch (InterruptedException ex) {
ex.printStackTrace();
}
recive();
}
}
}
and midlet :
import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.CommandListener;
import javax.microedition.lcdui.Display;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.TextBox;
import javax.microedition.lcdui.TextField;
import javax.microedition.midlet.*;
public class Midlet extends MIDlet implements CommandListener {
Display display = Display.getDisplay(this);
TextBox tb = new TextBox("Chat", null, 100, TextField.ANY);
Command cmdSend = new Command("Send", Command.OK, 1);
Command cmdRecive = new Command("Recive", Command.OK, 2);
Command cmdClear = new Command("Clear...", Command.OK, 3);
Command cmdExit = new Command("Exit", Command.EXIT, 4);
public void startApp() {
tb.addCommand(cmdSend);
tb.addCommand(cmdRecive);
tb.addCommand(cmdClear);
tb.addCommand(cmdExit);
tb.setCommandListener(this);
display.setCurrent(tb);
}
public void pauseApp() {
}
public void destroyApp(boolean unconditional) {
notifyDestroyed();
}
public void commandAction(Command c, Displayable d) {
if (c == cmdExit) {
destroyApp(true);
} else if (c == cmdClear) {
tb.delete(0, tb.size());
} else if (c == cmdSend && tb.getString().length() > 0) {
new Client(tb.getString(), this, display);
} else if (c == cmdRecive) {
tb.setString("Wait ...");
new Server(this, display);
}
}
}

error in java (CameraMIDlet)

i have the following code which is giving me error:
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Vector;
import javax.bluetooth.BluetoothStateException;
import javax.bluetooth.DeviceClass;
import javax.bluetooth.DiscoveryAgent;
import javax.bluetooth.DiscoveryListener;
import javax.bluetooth.LocalDevice;
import javax.bluetooth.RemoteDevice;
import javax.bluetooth.ServiceRecord;
import javax.bluetooth.UUID;
import javax.microedition.io.Connector;
import javax.microedition.io.StreamConnection;
import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.CommandListener;
import javax.microedition.lcdui.Display;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.Form;
import javax.microedition.lcdui.List;
import javax.microedition.midlet.MIDlet;
import javax.microedition.midlet.MIDletStateChangeException;
public class DeviceClientCOMM implements DiscoveryListener, CommandListener {
static final boolean DEBUG = false;
static final String DEBUG_address = "0013FDC157C8"; // N6630
protected UUID uuid = new UUID(0x1101); // serial port profile
protected int inquiryMode = DiscoveryAgent.GIAC; // no pairing is needed
protected int connectionOptions = ServiceRecord.NOAUTHENTICATE_NOENCRYPT;
protected int stopToken = 255;
private Command backCommand = new Command("Back", Command.BACK, 1);
protected Form infoArea = new Form("Bluetooth Client");
protected Vector deviceList = new Vector();
private CameraMIDlet mymidlet;
private byte[] imag;
public DeviceClientCOMM(CameraMIDlet m, byte[] imag) {
mymidlet = m;
this.imag = imag;
infoArea.setCommandListener(this);
infoArea.addCommand(backCommand);
try {
startApp();
} catch (MIDletStateChangeException ex) {
ex.printStackTrace();
}
}
protected void startApp() throws MIDletStateChangeException {
makeInformationAreaGUI();
if (DEBUG) // skip inquiry in debug mode
{
startServiceSearch(new RemoteDevice(DEBUG_address) {
});
} else {
try {
startDeviceInquiry();
} catch (Throwable t) {
log(t);
}
}
}
private void startDeviceInquiry() {
try {
log("Start inquiry method - this will take few seconds...");
DiscoveryAgent agent = getAgent();
agent.startInquiry(inquiryMode, this);
} catch (Exception e) {
log(e);
}
}
public void deviceDiscovered(RemoteDevice btDevice, DeviceClass cod) {
log("A device discovered (" + getDeviceStr(btDevice) + ")");
deviceList.addElement(btDevice);
}
public void inquiryCompleted(int discType) {
log("Inquiry compeleted. Please select device from combo box.");
makeDeviceSelectionGUI();
}
private void startServiceSearch(RemoteDevice device) {
try {
log("Start search for Serial Port Profile service from " + getDeviceStr(device));
UUID uuids[] = new UUID[]{uuid};
getAgent().searchServices(null, uuids, device, this);
} catch (Exception e) {
log(e);
}
}
public void servicesDiscovered(int transId, ServiceRecord[] records) {
log("Service discovered.");
for (int i = 0; i < records.length; i++) {
ServiceRecord rec = records[i];
String url = rec.getConnectionURL(connectionOptions, false);
handleConnection(url);
}
}
public void serviceSearchCompleted(int transID, int respCode) {
String msg = null;
switch (respCode) {
case SERVICE_SEARCH_COMPLETED:
msg = "the service search completed normally";
break;
case SERVICE_SEARCH_TERMINATED:
msg = "the service search request was cancelled by a call to DiscoveryAgent.cancelServiceSearch()";
break;
case SERVICE_SEARCH_ERROR:
msg = "an error occurred while processing the request";
break;
case SERVICE_SEARCH_NO_RECORDS:
msg = "no records were found during the service search";
break;
case SERVICE_SEARCH_DEVICE_NOT_REACHABLE:
msg = "the device specified in the search request could not be reached or the local device could not establish a connection to the remote device";
break;
}
log("Service search completed - " + msg);
}
private void handleConnection(final String url) {
Thread echo = new Thread() {
public void run() {
StreamConnection stream = null;
InputStream in = null;
OutputStream out = null;
try {
log("Connecting to server by url: " + url);
stream = (StreamConnection) Connector.open(url);
log("Bluetooth stream open.");
// InputStream in = stream.openInputStream();
out = stream.openOutputStream();
in = stream.openInputStream();
startReadThread(in);
// String stringImage = Base64.encode(imag);
log("Start echo loop.");
out.write(imag);
out.flush();
// out.flush();
// stream.close();
} catch (IOException e) {
log(e);
} finally {
log("Bluetooth stream closed.");
if (out != null) {
try {
out.close();
stream.close();
logSet("Image Transfer done\n----------------\n\nWaiting for results...");
} catch (IOException e) {
log(e);
}
}
}
}
};
echo.start();
}
private void startReadThread(final InputStream in) {
Thread reader = new Thread() {
public void run() {
byte[] s = new byte[512];
//boolean flag = true;
try {
while (true) {
int r = in.read(s);
if (r != -1) {
logSet(new String(s, 0, r));
} else {
break;
}
Thread.sleep(200);
}
} catch (Throwable e) {
log(e);
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
}
}
}
}
};
reader.start();
}
private void makeInformationAreaGUI() {
infoArea.deleteAll();
Display.getDisplay(mymidlet).setCurrent(infoArea);
}
private void makeDeviceSelectionGUI() {
final List devices = new List("Select a device", List.IMPLICIT);
for (int i = 0; i < deviceList.size(); i++) {
devices.append(
getDeviceStr((RemoteDevice) deviceList.elementAt(i)), null);
}
devices.setCommandListener(new
CommandListener( ) {
public void commandAction(Command arg0,
Displayable arg1)
{
makeInformationAreaGUI();
startServiceSearch((RemoteDevice) deviceList.elementAt(devices.getSelectedIndex()));
}
});
Display.getDisplay(mymidlet).setCurrent(devices);
}
synchronized private void log(String msg) {
infoArea.append(msg);
infoArea.append("\n\n");
}
synchronized private void logSet(String msg) {
infoArea.deleteAll();
infoArea.append(msg);
infoArea.append("\n\n");
}
private void log(Throwable e) {
log(e.getMessage());
}
private DiscoveryAgent getAgent() {
try {
return LocalDevice.getLocalDevice().getDiscoveryAgent();
} catch (BluetoothStateException e) {
throw new Error(e.getMessage());
}
}
private String getDeviceStr(RemoteDevice btDevice) {
return getFriendlyName(btDevice) + " - 0x" + btDevice.getBluetoothAddress();
}
private String getFriendlyName(RemoteDevice btDevice) {
try {
return btDevice.getFriendlyName(false);
} catch (IOException e) {
return "no name available";
}
}
public void commandAction(Command arg0, Displayable arg1) {
mymidlet.DisplayMainList();
}
}
the errors are
C:\Documents and Settings\admin\My Documents\NetBeansProjects\DeviceClientCOMM\src\DeviceClientCOMM.java:51: cannot find symbol
symbol : class CameraMIDlet
location: class DeviceClientCOMM
private CameraMIDlet mymidlet;
C:\Documents and Settings\admin\My Documents\NetBeansProjects\DeviceClientCOMM\src\DeviceClientCOMM.java:54: cannot find symbol
symbol : class CameraMIDlet
location: class DeviceClientCOMM
public DeviceClientCOMM(CameraMIDlet m, byte[] imag)
You don't have an import for CameraMIDlet, so the compiler doesn't know which class you mean.
Assuming you've got an appropriate classpath entry, you should just be able to add the right import and it should be fine.
Are you sure CameraMIDlet exists for your use though? I can see some sample code in JSR-135, but I'm not sure it's a full API to be used...

Resources