getBluetoothService() called with no BluetoothManagerCallback for Android Nexus 5 - android-bluetooth

I am going to implemenet the module for sending commands from my Android smartphone to HC-06 via BLuetooth. WHen it comes to the execution , it show s the following exception and find no clue for the error message as title . Would you please tell the way to modifiy ?
Exception Log Message :
07-29 13:51:37.701: W/BluetoothAdapter(1928): getBluetoothService() called with no BluetoothManagerCallback
07-29 13:51:37.711: D/BluetoothSocket(1928): connect(), SocketState: INIT, mPfd: {ParcelFileDescriptor: FileDescriptor[51]}
07-29 13:51:42.831: W/System.err(1928): java.io.IOException: read failed, socket might closed or timeout, read ret: -1
07-29 13:51:42.831: W/System.err(1928): at android.bluetooth.BluetoothSocket.readAll(BluetoothSocket.java:505)
07-29 13:51:42.831: W/System.err(1928): at android.bluetooth.BluetoothSocket.readInt(BluetoothSocket.java:516)
07-29 13:51:42.831: W/System.err(1928): at android.bluetooth.BluetoothSocket.connect(BluetoothSocket.java:320)
07-29 13:51:42.831: W/System.err(1928): at com.luugiathuy.apps.remotebluetooth.BluetoothCommandService$ConnectThread.run(BluetoothCommandService.java:260)
07-29 13:51:42.831: D/BluetoothCommandService(1928): setState() 2 -> 1
The below is my code
public class BluetoothCommandService {
// Debugging
private static final String TAG = "BluetoothCommandService";
private static final boolean D = true;
// Unique UUID for this application
// private static final UUID MY_UUID = UUID.fromString("04c6093b-0000-1000-8000-00805f9b34fb");
private static final UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805f9b34fb");
// Member fields
private final BluetoothAdapter mAdapter;
private final Handler mHandler;
private ConnectThread mConnectThread;
private ConnectedThread mConnectedThread;
private int mState;
// private BluetoothDevice mSavedDevice;
// private int mConnectionLostCount;
// Constants that indicate the current connection state
public static final int STATE_NONE = 0; // we're doing nothing
public static final int STATE_LISTEN = 1; // now listening for incoming connections
public static final int STATE_CONNECTING = 2; // now initiating an outgoing connection
public static final int STATE_CONNECTED = 3; // now connected to a remote device
// Constants that indicate command to computer
public static final int EXIT_CMD = -1;
public static final int VOL_UP = 1;
public static final int VOL_DOWN = 2;
public static final int MOUSE_MOVE = 3;
/**
* Constructor. Prepares a new BluetoothChat session.
* #param context The UI Activity Context
* #param handler A Handler to send messages back to the UI Activity
*/
public BluetoothCommandService(Context context, Handler handler) {
mAdapter = BluetoothAdapter.getDefaultAdapter();
mState = STATE_NONE;
//mConnectionLostCount = 0;
mHandler = handler;
}
/**
* Set the current state of the chat connection
* #param state An integer defining the current connection state
*/
private synchronized void setState(int state) {
if (D) Log.d(TAG, "setState() " + mState + " -> " + state);
mState = state;
// Give the new state to the Handler so the UI Activity can update
mHandler.obtainMessage(RemoteBluetooth.MESSAGE_STATE_CHANGE, state, -1).sendToTarget();
}
/**
* Return the current connection state. */
public synchronized int getState() {
return mState;
}
/**
* Start the chat service. Specifically start AcceptThread to begin a
* session in listening (server) mode. Called by the Activity onResume() */
public synchronized void start() {
if (D) Log.d(TAG, "start");
// Cancel any thread attempting to make a connection
if (mConnectThread != null) {mConnectThread.cancel(); mConnectThread = null;}
// Cancel any thread currently running a connection
if (mConnectedThread != null) {mConnectedThread.cancel(); mConnectedThread = null;}
setState(STATE_LISTEN);
}
/**
* Start the ConnectThread to initiate a connection to a remote device.
* #param device The BluetoothDevice to connect
*/
public synchronized void connect(BluetoothDevice device) {
if (D) Log.d(TAG, "connect to: " + device);
// Cancel any thread attempting to make a connection
if (mState == STATE_CONNECTING) {
if (mConnectThread != null) {mConnectThread.cancel(); mConnectThread = null;}
}
// Cancel any thread currently running a connection
if (mConnectedThread != null) {mConnectedThread.cancel(); mConnectedThread = null;}
// Start the thread to connect with the given device
mConnectThread = new ConnectThread(device);
mConnectThread.start();
setState(STATE_CONNECTING);
}
/**
* Start the ConnectedThread to begin managing a Bluetooth connection
* #param socket The BluetoothSocket on which the connection was made
* #param device The BluetoothDevice that has been connected
*/
public synchronized void connected(BluetoothSocket socket, BluetoothDevice device) {
if (D) Log.d(TAG, "connected");
// Cancel the thread that completed the connection
if (mConnectThread != null) {mConnectThread.cancel(); mConnectThread = null;}
// Cancel any thread currently running a connection
if (mConnectedThread != null) {mConnectedThread.cancel(); mConnectedThread = null;}
// Start the thread to manage the connection and perform transmissions
mConnectedThread = new ConnectedThread(socket);
mConnectedThread.start();
// Send the name of the connected device back to the UI Activity
Message msg = mHandler.obtainMessage(RemoteBluetooth.MESSAGE_DEVICE_NAME);
Bundle bundle = new Bundle();
bundle.putString(RemoteBluetooth.DEVICE_NAME, device.getName());
msg.setData(bundle);
mHandler.sendMessage(msg);
// save connected device
//mSavedDevice = device;
// reset connection lost count
//mConnectionLostCount = 0;
setState(STATE_CONNECTED);
}
/**
* Stop all threads
*/
public synchronized void stop() {
if (D) Log.d(TAG, "stop");
if (mConnectThread != null) {mConnectThread.cancel(); mConnectThread = null;}
if (mConnectedThread != null) {mConnectedThread.cancel(); mConnectedThread = null;}
setState(STATE_NONE);
}
/**
* Write to the ConnectedThread in an unsynchronized manner
* #param out The bytes to write
* #see ConnectedThread#write(byte[])
*/
public void write(byte[] out) {
// Create temporary object
ConnectedThread r;
// Synchronize a copy of the ConnectedThread
synchronized (this) {
if (mState != STATE_CONNECTED) return;
r = mConnectedThread;
}
// Perform the write unsynchronized
r.write(out);
}
public void write(int out) {
// Create temporary object
ConnectedThread r;
// Synchronize a copy of the ConnectedThread
synchronized (this) {
if (mState != STATE_CONNECTED) return;
r = mConnectedThread;
}
// Perform the write unsynchronized
r.write(out);
}
/**
* Indicate that the connection attempt failed and notify the UI Activity.
*/
private void connectionFailed() {
setState(STATE_LISTEN);
// Send a failure message back to the Activity
Message msg = mHandler.obtainMessage(RemoteBluetooth.MESSAGE_TOAST);
Bundle bundle = new Bundle();
bundle.putString(RemoteBluetooth.TOAST, "Unable to connect device");
msg.setData(bundle);
mHandler.sendMessage(msg);
}
/**
* Indicate that the connection was lost and notify the UI Activity.
*/
private void connectionLost() {
// mConnectionLostCount++;
// if (mConnectionLostCount < 3) {
// // Send a reconnect message back to the Activity
// Message msg = mHandler.obtainMessage(RemoteBluetooth.MESSAGE_TOAST);
// Bundle bundle = new Bundle();
// bundle.putString(RemoteBluetooth.TOAST, "Device connection was lost. Reconnecting...");
// msg.setData(bundle);
// mHandler.sendMessage(msg);
//
// connect(mSavedDevice);
// } else {
setState(STATE_LISTEN);
// Send a failure message back to the Activity
Message msg = mHandler.obtainMessage(RemoteBluetooth.MESSAGE_TOAST);
Bundle bundle = new Bundle();
bundle.putString(RemoteBluetooth.TOAST, "Device connection was lost");
msg.setData(bundle);
mHandler.sendMessage(msg);
// }
}
/**
* This thread runs while attempting to make an outgoing connection
* with a device. It runs straight through; the connection either
* succeeds or fails.
*/
private class ConnectThread extends Thread {
private final BluetoothSocket mmSocket;
private final BluetoothDevice mmDevice;
public ConnectThread(BluetoothDevice device) {
mmDevice = device;
BluetoothSocket tmp = null;
// Get a BluetoothSocket for a connection with the
// given BluetoothDevice
try {
tmp = device.createRfcommSocketToServiceRecord(MY_UUID);
} catch (IOException e) {
Log.e(TAG, "create() failed", e);
}
mmSocket = tmp;
}
public void run() {
Log.i(TAG, "BEGIN mConnectThread");
setName("ConnectThread");
// Always cancel discovery because it will slow down a connection
mAdapter.cancelDiscovery();
// Make a connection to the BluetoothSocket
try {
// This is a blocking call and will only return on a
// successful connection or an exception
mmSocket.connect();
} catch (IOException e) {
e.printStackTrace();
connectionFailed();
// Close the socket
try {
mmSocket.close();
} catch (IOException e2) {
Log.e(TAG, "unable to close() socket during connection failure", e2);
}
// Start the service over to restart listening mode
BluetoothCommandService.this.start();
return;
}
// Reset the ConnectThread because we're done
synchronized (BluetoothCommandService.this) {
mConnectThread = null;
}
// Start the connected thread
connected(mmSocket, mmDevice);
}
public void cancel() {
try {
mmSocket.close();
} catch (IOException e) {
Log.e(TAG, "close() of connect socket failed", e);
}
}
}
/**
* This thread runs during a connection with a remote device.
* It handles all incoming and outgoing transmissions.
*/
private class ConnectedThread extends Thread {
private final BluetoothSocket mmSocket;
private final InputStream mmInStream;
private final OutputStream mmOutStream;
public ConnectedThread(BluetoothSocket socket) {
Log.d(TAG, "create ConnectedThread");
mmSocket = socket;
InputStream tmpIn = null;
OutputStream tmpOut = null;
// Get the BluetoothSocket input and output streams
try {
tmpIn = socket.getInputStream();
tmpOut = socket.getOutputStream();
} catch (IOException e) {
Log.e(TAG, "temp sockets not created", e);
}
mmInStream = tmpIn;
mmOutStream = tmpOut;
}
public void run() {
Log.i(TAG, "BEGIN mConnectedThread");
byte[] buffer = new byte[1024];
// Keep listening to the InputStream while connected
while (true) {
try {
// Read from the InputStream
int bytes = mmInStream.read(buffer);
// Send the obtained bytes to the UI Activity
mHandler.obtainMessage(RemoteBluetooth.MESSAGE_READ, bytes, -1, buffer)
.sendToTarget();
} catch (IOException e) {
Log.e(TAG, "disconnected", e);
connectionLost();
break;
}
}
}
/**
* Write to the connected OutStream.
* #param buffer The bytes to write
*/
public void write(byte[] buffer) {
try {
mmOutStream.write(buffer);
mmOutStream.flush();
// Share the sent message back to the UI Activity
// mHandler.obtainMessage(BluetoothChat.MESSAGE_WRITE, -1, -1, buffer)
// .sendToTarget();
} catch (IOException e) {
Log.e(TAG, "Exception during write", e);
}
}
public void write(int out) {
try {
mmOutStream.write(out);
// Share the sent message back to the UI Activity
// mHandler.obtainMessage(BluetoothChat.MESSAGE_WRITE, -1, -1, buffer)
// .sendToTarget();
} catch (IOException e) {
Log.e(TAG, "Exception during write", e);
}
}
public void cancel() {
try {
mmOutStream.write(EXIT_CMD);
mmSocket.close();
} catch (IOException e) {
Log.e(TAG, "close() of connect socket failed", e);
}
}
}
}
Here is my Activity
public class RemoteBluetooth extends Activity {
// Layout view
private TextView mTitle;
// Intent request codes
private static final int REQUEST_CONNECT_DEVICE = 1;
private static final int REQUEST_ENABLE_BT = 2;
// Message types sent from the BluetoothChatService Handler
public static final int MESSAGE_STATE_CHANGE = 1;
public static final int MESSAGE_READ = 2;
public static final int MESSAGE_WRITE = 3;
public static final int MESSAGE_DEVICE_NAME = 4;
public static final int MESSAGE_TOAST = 5;
// Key names received from the BluetoothCommandService Handler
public static final String DEVICE_NAME = "device_name";
public static final String TOAST = "toast";
// Name of the connected device
private String mConnectedDeviceName = null;
// Local Bluetooth adapter
private BluetoothAdapter mBluetoothAdapter = null;
// Member object for Bluetooth Command Service
private BluetoothCommandService mCommandService = null;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Set up the window layout
requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
setContentView(R.layout.main);
getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.custom_title);
// Set up the custom title
mTitle = (TextView) findViewById(R.id.title_left_text);
mTitle.setText(R.string.app_name);
mTitle = (TextView) findViewById(R.id.title_right_text);
// Get local Bluetooth adapter
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
// If the adapter is null, then Bluetooth is not supported
if (mBluetoothAdapter == null) {
Toast.makeText(this, "Bluetooth is not available", Toast.LENGTH_LONG).show();
finish();
return;
}
}
#Override
protected void onStart() {
super.onStart();
// If BT is not on, request that it be enabled.
// setupCommand() will then be called during onActivityResult
if (!mBluetoothAdapter.isEnabled()) {
Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableIntent, REQUEST_ENABLE_BT);
}
// otherwise set up the command service
else {
if (mCommandService==null)
setupCommand();
}
}
#Override
protected void onResume() {
super.onResume();
// Performing this check in onResume() covers the case in which BT was
// not enabled during onStart(), so we were paused to enable it...
// onResume() will be called when ACTION_REQUEST_ENABLE activity returns.
if (mCommandService != null) {
if (mCommandService.getState() == BluetoothCommandService.STATE_NONE) {
mCommandService.start();
}
}
}
private void setupCommand() {
// Initialize the BluetoothChatService to perform bluetooth connections
mCommandService = new BluetoothCommandService(this, mHandler);
}
#Override
protected void onDestroy() {
super.onDestroy();
if (mCommandService != null)
mCommandService.stop();
}
private void ensureDiscoverable() {
if (mBluetoothAdapter.getScanMode() !=
BluetoothAdapter.SCAN_MODE_CONNECTABLE_DISCOVERABLE) {
Intent discoverableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);
startActivity(discoverableIntent);
}
}
// The Handler that gets information back from the BluetoothChatService
private final Handler mHandler = new Handler() {
#Override
public void handleMessage(Message msg) {
switch (msg.what) {
case MESSAGE_STATE_CHANGE:
switch (msg.arg1) {
case BluetoothCommandService.STATE_CONNECTED:
mTitle.setText(R.string.title_connected_to);
mTitle.append("HC-06");
break;
case BluetoothCommandService.STATE_CONNECTING:
mTitle.setText(R.string.title_connecting);
break;
case BluetoothCommandService.STATE_LISTEN:
case BluetoothCommandService.STATE_NONE:
mTitle.setText(R.string.title_not_connected);
break;
}
break;
case MESSAGE_DEVICE_NAME:
// save the connected device's name
mConnectedDeviceName = msg.getData().getString(DEVICE_NAME);
Toast.makeText(getApplicationContext(), "Connected to "
+ mConnectedDeviceName, Toast.LENGTH_SHORT).show();
break;
case MESSAGE_TOAST:
Toast.makeText(getApplicationContext(), msg.getData().getString(TOAST),
Toast.LENGTH_SHORT).show();
break;
}
}
};
public void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case REQUEST_CONNECT_DEVICE:
// When DeviceListActivity returns with a device to connect
if (resultCode == Activity.RESULT_OK) {
// Get the device MAC address
String address = data.getExtras()
.getString(DeviceListActivity.EXTRA_DEVICE_ADDRESS);
// Get the BLuetoothDevice object
BluetoothDevice device = BluetoothAdapter.getDefaultAdapter().getRemoteDevice(address);
// Attempt to connect to the device
mCommandService.connect(device);
}
break;
case REQUEST_ENABLE_BT:
// When the request to enable Bluetooth returns
if (resultCode == Activity.RESULT_OK) {
// Bluetooth is now enabled, so set up a chat session
setupCommand();
} else {
// User did not enable Bluetooth or an error occured
Toast.makeText(this, R.string.bt_not_enabled_leaving, Toast.LENGTH_SHORT).show();
finish();
}
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.option_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.scan:
// Launch the DeviceListActivity to see devices and do scan
Intent serverIntent = new Intent(this, DeviceListActivity.class);
startActivityForResult(serverIntent, REQUEST_CONNECT_DEVICE);
return true;
case R.id.discoverable:
// Ensure this device is discoverable by others
ensureDiscoverable();
return true;
}
return false;
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_VOLUME_UP) {
String blinkCommand = "&$V00X77V0" ;
String empty = "";
for (int i = 0 ; i < (100 - blinkCommand.length()) ; i ++){
empty += "0";
}
String limiter = "\r\n";
String fullCommand = blinkCommand + empty + limiter;
mCommandService.write(fullCommand.getBytes());
// mCommandService.write(BluetoothCommandService.VOL_UP);
return true;
}
else if (keyCode == KeyEvent.KEYCODE_VOLUME_DOWN){
String blinkCommand = "&$V00X77V0" + "\r\n";
mCommandService.write(blinkCommand.getBytes());
// mCommandService.write(BluetoothCommandService.VOL_DOWN);
return true;
}
return super.onKeyDown(keyCode, event);
}
}

