how to convert thread to multi thread? - multithreading

I want to the following code to convert the thread to newFixedThreadpool()
how do I do it?
//saddddddddddddddddddddddddddddffgfggggggggggggggggggggggggfdhfdhfdhdhdfhjhljgjhgdadsadsafds
class client :
import java.io.File;
import java.io.FileInputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.util.Arrays;
import java.lang.*;
import java.util.Scanner;
public class Client {
public static void main(String[] args) throws Exception {
String fileName = null;
try {
fileName = args[0];
} catch (Exception e) {
System.out.println("Enter the name of the file :");
Scanner scanner = new Scanner(System.in);
String file_name = scanner.nextLine();
File file = new File(file_name);
Socket socket = new Socket("localhost", 3332);
ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());
ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());
oos.writeObject(file.getName());
FileInputStream fis = new FileInputStream(file);
byte [] buffer = new byte[Server.BUFFER_SIZE];
Integer bytesRead = 0;
while ((bytesRead = fis.read(buffer)) > 0) {
oos.writeObject(bytesRead);
oos.writeObject(Arrays.copyOf(buffer, buffer.length));
}
oos.close();
ois.close();
System.exit(0);
}
}
}
class server:
import java.io.FileOutputStream;
import java.io.*;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.ServerSocket;
import java.net.Socket;
public class Server extends Thread {
public static final int PORT = 3332;
public static final int BUFFER_SIZE = 100;
public void run() {
try {
ServerSocket serverSocket = new ServerSocket(PORT);
while (true) {
Socket s = serverSocket.accept();
saveFile(s);
}
} catch (Exception e) {
e.printStackTrace();
}
}
private void saveFile(Socket socket) throws Exception {
ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());
ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());
FileOutputStream fos = null;
byte [] buffer = new byte[BUFFER_SIZE];
Object o = ois.readObject();
if (o instanceof String) {
fos = new FileOutputStream(new File("/home/reza/Desktop/reza"));
} else {
throwException("Something is wrong");
}
Integer bytesRead = 0;
do {
o = ois.readObject();
if (!(o instanceof Integer)) {
throwException("Something is wrong");
}
bytesRead = (Integer)o;
o = ois.readObject();
if (!(o instanceof byte[])) {
throwException("Something is wrong");
}
buffer = (byte[])o;
fos.write(buffer, 0, bytesRead);
} while (bytesRead == BUFFER_SIZE);
System.out.println("File transfer success");
fos.close();
ois.close();
oos.close();
}
public static void throwException(String message) throws Exception {
throw new Exception(message);
}
public static void main(String[] args) {
new Server().start();
}
}

