SessionListener causes ExceptionInInitializerError - xpages

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.

Related

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;
}

Xpages and EL: Syntax for retrieving HashMap Values

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)}

Camera snapshot in J2ME Null Pointer Exception

I've spent long on this but no success yet. In my application to capture image and send to the server, I get NullPointerException below;
java.lang.NullPointerException: 0
at Files.CameraMIDlet.snap(CameraMIDlet.java:120)
at Files.CameraForm.commandAction(CameraForm.java:116)
at javax.microedition.lcdui.Display$ChameleonTunnel.callScreenListener(), bci=46
at com.sun.midp.chameleon.layers.SoftButtonLayer.processCommand(), bci=74
at com.sun.midp.chameleon.layers.SoftButtonLayer.soft2(), bci=173
at com.sun.midp.chameleon.layers.SoftButtonLayer.keyInput(), bci=78
at com.sun.midp.chameleon.CWindow.keyInput(), bci=38
at javax.microedition.lcdui.Display$DisplayEventConsumerImpl.handleKeyEvent(), bci=17
at com.sun.midp.lcdui.DisplayEventListener.process(), bci=277
at com.sun.midp.events.EventQueue.run(), bci=179
at java.lang.Thread.run(Thread.java:722)
The errors happen at byte[] image = videoControl.getSnapshot("encoding = jpeg"); in the CameraMIDlet and also at midlet.snap(); in the CameraForm, in the code below.
The code for CameraForm is here:
package Files;
import javax.microedition.media.*;
import javax.microedition.lcdui.*;
import javax.microedition.media.control.*;
import java.io.IOException;
class CameraForm extends Form implements CommandListener {
private final CameraMIDlet midlet;
private final Command exitCommand;
private Command captureCommand = null;
private Command showImageCommand = null;
private Player player = null;
private static VideoControl videoControl = null;
private boolean active = false;
private StringItem messageItem;
public CameraForm(CameraMIDlet midlet) {
super("Camera");
this.midlet = midlet;
messageItem = new StringItem("Message", "start");
append(messageItem);
exitCommand = new Command("EXIT", Command.EXIT, 1);
addCommand(exitCommand);
setCommandListener(this);
try {
//creates a new player and set it to realize
player = Manager.createPlayer("capture://video");
player.realize();
//Grap the Video control and set it to the current display
videoControl = (VideoControl) (player.getControl("VideoControl"));
if (videoControl != null) {
append((Item) (videoControl.initDisplayMode(
VideoControl.USE_GUI_PRIMITIVE, null)));
captureCommand = new Command("CAPTURE", Command.SCREEN, 1);
addCommand(captureCommand);
messageItem.setText("OK");
} else {
messageItem.setText("No video control");
}
} catch (IOException ioe) {
messageItem.setText("IOException: " + ioe.getMessage());
} catch (MediaException me) {
messageItem.setText("Media Exception: " + me.getMessage());
} catch (SecurityException se) {
messageItem.setText("Security Exception: " + se.getMessage());
}
}
* the video should be visualized on the sreen
* therefore you have to start the player and set the videoControl visible
synchronized void start() {
if (!active) {
try {
if (player != null) {
player.start();
}
if (videoControl != null) {
videoControl.setVisible(true);
//midlet.snap();
}
} catch (MediaException me) {
messageItem.setText("Media Exception: " + me.getMessage());
} catch (SecurityException se) {
messageItem.setText("Security Exception: " + se.getMessage());
}
active = true;
}
}
* to stop the player. First the videoControl has to be set invisible
* than the player can be stopped
synchronized void stop() {
if (active) {
try {
if (videoControl != null) {
videoControl.setVisible(false);
}
if (player != null) {
player.stop();
}
} catch (MediaException me) {
messageItem.setText("Media Exception: " + me.getMessage());
}
active = false;
}
}
* on the captureCommand a picture is taken and transmited to the server
public void commandAction(Command c, Displayable d) {
if (c == exitCommand) {
midlet.cameraFormExit();
} else {
if (c == captureCommand) {
midlet.snap();
}
}
}
}
The code for CameraMIDlet is below:
package Files;
import java.io.*;
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
import javax.microedition.io.*;
import javax.microedition.media.control.*;
import java.io.IOException;
import javax.microedition.media.MediaException;
public class CameraMIDlet extends MIDlet {
private CameraForm cameraSave = null;
private DisplayImage displayImage = null;
CameraForm captureThread;
private static VideoControl videoControl;
private StringItem messageItem;
public CameraMIDlet() {
}
/*
* startApp()
* starts the MIDlet and generates cameraSave, displayImage, database
*
**/
public void startApp() {
Displayable current = Display.getDisplay(this).getCurrent();
if (current == null) {
//first call
cameraSave = new CameraForm(this);
displayImage = new DisplayImage(this);
Display.getDisplay(this).setCurrent(cameraSave);
cameraSave.start();
} else {
//returning from pauseApp
if (current == cameraSave) {
cameraSave.start();
}
Display.getDisplay(this).setCurrent(current);
}
}
public void pauseApp() {
if (Display.getDisplay(this).getCurrent() == cameraSave) {
cameraSave.stop();
}
}
public void destroyApp(boolean unconditional) {
if (Display.getDisplay(this).getCurrent() == cameraSave) {
cameraSave.stop();
}
}
private void exitRequested() {
destroyApp(false);
notifyDestroyed();
}
void cameraFormExit() {
exitRequested();
}
/**
* restart the camera again
*
*/
void displayCanvasBack() {
Display.getDisplay(this).setCurrent(cameraSave);
cameraSave.start();
}
/**
* the byte[] of the image should be transmitted to a server
*
**/
void buildHTTPConnection(byte[] byteImage) {
displayImage.setImage(byteImage);
Display.getDisplay(this).setCurrent(displayImage);
HttpConnection hc = null;
OutputStream out = null;
try {
//enode the image data by the Base64 algorithm
String stringImage = Base64.encode(byteImage);
// URL of the Sevlet
String url = new String(
"http://ip-adress:8080/C:/Users/HASENDE/Documents/NetBeansProjects/Mobile/pics");
// Obtain an HTTPConnection
hc = (HttpConnection) Connector.open(url);
// Modifying the headers of the request
hc.setRequestMethod(HttpConnection.POST);
// Obtain the output stream for the HttpConnection
out = hc.openOutputStream();
out.write(stringImage.getBytes());
} catch (IOException ioe) {
StringItem stringItem = new StringItem(null, ioe.toString());
} finally {
try {
if (out != null)
out.close();
if (hc != null)
hc.close();
} catch (IOException ioe) {
}
}
// ** end network
}
/**
* stop the camera, show the captured image and transmit the image to a server
**/
void transmitImage(byte[] image) {
cameraSave.stop();
Display.getDisplay(this).setCurrent(displayImage);
buildHTTPConnection(image);
}
public void snap(){
try {
byte[] image = videoControl.getSnapshot("encoding = jpeg");
transmitImage(image);
messageItem.setText("Ok");
} catch (MediaException me) {
messageItem.setText("Media Exception: " + me.getMessage());
}
}
}
By identifying the statement that throws NPE you get 99% close to finding the bug:
byte[] image = videoControl.getSnapshot("encoding = jpeg");
NPE in above statement means videoControl is null. Now if you look at it closer, you may notice that in CameraMIDlet, videoControl is initialized with null and never changes to anything else - that's why you are getting NPE. By the way, from CameraForm code it looks like you intended to use videoControl object that is defined there, didn't you.
Side note. CameraForm seems to be designed to used in multiple threads (there are synchronized modifiers) - if this is the case, you better make sure that videoControl is also obtained from it in a synchronized way. Also in that case, add volatile modifier in definition of active flag:
private volatile boolean active = false; // in CameraForm
For Capturing photo use canvas instead of Form,
Check follwing code for Photo Capture
public class ImageCaptureCanvas extends Canvas {
UrMidlet midlet;
VideoControl videoControl;
Player player;
SnapShotCanvas snap;
private Display display;
public ImageCaptureCanvas(UrMidlet midlet) throws MediaException {
this.midlet = midlet;
this.display = Display.getDisplay(midlet);
this.setFullScreenMode(true);
try {
player = Manager.createPlayer("capture://image");
player.realize();
videoControl = (VideoControl) player.getControl("VideoControl");
} catch (Exception e) {
dm(e.getClass().getName());
}
videoControl.initDisplayMode(VideoControl.USE_DIRECT_VIDEO, this);
try {
videoControl.setDisplayLocation(0,0);
videoControl.setDisplaySize(getWidth(), getHeight());
} catch (MediaException me) {
try {
videoControl.setDisplayFullScreen(true);
} catch (MediaException me2) {
}
}
dm("icc10");
videoControl.setVisible(true);
dm("icc11");
player.start();
this.display.setCurrent(this);
}
public void dm(String message) {
Form form = new Form("Error");
form.append(message);
display.setCurrent(form);
}
public void paint(Graphics g) {
}
protected void keyPressed(int keyCode) {
boolean prv=false;
int actn=getGameAction(keyCode);
switch (keyCode) {
case KEY_NUM5:
prv=true;
Thread t = new Thread() {
public void run() {
try {
byte[] raw = videoControl.getSnapshot(null);
Image image = Image.createImage(raw, 0, raw.length);
snap = new SnapShotCanvas(image);
display.setCurrent(snap);
} catch (Exception e) {
dm(e.getClass().getName() + " " + e.getMessage());
}
}
};
t.start();
break;
}
if(!prv){
switch (actn) {
case Canvas.FIRE:
Thread t1 = new Thread() {
public void run() {
try {
byte[] raw = videoControl.getSnapshot(null);
Image image = Image.createImage(raw, 0, raw.length);
snap = new SnapShotCanvas(image);
display.setCurrent(snap);
} catch (Exception e) {
dm(e.getClass().getName() + " " + e.getMessage());
}
}
};
t1.start();
break;
}
}
}
}
SnapShotCanvas Code here
class SnapShotCanvas extends Canvas {
private Image image;
public SnapShotCanvas(Image image) {
this.image = image;
setFullScreenMode(true);
}
public void paint(Graphics g) {
g.drawImage(image, getWidth() / 2, getHeight() / 2, Graphics.HCENTER | Graphics.VCENTER);
}
}

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