since android 4.2 , bluetooth stack changed, so i guess you are testing on android>=4.2 .
your problem is here tmp = device.createRfcommSocketToServiceRecord(MY_UUID); . this socket creation method is not compatible starting with 4.2 , so you will need to use the fallback one after it fails : tmp =(BluetoothSocket) device.getClass().getMethod("createRfcommSocket", new Class[] {int.class}).invoke(device,1);
Don't worry about called with no BluetoothManagerCallback being thrown, it doesn't matter.
So if you do it like this, it will work:
try {
socket = device.createRfcommSocketToServiceRecord(SERIAL_UUID);
} catch (Exception e) {Log.e("","Error creating socket");}
try {
socket.connect();
Log.e("","Connected");
} catch (IOException e) {
Log.e("",e.getMessage());
try {
Log.e("","trying fallback...");
socket =(BluetoothSocket) device.getClass().getMethod("createRfcommSocket", new Class[] {int.class}).invoke(device,1);
socket.connect();
Log.e("","Connected");
}
also, i answered here more detailed, about a similar problem.

Related

Reading and writing the file from and to winSCP from the S3 object store

I am trying to put and read file from the remote file system using winSCP through an SFTP connection. The leaf node of the file system is s3 object store which contain the files (for eg: xyz.txt).
Below is the overridden method of File Channel class.
XYZFileSystemProvider
public class XYZFileSystemProvider extends FileSystemProvider {
#Override
public FileChannel newFileChannel(Path path, Set<? extends OpenOption> options, FileAttribute<?>... attrs)
throws IOException {
// TODO Auto-generated method stub
Collection<XYZOptions.OpenMode> modes = XYZOptions.OpenMode.fromOpenOptions(options);
if (modes.isEmpty()) {
modes = EnumSet.of(XYZOptions.OpenMode.Read, MFEOptions.OpenMode.Write);
}
// TODO: process file attributes
return new XYZFileSystemChannel(path, modes);
}
}
XYZFileSystemChannel
public class XYZFileSystemChannel extends XYZRemotePathChannel{
public XYZFileSystemChannel(XYZPath p, Collection<XYZOptions.OpenMode> modes) throws IOException {
this(Objects.requireNonNull(p, "No target path").toString(), p.getFileSystem(), modes);
}
public XYZFileSystemChannel(String remotePath, XYZFileSystem fs, Collection<XYZOptions.OpenMode> modes) throws IOException {
super(remotePath, fs, true, modes);
}
}
XYZRemotePathChannel
public class XYZRemotePathChannel extends FileChannel {
private AmazonS3Component getAmazonS3Instance() {
return SpringContext.getBean(AmazonS3Component.class);
}
private final String path;
private final Collection<XYZOptions.OpenMode> modes;
private final boolean closeOnExit;
private XYZFileSystem fileSystem;
private final AtomicLong posTracker = new AtomicLong(0L);
public static final Set<XYZOptions.OpenMode> READ_MODES =
Collections.unmodifiableSet(EnumSet.of(XYZOptions.OpenMode.Read));
private final Object lock = new Object();
private final AtomicReference<Thread> blockingThreadHolder = new AtomicReference<>(null);
public XYZRemotePathChannel(String path, XYZFileSystem fileSystem, boolean closeOnExit,
Collection<XYZOptions.OpenMode> modes) throws IOException {
this.path = ValidateUtils.checkNotNullAndNotEmpty(path, "No remote file path specified");
this.modes = Objects.requireNonNull(modes, "No channel modes specified");
this.closeOnExit = closeOnExit;
this.fileSystem = fileSystem;
}
#Override
public int read(ByteBuffer dst) throws IOException {
// TODO Auto-generated method stub
log.debug("Position of dst is : {}",dst.position());
log.debug("Reading the bytes of the file : {}", dst);
//Some code to be done here in order to read dst and send bytes of the file recieved from s3 store
return (int) doRead(Collections.singletonList(dst), -1);
}
protected long doRead(List<ByteBuffer> buffers, long position) throws IOException {
log.debug("Do Reading the bytes of the file of list of buffer : {} and position :{}", buffers , position);
ensureOpen(READ_MODES);
synchronized (lock) {
boolean completed = false;
boolean eof = false;
long curPos = (position >= 0L) ? position : posTracker.get();
byte[] bytes = new byte[(int) curPos];
try {
long totalRead = 0;
beginBlocking();
String [] parts = this.path.toString().replaceFirst("^/", "").split("/");
String bucket = parts[parts.length-2];
String fileName = parts[parts.length-1];
InputStream fileContent = getAmazonS3Instance().getFileFromBucket(bucket, fileName);
log.debug("Contens of the file: {} from bucket: {} are : {}", fileName , bucket, fileContent);
//Some code to be done here to return the content byte length??
int fileLenght = fileContent.read(bytes, 1, (int) curPos);
log.debug("After reading the file content the file length is : {}" , fileLenght );
return fileLenght;
} finally {
if (position < 0L) {
posTracker.set(curPos);
}
endBlocking(completed);
}
}
}
private void endBlocking(boolean completed) throws AsynchronousCloseException {
blockingThreadHolder.set(null);
end(completed);
}
private void beginBlocking() {
begin();
blockingThreadHolder.set(Thread.currentThread());
}
#Override
public FileChannel position(long newPosition) throws IOException {
// TODO Auto-generated method stub
log.debug("Setting the position of the file : {}", newPosition);
if (newPosition < 0L) {
throw new IllegalArgumentException("position(" + this.path + ") illegal file channel position: " + newPosition);
}
ensureOpen(Collections.emptySet());
posTracker.set(newPosition);
return this;
}
private void ensureOpen(Collection<XYZOptions.OpenMode> reqModes) throws IOException {
if (!isOpen()) {
throw new ClosedChannelException();
}
if (GenericUtils.size(reqModes) > 0) {
for (XYZOptions.OpenMode m : reqModes) {
if (this.modes.contains(m)) {
return;
}
}
throw new IOException("ensureOpen(" + this.path + ") current channel modes (" + this.modes
+ ") do contain any of the required: " + reqModes);
}
}
}
XYZOptions
public class XYZOptions {
enum OpenMode {
Read, Write, Append, Create, Truncate, Exclusive;
public static final Set<OpenOption> SUPPORTED_OPTIONS = Collections
.unmodifiableSet(EnumSet.of(StandardOpenOption.READ, StandardOpenOption.APPEND,
StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING, StandardOpenOption.WRITE,
StandardOpenOption.CREATE_NEW, StandardOpenOption.SPARSE));
public static Set<OpenMode> fromOpenOptions(Collection<? extends OpenOption> options) {
if (GenericUtils.isEmpty(options)) {
return Collections.emptySet();
}
Set<OpenMode> modes = EnumSet.noneOf(OpenMode.class);
for (OpenOption option : options) {
if (option == StandardOpenOption.READ) {
modes.add(Read);
} else if (option == StandardOpenOption.APPEND) {
modes.add(Append);
} else if (option == StandardOpenOption.CREATE) {
modes.add(Create);
} else if (option == StandardOpenOption.TRUNCATE_EXISTING) {
modes.add(Truncate);
} else if (option == StandardOpenOption.WRITE) {
modes.add(Write);
} else if (option == StandardOpenOption.CREATE_NEW) {
modes.add(Create);
modes.add(Exclusive);
} else if (option == StandardOpenOption.SPARSE) {
continue;
} else {
throw new IllegalArgumentException("Unsupported open option: " + option);
}
}
return modes;
}
}
}
I am able to fetch the file from the s3 store but nor sure how to read and pass all the contents while someone drag and drop from remote file location to their own system using winSCP. I know i am missing some code at the mentioned place but not sure how to achieve it.

Need examples headers and cookies

IDE: NetBeans
Desktop OS Windows 10
Simulator Android/iOS
Device Android/iOS
I am able to get authentication to work with connection request. I am having to get header information and then in another part of the app, send that same information back to the cgi-bin. Below is my code and I commented on the parts where I believe I need to do something with a header and or cookie. I'm very new to this and It's been difficult finding even a basic header/cookie tutorial.
/**
* Your application code goes here<br>
* This file was generated by Codename One for the purpose
* of building native mobile applications using Java.
*/
package userclasses;
import com.codename1.io.ConnectionRequest;
import com.codename1.io.Cookie;
import com.codename1.io.NetworkEvent;
import com.codename1.io.NetworkManager;
import com.codename1.io.Storage;
import com.codename1.notifications.LocalNotification;
import generated.StateMachineBase;
import com.codename1.ui.*;
import com.codename1.ui.events.*;
import com.codename1.ui.util.Resources;
import java.util.Timer;
import java.util.TimerTask;
//import org.apache.commons.httpclient.UsernamePasswordCredentials;
//import org.apache.commons.httpclient.auth.AuthScope;
/**
*
* #John Barrett
*/
public class StateMachine extends StateMachineBase {
public StateMachine(String resFile) {
super(resFile);
// do not modify, write code in initVars and initialize class members there,
// the constructor might be invoked too late due to race conditions that might occur
}
/**
* this method should be used to initialize variables instead of
* the constructor/class scope to avoid race conditions
*/
protected void initVars(Resources res) {
}
boolean stop = false;
boolean notify = false;
String OnOff;
#Override // Starts monitor action.
protected void onMain_ButtonAction(Component c, ActionEvent event){
// starts a timer to repeat monitor every minute.
Timer timer = new Timer();
String text = (String) Storage.getInstance().readObject("SavedData");
timer.schedule( new TimerTask(){
#Override
public void run(){
if (stop == true){
cancel();//Monitor ends
}
//Starts a connection with the URL to monitor
ConnectionRequest r = new ConnectionRequest();
r.setUrl("http://vault.infinitevault.com/cgi-bin/absentmedia?customer=" + text.toLowerCase().trim());
r.setPost(true);
// Post Header/Cookie information to URL for access NEED HELP WITH THIS!
r.setHttpMethod("HEAD");
r.setContentType("text/xml");
r.setCookiesEnabled(true);
findCodeLabel(c).setText("Monitoring: " + text.toUpperCase());
r.addResponseListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent ev){
// Monitor starts
try{
NetworkEvent event = (NetworkEvent) ev;
// Need to post header/cookie information here? HELP!
Cookie.isAutoStored();
byte[] data= (byte[]) event.getMetaData();
String decodedData = new String(data,"UTF-8");
boolean none;
none = decodedData.endsWith("NONE\n");
if (!none){
System.out.println(decodedData);
findCodeTextArea(c).setText(decodedData);
LocalNotification n = new LocalNotification();
n.setId("OSStorage");
n.setAlertBody(decodedData);
n.setAlertTitle("Absent Media");
Display.getInstance().scheduleLocalNotification(
n,
System.currentTimeMillis() + 10 * 1000, // fire date/time
LocalNotification.REPEAT_MINUTE // Whether to repeat and what frequency
);
if (notify != true){
Display.getInstance().vibrate(5000);
}
Storage.getInstance().writeObject("MonitorData", decodedData);
}
else{
System.out.println("None");
findCodeTextArea(c).setText("System is Good");
}
}
catch (Exception ex){
ex.printStackTrace();
}
}
});
NetworkManager.getInstance().addToQueue(r);
}
}, 0, 60*1000);
}
#Override // Stops the monitoring action.
protected void onMain_StopButtonAction(Component c, ActionEvent event) {
super.onMain_StopButtonAction(c, event);//To change body of generated methods, choose Tools | Templates.
stop = true;
findCodeLabel(c).setText("Monitor Stopped");
findCodeTextArea(c).setText("");
findCodeTextArea(c).setHint("System information will show here");
Storage.getInstance().deleteStorageFile("MonitorData");
}
#Override // Saves the settings to storage.
protected void onSettings_SetSaveAction(Component c, ActionEvent event) {
String Station = findSetStation(c).getText();
Storage.getInstance().writeObject("SavedData", Station);
String LoadStation = (String) Storage.getInstance().readObject("SavedData");
findStationLabel(c).setText("Saved Station is " + LoadStation);
}
#Override // Sets what is saved to appear when in settings.
protected void beforeSettings(Form f) {
String LoadStation = (String) Storage.getInstance().readObject("SavedData");
findStationLabel(f).setText("Saved Station is " + LoadStation);
findSetStation(f).setText(LoadStation);
String CurrentNotify = (String) Storage.getInstance().readObject("OnOff");
findSetNotifyLabel(f).setText("Vibration is " + CurrentNotify);
}
#Override // Sets what is saved to appear when in monitor screen.
protected void beforeMain(Form f) {
String LoadStation = (String) Storage.getInstance().readObject("SavedData");
findCodeLabel(f).setText(LoadStation);
if (findCodeTextArea(f) != null){
String foundData = (String) Storage.getInstance().readObject("MonitorData");
findCodeTextArea(f).setText(foundData);
}
}
#Override // Sets notification for turning vibration on.
protected void onSettings_SetNotifyOnAction(Component c, ActionEvent event) {
notify = false;
OnOff = "ON";
Storage.getInstance().writeObject("NotifyOn", notify);
Storage.getInstance().writeObject("OnOff", OnOff);
findSetNotifyLabel(c).setText("Vibration is " + OnOff);
}
#Override // Sets notification for turning vibration off.
protected void onSettings_SetNotifyOffAction(Component c, ActionEvent event) {
notify = true;
OnOff = "OFF";
Storage.getInstance().writeObject("NotifyOn", notify);
Storage.getInstance().writeObject("OnOff", OnOff);
findSetNotifyLabel(c).setText("Vibration is " + OnOff);
}
#Override // Sets message for monitoring or not.
protected void beforeStartPage(Form f) {
Storage.getInstance().deleteStorageFile("MonitorData");
String LoadStation = (String) Storage.getInstance().readObject("SavedData");
}
#Override // Login button pressed after entering username and password.
protected void onLogin_LoginAction(Component c, ActionEvent event) {
// Gets the username and password entered.
String userName = findUsename().getText();
String passWord = findPassword().getText();
// Establishes a conneciton to authentication.
ConnectionRequest req=new ConnectionRequest();
req.setPost(false);
req.setUrl("http://authentication.infinitevault.com/validate.php");
req.addArgument("username",userName);
req.addArgument("password",passWord);
req.addArgument("grant_type","client_credentials");
// To get the Header/Cookie information.
req.getHttpMethod();
req.setCookiesEnabled(true);
Cookie.setAutoStored(true);
Cookie.isAutoStored();
// Sends message to user that system is verifying.
findDenied(c).setText("Verifying");
NetworkManager.getInstance().addToQueueAndWait(req);
if (req.getResponseData() != null) {
String token = new String(req.getResponseData());
token = token.substring(token.indexOf('=') + 1);
System.out.println(token);
// Checks credentials if response is denied, goes back,
// If response is authenticated goes to main monitor form.
if (token.endsWith("denied")){
/*try {
Thread.sleep(2000); //1000 milliseconds is one second.
} catch(InterruptedException e) {
Thread.currentThread().interrupt();
}*/
back();
}
else {
showForm("Main",null);
}
}
}
}//end of app
Just override the connection request method cookieReceived(Cookie c) and handle the logic of each cookie there.

