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;
}
Related
I am trying to implement a SessionListener which I plan to use for logging active user sessions (name/time) so that I can let manager know who all are available at anytime. However, when I add it, I see sessionCreated message and then I see this JVM error on server console. No java code is executed after it.
HTTP JVM: com.ibm.xsp.webapp.FacesServlet$ExtendedServletException:
java.lang.ExceptionInInitializerError HTTP JVM: Error type not
found:java.lang.ExceptionInInitializerError import
javax.servlet.http.HttpSessionEvent;
Here is my SessionTracker.java:
import com.ibm.xsp.application.ApplicationEx;
import com.ibm.xsp.application.events.SessionListener;
public class SessionTracker implements SessionListener {
public void sessionCreated(ApplicationEx arg0, HttpSessionEvent arg1) {
System.out.println("***session created***");
}
public void sessionDestroyed(ApplicationEx arg0, HttpSessionEvent arg1) {
System.out.println("***session destroyed ***");
}
}
Here is what I see in xpages_exec*.log under IBM_Technical_Support directory.
Context Path: /igdmnext/igdm.nsf Page Name: /Services.xsp
java.lang.ExceptionInInitializerError at
java.lang.J9VMInternals.initialize(J9VMInternals.java:221) at
java.lang.J9VMInternals.newInstanceImpl(Native Method) at
java.lang.Class.newInstance(Class.java:1688) at
com.ibm.xsp.util.ManagedBeanUtil.getBean(ManagedBeanUtil.java:61) at
com.ibm.xsp.extlib.component.rest.CustomService.findBeanInstance(CustomService.java:225)
at
com.ibm.xsp.extlib.component.rest.CustomService$ScriptServiceEngine.renderService(CustomService.java:257)
at
com.ibm.domino.services.HttpServiceEngine.processRequest(HttpServiceEngine.java:170)
at
com.ibm.xsp.extlib.component.rest.UIBaseRestService._processAjaxRequest(UIBaseRestService.java:259)
at
com.ibm.xsp.extlib.component.rest.UIBaseRestService.processAjaxRequest(UIBaseRestService.java:236)
at
com.ibm.xsp.util.AjaxUtilEx.renderAjaxPartialLifecycle(AjaxUtilEx.java:206)
at
com.ibm.xsp.webapp.FacesServletEx.renderAjaxPartial(FacesServletEx.java:249)
at
com.ibm.xsp.webapp.FacesServletEx.serviceAjaxPartialView(FacesServletEx.java:200)
at
com.ibm.xsp.webapp.FacesServletEx.serviceAjaxPartialViewSync(FacesServletEx.java:169)
at
com.ibm.xsp.webapp.FacesServletEx.serviceView(FacesServletEx.java:155)
at com.ibm.xsp.webapp.FacesServlet.service(FacesServlet.java:160) at
com.ibm.xsp.webapp.FacesServletEx.service(FacesServletEx.java:138) at
com.ibm.xsp.webapp.DesignerFacesServlet.service(DesignerFacesServlet.java:103)
at
com.ibm.designer.runtime.domino.adapter.ComponentModule.invokeServlet(ComponentModule.java:576)
at
com.ibm.domino.xsp.module.nsf.NSFComponentModule.invokeServlet(NSFComponentModule.java:1335)
at
com.ibm.designer.runtime.domino.adapter.ComponentModule$AdapterInvoker.invokeServlet(ComponentModule.java:853)
at
com.ibm.designer.runtime.domino.adapter.ComponentModule$ServletInvoker.doService(ComponentModule.java:796)
at
com.ibm.designer.runtime.domino.adapter.ComponentModule.doService(ComponentModule.java:565)
at
com.ibm.domino.xsp.module.nsf.NSFComponentModule.doService(NSFComponentModule.java:1319)
at
com.ibm.domino.xsp.module.nsf.NSFService.doServiceInternal(NSFService.java:662)
at
com.ibm.domino.xsp.module.nsf.NSFService.doService(NSFService.java:482)
at
com.ibm.designer.runtime.domino.adapter.LCDEnvironment.doService(LCDEnvironment.java:357)
at
com.ibm.designer.runtime.domino.adapter.LCDEnvironment.service(LCDEnvironment.java:313)
at
com.ibm.domino.xsp.bridge.http.engine.XspCmdManager.service(XspCmdManager.java:272)
Caused by: java.lang.NullPointerException at
org.openntf.domino.xsp.session.AbstractXPageSessionFactory.wrapSession(AbstractXPageSessionFactory.java:23)
at
org.openntf.domino.xsp.session.XPageSignerSessionFactory.createSession(XPageSignerSessionFactory.java:18)
at org.openntf.domino.utils.Factory.getSession(Factory.java:952) at
com.hcl.igdm.util.EndUserMap.(EndUserMap.java:46) --> this is my custom java class which works if I do not implement SessionTracker above at
java.lang.J9VMInternals.initializeImpl(Native Method) at
java.lang.J9VMInternals.initialize(J9VMInternals.java:199) ... 27
more
** EndUserMap.java **
package com.hcl.igdm.util;
import java.io.PrintWriter;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import javax.faces.context.FacesContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.lang.StringUtils;
import org.openntf.domino.Database;
import org.openntf.domino.Session;
import org.openntf.domino.View;
import org.openntf.domino.ViewEntry;
import org.openntf.domino.ViewEntryCollection;
import org.openntf.domino.utils.Factory;
import org.openntf.domino.utils.Factory.SessionType;
import com.hcl.igdm.Activity;
import com.hcl.igdm.Phases;
import com.hcl.igdm.Stages;
import com.ibm.commons.util.StringUtil;
import com.ibm.commons.util.io.json.JsonJavaArray;
import com.ibm.commons.util.io.json.JsonJavaObject;
import com.ibm.domino.services.ServiceException;
import com.ibm.domino.services.rest.RestServiceEngine;
import com.ibm.xsp.extlib.component.rest.CustomService;
import com.ibm.xsp.extlib.component.rest.CustomServiceBean;
import com.ibm.xsp.extlib.util.ExtLibUtil;
/**
* #author agnihotri.a
*
*/
public class EndUserMap extends CustomServiceBean implements Serializable {
private static final long serialVersionUID = 1L;
private static String requestedType = "";
static Session session = Factory.getSession(SessionType.NATIVE);
static Database db = session.getCurrentDatabase();
static View allView = db.getView("mapAll");
public static void setRequestedType(String requestType) {
requestedType = requestType;
}
public static String getRequestedType() {
return requestedType;
}
#Override
public void renderService(CustomService service, RestServiceEngine engine) throws ServiceException {
HttpServletRequest request = engine.getHttpRequest();
HttpServletResponse response = engine.getHttpResponse();
response.setHeader("Content-Type", "application/json; charset=UTF-8");
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
FacesContext faccon = FacesContext.getCurrentInstance();
/**** read requested type from query string parameters ****/
String reqType = request.getParameter("type");
try {
JsonJavaObject jjo = new JsonJavaObject();
PrintWriter pw = response.getWriter();
if (reqType.equalsIgnoreCase("Map") || "".equalsIgnoreCase(reqType)) {
setRequestedType("Map");
pw.write(getEndUserMap().toString());
} else if (reqType.equalsIgnoreCase("Activity")) {
setRequestedType("Activity");
request.getParameter("ukey");
try {
jjo = getActivity(request.getParameter("ukey"));
// jjo.put("map", getEndUserMap());
pw.write(jjo.toString());
} catch (Exception e) {
e.printStackTrace();
}
} else if (reqType.equalsIgnoreCase("Phase")) {
request.getParameter("ukey");
try {
setRequestedType("Phase");
jjo = getPhase(request.getParameter("ukey"));
jjo.put("map", getEndUserMap());
pw.write(jjo.toString());
} catch (Exception e) {
e.printStackTrace();
}
} else if (reqType.equalsIgnoreCase("Stage")) {
request.getParameter("ukey");
try {
setRequestedType("Stage");
jjo = getStage(request.getParameter("ukey"));
// jjo.put("map", getEndUserMap());
pw.write(jjo.toString());
} catch (Exception e) {
e.printStackTrace();
}
}
pw.flush();
} catch (Exception e) {
e.printStackTrace();
}
faccon.responseComplete();
}
public static JsonJavaObject getActivity(String ukey) throws Exception {
Activity activity = new Activity();
activity.load(ukey);
JsonJavaObject jjo = new JsonJavaObject();
if (!isAdmin() && !StringUtil.equalsIgnoreCase((String) activity.getValue("Status"), "Live")) {
jjo.put("error", "You are not authorized to view this document.");
return jjo;
}
jjo.put("title", activity.getValue("Title"));
jjo.put("teaser", activity.getValue("Teaser"));
jjo.put("ukey", activity.getUnid());
jjo.put("overview", activity.getValue("Overview"));
jjo.put("inputs", activity.getValue("Inputs"));
jjo.put("outputs", activity.getValue("Outputs"));
jjo.put("order", activity.getValue("SortOrder"));
jjo.put("artefacts", activity.getArtefacts());
jjo.put("kmlinks", activity.getValue("KMLinks"));
jjo.put("kmenabled", activity.getValue("KMEnabled"));
jjo.put("resources", activity.getResources());
TreeMap<String, ArrayList<String>> mappings = Mappings.loadMyMap(ukey);
if (!mappings.isEmpty()) {
if (mappings.containsKey("Substage")) {
// jjo.put("substage", mappings.get("Substage").get(0));
jjo.put("substage", getStage(mappings.get("Substage").get(0)));
} else if (mappings.containsKey("Stage")) {
// jjo.put("stage", mappings.get("Stage").get(0));
jjo.put("stage", getStage(mappings.get("Stage").get(0)));
}
}
return jjo;
}
public static JsonJavaObject getStage(String ukey) {
Stages stage = new Stages();
stage.load(ukey);
String stageType = (String) stage.getValue("StageType");
JsonJavaObject jjo = new JsonJavaObject();
if (!isAdmin() && !StringUtil.equalsIgnoreCase((String) stage.getValue("Status"), "Live")) {
jjo.put("error", "You are not authorized to view this document.");
return jjo;
}
TreeMap<String, ArrayList<String>> mappings = Mappings.loadMyMap(ukey);
jjo.put("title", stage.getValue("Title"));
jjo.put("ukey", stage.getUnid());
jjo.put("overview", stage.getValue("Overview"));
jjo.put("order", stage.getValue("Row"));
jjo.put("type", stageType);
jjo.put("status", (String) stage.getValue("Status"));
if (!mappings.isEmpty()) {
if (mappings.containsKey("Stream")) {
JsonJavaArray mapStreamJJA = new JsonJavaArray();
for (String key : mappings.get("Stream")) {
try {
Map<String, Object> entryMap = allView.getFirstEntryByKey(key).getColumnValuesMap();
if ("Live".equalsIgnoreCase((String) entryMap.get("status")) || isAdmin()) {
mapStreamJJA.add(entryMap);
}
} catch (Exception ex) {
// do nothing
}
}
jjo.put("stream", mapStreamJJA);
} else {
jjo.put("stream", "");
}
/** below mapping check handles substages */
if (mappings.containsKey("Stage") && !StringUtils.equalsIgnoreCase(stageType, "Stage")) {
JsonJavaArray mapStreamJJA = new JsonJavaArray();
JsonJavaArray mapPhaseJJA = new JsonJavaArray();
// as this is substage ..we'll get phase from parent stage
for (String key : mappings.get("Stage")) {
try {
Map<String, Object> entryMap = allView.getFirstEntryByKey(key).getColumnValuesMap();
if ("Live".equalsIgnoreCase((String) entryMap.get("status")) || isAdmin()) {
mapStreamJJA.add(entryMap);
TreeMap<String, ArrayList<String>> stageMap = Mappings.loadMyMap(key);
if (!stageMap.isEmpty() && stageMap.containsKey("Phase")) {
for (String phase : stageMap.get("Phase")) {
Map<String, Object> entryMapPhase = allView.getFirstEntryByKey(phase).getColumnValuesMap();
if ("Live".equalsIgnoreCase((String) entryMapPhase.get("status")) || isAdmin()) {
mapPhaseJJA.add(entryMapPhase);
}
}
}
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
jjo.put("stage", mapStreamJJA);
jjo.put("phase", mapPhaseJJA);
}
if (mappings.containsKey("Phase") && StringUtils.equalsIgnoreCase(stageType, "Stage")) {
JsonJavaArray mapPhJJA = new JsonJavaArray();
for (String key : mappings.get("Phase")) {
Map<String, Object> entryMap = allView.getFirstEntryByKey(key).getColumnValuesMap();
if ("Live".equalsIgnoreCase((String) entryMap.get("status")) || isAdmin()) {
mapPhJJA.add(entryMap);
}
}
jjo.put("phase", mapPhJJA);
} else {
if (!jjo.containsKey("phase")) {
jjo.put("phase", "");
}
}
if (mappings.containsKey("Activity")) {
JsonJavaArray actJJA = new JsonJavaArray();
for (String key : mappings.get("Activity")) {
try {
Map<String, Object> entryMap = allView.getFirstEntryByKey(key).getColumnValuesMap();
if ("Live".equalsIgnoreCase((String) entryMap.get("status")) || isAdmin()) {
actJJA.add(entryMap);
}
} catch (Exception ex) {
}
}
jjo.put("child", "Activities");
jjo.put("activities", actJJA);
} else if (mappings.containsKey("Substage") && StringUtils.equalsIgnoreCase(stageType, "Stage")) {
JsonJavaArray ssJJA = new JsonJavaArray();
for (String key : mappings.get("Substage")) {
Map<String, Object> entryMap = allView.getFirstEntryByKey(key).getColumnValuesMap();
if ("Live".equalsIgnoreCase((String) entryMap.get("status")) || isAdmin()) {
ssJJA.add(entryMap);
}
}
jjo.put("child", "Substages");
jjo.put("substages", ssJJA);
}
}
return jjo;
}
public static JsonJavaObject getPhase(String ukey) {
Phases phase = new Phases();
phase.load(ukey);
JsonJavaObject jjo = new JsonJavaObject();
if (!isAdmin() && !StringUtil.equalsIgnoreCase((String) phase.getValue("Status"), "Live")) {
return null;
}
jjo.put("title", phase.getValue("Title"));
jjo.put("ukey", phase.getUnid());
jjo.put("status", phase.getValue("Status"));
jjo.put("overview", phase.getValue("Overview"));
jjo.put("order", phase.getValue("SortOrder"));
try {
jjo.put("artefacts", phase.getArtefacts());
} catch (Exception e) {
jjo.put("artefacts", null);
e.printStackTrace();
}
TreeMap<String, ArrayList<String>> mappings = Mappings.loadMyMap(ukey);
if (!mappings.isEmpty() && mappings.containsKey("Stage")) {
JsonJavaArray jja = new JsonJavaArray();
for (String key : mappings.get("Stage")) {
ViewEntry stage = allView.getFirstEntryByKey(key);
if (null != stage) {
if (isAdmin() || "Live".equalsIgnoreCase((String) stage.getColumnValue("status"))) {
Map<String, Object> stg = stage.getColumnValuesMap();
TreeMap<String, ArrayList<String>> stgMap = Mappings.loadMyMap(key);
if (!stgMap.isEmpty() && stgMap.containsKey("Stream")) {
JsonJavaArray stgStreamArr = new JsonJavaArray();
for (String stream : stgMap.get("Stream")) {
try {
Map<String, Object> entryMap = allView.getFirstEntryByKey(stream).getColumnValuesMap();
if ("Live".equalsIgnoreCase((String) entryMap.get("status")) || isAdmin()) {
stgStreamArr.add(entryMap);
}
} catch (Exception ex) {
}
}
stg.put("stream", stgStreamArr);
}
jja.add(stg);
}
}
}
jjo.put("stages", jja);
}
return jjo;
}
public static JsonJavaObject getEndUserMap() {
setRequestedType("Map");
JsonJavaObject endUserMap = new JsonJavaObject();
try {
ArrayList<String> docTypes = new ArrayList<String>();
docTypes.add("Phase");
docTypes.add("Stream");
for (String dtype : docTypes) {
View view = db.getView("map" + dtype);
JsonJavaArray jja = new JsonJavaArray();
ViewEntryCollection vec;
if (isAdmin()) {
vec = view.getAllEntries();
} else {
vec = view.getAllEntriesByKey("Live");
}
for (ViewEntry ve : vec) {
jja.add(ve.getColumnValuesMap());
}
endUserMap.put(dtype, jja);
}
} catch (Exception e) {
e.printStackTrace();
}
return endUserMap;
}
#SuppressWarnings("unchecked")
public static boolean isAdmin() {
List<String> roleList = ExtLibUtil.getXspContext().getUser().getRoles();
if (!roleList.isEmpty() && roleList.contains("[admin]")) {
return true;
} else {
return false;
}
}
}
Caused by: java.lang.NullPointerException at org.openntf.domino.xsp.session.AbstractXPageSessionFactory.wrapSession(AbstractXPageSessionFactory.java:23) at org.openntf.domino.xsp.session.XPageSignerSessionFactory.createSession(XPageSignerSessionFactory.java:18) at org.openntf.domino.utils.Factory.getSession(Factory.java:952) at
It seems to be hitting an error getting the signer session.
This may be a timing issue, caused by it running in a different ClassLoader, before the ODA Factory has initialised the factory's sessions. I'm not sure how to confirm that, but if your error is hitting the logs before the XOTS logging at server startup, that would almost certainly be the case.
Alternatively, it may be specific to not finding the signer. I've tended to use Factory.getSession(SessionType.NATIVE) rather than a signer session. That runs under server's identity, which should be high enough and avoids the issue of multiple signers etc.
I have a cacheBean written in Java. I am successfully pulling out Vectors using EL, but I have a HashMap and when I try to access a value I throw an error.
My cacheBean is:
package com.scoular.cache;
import java.io.Serializable;
import java.util.HashMap;
import java.util.Vector;
import org.openntf.domino.utils.Factory;
import org.openntf.domino.Database;
import org.openntf.domino.Session;
import org.openntf.domino.View;
import org.openntf.domino.ViewEntry;
import org.openntf.domino.ViewNavigator;
public class PCConfig implements Serializable {
private static final long serialVersionUID = 1L;
private Database thisDB;
private Database compDirDB;
public Database PCDataDB;
public HashMap<Integer, String> status = new HashMap<Integer, String>();
public static Vector<Object> geoLocations = new Vector<Object>();
public static Vector<Object> models = new Vector<Object>();
// #SuppressWarnings("unchecked")
private void initConfigData() {
try {
getStatus();
getGeoLocations();
getModels();
} catch (Exception e) {
e.printStackTrace();
}
}
public PCConfig() {
// initialize application config
System.out.println("Starting CacheBean");
initConfigData();
System.out.println("Ending CacheBean");
}
public static void setModels(Vector<Object> models) {
PCConfig.models = models;
}
public void getStatus() {
status.put(1, "In Inventory");
status.put(2, "Being Built");
status.put(3, "In Production");
status.put(4, "Aquiring PC");
status.put(5, "Decommissioning");
}
public Vector<Object> getGeoLocations() {
if (PCConfig.geoLocations == null || PCConfig.geoLocations.isEmpty()) {
try {
Session session = Factory.getSession();
thisDB = session.getCurrentDatabase();
compDirDB = session.getDatabase(thisDB.getServer(), "compdir.nsf", false);
View geoView = compDirDB.getView("xpGeoLocationsByName");
for (ViewEntry ce : geoView.getAllEntries()) {
Vector<Object> rowVal = ce.getColumnValues();
geoLocations.addElement(rowVal.elementAt(0));
}
} catch (Exception e) {
e.printStackTrace();
}
}
return geoLocations;
}
public Vector<Object> getModels() {
if (PCConfig.models == null || PCConfig.models.isEmpty()) {
try {
Session session = Factory.getSession();
thisDB = session.getCurrentDatabase();
PCDataDB = session.getDatabase(thisDB.getServer(), "scoApps\\PC\\PCData.nsf", false);
ViewNavigator vn = PCDataDB.getView("dbLookupModels").createViewNav();
ViewEntry entry = vn.getFirstDocument();
while (entry != null) {
Vector<Object> thisCat = entry.getColumnValues();
if (entry.isCategory()) {
String thisCatString = thisCat.elementAt(0).toString();
models.addElement(thisCatString);
}
entry = vn.getNext(entry);
}
} catch (Exception e) {
e.printStackTrace();
}
}
return models;
}
}
and the code to grab the a value is:
<xp:text escape="true" id="computedField2">
<xp:this.value><![CDATA[#{PCConfig.status[0]}]]></xp:this.value></xp:text>
Your method getStatus() has to return the HashMap.
public HashMap<Integer, String> getStatus() {
...
return status;
}
In addition, #{PCConfig.status[0]} tries to read the value for key 0. There is no key 0 in your HashMap status though...
As far I know you should do as follow
#{javascript:PCConfig.status.get(1)}
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;
}
}
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);
}
}
}
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...