Failed to connect [10048] - bluetooth

I've got this code on a button, when I press it I get the Error:
Error: Exception connecting to NXT.
Caused by lejos.pc.comm.NXTCommException: Open of NXT failed.
at lejos.pc.comm.NXTCommBluecove.open(NXTCommBluecove.java:136)
Caused by javax.bluetooth.BluetoothConnectionException: Failed to connect; [10048]
Only one usage of each socket address (protocol/network address/port) is normally permitted.
at com.intel.bluetooth.BluetoothStackMicrosoft.connect(Native Method)
Failed to connect to any NXT
I am posting because it was working fine yesterday but seems not to be working today.
btnConnectBot.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (Cnt1){
try {
conn.close();
Cnt1=!Cnt1;
txtConnState.setText("Off");
txtConnState.setForeground(Color.RED);
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
else{
conn.addLogListener(new NXTCommLogListener() {
public void logEvent(String message) {
System.out.println(message);
}
public void logEvent(Throwable throwable) {
System.err.println(throwable.getMessage());
}
});
conn.setDebug(true);
if (!conn.connectTo(txtBotName.getText(), NXTComm.LCP)) {
System.err.println("Fallo de conexión");
txtConnState.setText("Off");
txtConnState.setForeground(Color.RED);
System.exit(1);
}
Cnt1=!Cnt1;
txtConnState.setText("On");
txtConnState.setForeground(Color.GREEN);
if (chckbxLock_2.isSelected()){
btnConnectBot_2.doClick();
}
if (chckbxLock_1.isSelected()){
btnConnectBot_1.doClick();
}
}
}
});
According to my research this is because the bluetooth port being used is being accessed by more than one instance. But I don't see how this happens in this code.

Do you have a Bluetooth virtual COM port configured for the remote device? Maybe it is opened by some program...
Or, does the error occur the first time you run your program? Are there any old copies of your program running -- check in taskmgr.exe

Related

How to abort a Task in JavaFX?

Is it possible to abort a Task in JavaFX? My Task could run into situations where I want to cancel the rest of the operations within it.
I would need to return a value, somehow, so I can handle the cause of the abort in the JFX Application Thread.
Most of the related answers I've seen refer to handling an already-canceled Task, but now how to manually cancel it from within the Task itself.
The cancel() method seems to have no effect as both messages below are displayed:
public class LoadingTask<Void> extends Task {
#Override
protected Object call() throws Exception {
Connection connection;
// ** Connect to server ** //
updateMessage("Contacting server ...");
try {
connection = DataFiles.getConnection();
} catch (SQLException ex) {
updateMessage("ERROR: " + ex.getMessage());
ex.printStackTrace();
cancel();
return null;
}
// ** Check user access ** //
updateMessage("Verifying user access ...");
try {
String username = System.getProperty("user.name");
ResultSet resultSet = connection.createStatement().executeQuery(
SqlQueries.SELECT_USER.replace("%USERNAME%", username));
// If user doesn't exist, block access
if (!resultSet.next()) {
}
} catch (SQLException ex) {
}
return null;
}
}
And example would be greatly appreciated.
Why not just let the task go into a FAILED state if it fails? All you need (I also corrected the errors with the type of the task and return type of the call method) is
public class LoadingTask extends Task<Void> {
#Override
protected Void call() throws Exception {
Connection connection;
// ** Connect to server ** //
updateMessage("Contacting server ...");
connection = DataFiles.getConnection();
// ** Check user access ** //
updateMessage("Verifying user access ...");
String username = System.getProperty("user.name");
ResultSet resultSet = connection.createStatement().executeQuery(
SqlQueries.SELECT_USER.replace("%USERNAME%", username));
// I am not at all sure what this is supposed to do....
// If user doesn't exist, block access
if (!resultSet.next()) {
}
return null;
}
}
Now if an exception is thrown by DataFiles.getConnection(), the call method terminates immediately with an exception (the remained is not executed) and the task enters a FAILED state. If you need access to the exception in the case that something goes wrong, you can do:
LoadingTask loadingTask = new LoadingTask();
loadingTask.setOnFailed(e -> {
Throwable exc = loadingTask.getException();
// do whatever you need with exc, e.g. log it, inform user, etc
});
loadingTask.setOnSucceeded(e -> {
// whatever you need to do when the user logs in...
});
myExecutor.execute(loadingTask);