public class Server extends Thread {
public void run() {
try {
ServerSocket serverSocket = new ServerSocket(PORT);
while (true) {
Socket s = serverSocket.accept();
new ServerWorker(s).start();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
public class ServerWorker extends Thread {
private Socket _socket;
public ServerWorker(Socket socket) {
this._socket = socket;
}
public void run() {
saveFile(this._socket);
// Thread should terminate when run returns.
}
private void saveFile(Socket socket) throws Exception {
...
}
}

Related

Proper way to send e-mail in managed bean

I'm using this Java code to send messages in JSF page:
import com.web.utils.SendEmail;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.Serializable;
import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import javax.faces.view.ViewScoped;
import javax.inject.Named;
import javax.mail.MessagingException;
import javax.servlet.http.Part;
#Named
#ViewScoped
public class Contacts implements Serializable
{
private static final long serialVersionUID = 1L;
private Part file;
private String name;
private String senderEmail;
private String telephone;
private String comment;
private String result;
public Contacts()
{
}
public void sendEmail() throws IOException, MessagingException
{
String[] to =
{
"test#gmail.com"
}; // list of recipient email addresses
String subject = name + " " + senderEmail + " " + telephone;
SendEmail mail = new SendEmail();
result = mail.intiSendEmail(to, subject, comment, file);
}
public void upload()
{
if (file != null)
{
try (InputStream inputStream = file.getInputStream(); FileOutputStream outputStream = new FileOutputStream("D:" + File.separator + "files" + File.separator + file.getSubmittedFileName()))
{
int bytesRead = 0;
final byte[] chunck = new byte[1024];
while ((bytesRead = inputStream.read(chunck)) != -1)
{
outputStream.write(chunck, 0, bytesRead);
}
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage("Upload successfully ended!"));
}
catch (IOException e)
{
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage("Upload failed!"));
}
}
}
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
public String getSenderEmail()
{
return senderEmail;
}
public void setSenderEmail(String senderEmail)
{
this.senderEmail = senderEmail;
}
public String getTelephone()
{
return telephone;
}
public void setTelephone(String telephone)
{
this.telephone = telephone;
}
public String getComment()
{
return comment;
}
public void setComment(String comment)
{
this.comment = comment;
}
public String getResult()
{
return result;
}
public void setResult(String result)
{
this.result = result;
}
public Part getFile()
{
return file;
}
public void setFile(Part file)
{
this.file = file;
}
}
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.Serializable;
import java.util.Properties;
import javax.activation.DataHandler;
import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import javax.mail.util.ByteArrayDataSource;
import javax.servlet.http.Part;
public class SendEmail implements Serializable
{
private String USER_NAME = "test";
private String PASSWORD = "test!";
public String intiSendEmail(String[] to, String subject, String body, Part file) throws IOException, MessagingException
{
String status;
Properties props = System.getProperties();
String host = "smtp.gmail.com";
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.host", host);
props.put("mail.smtp.user", USER_NAME);
props.put("mail.smtp.password", PASSWORD);
props.put("mail.smtp.port", "587");
props.put("mail.smtp.auth", "true");
Session session = Session.getDefaultInstance(props);
MimeMessage message = new MimeMessage(session);
try
{
message.setFrom(new InternetAddress(USER_NAME));
InternetAddress[] toAddress = new InternetAddress[to.length];
// To get the array of addresses
for (int i = 0; i < to.length; i++)
{
toAddress[i] = new InternetAddress(to[i]);
}
for (int i = 0; i < toAddress.length; i++)
{
message.addRecipient(Message.RecipientType.TO, toAddress[i]);
}
message.setSubject(subject);
message.setText(body);
/**
* If file is not attached skip setting content
*/
if (file != null)
{
MimeBodyPart messageBodyPart = new MimeBodyPart();
Multipart multipart = new MimeMultipart();
messageBodyPart = new MimeBodyPart();
ByteArrayDataSource ds = new ByteArrayDataSource(file.getInputStream(), file.getContentType());
messageBodyPart.setDataHandler(new DataHandler(ds));
messageBodyPart.setFileName(file.getName());
multipart.addBodyPart(messageBodyPart);
message.setContent(multipart);
}
Transport transport = session.getTransport("smtp");
transport.connect(host, USER_NAME, PASSWORD);
transport.sendMessage(message, message.getAllRecipients());
transport.close();
}
catch (AddressException ae)
{
ae.printStackTrace();
return status = "Cannot send Message!";
}
catch (MessagingException me)
{
me.printStackTrace();
return status = "Cannot send Message!";
}
return status = "Message is send!";
}
/**
* For testing
*/
public void upload()
{
Part file = null;
if (file != null)
{
try (InputStream inputStream = file.getInputStream(); FileOutputStream outputStream = new FileOutputStream("D:" + File.separator + "files" + File.separator + file.getSubmittedFileName()))
{
int bytesRead = 0;
final byte[] chunck = new byte[1024];
while ((bytesRead = inputStream.read(chunck)) != -1)
{
outputStream.write(chunck, 0, bytesRead);
}
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage("Upload successfully ended!"));
}
catch (IOException e)
{
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage("Upload failed!"));
}
}
}
}
I added thread pool in order to speedup page performance. But I as you can see the code execution is not properly handled when package is redeployed. What it the proper way to stop Thread pool in JSF?

Pass String from thread to UI for display

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.

Why I am getting the bad length exception when I am running this application?

