We have a tool using Jetty WebSocketClient to connect to a server. We need to restart the connection to the server sometimes.
With the current code we run into memory leak at org.eclipse.jetty.util.thread.ShutdownThread, where all used instances of org.eclipse.jetty.websocket.client.WebSocketClient are kept.
As in the documentation at http://www.eclipse.org/jetty/documentation/current/jetty-websocket-client-api.html the only thing to do, is to call client.stop().
Is there some issue with the code or with Jetty itself?
The following is a "minimal" example of the code. Where the main runs a "test" where the consumed memory is tracked and compared.
The result is: more heap used: 97 / 100 - telling me that something is wrong...
Task handles the connection to the server (and would keep additional info):
package example;
import java.io.IOException;
import java.net.URI;
import org.eclipse.jetty.websocket.client.ClientUpgradeRequest;
import org.eclipse.jetty.websocket.client.WebSocketClient;
class Task {
public enum StopReason {
CLOSED,
EXIT,
RESTART
}
private WebSocketClient client;
private ClientSocket socket;
private URI uri;
public Task(URI uri) {
this.uri = uri;
}
public void restart() throws IOException {
System.out.println("Task.restart");
stop(StopReason.RESTART);
synchronized (this) {
try {
this.wait(10);
} catch (InterruptedException e) {
// ignore
}
}
start();
}
public void start() throws IOException {
System.out.println("Task.start");
client = new WebSocketClient();
client.getPolicy().setIdleTimeout(120000);
client.setMaxIdleTimeout(1000);
socket = new ClientSocket(this);
try {
client.start();
System.out.println("Task started");
} catch (Exception e) {
throw new IOException("Failed to start WebSocketClient: " + e.getLocalizedMessage(), e);
}
ClientUpgradeRequest request = new ClientUpgradeRequest();
request.setRequestURI(uri);
client.connect(socket, request.getRequestURI(), request);
System.out.println("Task connected");
}
public void stop(Task.StopReason stopReason) throws IOException {
System.out.println("Task.stop " + stopReason);
if (stopReason != StopReason.CLOSED) {
try {
client.stop();
} catch (Exception e) {
throw new IOException("Task Error at 'stop': " + e.getLocalizedMessage(), e);
}
client.destroy();
try {
client.getConnectionManager().stop();
} catch (Exception e) {
System.err.println("Task Error at 'stop': " + e.getLocalizedMessage());
}
client.getConnectionManager().destroy();
}
System.out.println("Task.stop done " + stopReason);
}
}
main class to run the "test":
package example;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.Collections;
import java.util.Map;
import javax.websocket.DeploymentException;
import javax.websocket.server.ServerEndpoint;
import org.glassfish.tyrus.server.Server;
import example.Task.StopReason;
#SuppressWarnings("javadoc")
#ServerEndpoint(value = "/test")
public class MemoryLeakDebug {
public static void main(String[] args) throws IOException, URISyntaxException, DeploymentException {
Map<String, Object> config = Collections.emptyMap();
Server server = new Server("localhost", 10000, "/test", config, DummyEndpoint.class);
server.start();
Task task = new Task(new URI("ws://localhost:10000/test/test"));
task.start();
long[] useds = new long[100];
try {
for (int i = 0; i < useds.length; i++) {
System.out.println("------------------------");
Runtime.getRuntime().gc();
long used = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory();
System.out.println("used: " + used);
useds[i] = used;
task.restart();
synchronized (task) {
try {
task.wait(100);
} catch (InterruptedException e) {
System.err.println(e.getLocalizedMessage());
}
}
}
} catch (AssertionError e) {
throw e;
} finally {
task.stop(StopReason.EXIT);
server.stop();
StringBuilder sb = new StringBuilder("useds:\n");
int index = 0;
int count = 0;
int moreCount = 0;
long last = -1;
for (long used : useds) {
sb.append((index++) + "\t" + used + "\n");
if (used > 0) {
count++;
}
if (last != -1) {
if (used > last) {
moreCount++;
}
}
last = used;
}
System.out.println(sb.toString());
System.out.println(moreCount + " / " + count);
if (moreCount > count * .75) {
throw new IllegalStateException("more heap used: " + moreCount + " / " + count);
}
}
}
}
Mock endpoint:
package example;
import javax.websocket.CloseReason;
import javax.websocket.EndpointConfig;
import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;
#SuppressWarnings("javadoc")
#ServerEndpoint(value = "/test")
public class DummyEndpoint {
public DummyEndpoint() {
System.out.println("DummyEndpoint");
}
#OnClose
public void handleOnClose(Session session, CloseReason reason) {
System.out.println("DummyEndpoint#OnClose: " + reason + " " + session);
}
#OnError
public void handleOnError(Session session, Throwable error) {
System.out.println("DummyEndpoint#OnError: " + error + " " + session + " " + error.toString());
}
#OnMessage
public void handleOnMessage(Session session, String message) {
System.out.println("DummyEndpoint#OnMessage: " + message + " " + session);
}
#OnOpen
public void handleOnOpen(final Session session, EndpointConfig conf) {
System.out.println("DummyEndpoint#OnOpen: " + conf + " " + session);
}
}
Simplified dummy client:
package example;
import java.io.IOException;
import org.eclipse.jetty.websocket.api.Session;
import org.eclipse.jetty.websocket.api.annotations.OnWebSocketClose;
import org.eclipse.jetty.websocket.api.annotations.OnWebSocketConnect;
import org.eclipse.jetty.websocket.api.annotations.OnWebSocketError;
import org.eclipse.jetty.websocket.api.annotations.OnWebSocketMessage;
import org.eclipse.jetty.websocket.api.annotations.WebSocket;
import example.Task.StopReason;
#SuppressWarnings("javadoc")
#WebSocket
public class ClientSocket {
private Session session;
private Task task;
public ClientSocket(Task task) {
this.task = task;
}
#OnWebSocketClose
public void handleClose(int statusCode, String reason) {
System.out.println("ClientSocket#OnWebSocketClose " + statusCode + " " + reason);
session = null;
try {
task.stop(StopReason.CLOSED);
} catch (IOException e) {
throw new IllegalStateException("Error at 'handleClose': " + e.getLocalizedMessage(), e);
}
}
#OnWebSocketConnect
public void handleConnect(Session session) {
System.out.println("ClientSocket#OnWebSocketConnect " + session);
this.session = session;
}
#OnWebSocketError
public void handleError(Throwable cause) {
System.err.println("ClientSocket#OnError" + cause);
cause.printStackTrace();
}
#OnWebSocketMessage
public void handleMessage(String message) {
System.out.println("ClientSocket#OnWebSocketMessage " + message);
}
public boolean isConnected() {
return session != null;
}
}
Our dependencies:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>example</groupId>
<artifactId>WebSocketClientDebug</artifactId>
<version>0.1.0-SNAPSHOT</version>
<properties>
<tyrus-version>[1.8.3,1.9)</tyrus-version>
</properties>
<dependencies>
<!-- + + + + + external dependencies + + + + + -->
<dependency>
<groupId>org.eclipse.jetty.websocket</groupId>
<artifactId>websocket-client</artifactId>
<version>9.2.3.v20140905</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>[2.6.0,3.2.0)</version>
</dependency>
<!-- + + + + + external test dependencies + + + + + -->
<dependency>
<groupId>org.glassfish.tyrus</groupId>
<artifactId>tyrus-client</artifactId>
<version>[1.8.3,1.9)</version>
</dependency>
<dependency>
<groupId>org.glassfish.tyrus</groupId>
<artifactId>tyrus-container-grizzly-server</artifactId>
<version>${tyrus-version}</version>
</dependency>
<dependency>
<groupId>org.glassfish.tyrus</groupId>
<artifactId>tyrus-server</artifactId>
<version>${tyrus-version}</version>
</dependency>
<dependency>
<groupId>org.glassfish.tyrus</groupId>
<artifactId>tyrus-container-grizzly-client</artifactId>
<version>${tyrus-version}</version>
</dependency>
</dependencies>
</project>
This was a bug in Jetty's WebSocketClient behavior.
See https://bugs.eclipse.org/bugs/show_bug.cgi?id=444748
This fix is in for Jetty 9.2.4 (currently staged, being tested, and due for a release in the next 7 days)
Contact me on irc.freenode.net/#jetty if you want to access to this staged version, or just wait for it to be released.
Related
i'm try to create a simple client/server java application;
I have to send a java object throw a socket ...
this is the code:
client:
package performancethinclient;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
public class PerformanceThinClient
{
public static void main(String[] args)
{
startClient("localhost");
}
static void startClient(String HOST)
{
try
{
Socket clientSocket = new Socket(HOST, 50000);
// Create the input & output streams to the server
ObjectInputStream inFromServer = new ObjectInputStream(clientSocket.getInputStream());
Rilevazione rl=(Rilevazione) inFromServer.readObject();
inFromServer.close();
clientSocket.close();
rl.printit();
}
catch (IOException | ClassNotFoundException e)
{
System.err.println("Client Error: " + e.getMessage());
System.err.println("Localized: " + e.getLocalizedMessage());
System.err.println("Stack Trace: " + e.getStackTrace());
}
}
}
server:
import java.io.*;
import java.net.Socket;
import java.net.ServerSocket;
public class PerformanceServer
{
public static void main(String args[]) throws IOException, InterruptedException
{
StartServer();
}
public static void StartServer()
{
try
{
ServerSocket welcomeSocket = new ServerSocket(50000);
while (true)
{
// Create the Client Socket
Socket client = welcomeSocket.accept();
System.out.println("Socket Extablished...");
// Create input and output streams to client
ObjectOutputStream outToClient = new ObjectOutputStream(client.getOutputStream());
ObjectInputStream inFromClient = new ObjectInputStream(client.getInputStream());
Rilevazione rl=new Rilevazione();
outToClient.writeObject(rl);
System.out.println("Object Send");
}
}
catch (Exception e)
{
System.err.println("Server Error: " + e.getMessage());
System.err.println("Localized: " + e.getLocalizedMessage());
System.err.println("Stack Trace: " + e.getStackTrace());
System.err.println("To String: " + e.toString());
}
}
}
Rilevazione is a java class that i have create in the same folder .
the code:
package performancethinclient;
import java.io.IOException;
import java.util.*;
public class Rilevazione
{
Date DataOra;
GeneralInfo GeneralInformation ;
CPU ControlProcessingUnit;
RAM RandomAccessMemory;
HDD HardDrive;
Apache apache;
public Rilevazione() throws IOException, InterruptedException
{
DataOra = new Date();
GeneralInformation=new GeneralInfo();
ControlProcessingUnit=new CPU();
RandomAccessMemory=new RAM();
HardDrive=new HDD();
apache=new Apache();
}
public void printit()
{
System.out.println("--------------------------------GENERAL INFORMATION------------------------------------------");
System.out.println("----BIOS");
System.out.println(this.GeneralInformation.BIOS);
}
}
now the Class Rilevazione is present in both application(client and server) in src folder where there are .java files and then Rilevazione.java
My problem is about sending object throw socket ...
javac compiler does not work , the error occured is in the cast of Rilevazione
Rilevazione rl=(Rilevazione) inFromServer.readObject();
it can't compile when in the folder i type: javac PerformanceThinClient.java
Can anyone help me?
Thank's
I do have a multi node spark cluster and submitting my spark program on node where master resides.
When the job submitted to worker nodes, the HOSTNAME paramter is giving null value. Here is the line where properties are being read as null.
System.getenv(HOSTNAME) is not being read from worker node.
System.out.println("line 76 System.getenv(HOSTNAME)=" + System.getenv("HOSTNAME"));
AUDIT_USER, AUDIT_PASSWORD also null when being read(they both were on properties file).
If i submit job with one node i have no issues with these parameters. But, if u submit job on standalone mode with 6 nodes i am getting this issue.
I have created the same folder for properties file on all nodes.
Here is my code. could you please let me know why System.env is not giving null and my properties are null?
package com.fb.cpd.myapp;
import java.io.Serializable;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import java.util.UUID;
import java.util.concurrent.Future;
import org.apache.commons.configuration.ConfigurationConverter;
import org.apache.commons.configuration.ConfigurationException;
import org.apache.commons.configuration.PropertiesConfiguration;
import org.apache.commons.configuration.reloading.FileChangedReloadingStrategy;
import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.clients.producer.Producer;
import org.apache.kafka.clients.producer.ProducerRecord;
import org.apache.kafka.clients.producer.RecordMetadata;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.apache.spark.TaskContext;
import org.apache.spark.api.java.JavaSparkContext;
import org.apache.spark.api.java.function.Function;
import org.apache.spark.streaming.Duration;
import org.apache.spark.streaming.api.java.JavaInputDStream;
import org.apache.spark.streaming.api.java.JavaStreamingContext;
import org.apache.spark.streaming.kafka.KafkaUtils;
import kafka.common.TopicAndPartition;
import kafka.message.MessageAndMetadata;
import kafka.serializer.DefaultDecoder;
import kafka.serializer.StringDecoder;
public class GenericLogic implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
private static final Logger logger = LogManager.getLogger(GenericLogic.class);
private PropertiesConfiguration props;
private Producer<String, String> producer = null;
private Future<RecordMetadata> receipt = null;
private RecordMetadata receiptInfo = null;
private ConnectToRDBMS auditor = null;
private ConnectToRDBMS df = null;
private static String myId = null;
private Map<TopicAndPartition, Long> getOffsets(String topic) throws SQLException {
String appName = "myapp";
String TopicName = topic;
Map<TopicAndPartition, Long> topicMap = new HashMap<>(); //
System.out.println("line 64 before making connection");
try {
props = new PropertiesConfiguration("/app/lock/conf/empty.properties");
} catch (ConfigurationException e) { // TODO Auto-generated catch block
System.out.println("Line 70");
e.printStackTrace();
}
try {
System.out.println("line 76 System.getenv(HOSTNAME)=" + System.getenv("HOSTNAME"));
auditor = new ConnectToRDBMS(System.getenv("HOSTNAME"), "lockSparkCollector", null, null, null, null, null,
0, props.getString("AUDIT_USER"), props.getString("AUDIT_PASSWORD"),
props.getString("AUDIT_DB_URL"));
} catch (SQLException e) {
logger.error("ASSERT: run() ERROR CONNECTING TO AUDIT DB " + e.getMessage());
}
System.out.println("line 64 after making connection");
Statement stmt = null;
String query = "select va_application, topic_name, partition_id, from_offset,until_offset from lock_spark_offsets where va_application = "
+ "'" + appName + "'" + " and topic_name= " + "'" + TopicName + "'";
System.out.println("query" + query);
System.out.println("before query exection");
try {
stmt = auditor.dbConnection.createStatement();
System.out.println("line 81");
ResultSet rs = stmt.executeQuery(query);
System.out.println("line 83");
while (rs.next()) {
System.out.println("pass 1 of Resultset");
System.out.println("getOffsets=" + topic.trim() + " " + rs.getInt("partition_id") + " "
+ rs.getString("until_offset") + " " + rs.getString("until_offset"));
Integer partition = rs.getInt("partition_id");
TopicAndPartition tp = new TopicAndPartition(topic.trim(), partition);
System.out.println("102");
Long.parseLong(rs.getString("until_offset"));
topicMap.put(tp, Long.parseLong(rs.getString("until_offset")));
System.out.println("105");
}
System.out.println("after populating topic map");
} catch (
SQLException e) {
System.out.println("printing exception");
e.printStackTrace();
} finally {
if (stmt != null) {
System.out.println("closing statement");
stmt.close();
}
}
return topicMap;
}
public void setDefaultProperties() {
FileChangedReloadingStrategy strategy = new FileChangedReloadingStrategy();
strategy.setRefreshDelay(10000);
System.out.println("Line 45");
// supply the properties file.
try {
props = new PropertiesConfiguration("/app/lock/conf/empty.properties");
} catch (ConfigurationException e) {
// TODO Auto-generated catch block
System.out.println("Line 51");
e.printStackTrace();
}
props.setReloadingStrategy(strategy);
System.out.println("Line 56");
// Producer configs
if (!props.containsKey("acks")) {
props.setProperty("acks", "1");
}
if (!props.containsKey("retries")) {
props.setProperty("retries", "1000");
}
if (!props.containsKey("compression.type")) {
props.setProperty("compression.type", "gzip");
}
if (!props.containsKey("request.timeout.ms")) {
props.setProperty("request.timeout.ms", "600000");
}
if (!props.containsKey("batch.size")) {
props.setProperty("batch.size", "32768");
}
if (!props.containsKey("buffer.memory")) {
props.setProperty("buffer.memory", "134217728");
}
if (!props.containsKey("block.on.buffer.full")) {
props.setProperty("block.on.buffer.full", "true");
}
if (!props.containsKey("SHUTDOWN")) {
props.setProperty("SHUTDOWN", "false");
}
if (!props.containsKey("producer.topic")) {
props.setProperty("producer.topic", "mytopic1");
}
Properties producer_props = ConfigurationConverter.getProperties(props);
producer_props.setProperty("bootstrap.servers", props.getString("target.bootstrap.servers"));
producer_props.setProperty("key.serializer", "org.apache.kafka.common.serialization.StringSerializer");
producer_props.setProperty("value.serializer", "org.apache.kafka.common.serialization.StringSerializer"); // ????
this.producer = new KafkaProducer<String, String>(producer_props);
System.out.println("Line 107");
}
public void PublishMessages(String st) {
try {
System.out.println("Line 111");
String key = UUID.randomUUID().toString().replace("-", "");
System.out.println("Started Producing...");
receipt = producer.send(new ProducerRecord<String, String>(props.getString("producer.topic"), key, // Key
st));
System.out.println("After Completion of Producing Producing");
} catch (Exception e) {
e.printStackTrace();
System.out.println("Exception in PublishMessages ");
}
}
public void DBConnect() {
try {
auditor = new ConnectToRDBMS(System.getenv("HOSTNAME"), "myapp", props.getString("consumer.topic"), null,
null, null, null, 0, props.getString("AUDIT_USER"), props.getString("AUDIT_PASSWORD"),
props.getString("AUDIT_DB_URL"));
} catch (SQLException e) {
logger.error("ASSERT: run() ERROR CONNECTING TO AUDIT DB " + e.getMessage());
return;
}
}
private void writeToDB(Long startTime, Integer partnId, String fromOffset, String untilOffset, Integer count) {
this.auditor.audit(startTime, partnId, fromOffset, untilOffset, count);
}
/**
*
* #param jsc
* #param topicSet
* #throws Exception
*/
public static void main(String[] args) {
String topicNames = "MySourceTopic";
GenericLogic ec = new GenericLogic();
Map<TopicAndPartition, Long> topicMap = null;
try {
topicMap = ec.getOffsets("MySourceTopic");
} catch (SQLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
boolean clusterMode = false;
Integer batchDuration = Integer.parseInt("30000");
JavaSparkContext sparkConf = new JavaSparkContext("abcd.net:7077", "Kafka-Spark-Integration");
sparkConf.getConf().set("spark.local.ip", "lock-dt-a4d.xyz.com");
sparkConf.getConf().set("spark.eventLog.enabled", "false");
sparkConf.getConf().set("spark.shuffle.blockTransferService", "nio");
JavaStreamingContext jsc = new JavaStreamingContext(sparkConf, new Duration(10000));
Map<String, String> kafkaParams = new HashMap<String, String>();
String pollInterval = "10000";
String zookeeper = "lock-dt-a5d.xyz.com:2181,lock-dt-a6d.xyz.com:2181";
kafkaParams.put("metadata.broker.list", "lock-dt-a5d.xyz.com:9092,lock-dt-a6d.xyz.com:9092");
kafkaParams.put("group.id", "Consumer");
kafkaParams.put("client.id", "Consumer");
kafkaParams.put("zookeeper.connect", zookeeper);
JavaInputDStream<byte[]> directKafkaStream = KafkaUtils.createDirectStream(jsc, String.class, byte[].class,
StringDecoder.class, DefaultDecoder.class, byte[].class, kafkaParams, topicMap,
(Function<MessageAndMetadata<String, byte[]>, byte[]>) MessageAndMetadata::message);
directKafkaStream.foreachRDD(rdd -> {
if (rdd.isEmpty()) {
System.out.println("No events polled in last " + pollInterval + " milli seconds");
return;
}
rdd.foreachPartition(itr -> {
Integer partnId = TaskContext.get().partitionId();
Long systime = System.nanoTime();
Map<String, String> hmap = new HashMap<String, String>();
GenericLogic ec2 = new GenericLogic();
ec2.setDefaultProperties();
ec2.DBConnect();
try {
while (itr.hasNext()) {
System.out.println("232");
}
} catch (Exception e) {
logger.error(e.getMessage(), e);
}
});
});
jsc.start();
jsc.awaitTermination();
}
}
I started the salves with start-slaves.sh.
That's the issue. I have to start workers by supplying master addres.
Can you please let us know OS of all the nodes and if you have ensured that noting on Master node is exporting the HOSTNAME. Answering your question will be better if you let us know about your OS detail.
May not be correctly related to your context but just for information System.getenv("HOSTNAME") may not provide hostname in all the platforms (for example Ubuntu or Mac).
Better is why not export the HOSTNAME.
Note: I am assuming you have already checked that props is not null or empty?
If not debug and check whether properties files is loaded or not and if loaded it is not the empty properties file and hence it has loaded the properties from the file.
Looking at your problem (not only environment variable but properties are also not returning, there may be something wrong with properties file or its relative location on different computers.
If it is not exact copy which is placed at different computers, please also check if it is a file good for Linux (not written and edited in windows and put in linux).
I am new to android and java programming. I am try to write a program to read data via bluetooth.
I trying to pass a String apple which I decipher from my bluetooth input data from my thread to my UI for display CalibrationActivity.
I am using handler for the passing.
I keep getting force quit. Can anyone please advice me how can I solve this problem.
Below is my entire code of my extend Thread.
package com.android.backend.data.bluetooth;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.Method;
import java.util.ArrayList;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import com.android.AutoActivity;
import com.android.CalibrationActivity;
import com.android.ui.UIManager;
public class Connection extends Thread {
final Connection tt = this;
private final String TAG = "Connection"; // Class name for logging
public boolean connected = false;
public BluetoothSocket bSocket = null;
public InputStream mmInStream = null;
public OutputStream mmOutStream = null;
public ArrayList<String> message = new ArrayList<String>();
public BluetoothDevice currentDevice = null;
public UIManager mgr;
public boolean connectFailure = false;
public boolean stopAutoConnect = false;
public String type = null;
public AutoActivity ff;
public void bsocketcancel() {
try {
bSocket.close();
} catch (IOException e) { }
}
public Connection(UIManager mgr, BluetoothDevice device, String message,
String type) {
this.mgr = mgr;
currentDevice = device;
this.message.add(message);
this.type = type;
}
public Connection(UIManager mgr, BluetoothDevice device, ArrayList<String> message,
String type) {
this.mgr = mgr;
currentDevice = device;
this.message = message;
this.type = type;
}
#Override
public void run() {
if (type.compareToIgnoreCase("Manual") == 0) {
Log.d("thread", "manual");
if (!connected)
connect(currentDevice);
if (bSocket != null){
for(String msg : message)
write(msg.getBytes());
}
mgr.hideConnectingProgressBox();
if(connected){
mgr.connectedDialog();
System.out.println("Maunal connected");
}
Log.d("thread", "hideprogressBox");
if (!connected)
mgr.showConnectionErrBox();
}
if (type.compareToIgnoreCase("auto") == 0){
Log.d("thread", "auto");
stopConnection();
int i = 0;
while (true) { //Set to 5 second
if (!connected)
connect(currentDevice);
if (bSocket != null){
for(String msg : message)
write(msg.getBytes());
}
mgr.hideConnectingProgressBox();
Log.d("thread", "hideprogressBox");
if (!connected) {
mgr.connecting();
}
if (connected) {
mgr.connectedDialog();
bsocketcancel();
System.out.println("Auto connected");
//BluetoothManager.getInstance().disconnectAll(); // cut all connection after transmit
break;
}
if(stopAutoConnect){
mgr.cancelconnecting();
break;
}
}
}
if (type.compareToIgnoreCase("calibrate") == 0) {
Log.d("thread", "calibrate");
if (!connected)
connect(currentDevice);
if (bSocket != null){
for(String msg : message)
write(msg.getBytes());
}
mgr.hideConnectingProgressBox();
if(connected){
mgr.connectedDialog();
mgr.msgsent();
System.out.println("Calibration connected");
int bufferSize = 1024;
byte[] buffer = new byte[bufferSize];
int bytes;
String apple = "";
// Keep listening to the InputStream while connected
while (true) {
try {
// Read from the InputStream
bytes = mmInStream.read(buffer);
if ( bytes != -1){
while ((bytes==bufferSize)&&(buffer[bufferSize-1] != 0)){
apple = apple + "_" + new String(buffer, 0, bytes);
bytes = mmInStream.read(buffer);
}
apple = apple + new String(buffer, 0, bytes -1);
System.out.println("message " + apple);
//pass data to UI CalibrationActivity
System.out.println("message out " + apple);
Message msga = mhandler.obtainMessage();
Bundle bundle = new Bundle();
bundle.putString("key", apple);
msga.setData(bundle);
mhandler.sendMessage(msga);
}
} catch (IOException e) {
Log.e(TAG, "disconnected", e);
break;
}
}
}
Log.d("thread", "hideprogressBox");
if (!connected){
mgr.showConnectionErrBox();
}
}
}
public void connect(BluetoothDevice device) {
currentDevice = device;
BluetoothSocket tmp = null;
BluetoothManager.getInstance().getBluetoothAdapter().cancelDiscovery();
// Get a BluetoothSocket for a connection with the
// given BluetoothDevice
try {
// tmp = device
// .createRfcommSocketToServiceRecord(BluetoothManager.SerialPortServiceClass_UUID);
Method m = device.getClass().getMethod("createRfcommSocket",
new Class[] { int.class });
tmp = (BluetoothSocket) m.invoke(device, 1);
// } catch (IOException e) {
// Log.e(TAG, "create() failed", e);
// return;
} catch (Exception e) {
Log.e(TAG, "Socket connection failed", e);
return;
}
bSocket = tmp;
try {
bSocket.connect();
} catch (IOException e1) {
Log.e(TAG, "Connection err", e1);
connectFailure = true;
return;
}
if (tmp != null) {
// Get Input/output stream for Socket
try {
mmInStream = bSocket.getInputStream();
mmOutStream = bSocket.getOutputStream();
} catch (IOException e) {
Log.e(TAG, "temp sockets not created", e);
return;
}
}
connected = true;
connectFailure = false;
}
private Handler mhandler;
public void read(){
Log.i(TAG, "Read is running");
int bufferSize = 1024;
byte[] buffer = new byte[bufferSize];
int bytes;
String a = "";
// Keep listening to the InputStream while connected
while (true) {
try {
// Read from the InputStream
bytes = mmInStream.read(buffer);
if ( bytes != -1){
while ((bytes==bufferSize)&&(buffer[bufferSize-1] != 0)){
a = a + new String(buffer, 0, bytes);
bytes = mmInStream.read(buffer);
}
a = a + new String(buffer, 0, bytes -1);
System.out.println("message " + a);
}
} catch (IOException e) {
Log.e(TAG, "disconnected", e);
break;
}
}
}
public void write(byte[] buffer) {
if (mmOutStream != null) {
try {
mmOutStream.write(buffer);
Log.d(TAG, "Message Sent");
} catch (IOException e) {
Log.e(TAG, "Exception during write", e);
}
} else {
//mgr.showConnectionErrBox();
}
}
public void stopConnection() {
try {
if(bSocket != null)
bSocket.close();
Log.e(TAG, "Connection closed");
} catch (IOException e) {
Log.e(TAG, "close() of connect socket failed", e);
}
}
public BluetoothDevice getCurrentDevice() {
return currentDevice;
}
public void setCurrentDevice(BluetoothDevice currentDevice) {
this.currentDevice = currentDevice;
}
public ArrayList<String> getMessage() {
return message;
}
public void setMessage(ArrayList<String> message) {
this.message = message;
}
}
Below is the affect portion
if(connected){
mgr.connectedDialog();
mgr.msgsent();
System.out.println("Calibration connected");
int bufferSize = 1024;
byte[] buffer = new byte[bufferSize];
int bytes;
String apple = "";
// Keep listening to the InputStream while connected
while (true) {
try {
// Read from the InputStream
bytes = mmInStream.read(buffer);
if ( bytes != -1){
while ((bytes==bufferSize)&&(buffer[bufferSize-1] != 0)){
apple = apple + "_" + new String(buffer, 0, bytes);
bytes = mmInStream.read(buffer);
}
apple = apple + new String(buffer, 0, bytes -1);
System.out.println("message " + apple);
//pass data to UI CalibrationActivity
System.out.println("message out " + apple);
Message msga = mhandler.obtainMessage();
Bundle bundle = new Bundle();
bundle.putString("key", apple);
msga.setData(bundle);
mhandler.sendMessage(msga);
}
} catch (IOException e) {
Log.e(TAG, "disconnected", e);
break;
}
}
}
Below is the code for my Calibration Activity
package com.android;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import com.android.SimpleGestureFilter.SimpleGestureListener;
import com.android.backend.data.Playlist;
import com.android.backend.data.PlaylistManager;
import com.android.backend.data.SwitchBar;
import com.android.backend.data.bluetooth.BluetoothManager;
import com.android.backend.data.bluetooth.Connection;
import com.android.ui.UIManager;
import com.android.ui.playlist.PlaylistEntryList;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.Window;
import android.view.WindowManager.LayoutParams;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ToggleButton;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
//public class CalibrationActivity extends Activity{
public class CalibrationActivity extends Activity implements SimpleGestureListener{
String gotBread;
public void handleMessage(Message msg)
{ switch(msg.what){
case 2:
Bundle got = getIntent().getExtras();
gotBread = got.getString("key");
TextView aa = (TextView) this.findViewById(R.id.stringinput);
aa.setText(gotBread);
break;
}
}
private SimpleGestureFilter detector;
#Override
public boolean dispatchTouchEvent(MotionEvent me){
this.detector.onTouchEvent(me);
return super.dispatchTouchEvent(me);
}
#Override
public void onSwipe(int direction) {
// TODO Auto-generated method stub
//final MainActivity tt = this;
String str = "";
switch (direction) {
//case SimpleGestureFilter.SWIPE_RIGHT : str = "Swipe Right";
case SimpleGestureFilter.SWIPE_RIGHT : this.finish();
break;
case SimpleGestureFilter.SWIPE_LEFT : str = "Swipe Left";
break;
case SimpleGestureFilter.SWIPE_DOWN : str = "Swipe Down";
break;
case SimpleGestureFilter.SWIPE_UP : str = "Swipe Up";
break;
}
//Toast.makeText(this, str, Toast.LENGTH_SHORT).show();
}
#Override
public void onDoubleTap() {
// TODO Auto-generated method stub
//Toast.makeText(this, "Double Tap", Toast.LENGTH_SHORT).show();
//Do Nothing for now future development
}
private PlaylistManager playlistMgr;
private PlaylistEntryList playlistView; // Data for listview, stores current
// playlist in memory
public String createdNameList; // Indicated the name of currently Name of
// playlist that is being created
public Dialog dialog_customizePL, dialog_createPL, dialog_customizePLms; // Dialog boxes for
// Playlist creation
public UIManager uiMgr = new UIManager();
public String CONNECTED_DEVICE_MAC;
public String dialogboxtext;
public Connection Conn;
int i = 0;
protected void onPause() {
super.onPause();
//BluetoothManager.getInstance().disconnectAll();
unregisterReceiver(mRvcau); //Sequence is important
System.exit(0); // Kill off all thread to prevent connectiong lost popup
// I use system because is a calibration so I want user not to leave the activity else cannot calibrate
}
protected void onResume() { //restart bluetooth is accidently off it
super.onResume();
BluetoothManager.getInstance().init();
BluetoothManager.getInstance().getBluetoothAdapter().enable();
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_ACL_CONNECTED); // IntentFilter class is important to declare for below filter
registerReceiver(mRvcau,filter); // mRvcau is the location of logic, filter is message identify by android
filter = new IntentFilter(BluetoothDevice.ACTION_ACL_DISCONNECTED); // Future deveploment
registerReceiver(mRvcau,filter);
filter = new IntentFilter(BluetoothDevice.ACTION_ACL_DISCONNECT_REQUESTED); // Future deveploment
registerReceiver(mRvcau,filter);
filter = new IntentFilter(BluetoothDevice.ACTION_BOND_STATE_CHANGED); // Future deveploment
registerReceiver(mRvcau,filter);
}
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.remotedevicecalibration);
detector = new SimpleGestureFilter(this,this); ////////////////// For Gesture
playlistMgr = PlaylistManager.getInstance();
initUI();
uiMgr.initPlayListUI(this);
}
int connect = 0; // Check connection
int disconnect = 0; // Check disconnection
int requestdisconnect = 0;
int connectstatuschanges = 0;
public BroadcastReceiver mRvcau = new BroadcastReceiver(){ // The new is instantiate the class **always read from the back
// The line from the back is creating an instantiate of this class
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (BluetoothDevice.ACTION_ACL_CONNECTED.equals(action)) {
//AutoActivity.this.finish();
connect = 1; // prevent activity from exiting
System.out.println("ACTION_ACL_CONNECTED " + connect);
}
else
{
connect = 0;
System.out.println("ACTION_ACL_CONNECTED " + connect);
}
if (BluetoothDevice.ACTION_ACL_DISCONNECTED.equals(action)) { //future development
disconnect = 1;
System.out.println("ACTION_ACL_DISCONNECTED " + disconnect);
}
else
{
disconnect = 0;
System.out.println("ACTION_ACL_DISCONNECTED " + disconnect);
}
if (BluetoothDevice.ACTION_ACL_DISCONNECT_REQUESTED.equals(action)) { //future development
requestdisconnect = 1;
System.out.println("ACTION_ACL_DISCONNECT_REQUESTED " + requestdisconnect);
}
else
{
requestdisconnect = 0;
System.out.println("ACTION_ACL_DISCONNECT_REQUESTED " + requestdisconnect);
}
if (BluetoothDevice.ACTION_BOND_STATE_CHANGED.equals(action)) { //future development
connectstatuschanges = 1;
System.out.println("ACTION_BOND_STATE_CHANGED " + connectstatuschanges);
}
else
{
connectstatuschanges = 0;
System.out.println("ACTION_BOND_STATE_CHANGED " + connectstatuschanges);
}
}
};
/**
* Init layout component. Define Listener for Buttons and Dataset for
* ListViews
*/
#SuppressLint("ParserError")
public void initUI() {
Button Orange = (Button) findViewById(R.id.CalibrationOrange); // new method on test using image
Orange.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v){
// TODO Auto-generated method stub
activiteSingleConnection(20);
}
});
Button Blue = (Button) findViewById(R.id.CalibrationBlue); // new method on test using image icon to on the switch
Blue.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v){
// TODO Auto-generated method stub
activiteSingleConnection(21);
}
});
Button Green = (Button) findViewById(R.id.CalibrationGreen); // new method on test using image icon to on the switch
Green.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v){
// TODO Auto-generated method stub
activiteSingleConnection(22);
}
});
loadDataToMem();
}
public void activiteSingleConnection(int i) {
BluetoothManager btMgr = BluetoothManager.getInstance();
BluetoothDevice device = btMgr.getBluetoothAdapter().getRemoteDevice(
CONNECTED_DEVICE_MAC);
ArrayList<String> msg = new ArrayList<String>();
if(i == 20){
msg.add("N");
}
if(i == 21){
msg.add("J");
}
if(i == 22){
msg.add("I");
}
CharSequence fruit = null;
TextView aa = (TextView) this.findViewById(R.id.stringinput);
aa.setText(fruit);
btMgr.calibratesentMessage(uiMgr, device, msg);
}
public void loadDataToMem() {
try {
String str = "";
//StringBuffer buf = new StringBuffer();
FileInputStream input = this.openFileInput("bone.txt");
BufferedReader reader = new BufferedReader(new InputStreamReader(
input));
if (input != null) {
while ((str = reader.readLine()) != null) {
String[] buff = str.split(",");
TextView topView = (TextView) this
.findViewById(R.id.remotedevicecalibrationtextview1);
TextView bottomView = (TextView) this
.findViewById(R.id.remotedevicecalibrationtextView2);
topView.setText("Name : " + buff[0]);
bottomView.setText("Mac : " + buff[2]);
this.CONNECTED_DEVICE_MAC = buff[2];
Log.d("loadDataToMem", str);
}
}
input.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
Below are my log cat error message
09-13 10:50:33.640: W/dalvikvm(2086): threadid=9: thread exiting with uncaught exception (group=0x40015560)
09-13 10:50:33.667: E/AndroidRuntime(2086): FATAL EXCEPTION: Thread-10
09-13 10:50:33.667: E/AndroidRuntime(2086): java.lang.NullPointerException
09-13 10:50:33.667: E/AndroidRuntime(2086): at com.android.backend.data.bluetooth.Connection.run(Connection.java:196)
Hope someone can advice me how to solve. Thank You.
I am trying to send a text message to a phone and I get an error
Fail to send because of unknown reason. -java.io.IOException
import javax.microedition.io.Connector;
import javax.microedition.lcdui.Display;
import javax.microedition.lcdui.Form;
import javax.microedition.midlet.*;
import javax.wireless.messaging.MessageConnection;
import javax.wireless.messaging.TextMessage;
public class Midlet extends MIDlet {
Form form = new Form("Form");
Display display;
public void startApp()
{
display = Display.getDisplay(this);
display.setCurrent(form);
sendSMS("Hello from j2me");
}
public void pauseApp() {
}
public void destroyApp(boolean unconditional) {
}
private void sendSMS(String s) {
String destination = "+12234567890";
String addr = "sms://" + destination;
out("Setting up message");
MessageConnection sender = null;
try
{
try
{
sender = (MessageConnection) Connector.open(addr);
TextMessage msg = (TextMessage) sender.newMessage(MessageConnection.TEXT_MESSAGE);
msg.setPayloadText(s);
out("sending");
sender.send(msg);
out("sent successfully");
}
catch (Exception ex)
{
out("Error1:" + ex.getMessage() + " : " + ex.toString() + "\n\n");
}
finally
{
sender.close();
}
}
catch (Exception ex) {
//handle exception
out("Error2:" + ex.getMessage() + " : " + ex.toString() + "\n\n");
}
}
private void out(String str)
{
form.append(str + "\n");
}
}
Did you add permissions to your jad?
MIDlet-Permissions: javax.microedition.io.Connector.sms,javax.wireless.messaging.sms.send
All sorts of reasons:
No credit on PAYG phone
No mobile reception
SMS API blocked by handset operator
User rejected security prompt (this would cause a SecurityException)
Invalid mobile number
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...