javamail idle stops triggering messagesAdded after a while, thread locked

I'm developing an android app that receives and processes mail messages. The app must be connected to an IMAP server and keep the connection alive, so it can see and process new mail messages instantly (mails contains json data from a mail api server). The app have two modes, manual and live connection. Here is some of my code:
class Idler {
Thread th;
volatile Boolean isIdling=false;
boolean shouldsync=false;//we need to see if we have unseen mails
Object idleLock;
Handler handler=new Handler();
IMAPFolder inbox;
public boolean keppAliveConnection;//keep alive connection, or manual mode
//This thread should keep the idle connection alive, or in case it's set to manual mode (keppAliveConnection=false) get new mail.
Thread refreshThread;
synchronized void refresh()
{
if(isIdling)//if already idling, just keep connection alive
{
refreshThread =new Thread(new Runnable() {
#Override
public void run() {
try {
inbox.doCommand(new IMAPFolder.ProtocolCommand() {
#Override
public Object doCommand(IMAPProtocol protocol) throws ProtocolException {
//Why not noop?
//any call to IMAPFolder.doCommand() will trigger waitIfIdle, this
//issues a "DONE" command and waits for idle to return(ideally with a DONE server response).
// So... I think NOOP is unnecessary
//protocol.simpleCommand("NOOP",null); I'm not issuing noop due to what I said ^
//PD: if connection was broken, then server response will never arrive, and idle will keep running forever
//without triggering messagesAdded event any more :'( I see any other explanation to this phenomenon
return null;
}
});
} catch (MessagingException e) {
e.printStackTrace();
}
}
},"SyncThread");
refreshThread.start();
}
else
{
getNewMail();//If manual mode keppAliveConnection=false) get the new mail
}
}
public Idler()
{
th=new Thread(new Runnable() {
#SuppressWarnings("InfiniteLoopStatement")
#Override
public void run() {
while (true)
{
try {
if(refreshThread !=null && refreshThread.isAlive())
refreshThread.interrupt();//if the refresher thread is active: interrupt. I thing this is not necessary at this point, but not shure
initIMAP();//initializes imap store
try {
shouldsync=connectIMAP()||shouldsync;//if was disconnected or ordered to sync: needs to sync
}
catch (Exception e)
{
Thread.sleep(5000);//if can't connect: wait some time and throw
throw e;
}
shouldsync=initInbox()||shouldsync;//if inbox was null or closed: needs to sync
if(shouldsync)//if needs to sync
{
getNewMail();//gets new unseen mail
shouldsync=false;//already refreshed, clear sync "flag"
}
while (keppAliveConnection) {//if sould keep idling "forever"
synchronized (idleLock){}//MessageCountListener may be doing some work... wait for it
isIdling = true; //set isIdling "flag"
handler.removeCallbacksAndMessages(null);//clears refresh scheduled tasks
handler.postDelayed(new Runnable() {
#Override
public void run() {
refresh();
}
},1200000);//Schedule a refresh in 20 minutes
inbox.idle();//start idling
if(refreshThread !=null && refreshThread.isAlive())
refreshThread.interrupt();//if the refresher thread is active: interrupt. I thing this is not necessary at this point, but not shure
handler.removeCallbacksAndMessages(null);//clears refresh scheduled tasks
isIdling=false;//clear isIdling "flag"
if(shouldsync)
break;//if ordered to sync... break. The loop will handle it upstairs.
synchronized (idleLock){}//MessageCountListener may be doing some work... wait for it
}
}
catch (Exception e) {
//if the refresher thread is active: interrupt
//Why interrupt? refresher thread may be waiting for idle to return after "DONE" command, but if folder was closed and throws
//a FolderClosedException, then it could wait forever...., so... interrupt.
if (refreshThread != null && refreshThread.isAlive())
refreshThread.interrupt();
handler.removeCallbacksAndMessages(null);//clears refresh scheduled tasks
}
}
}
},"IdlerThread");
th.start();
}
private synchronized void getNewMail()
{
shouldsync=false;
long uid=getLastSeen();//get last unprocessed mail
SearchTerm searchTerm=new UidTerm(uid,Long.MAX_VALUE);//search from las processed message to the las one.
IMAPSearchOperation so=new IMAPSearchOperation(searchTerm);
try {
so.run();//search new messages
final long[] is=so.uids();//get unprocessed messages count
if (is.length > 0) {//if some...
try {
//there are new messages
IMAPFetchMessagesOperation fop=new IMAPFetchMessagesOperation(is);
fop.run();//fetch new messages
if(fop.messages.length>0)
{
//process fetched messages (internally sets the last seen uid value & delete some...)
processMessages(fop.messages);
}
inbox.expunge();//expunge deleted messages if any
}
catch (Exception e)
{
//Do something
}
}
else
{
//Do something
}
}
catch (Exception e)
{
//Do something
}
}
private synchronized void initIMAP()
{
if(store==null)
{
store=new IMAPStore(mailSession,new URLName("imap",p.IMAPServer,p.IMAPPort,null,p.IMAPUser,p.IMAPPassword));
}
}
private boolean connectIMAP() throws MessagingException {
try {
store.connect(p.IMAPServer, p.IMAPPort, p.IMAPUser, p.IMAPPassword);
return true;
}
catch (IllegalStateException e)
{
return false;
}
}
//returns true if the folder was closed or null
private synchronized boolean initInbox() throws MessagingException {
boolean retVal=false;
if(inbox==null)
{//if null, create. This is called after initializing store
inbox = (IMAPFolder) store.getFolder("INBOX");
inbox.addMessageCountListener(countListener);
retVal=true;//was created
}
if(!inbox.isOpen())
{
inbox.open(Folder.READ_WRITE);
retVal=true;//was oppened
}
return retVal;
}
private MessageCountListener countListener= new MessageCountAdapter() {
#Override
public void messagesAdded(MessageCountEvent ev) {
synchronized (idleLock)
{
try {
processMessages(ev.getMessages());//process the new messages, (internally sets the last seen uid value & delete some...)
inbox.expunge();//expunge deleted messajes if any
} catch (MessagingException e) {
//Do something
}
}
}
};
}
The problem is: Sometimes when the user is refreshing or the app auto-refreshes, in the Alive Connection mode, one or both of this conditions keeps my app from getting new messages. This is from the javamail source code.
1: The IdlerThread enters monitor state in:
//I don't know why sometimes it enters monitor state here.
private synchronized void throwClosedException(ConnectionException cex)
throws FolderClosedException, StoreClosedException {
// If it's the folder's protocol object, throw a FolderClosedException;
// otherwise, throw a StoreClosedException.
// If a command has failed because the connection is closed,
// the folder will have already been forced closed by the
// time we get here and our protocol object will have been
// released, so if we no longer have a protocol object we base
// this decision on whether we *think* the folder is open.
if ((protocol != null && cex.getProtocol() == protocol) ||
(protocol == null && !reallyClosed))
throw new FolderClosedException(this, cex.getMessage());
else
throw new StoreClosedException(store, cex.getMessage());
}
2: The "refresherThread" enters wait state in:
void waitIfIdle() throws ProtocolException {
assert Thread.holdsLock(messageCacheLock);
while (idleState != RUNNING) {
if (idleState == IDLE) {
protocol.idleAbort();
idleState = ABORTING;
}
try {
// give up lock and wait to be not idle
messageCacheLock.wait();//<-----This is the line is driving me crazy.
} catch (InterruptedException ex) { }
}
}
As one of both of this threads "stops" running (wait & monitor state) my app is useless when reach this condition. In my country the mobile data network is very unstable, slow & expensive(GSM) So it must be failure resilient and take care about every transferred bit.
I guess the problem arises when the connection silently fails and the refresherThread starts to do its job. It issues a DONE command if idle is active, but, as the connection is gone, when idle tries to throw a FolderClosedException, one or both threads gets locked indefinitely.
So, my question is: Why is this situation arising and how to prevent it? How can I keep the idle loop securely running without getting locked?
I've tried a lot of things till exhaustion with no results.
Here are some threads I've read without getting a solution to my problem. In my country internet is EXTREMELY expensive too, so I can't research as much as I want, nor list all the urls I've visited looking for information.
JavaMail: Keeping IMAPFolder.idle() alive
JavaMail: Keeping IMAPFolder.idle() alive
Javamail : Proper way to issue idle() for IMAPFolder
Please, excuse my english. Any suggestion will be greatly appreciated. I've heard about this site strictness, so please be gentle, I'm new over here.
Be sure to set the timeout properties to make sure you don't hang waiting for a dead connection or server.
Instead of issuing a nop command directly, you should call Folder.isOpen or Folder.getMessageCount; they'll issue the nop command if needed.
If the folder is closed asynchronously (FolderClosedException), you'll need to restart the idle loop.