JMS Request Reply Pattern, No Output

TestRequestresponse:
public static void main(String args[]) throws JMSException {
TibjmsConnectionFactory connectionFactory = new TibjmsConnectionFactory(
"tcp://localhost:7222");
Connection con = connectionFactory.createConnection("admin", "");
con.start();
Session s = con.createSession();
System.out.println("Successfully created JMS Connection and Session!");
Queue q1 = s.createQueue("train.ems.queue.test");
System.out.println(q1);
System.out.println("Queue created!");
TemporaryQueue tq = s.createTemporaryQueue();
MessageProducer mp = s.createProducer(q1);
MessageConsumer mc = s.createConsumer(tq);
TextMessage tm = s.createTextMessage("Hi this is ABHISHEK!");
tm.setStringProperty("Country", "IN");
tm.setJMSCorrelationID("SENDER");
tm.setJMSReplyTo(tq);
mp.setTimeToLive(30000);
mp.setDeliveryMode(DeliveryMode.NON_PERSISTENT);
mp.setPriority(Message.DEFAULT_PRIORITY);
mp.send(tm);
Message recv = mc.receive(60000);
if (recv != null) {
System.out.println(recv.getBody(String.class));
}
mp.close();
s.close();
con.close();
}
TestAsyncReceiveMessage:
public class TestAsyncReceiveMessage implements MessageListener {
Session s;
Queue q1;
MessageProducer mp;
public static void main(String ars[]) throws JMSException {
TestAsyncReceiveMessage obj = new TestAsyncReceiveMessage();
obj.createSession();
obj.createQueue();
obj.msgConsumer();
}
private void msgConsumer() throws JMSException {
// TODO Auto-generated method stub
MessageConsumer mc = s.createConsumer(q1, "Country='IN'");
mc.setMessageListener(new TestAsyncReceiveMessage());
}
private void createQueue() throws JMSException {
// TODO Auto-generated method stub
q1 = s.createQueue("train.ems.queue.test");
// t1=s.createTopic("train.ems.topic.test");
}
private void createSession() throws JMSException {
// TODO Auto-generated method stub
TibjmsConnectionFactory connectionFactory = new TibjmsConnectionFactory(
"tcp://localhost:7222");
Connection con = connectionFactory.createConnection("admin", "");
s = con.createSession();
System.out.println("Successfully created JMS Connection and Session!");
}
public void onMessage(Message arg0) {
try {
System.out.println(arg0.getBody(String.class));
TextMessage tm = s.createTextMessage("ACk");
Queue t = (Queue) arg0.getJMSReplyTo();
mp = s.createProducer(t);
mp.send(tm);
} catch (JMSException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Well First it showed me NullPointerException when creating TextMessage in onMessage, i changed something and theres no more exception, but theres no putput either. Help! :)
You have not called Connection.Start() method after creating it in TestAsyncReceiveMessage code. Application has to call Connection.Start() to inform the messaging provider to start delivering messages. Otherwise messages will not be delivered to consumer.
Connection.Start is typically called after consumer is created and any message listeners are attached to consumer so that the consumer is ready to receive messages.

BluetoothServerSocket accept() not returning on HTC Desire

I'm working on a bluetooth-capable application, based on the well-known BluetoothChat example.
Basically with this app a client can send some packets to a server.
I have tested the application using two Xperia smartphones (Xperia X8 and Xperia Sola, android 2.1 and 4.0) and all is working fine: they both can act as client or server.
Unfortunately if I use an HTC Desire (android 2.3) as server, it won't be able to accept incoming connection from one of the Xperia client. It seems that the client connect() returns as if all was fine, but instead the server is blocked on its accept() as if nothing was happened.
Relevant code snippets:
1. "Accept Thread"
private class BluetoothAcceptThread extends Thread
{
private final BluetoothServerSocket serverSocket;
public BluetoothAcceptThread()
{
BluetoothServerSocket tmpSocket = null;
try
{
Method m = bluetoothAdapter.getClass().getMethod("listenUsingRfcommOn", new Class[] {int.class});
tmpSocket = (BluetoothServerSocket) m.invoke(bluetoothAdapter, APP_BT_CHANNEL);
}
catch (NoSuchMethodException e)
{
e.printStackTrace();
}
catch (InvocationTargetException e)
{
Log.e(MainActivity.ERROR_TAG, "BluetoothAcceptThread listen() (with reflection) failed", e);
}
catch (IllegalAccessException e)
{
e.printStackTrace();
}
serverSocket = tmpSocket;
Log.d(MainActivity.DEBUG_TAG, "BluetoothAcceptThread ServerSocket created");
}
#Override
public void run()
{
BluetoothSocket socket = null;
try
{
Log.d(MainActivity.DEBUG_TAG, "BluetoothAcceptThread calling accept()...");
socket = serverSocket.accept();
Log.d(MainActivity.DEBUG_TAG, "BluetoothAcceptThread accept() returned");
}
catch (IOException e)
{
Log.e(MainActivity.ERROR_TAG, "BluetoothAcceptThread accept() failed: " + e.getMessage());
}
if (socket != null)
{
Log.d(MainActivity.DEBUG_TAG, "BluetoothAcceptThread accept() successfully");
synchronized (BluetoothManager.this)
{
if (currentState == SocketState.LISTENING || currentState == SocketState.CONNECTING)
startBluetoothConnection(socket); // all is ok, it can proceed
else if (currentState == SocketState.INACTIVE || currentState == SocketState.CONNECTED)
cancel(socket);
}
}
}
#Override
public void cancel()
{
try
{
serverSocket.close();
Log.d(MainActivity.DEBUG_TAG, "BluetoothAcceptThread ServerSocket closed");
}
catch (IOException e)
{
Log.e(MainActivity.ERROR_TAG, "BluetoothAcceptThread close() failed", e);
}
}
private void cancel(BluetoothSocket newSocket)
{
try
{
newSocket.close();
Log.d(MainActivity.DEBUG_TAG, "BluetoothAcceptThread client socket closed");
}
catch (IOException e)
{
Log.e(MainActivity.ERROR_TAG, "BluetoothAcceptThread client socket close() failed", e);
}
}
}
2. "Connect thread"
private class BluetoothConnectThread extends Thread
{
private final BluetoothSocket socket;
private final BluetoothDevice device;
public BluetoothConnectThread(BluetoothDevice d)
{
device = d;
BluetoothSocket tmpSocket = null;
try
{
Method m = device.getClass().getMethod("createRfcommSocket", new Class[] {int.class});
tmpSocket = (BluetoothSocket) m.invoke(device, APP_BT_CHANNEL);
}
catch (NoSuchMethodException e)
{
e.printStackTrace();
}
catch (InvocationTargetException e)
{
Log.e(MainActivity.ERROR_TAG, "BluetoothConnectThread create() (with reflection) failed", e);
}
catch (IllegalAccessException e)
{
e.printStackTrace();
}
socket = tmpSocket;
Log.d(MainActivity.DEBUG_TAG, "BluetoothConnectThread client socket created");
}
#Override
public void run()
{
stopBluetoothDiscovery(); // otherwise it will slow down the connection
try
{
socket.connect();
Log.d(MainActivity.DEBUG_TAG, "BluetoothConnectThread connect() successfully");
}
catch (IOException e)
{
Log.e(MainActivity.ERROR_TAG, "BluetoothConnectThread connect() failed", e);
String deviceName = device != null ? device.getName() : "none";
connectionFailed(deviceName); // notify UI thread
return;
}
synchronized (BluetoothManager.this)
{
bluetoothConnectThread = null;
}
startBluetoothConnection(socket); // create the "Communication" Thread
}
#Override
public void cancel()
{
try
{
socket.close();
Log.d(MainActivity.DEBUG_TAG, "BluetoothConnectThread client socket closed");
}
catch (IOException e)
{
Log.e(MainActivity.ERROR_TAG, "BluetoothConnectThread close() failed", e);
}
}
}
3. "Communication Thread" (aka ConnectedThread in BluetoothChat sample)
private class BluetoothCommunicationThread extends Thread
{
private final BluetoothSocket socket;
private final InputStream inputStream;
private final OutputStream outputStream;
public BluetoothCommunicationThread(BluetoothSocket s)
{
socket = s;
InputStream in = null;
OutputStream out = null;
try
{
in = socket.getInputStream();
out = socket.getOutputStream();
}
catch (IOException e)
{
Log.e(MainActivity.ERROR_TAG, "BluetoothCommunicationThread failed to get streams", e);
}
inputStream = in;
outputStream = out;
}
#Override
public void run()
{
byte[] buffer = new byte[BT_BUFF_SIZE];
int readBytes;
while (true)
{
try
{
readBytes = inputStream.read(buffer, 0, buffer.length);
if (readBytes != -1)
{
Message message = messageHandler.obtainMessage(DATA_MSG, readBytes, -1, buffer);
message.sendToTarget(); // notify to UI thread the bytes counter
}
else
{
BluetoothDevice device = socket.getRemoteDevice();
String deviceName = device != null ? device.getName() : "none";
connectionLost(deviceName);
break;
}
}
catch (IOException e)
{
Log.e(MainActivity.ERROR_TAG, "BluetoothCommunicationThread read() failed", e);
BluetoothDevice device = socket.getRemoteDevice();
String deviceName = device != null ? device.getName() : "none";
connectionLost(deviceName);
break;
}
}
}
public void write(byte[] buffer)
{
try
{
outputStream.write(buffer);
}
catch (IOException e)
{
Log.e(MainActivity.ERROR_TAG, "BluetoothCommunicationThread write() failed", e);
}
}
#Override
public void cancel()
{
try
{
socket.close();
Log.d(MainActivity.DEBUG_TAG, "BluetoothCommunicationThread socket closed");
}
catch (IOException e)
{
Log.e(MainActivity.ERROR_TAG, "BluetoothCommunicationThread close() failed", e);
}
}
}
So the steps of the problem are the following:
HTC Desire server calls accept()
Xperia client calls connect()
The connect returns as if the connection was established
Nothing is happening on the HTC, always blocked on accept()
Xperia client thinks that it's connected, so it creates the CommunicationThread and calls the blocking read(); this function throws java.io.IOException: Software caused connection abort, probably because the socket is not connected.
Finally these are the relevant logcats:
Xperia client:
09-20 00:44:23.562 9106-9106/com.powertester D/[PowerTester Debug]﹕ BluetoothConnectThread client socket created
09-20 00:44:25.704 9106-9579/com.powertester D/[PowerTester Debug]﹕ BluetoothConnectThread connect() successfully
09-20 00:44:25.734 9106-9579/com.powertester D/[PowerTester Debug]﹕ BluetoothCommunicationThread started and I/O streams ready
09-20 00:44:25.764 9106-9589/com.powertester E/[PowerTester Error]﹕ BluetoothCommunicationThread read() failed
java.io.IOException: Software caused connection abort
at android.bluetooth.BluetoothSocket.readNative(Native Method)
at android.bluetooth.BluetoothSocket.read(BluetoothSocket.java:333)
at android.bluetooth.BluetoothInputStream.read(BluetoothInputStream.java:96)
at com.powertester.net.BluetoothManager$BluetoothCommunicationThread.run(BluetoothManager.java:518)
09-20 00:44:25.844 9106-9106/com.powertester D/[PowerTester Debug]﹕ BluetoothCommunicationThread socket closed
HTC server:
09-19 15:47:07.591 2422-2422/com.powertester D/[PowerTester Debug]﹕ BluetoothAcceptThread ServerSocket created
09-19 15:47:07.591 2422-2484/com.powertester D/[PowerTester Debug]﹕ BluetoothAcceptThread calling accept()...
The really strange thing is that the HTC Desire works if used as client with one of the Xperia used as server.
So, is a problem of my app or a problem in the HTC Desire bluetooth stack?
After some troubles I have realized that the problem is the reflection itself and the explicit use of a Bluetooth Channel.
Using the normal way (i.e. the not-hidden bluetooth methods) my app works perfectly.

Asynchronous Socket losing connection

I'm trying to develop socket based application on wp7 (client) and WPF (server) and I have issue that I don't understand.
I've written "Server" class which should handle connecting with client and recieving strings.
The problem is that server recieving just first string sent by client and then the connection is breaking, I have to reset my client app (only client). I'm assuming it's server side problem because I'm rewriting server application using Async calls. Before that client works well. My server side code:
public class StateObject
{
public byte[] Buffer { get; set; }
public Socket WorkSocket { get; set; }
}
public class MessageRecievedEventArgs : EventArgs
{
public string Message { get; set; }
}
public class Server
{
ManualResetEvent _done;
TcpListener _listener;
public event EventHandler<MessageRecievedEventArgs> OnMessageRecieved;
public Server()
{
_done = new ManualResetEvent(false);
_listener = new TcpListener(IPAddress.Any, 4124);
}
public void Start()
{
Thread th = new Thread(StartListening);
th.IsBackground = true;
th.Start();
}
private void StartListening()
{
_listener.Start();
while (true)
{
_done.Reset();
_listener.BeginAcceptTcpClient(new AsyncCallback(OnConnected), _listener);
_done.WaitOne();
}
}
private void OnConnected(IAsyncResult result)
{
TcpListener listener = result.AsyncState as TcpListener;
Socket socket = listener.EndAcceptSocket(result);
byte[] buffer = new byte[256];
StateObject state = new StateObject { Buffer = buffer, WorkSocket = socket };
socket.BeginReceive(state.Buffer, 0, state.Buffer.Length, SocketFlags.None, new AsyncCallback(OnRead), state);
}
private void OnRead(IAsyncResult result)
{
var state = (StateObject)result.AsyncState;
int buffNum = state.WorkSocket.EndReceive(result);
string message = Encoding.UTF8.GetString(state.Buffer, 0, buffNum);
if (OnMessageRecieved != null)
{
MessageRecievedEventArgs args = new MessageRecievedEventArgs();
args.Message = message;
OnMessageRecieved(this, args);
}
_done.Set();
}
}
Client:
protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
{
try
{
base.OnNavigatedTo(e);
_socketEventArgs = new SocketAsyncEventArgs() { RemoteEndPoint = App.Connection.RemoteEndPoint };
Send("{ECHO}");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void Send(string key)
{
var bytes = Encoding.UTF8.GetBytes(key + "$");
_socketEventArgs.SetBuffer(bytes, 0, bytes.Count());
if (Socket.Connected)
Socket.SendAsync(_socketEventArgs);
else
MessageBox.Show("Application is not connected. Please reset connection (press 'back' key and 'connect' button). It may be needed to restart server application");
}
The "{ECHO}" message is sent by client and recieved by server - each next is sent, but not recieved. I assuming that I don't understand sockets async calls mechanism... can someone enlighten me? :)
It seems like you are only reading once. Probably you want to call read repeatedly to deplete the entire stream.

Resources