I want to communicate to a server from J2me app using UDP.However, when I am running the app, I am getting a bad length exception.My codes and output are given below.
client code
import javax.microedition.midlet.MIDlet;
import javax.microedition.lcdui.Display;
import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.CommandListener;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.TextBox;
import javax.microedition.lcdui.TextField;
import javax.microedition.io.Connector;
import javax.microedition.io.Datagram;
import javax.microedition.io.DatagramConnection;
import java.io.IOException;
public class DatagramTest extends MIDlet
implements CommandListener, Runnable
{
private static final int BUF_SIZE = 1024;
private static Command exit = new Command("Exit", Command.EXIT, 1);
private static DatagramTest instance;
private Display display;
private TextBox dgramText;
private DatagramConnection conn;
private Datagram dgram;
private String address = "datagram://myip:9876";
public DatagramTest()
{
super();
instance = this;
}
public DatagramTest(String service)
{
this();
address = service;
}
/**
Returns the single instance of this class. Calling
this method before constructing an object will return
a null pointer.
#return an instance of this class.
*/
public static DatagramTest getInstance()
{
return instance;
}
public void startApp()
{
display = Display.getDisplay(this);
dgramText = new TextBox("Datagram contents",
null,
2048,
TextField.ANY);
dgramText.setCommandListener(this);
display.setCurrent(dgramText);
System.out.println("Starting run....");
run();
System.out.println("Stopping run....");
}
public void run()
{
System.out.println("In run....");
try
{
int maxLength;
conn = (DatagramConnection)Connector.open(address);
maxLength = conn.getMaximumLength();
dgram = conn.newDatagram(1024);
dgram.reset();
conn.send(dgram);
conn.receive(dgram);
byte[] data = dgram.getData();
// Extract the response string.
String str = new String(data);
System.out.println(str);
dgram.reset();
System.out.println("Exit run....");
}
catch (IOException ioe)
{
System.out.println(ioe.getMessage());
ioe.printStackTrace();
quit();
}
return;
}
public void pauseApp()
{
}
void quit()
{
destroyApp(true);
notifyDestroyed();
}
public void destroyApp(boolean destroy)
{
try
{
conn.close();
}
catch (IOException ioe)
{
ioe.printStackTrace();
}
}
public void display()
{
Display.getDisplay(this).setCurrent(dgramText);
}
public void commandAction(Command c, Displayable d)
{
if (c == exit)
{
quit();
}
}
}
Server code
import java.io.*;
import java.net.*;
class UDPServer
{
public static void main(String args[]) throws Exception
{
DatagramSocket serverSocket = new DatagramSocket(9876);
byte[] receiveData = new byte[1024];
byte[] sendData = new byte[1024];
while(true)
{
DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
serverSocket.receive(receivePacket);
String sentence = new String( receivePacket.getData());
System.out.println("RECEIVED: " + sentence);
InetAddress IPAddress = receivePacket.getAddress();
int port = receivePacket.getPort();
String capitalizedSentence = sentence.toUpperCase();
sendData = capitalizedSentence.getBytes();
DatagramPacket sendPacket =
new DatagramPacket(sendData, sendData.length, IPAddress, port);
serverSocket.send(sendPacket);
}
}
}
Output at clientside
Starting run.... In run.... Bad
datagram length java.io.IOException:
Bad datagram length
at com.sun.midp.io.j2me.datagram.Protocol.receive(Protocol.java:367)
at hello.DatagramTest.run(DatagramTest.java:89)
at hello.DatagramTest.startApp(DatagramTest.java:69)
at javax.microedition.midlet.MIDletProxy.startApp(MIDletProxy.java:43)
at com.sun.midp.midlet.Scheduler.schedule(Scheduler.java:374)
at com.sun.midp.main.Main.runLocalClass(Main.java:466)
at com.sun.midp.main.Main.main(Main.java:120)
Stopping run....
Why I am getting this bad length exception and how do I sort it out?
One thing you need to try is to send and receive datagrams in a separate thread.
The documentation for DatagramConnection.receive() says: "This method blocks until a datagram is received"
You are calling it from inside MIDlet.startApp().
Blocking the application management system thread that calls startApp() is bad practice.

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