join() waiting forever when exception occurs, jvm shutdown hook not working

I am trying to shutdown the application, whenever any Fatal
Error/Exception comes but before shut down the application my current
thread/task should complete, so I have written mainThread.join()
inside run(), its working fine when there is no exception. But whenever my
doTask() throwing exception that time join() waiting forever.
public class POC
{
public void doTask() throws Exception
{
throw new Exception("Fatal Error");
//throw new Exception("Fatal Error"); By commenting working fine.
}
public static void main(String[] args)
{
POC ob = new POC();
final Thread mainThread = Thread.currentThread();
Runtime.getRuntime().addShutdownHook(new Thread()
{
public void run()
{
try
{
System.out.println("Join() Start");
mainThread.join();
System.out.println("Join() End"); //Why this is not printing?
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
});
try
{
System.out.println("Before doTask()");
ob.doTask(); //User Defined Run()
System.out.println("After doTask()");
}
catch (Exception ex) // FATAL
{
System.err.println("Exception : " + ex.getLocalizedMessage());
System.exit(-1);
}
}
}
OutPut : 0
Before Run()
Exception : Fatal Error
Join() Start
Why System.out.println("Join() End"); is not printing?
You have a simple deadlock.
When you throw an exception, exception handler call System.exit(-1), which is blocking, see javadoc:
Terminates the currently running Java virtual machine by initiating its shutdown sequence
...
The virtual machine's shutdown sequence consists of two phases. In the first phase all registered #addShutdownHook shutdown hooks, if any, are started in some unspecified order and allowed to run concurrently until they finish.
So main thread is waiting in System#exit call until all shutdown hook will be finished and your only shutdown hook blocks and waits until main thread will finish (which is waiting in System#exit ... GOTO 1).

Midlet crashes when calling bluetooth API

When I run following code on my phone I get black screen saying there was uncaught exception but whole block is wrapped in try/catch block so it is weird, anyway when I proceed with execution code just gets to "Getting device.." so it obviously fails on this line:
LocalDevice local = LocalDevice.getLocalDevice();
Here is whole method:
public void startBT()
{
try
{
f.append("Getting device..");
LocalDevice local = LocalDevice.getLocalDevice();
f.append("Got local device..");
DiscoveryAgent agent = local.getDiscoveryAgent();
f.append("Got local discovery agent..");
connString = agent.selectService(new UUID(
"86b4d249fb8844d6a756ec265dd1f6a3", false),
ServiceRecord.NOAUTHENTICATE_NOENCRYPT, false);
f.append("Got connection string - >" + connString);
}
catch (Exception ex)
{
Alert message = new Alert("info");
message.setString(ex.getMessage());
Display.getDisplay(this).setCurrent(message);
}
}
Any ideas?
It looks like device I used doesn't support JSR-82 which is J2ME Bluetooth API(this is built into phone, no way of "installing" it) required to use Bluetooth from J2ME Midlets,here is snippet which should check for JSR-82 support:
public static boolean IsBtJsrComaptible() {
try {
Class.forName("javax.bluetooth.LocalDevice");
return true;
} catch (Exception e) {
return false;
}
}
Please note that I got uncaught exception trying to run above snippet, but maybe it would work on some other device.

Unable to open camera on samsung phone in j2me

I have written following piece of code. It is used to create camera player. I tested it on nokia phones. It's working fine and I am able to see camera and use its functionality.
But the issue is that when the code is tested on samsung phone it throws Media exception and eventually have to make an exit from the application. Due to this code, my inbuilt camera functionality (i.e. on samsung phone) also stops working. So what's the reason to it?
public void startCamera()
{
try
{
try
{
// if player==null
player = createPlayer();
}
catch (Exception ex)
{
ex.printStackTrace();
ErrorDialog.show(ex, "We are exiting the application.",
"Exit", new com.auric.qrev.scanqrcode.lwuit.ui.Action(){
public void actionPerformed() {
m_objMIDlet.exitApp();
}
});
}
try
{
player.realize();
player.prefetch();
}
catch (MediaException ex)
{
ex.printStackTrace();
ErrorDialog.show(ex, "We are exiting the application.",
"Exit", new com.auric.qrev.scanqrcode.lwuit.ui.Action(){
public void actionPerformed() {
m_objMIDlet.exitApp();
}
});
}
//Grab the video control and set it to the current display.
videoControl = (VideoControl)(player.getControl("VideoControl"));
if (videoControl == null)
{
//discardPlayer();
stopCamera();
ErrorDialog.show("Unsupported:\n"+
"Can't get video control\n"+
"We are exiting the application.",
"Exit", new com.auric.qrev.scanqrcode.lwuit.ui.Action(){
public void actionPerformed() {
m_objMIDlet.exitApp();
}
});
}
mediaComponent = new MediaComponent(player);
mediaComponent.setFocusable(false);
m_cameraScreen.showCamera(mediaComponent);
start();
}
catch(Exception ex)
{
ex.printStackTrace();
//discardPlayer();
stopCamera();
ErrorDialog.show("Sorry,Resources unavailable.\nWe are exiting the application.",
"Exit", new com.auric.qrev.scanqrcode.lwuit.ui.Action(){
public void actionPerformed() {
m_objMIDlet.exitApp();
}
});
}
}
private Player createPlayer()throws MediaException, Exception
{
Player mPlayer = null;
// try capture://image first for series 40 phones
try
{
mPlayer = Manager.createPlayer("capture://image");
}
catch (Exception e)
{
e.printStackTrace();
}
catch (Error e)
{
e.printStackTrace();
}
// if capture://image failed, try capture://video
if (mPlayer == null)
{
try
{
mPlayer = Manager.createPlayer("capture://video");
}
catch (Exception e)
{
e.printStackTrace();
throw new MediaException("Sorry,Resources unavailable.");
}
}
if(mPlayer == null)
throw new Exception("Sorry,Resources unavailable.");
return mPlayer;
}
First things first, you have to realize that printStackTrace() is pretty much useless outside of the emulator unless you are using a Symbian phone.
You can also use java.lang.Throwable instead of separating Exception and Error
You can figure out exactly what happens by gathering information as a String and appending it to a simple lcdui Form while you are testing:
try {
// do something that could potentially fail
} catch (Throwable th) {
myDebugLcduiForm.append("potential failure number xx." + th + th.getMessage());
// if necessary, throw a new RuntimeException
}
You might want to update/repost your question once you know exactly what line of code throws what exception.

Resources