Bluecove: SERVICE_SEARCH_DEVICE_NOT_REACHABLE issue - java

I try to connect to a custom Bluetooth device using BlueCove. I can pair the device, but when I try to search for services I always get SERVICE_SEARCH_DEVICE_NOT_REACHABLE in serviceSearchCompleted() and no services are discovered. If I try the same thing outside Java (in Windows), the PC bluetooth device discovers and can connect (using COM21, COM22, ...) to the SPP service on my device.
What am I doing wrong?
I also tried to do the service search after the device discovery is ended. Same issue.
Please find below my code.
Many thanks in advance for any idea on how to solve this,
Adrian.
public class Test {
private static Logger LOG = Logger.getLogger(Test.class.getName());
private static final String NAME = "XXXX";
private static final String PIN = "1234";
private static final UUID[] UUIDS = new UUID[] {new UUID(0x0003), new UUID(0x1101)};
private LocalDevice localDevice;
private DiscoveryAgent discoveryAgent;
private DiscoveryListener discoveryListener = new GDiscoveryListener();
private Map<Integer, RemoteDevice> searchForServices = new HashMap<Integer, RemoteDevice>();
private Collection<ServiceRecord> servicesDiscovered = new HashSet<ServiceRecord>();
private Object lock = new Object();
private CountDownLatch waitForDevices;
protected void connect() {
try {
localDevice = LocalDevice.getLocalDevice();
localDevice.setDiscoverable(DiscoveryAgent.GIAC);
LOG.info("Local Device: " + localDevice.getFriendlyName()
+ "(" + localDevice.getBluetoothAddress() + ")");
discoveryAgent = localDevice.getDiscoveryAgent();
LOG.finest("Start discovering devices");
discoveryAgent.startInquiry(DiscoveryAgent.GIAC, discoveryListener);
try {
synchronized(lock) {
lock.wait();
}
if (searchForServices.size() > 0) {
waitForDevices = new CountDownLatch(searchForServices.size());
waitForDevices.await();
}
}
catch (InterruptedException e) {
LOG.log(Level.WARNING, "Error waiting to terminate discovery", e);
}
LOG.finest(servicesDiscovered.size() + " services discovered");
LOG.finest("Device discovery completed");
} catch (BluetoothStateException e) {
LOG.log(Level.WARNING, "Error initializing Bluetooth", e);
}
}
private class GDiscoveryListener implements DiscoveryListener {
public void deviceDiscovered(RemoteDevice rd, DeviceClass dc) {
try {
String name = rd.getFriendlyName(false);
boolean isMine = NAME.equals(name);
LOG.info("Discovered: " + name + "(" + rd.getBluetoothAddress() + ")"
+ (isMine ? "" : " - ignoring"));
if (!isMine)
return;
if (!rd.isAuthenticated()) {
LOG.finest("Try to pair with " + name
+ " PIN: " + PIN);
boolean paired = RemoteDeviceHelper.authenticate(rd, PIN);
LOG.info("Pair with " + name + (paired ? " succesfull" : " failed"));
}
int transID = discoveryAgent.searchServices(null, UUIDS, rd, discoveryListener);
searchForServices.put(transID, rd);
LOG.finest("Searching for services for " + name + " with transaction " + transID);
} catch (BluetoothStateException e) {
LOG.log(Level.WARNING, "Cannot search services for "
+ rd.getBluetoothAddress(), e);
} catch (IOException e) {
LOG.log(Level.WARNING, "Error connecting ", e);
} catch (Throwable t) {
LOG.log(Level.WARNING, "Cannot search services for "
+ rd.getBluetoothAddress(), t);
}
}
public void inquiryCompleted(int respCode) {
synchronized(lock) {
lock.notify();
}
switch (respCode) {
case DiscoveryListener.INQUIRY_COMPLETED :
LOG.fine("INQUIRY_COMPLETED");
break;
case DiscoveryListener.INQUIRY_TERMINATED :
LOG.fine("INQUIRY_TERMINATED");
break;
case DiscoveryListener.INQUIRY_ERROR :
LOG.fine("INQUIRY_ERROR");
break;
default :
LOG.fine("Unknown Response Code - " + respCode);
break;
}
}
public void serviceSearchCompleted(int transID, int respCode) {
String rd = searchForServices.get(transID).getBluetoothAddress();
//searchForServices.remove(transID);
switch (respCode) {
case DiscoveryListener.SERVICE_SEARCH_COMPLETED:
LOG.fine(rd + ": The service search completed normally");
break;
case DiscoveryListener.SERVICE_SEARCH_TERMINATED:
LOG.fine(rd + ": The service search request was cancelled by a call to DiscoveryAgent.cancelServiceSearch(int)");
break;
case DiscoveryListener.SERVICE_SEARCH_ERROR:
LOG.warning(rd + ": An error occurred while processing the request");
break;
case DiscoveryListener.SERVICE_SEARCH_NO_RECORDS:
LOG.info(rd + ": No records were found during the service search");
break;
case DiscoveryListener.SERVICE_SEARCH_DEVICE_NOT_REACHABLE:
LOG.warning(rd + ": 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;
default:
LOG.warning(rd + ": Unknown Response Code - " + respCode);
break;
}
if (waitForDevices != null)
waitForDevices.countDown();
}
public void servicesDiscovered(int transID, ServiceRecord[] srs) {
LOG.info("Services discovered in transaction " + transID + " : " + srs.length);
for (ServiceRecord sr : srs) {
LOG.info(sr.getConnectionURL(ServiceRecord.NOAUTHENTICATE_NOENCRYPT, false));
servicesDiscovered.add(sr);
}
}
}
public static void main(String[] args) {
new Test().connect();
}
}

I had the same problem while connecting to a Bluetooth earpiece. Like you I was also searching for more than one service at a time and It always returned SERVICE_SEARCH_DEVICE_NOT_REACHABLE. So, I tried searching for only one service and it worked. So, try modifying your code as:
...
private static final UUID[] UUIDS = new UUID[] {new UUID(0x0003)}

Related

singleton java class returning null value

I created a java class which return a DB connection object. But it is returning the null value at the caller method. When i am running the code in debug mode it is not going to the method itself. Need suggestions.
package com.cisco.installbase.hiveconnector;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Connection;
public class CreateConnection {
private static Connection instance = null;
static final String drivername = "org.apache.hive.jdbc.HiveDriver";
private CreateConnection() {
try {
Class.forName(drivername);
// instance =
// DriverManager.getConnection("jdbc:hive2://hddev-c01-edge-01:20000/",
// "phodisvc", "B1GD4T4dev");
// for hive 1 use this ------> instance =
// DriverManager.getConnection("thrift://hddev-c01-edge-02:9083");
instance = DriverManager.getConnection("thrift://hddev-c01-edge-02:9083");
System.out.println("get instance"+instance);
Constants.setFlag(true);
} catch (ClassNotFoundException e) {
e.printStackTrace();
Constants.setFlag(false);
} catch (SQLException e) {
e.printStackTrace();
Constants.setFlag(false);
}
}
public static Connection getInstance() {
Constants.setFlag(true);
return instance;
}
}
Below is the code which is calling the getInstance() method
package com.cisco.installbase.hiveconnector;
import java.util.Date;
public class MainApp {
private static final String hiveDB = ReadProperties.getInstance().getProperty("hive_db");
private static final String logTable = ReadProperties.getInstance().getProperty("IB_log_table");
private static final String dataGovernanceLogTable = ReadProperties.getInstance().getProperty("SR_DG_table");
private static final String dataGovernanceMasterTable = ReadProperties.getInstance()
.getProperty("SR_DG_master_table");
private static final String count_xxccs_ds_sahdr_core = "select count(*) from " + hiveDB + "."
+ "xxccs_ds_sahdr_core";
private static final String count_mtl_system_items_b = "select count(*) from " + hiveDB + "."
+ "mtl_system_items_b";
private static final String count_xxccs_scdc_product_profile = "select count(*) from " + hiveDB + "."
+ "xxccs_scdc_product_profile";
private static final String count_xxccs_ds_cvdprdline_detail = "select count(*) from " + hiveDB + "."
+ "xxccs_ds_cvdprdline_detail";
private static final String count_xxccs_ds_instance_detail = "select count(*) from " + hiveDB + "."
+ "xxccs_ds_instance_detail";
private static int currentJobID = 0;
private static Date startTime = null;
private static Date stopTime = null;
private static int runTime = 0;
static CommonDBUtilities commonDB = new CommonDBUtilities();
static ShellUtilities shellUtilities = new ShellUtilities();
static SqoopUtility sqoop = new SqoopUtility();
public static void main(String[] args) {
MainApp.startTimeLogger();
System.out.println("Started the Job");
}
public static void startTimeLogger() {
// getting the Job ID and the start time for the log table
if (Constants.isFlag()) {
currentJobID = commonDB.getMaximumJobID();
startTime = commonDB.getTime();
MainApp.importTables();
System.out.println("executing startTimeLogger");
} else {
MainApp.onFailure();
JobMailer.PostMail("IB Load Failed", "Load failed while logging method name startTimeLogger()");
System.out.println("executing startTimeLogger failed");
}
}
public static void importTables() {
// Delete target directory before running the sqoop imports
if (Constants.isFlag()) {
shellUtilities.DeleteDirectory(Constants.getMtlSystems());
shellUtilities.DeleteDirectory(Constants.getProductLine());
shellUtilities.DeleteDirectory(Constants.getInstanceDetail());
shellUtilities.DeleteDirectory(Constants.getProductLine());
shellUtilities.DeleteDirectory(Constants.getHeaderCore());
// Run the sqoop imports to load the data from oracle to hive
sqoop.runSqoop();
MainApp.getCounts();
System.out.println("executing importTables");
} else {
MainApp.onFailure();
JobMailer.PostMail("IB Load Failed", "Load failed while running sqoop import method name importTables()");
System.out.println("executing importTables failed");
}
}
public static void getCounts() {
// Get the record counts for all the IB tables pulled
if (Constants.isFlag()) {
commonDB.getCounts(count_xxccs_ds_instance_detail);
commonDB.getCounts(count_xxccs_ds_cvdprdline_detail);
commonDB.getCounts(count_xxccs_scdc_product_profile);
commonDB.getCounts(count_mtl_system_items_b);
commonDB.getCounts(count_xxccs_ds_sahdr_core);
MainApp.stopTimeLogger();
System.out.println("executing getCounts");
} else {
MainApp.onFailure();
JobMailer.PostMail("IB Load Failed", "Load failed while getting counts method name getCounts()");
System.out.println("executing getCounts failed");
}
}
public static void stopTimeLogger() {
// Get the stop time or end time
if (Constants.isFlag()) {
stopTime = commonDB.getTime();
MainApp.runTimeLogger();
System.out.println("executing stopTimeLogger");
} else {
MainApp.onFailure();
JobMailer.PostMail("IB Load Failed", "Load failed while end logging method name stopTimeLogger()");
System.out.println("executing stopTimeLogger failed");
}
}
public static void runTimeLogger() {
// Get the run time or total time taken
if (Constants.isFlag()) {
runTime = (int) (stopTime.getTime() - startTime.getTime()) / 1000 * 60 * 60 * 24;
MainApp.onSuccess();
MainApp.logGovernance();
System.out.println("executing runTimeLogger");
} else {
MainApp.onFailure();
JobMailer.PostMail("IB Load Failed", "Load failed while runtime logging method name runTimeLogger()");
System.out.println("executing runTimeLogger failed");
}
}
public static void logGovernance() {
// IB Data governance
if (Constants.isFlag()) {
String dataGovernance = "Insert into table " + hiveDB + "." + dataGovernanceLogTable
+ " select Data_Asset_Reference,File_Name,Origin_System,Transfer_System," + startTime
+ ",Column_Reference,Element_Reference,Rule_Priority,Delete_By_Date,Classification,Geographic_Inclusion,Geographic_Restriction,Group_Inclusion,Group_Restriction,Reserved from "
+ hiveDB + "." + dataGovernanceMasterTable;
commonDB.InsertToTable(dataGovernance);
System.out.println("executing logGovernance");
} else {
MainApp.onFailure();
JobMailer.PostMail("IB Load Failed",
"Load failed while inserting into datagovernance method name logGovernance()");
System.out.println("executing logGovernance failed");
}
}
public static void onFailure() {
// Write to log on Failure
String insertOnFailure = "insert into table " + hiveDB + "." + logTable + " select " + currentJobID + ","
+ stopTime + "," + runTime + "," + "FAILED from " + hiveDB + "." + "dual" + " limit 1; ";
commonDB.InsertToTable(insertOnFailure);
JobMailer.PostMail("IB Load Failed", "Load failed");
System.out.println("executing onFailure");
}
public static void onSuccess() {
// Write to log on Success
String insertOnSuccess = "insert into table " + hiveDB + "." + logTable + " select " + currentJobID + ","
+ stopTime + "," + runTime + "," + "SUCCESS from " + hiveDB + "." + "dual" + " limit 1; ";
commonDB.InsertToTable(insertOnSuccess);
JobMailer.PostMail("IB Load Successfully completed", "Load completed");
System.out.println("executing onSuccess");
}
}
private static Connection instance = null;
static final String drivername = "org.apache.hive.jdbc.HiveDriver";
public static Connection getInstance() {
if(instance==null){
try {
Class.forName(drivername);
instance = DriverManager.getConnection("thrift://hddev-c01-edge-02:9083");
Constants.setFlag(true);
} catch (ClassNotFoundException e) {
e.printStackTrace();
Constants.setFlag(false);
} catch (SQLException e) {
e.printStackTrace();
Constants.setFlag(false);
}
}
return instance;
}
Your implementation of sigleton is wrong.
You never call the constructor. This is th correct way to implement a singleton.
public static Connection getInstance() {
if (instance==null){
instance = new CreateConnection();
}
Constants.setFlag(true);
return instance;
}
You never call the constructor CreateConnection() (besides, this shouldn't be a constructor anyway, rather a utility method returning a Connection).

QuickBooks NULL CallbackHandler

I'm trying to perform a batch operation in QuickBook but getting null callbackhandler.
private static void AddBulkCustomer(DataService ds) throws FMSException{
BatchOperation bo = new BatchOperation();
Customer c1 = new Customer();
c1.setGivenName("Customer 3");
c1.setDisplayName("Disp Customer 3");
EmailAddress email = new EmailAddress();
email.setAddress("customer1#zzz.com");
c1.setPrimaryEmailAddr(email);
bo.addEntity(c1, OperationEnum.CREATE, "b3");
c1= null;
c1 = new Customer();
c1.setGivenName("Customer 4");
c1.setDisplayName("Disp Customer 4");
email = null;
email = new EmailAddress();
email.setAddress("customer2#z2zz.com");
c1.setPrimaryEmailAddr(email);
bo.addEntity(c1, OperationEnum.CREATE, "b4");
// String strQuery = " select * from customer where givenname ='"+c1.getGivenName()+"'";
// bo.addQuery(strQuery, "b3Query");
ds.executeBatchAsync(bo, new AsyncCallBackBatch());
}
For AsyncCallback operation
public class AsyncCallBackBatch implements CallbackHandler {
#Override
public void execute(CallbackMessage callbackMsg) {
System.out.println("asyncCallbackBatch is executing... ");
try {
System.out.println("QR = "+callbackMsg.getFMSException().toString());
BatchOperation BO = callbackMsg.getBatchOperation();
if (BO != null) {
List<String> bId = BO.getBIds();
for (String strBId : bId) {
if (BO.isFault(strBId)) {
Fault fault = BO.getFault(strBId);
System.out.println("asyncCallBackBatch Error Code : "+ fault.getError().get(0).getCode() + " "+ "Error : "
+ fault.getError().get(0).getDetail()+ ", Message : "+ fault.getError().get(0).getMessage());
} else if (BO.isEntity(strBId)) {
System.out.println("Batch having entity message.. ");
Customer cust = (Customer) BO.getEntity(strBId);
System.out.println("cust id : " + cust.getId()+ " CustName = " + cust.getGivenName());
} else if (BO.isQuery(strBId)) {
System.out.println("Batch having Query ... Parsing... ");
QueryResult qR = BO.getQueryResponse(strBId);
System.out.println("Query : " + qR.getTotalCount());
} else if (BO.isReport(strBId)) {
System.out.println("Batch having Report... ");
Report report = BO.getReport(strBId);
System.out.println(" " + report.getClass().getName());
} else {
System.out.println("Something went wrong... ");
}
}
}else{
System.out.println("Batch Operation terminated, reason: NULL callbackMsg ");
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
OAuthAuthorizer oAuth = new OAuthAuthorizer(consumerKey, consumerSecret, accessToken, accessTokenSecret);
//403352746
try {
Context context = new Context(oAuth, ServiceType.QBO, "403352746");
System.out.println("RealmID : "+context.getRealmID());
context.setCustomerRequestTimeout(99999);
System.out.println("TimeOut Set to = "+context.getCustomerRequestTimeout());
System.out.println("BASE_URL_QBO = "+Config.getProperty(Config.BASE_URL_QBO));
Config.setProperty(Config.BASE_URL_QBO, "https://sandbox-quickbooks.api.intuit.com/v3/company");
System.out.println("BASE_URL_QBO = "+Config.getProperty(Config.BASE_URL_QBO));
DataService ds = new DataService(context);
AddBulkCustomer(ds);
System.out.println("Operation Complete..");
} catch (Exception e) {
e.printStackTrace();
}
}
When I debug, in execute method, I'm getting Null BatchOperation in return. I'm not sure performing Batch operation is allowed in sandbox environment.
I found the solution after so much of testing and communication with Quickbooks Devs thought would be helpful for others.
In sandbox environment even if you set the config properties to sandbox URL it still picks as PROD URL in Callbackhandler.
Config.setProperty(Config.BASE_URL_QBO, "https://sandbox-quickbooks.api.intuit.com/v3/company");
In this case they called this as a bug, currently all you can do is to make a trial account in PROD and then test this.

asynccallback failures

In my app I need to add string vallues to the file(.property file, if it is important). and user enter this values in gwt GUI. Here is it's important part:
final Button submit = new Button("Submit");
addButton(submit);
submit.addSelectionListener(new SelectionListener<ButtonEvent>() {
#Override
public void componentSelected(ButtonEvent ce) {
keyWord.selectAll();
regexp.selectAll();
if (keyWord.getValue() != null){
setKeyWord(customerId, keyWord.getValue());
keyWord.setValue("");
}
if (regexp.getValue() != null){
setRegExp(customerId, regexp.getValue());
regexp.setValue("");
}
}
});
}
private void setKeyWord(final String customerId, final String keyword){
final AsyncCallback<String> callbackItems = new AsyncCallback<String>() {
public void onFailure(final Throwable caught) {
Window.alert("unable to add " + caught.toString());
}
public void onSuccess(final String x) {
Window.alert(x);
}
};
serverManagementSvc.setKeyWords(customerId, keyword, callbackItems);
}
private void setRegExp(final String customerId, final String regexp){
final AsyncCallback<String> calbackItems = new AsyncCallback<String>() {
#Override
public void onFailure(Throwable throwable) {
Window.alert("unable to add " + throwable.toString());
}
#Override
public void onSuccess(String s) {
Window.alert(s);
}
};
serverManagementSvc.setRegExp(customerId, regexp, calbackItems);
}
So I need to use Asunccallback to call methods which are in the "server part".
here are these methods:
//adds a new keyword to customers properties
public String setKeyWords(String customer, String word){
try{
PropertiesConfiguration props = new PropertiesConfiguration("/home/mikhail/bzrrep/DLP/DLPServer/src/main/resources/rules.properties");
String newKeyWord = new String(props.getString("users." + customer + ".keywords" + "," + word));
props.setProperty("users." + customer + ".keywords", newKeyWord);
props.save();
}catch (ConfigurationException e){
e.printStackTrace();
}
return "keyword " + word + " added";
}
// adds a new regexp to customer properties
public String setRegExp(String customer, String regexp){
try {
PropertiesConfiguration props = new PropertiesConfiguration("/home/mikhail/bzrrep/DLP/DLPServer/src/main/resources/rules.properties");
String newRegValue = new String(props.getString("users." + customer + ".regexps" + "," + regexp));
props.setProperty("users." + customer + ".regexps", newRegValue);
props.save();
} catch (ConfigurationException e){
e.printStackTrace();
}
return "regexp " + regexp + " added to " + customer + "'s config";
}
all interfaces are present.
when I run my code And press "submit" button in gui I see that both asynccallback failured(Window.alert, as you can see, shows "null pointer exception" despite of the fact that values which I send to methods are not null). why can it be? can you suggest me something?
UPD here is error which is shown by firebug:
uncaught exception: java.lang.ClassCastException
function W8(){try{null.a()}catch(a){return a}}
the problem is solved: there were a simple mistake in the code. I've closed brackets at the wrong place:
//adds a new keyword to customers properties
public String setKeyWords(String customer, String word){
try{
PropertiesConfiguration props = new PropertiesConfiguration("/home/mikhail/bzrrep/DLP/DLPServer/src/main/resources/rules.properties");
String newKeyWord = new String(props.getString("users." + customer + ".keywords") + "," + word);
props.setProperty("users." + customer + ".keywords", newKeyWord);
props.save();
}catch (ConfigurationException e){
e.printStackTrace();
}
return "keyword " + word + " added";
}
// adds a new regexp to customer properties
public String setRegExp(String customer, String regexp){
try {
PropertiesConfiguration props = new PropertiesConfiguration("/home/mikhail/bzrrep/DLP/DLPServer/src/main/resources/rules.properties");
String newRegValue = new String(props.getString("users." + customer + ".regexps") + "," + regexp);
props.setProperty("users." + customer + ".regexps", newRegValue);
props.save();
} catch (ConfigurationException e){
e.printStackTrace();
}
return "regexp " + regexp + " added to " + customer + "'s config";
}
I recommend that you recompile the GWT code using
-style PRETTY
and then check that firebug output again; it may give you a better clue, compared to your updated uncaught exception.
Next, I suggest you run it in the eclipse debugger, and set breakpoints in both the client and server code, and then you can inspect the variables and step through the code.

mac address problem

I want to get the mac address of another computer in lan how can I do it? I am using JPCAP
private void getPackage(JpcapCaptor captor)
{
try{
IPPacket ip = (IPPacket)captor.getPacket();
for(int a =0 ; a <found.size(); a++ )
{
if(ip.dst_ip.equals(found.get(a)))
check = true;
}
if(!check)
{
if(ip.dst_ip.isSiteLocalAddress())
{
host = ip.dst_ip.getHostName();
System.out.println("destination ip : " + ip.dst_ip + " " + ip.dst_ip.getHostName());
System.out.println("Source ip : " + ip.src_ip + " " + ip.src_ip.getHostName());
found.addElement(ip.dst_ip);
}
}
check = false;
}catch(Exception ex)
{
//Sys.alert("Error" ,"lobby exeption :" + ex);
//wegens null reverence exeption
}
}
this code just get the IP address but I want mac address too
http://netresearch.ics.uci.edu/kfujii/Jpcap/doc/javadoc/jpcap/packet/ARPPacket.html
You need the method:
public java.lang.Object getSenderHardwareAddress()
package jpcapExample;
import jpcap.*;
import jpcap.packet.*;
class PacketPrinter implements PacketReceiver {
public void receivePacket(Packet packet) {
if (packet instanceof ARPPacket){
ARPPacket arpp = (ARPPacket) packet;
Object str = arpp.getSenderHardwareAddress();
System.out.println("got arp from: " + str.toString());
}
System.out.println(packet);
}
}
---------------------[ different file ]-------------
try {
JpcapCaptor eth0=
JpcapCaptor.
openDevice(devices[eth0idx], 65535, false, 20000);
while (true){
eth0.processPacket(1233,new PacketPrinter());
}
} catch (IOException io){
io.printStackTrace();
}

polling a web service in Java

I have implemented a chat service and desktop client using Java, the program works pefectly but the client is consuming lots of CPU, the idea is :
Every client has an events queue in the server
different events are added to the queue during the program, for example a new user logs in so an event is added to refresh the users list, if a new message is sent another event is added ... etc
the client has a thread that is polling continually for events in its queue and responding to these events appropriately
The only problem is that the polling thread is consuming lots of CPU, i do not know if using Asynchronous web services will help ..
for example :
This is the class where the events are added to the queue
public class Session {
private String owner;
private int sessionID;
private BlockingQueue<Events> eventsQueue = new LinkedBlockingQueue<Events>();
public Session() {
}
public Session(String owner, int sessionID) {
this.owner = owner;
this.sessionID = sessionID;
}
public Events getEvent() {
try {
return eventsQueue.take();
} catch (InterruptedException ex) {
System.err.println("Error retreiving Events");
}
return null;
}
public void addEvent(Events ev) {
try {
eventsQueue.put(ev);
eventsQueue.put(ev);
System.out.println("New Event Created with ID : " + ev.getId());
System.out.println("Number Of Evenets in Queue " + getOwner() + " : " + eventsQueue.size());
} catch (InterruptedException ex) {
System.err.println("Error Creating New Event");
}
}
public int queueSize() {
return eventsQueue.size();
}
public String getOwner() {
return owner;
}
public void setOwner(String owner) {
this.owner = owner;
}
public int getSessionID() {
return sessionID;
}
public void setSessionID(int sessionID) {
this.sessionID = sessionID;
}
}
And this is the polling thread
public class pollingThread implements Runnable {
public void run() {
while (true) {
if (checkQueue(Login.getUserName()) != null) {
final Events ev = (Events) ObjectSerialization.Deserialize(checkQueue(Login.getUserName()));
if (ev != null) {
switch (ev.getId()) {
case 1:
System.out.println("Event Retreived : " + ev.getEventType());
RefreshOnlineList RfEv = (RefreshOnlineList) ev;
if (RfEv.getLogEvent().equals("1") && !RfEv.getUname().equals(Login.getUserName())) {
Chatter.showTrayMessage(RfEv.getUname() + " Has Just logged In", MessageType.INFO);
} else if (!RfEv.getUname().equals(Login.getUserName())) {
Chatter.showTrayMessage(RfEv.getUname() + " Has Just logged Out", MessageType.INFO);
}
Chatter.updateUsersCounter();
Chatter.updateList();
break;
case 2:
System.out.println("Event Retreived : " + ev.getEventType());
final RegistrationEvent RegEv = (RegistrationEvent) ev;
Chatter.showTrayMessage(RegEv.getUser().getUser_name() + " Has Just Registered", MessageType.INFO);
SwingUtilities.invokeLater(new Runnable() {
public void run() {
Chatter.addNewUserPanel(RegEv.getUser());
}
});
break;
case 3:
System.out.println("Event Retreived : " + ev.getEventType());
final ChatRequestEvent ChEv = (ChatRequestEvent) ev;
SwingUtilities.invokeLater(
new Runnable() {
public void run() {
int res = JOptionPane.showConfirmDialog(
null,
ChEv.getRequestingUser() + " Wishes to connect with you !! ",
"Incoming Request",
JOptionPane.YES_NO_OPTION);
if (res == 1) {
replyRequest(ChEv.getRequestingUser(), ChEv.getReceivingUser(), false, ChEv.getRequestID());
} else {
chatWindow s = new chatWindow(ChEv.getRequestID(), ChEv.getRequestingUser() + " - " + ChEv.getReceivingUser());
Chatter.addChatwindow(ChEv.getRequestID(), s);
Chatter.setUserIsChatting(ChEv.getRequestingUser(), true);
chatWindow.main(ChEv.getRequestID(), ChEv.getRequestingUser() + " - " + ChEv.getReceivingUser() + " Are Talking ...", s);
replyRequest(ChEv.getRequestingUser(), ChEv.getReceivingUser(), true, ChEv.getRequestID());
startChatSession(Login.getUserName(), ChEv.getRequestingUser(), ChEv.getRequestID(), Chatter.getDate());
}
}
});
break;
case 4:
System.out.println("Event Retreived : " + ev.getEventType());
final RequestResponseEvent ResponseEv = (RequestResponseEvent) ev;
SwingUtilities.invokeLater(
new Runnable() {
public void run() {
if (ResponseEv.isResponse()) {
chatWindow s = new chatWindow(ResponseEv.getChatRequestID(), ResponseEv.getRequestinguser() + " - " + ResponseEv.getReceivingUser());
Chatter.addChatwindow(ResponseEv.getChatRequestID(), s);
Chatter.setUserIsChatting(ResponseEv.getReceivingUser(), true);
chatWindow.main(ResponseEv.getChatRequestID(), ResponseEv.getRequestinguser() + " - " + ResponseEv.getReceivingUser() + " Are Talking ...", s);
} else {
JOptionPane.showMessageDialog(null, ResponseEv.getReceivingUser() + " Ignored Your Request");
}
}
});
break;
case 5:
System.out.println("Event Retreived : " + ev.getEventType());
//Add Code to beautify the message not only the body
final SendMessageEvent MessageEv = (SendMessageEvent) ev;
SwingUtilities.invokeLater(
new Runnable() {
public void run() {
Chatter.addMessage(MessageEv.getMessage(), MessageEv.getChatID());
}
});
break;
case 6:
System.out.println("Event Retreived : " + ev.getEventType());
final LeaveChatEvent LeaveEv = (LeaveChatEvent) ev;
SwingUtilities.invokeLater(new Runnable() {
public void run() {
System.out.println(LeaveEv.getUserName() + " has left the Chat with ID: " + LeaveEv.getChatID());
Chatter.addMessage(new shared.Message(LeaveEv.getUserName(), 1), LeaveEv.getChatID());
Chatter.setUserIsChatting(LeaveEv.getUserName(), false);
}
});
break;
case 7:
System.out.println("Event Retreived : " + ev.getEventType());
final GroupChatRequestEvent GroupChatEvent = (GroupChatRequestEvent) ev;
SwingUtilities.invokeLater(
new Runnable() {
public void run() {
int res = JOptionPane.showConfirmDialog(
null,
GroupChatEvent.getRequestingUser() + " Wants to Join his Group Conference !! ",
"Incoming Request",
JOptionPane.YES_NO_OPTION);
if (res != 1) {
chatWindow s = new chatWindow(GroupChatEvent.getChatID(), "Conference - " + GroupChatEvent.getRequestingUser() + " - " + Login.getUserName());
Chatter.addChatwindow(GroupChatEvent.getChatID(), s);
Chatter.setUserIsChatting(GroupChatEvent.getRequestingUser(), true);
chatWindow.main(GroupChatEvent.getChatID(), "Conference - " + GroupChatEvent.getRequestingUser() + " - " + Login.getUserName() + " Are Talking ...", s);
joinChat(Login.getUserName(), GroupChatEvent.getChatID());
}
}
});
break;
case 8:
System.out.println("Event Retreived : " + ev.getEventType());
final LeaveChatEvent joinEv = (LeaveChatEvent) ev;
SwingUtilities.invokeLater(new Runnable() {
public void run() {
System.out.println(joinEv.getUserName() + " has Joined the Chat with ID: " + joinEv.getChatID());
Chatter.addMessage(new shared.Message(joinEv.getUserName(), 2), joinEv.getChatID());
Chatter.setUserIsChatting(joinEv.getUserName(), true);
}
});
break;
case 9:
System.out.println("Event Retreived : " + ev.getEventType());
final UpdateStatusEvent updateEv = (UpdateStatusEvent) ev;
SwingUtilities.invokeLater(new Runnable() {
public void run() {
System.out.println(updateEv.getUser() + " has updated his status to " + updateEv.getStatus());
Chatter.updateStatusList(updateEv.getUser(), updateEv.getStatus());
}
});
break;
case 10:
System.out.println("Event Retreived : " + ev.getEventType());
final RefreshDetailsEvent refEvenet = (RefreshDetailsEvent) ev;
SwingUtilities.invokeLater(new Runnable() {
public void run() {
System.out.println(refEvenet.getUser() + " has updated his Details ");
Chatter.updateDetails(refEvenet.getUser());
}
});
break;
case 11:
System.out.println("Event Retreived : " + ev.getEventType());
final BlockedEvent BlockedEv = (BlockedEvent) ev;
SwingUtilities.invokeLater(new Runnable() {
public void run() {
System.out.println(BlockedEv.getUserName() + " has Been Blocked ");
JOptionPane.showMessageDialog(null, "You have Been Blocked\nReason: " + BlockedEv.getReason());
Chatter.signOut();
}
});
break;
}
}
}
}
}
private static byte[] checkQueue(java.lang.String uname) {
db.Database service = new db.Database();
db.DatabasePortType port = service.getDatabaseHttpSoap12Endpoint();
return port.checkQueue(uname);
}
private static void replyRequest(java.lang.String requestingUser, java.lang.String receivingUser, java.lang.Boolean result, java.lang.Integer id) {
db.Database service = new db.Database();
db.DatabasePortType port = service.getDatabaseHttpSoap12Endpoint();
port.replyRequest(requestingUser, receivingUser, result, id);
}
private static void startChatSession(java.lang.String initiatingUser, java.lang.String receivingUser, java.lang.Integer id, java.lang.String sessionTime) {
db.Database service = new db.Database();
db.DatabasePortType port = service.getDatabaseHttpSoap12Endpoint();
port.startChatSession(initiatingUser, receivingUser, id, sessionTime);
}
private static void joinChat(java.lang.String uname, java.lang.Integer chatID) {
db.Database service = new db.Database();
db.DatabasePortType port = service.getDatabaseHttpSoap12Endpoint();
port.joinChat(uname, chatID);
}
}
And Queue checking
appreciate help
Instead of having the clients polling the main server, I would say use a push technology so the server will push changes to the appropriate client if any. However, this may require a lot of changes depending on your current architecture.
UPDATE:
The basic idea is:
Instead of having client poll the server to get updates if there is any, change your client code so that they are waiting to receive updates from server (another thread in the client side waiting to receive updates from server). The server will have a list of events with client information so it will send the correct data to correct client.
So at the client side, you will need at least 2 threads one for sending updates to the server and another that waits to receive updates from server (pushed by server).

Categories

Resources