Custom handler class method handleMessage() not trigerred - java

I have a utility class where I attempt to send a message. I also created a custom Handler class to handle the messages response. The problem is that handleMessage(Message msg) is not getting called at all. Is it that I'm understanding something incorrectly?
I've tried playing around with placing the handler in different areas of the app structure but I still don't receive any messages.
Below are the public methods that I use in my utility class to send the message into the queue:
public boolean sendRequestToService(int what, Bundle data){
boolean ok = false;
Message message = new Message();
message.what = what;
if(data!=null){
message.setData(data);
}
if (null != mService) {
try {
mService.send(message);
ok = true;
} catch (RemoteException e) {
e.printStackTrace();
}
}
return ok;
}
private void registerToService() {
try {
Message msg = Message.obtain(null, 14);
Messenger mFromService = new Messenger(new MyAppHandler(this));
msg.replyTo = mFromService;
if (null != mService) {
mService.send(msg);
}
} catch (RemoteException e) {
}
}
/////////////////////////////
//////MyAppHandler.java//////
/////////////////////////////
public class MyAppHandler extends Handler implements BluetoothAPI {
private BluetoothDataListener dataListener;
public MyAppHandler(BluetoothDataListener dataListener){
super();
this.dataListener = dataListener;
}
#Override
public void handleMessage(Message msg) {
System.out.println("handle message");
}
}

Related

AsynchronousSocketChannel result not returning -1 on end-of-stream

I am trying to setup an AsynchronousServerSocketChannel that accepts connections from clients and send and receive messages as needed (not necessarily request->response). To facilitate this, I am using asynchronous read and write calls with separate completion handlers. The issue I am having now is that when a client disconnects, the result that is passed to my completion handler isn't -1 and the tread continues to attempt to read. I would like my servers connections to be closed automatically when the corresponding client connection closes.
Here is the code for my read completion handler:
class ReadHandler implements CompletionHandler<Integer, Attachment> {
#Override
public void completed(Integer result, Attachment att) {
if (result < 0) {
try {
System.out.println("Peer at " + att.clientAddr + " has disconnected.");
att.channel.close();
} catch (IOException e) {
e.printStackTrace();
}
} else {
att.readBuffer.flip();
int limits = att.readBuffer.limit();
byte bytes[] = new byte[limits];
att.readBuffer.get(bytes, 0, limits);
att.readBuffer.clear();
if(att.hsDone) {
// process incoming msg
peer.processMessage(att.connectedPeerId, bytes);
} else { // if handshake has not been done
att.connectedPeerId = peer.processHandshake(bytes);
System.out.println("Shook hands with peer " + att.connectedPeerId + ".");
if(att.connectedPeerId < 0) {
try {
att.channel.close();
} catch (IOException e) {
e.printStackTrace();
}
} else {
att.hsDone = true;
att.writeBuffer.put(message.handshakeMsg(peer.id));
att.writeBuffer.flip();
WriteHandler handler = new WriteHandler();
att.channel.write(att.writeBuffer, att, handler);
}
}
att.readBuffer.flip();
att.channel.read(att.readBuffer, att, this);
}
}
#Override
public void failed(Throwable exc, Attachment att) {
System.err.println(exc.getMessage());
}
}
And for my write completion handler:
class WriteHandler implements CompletionHandler<Integer, Attachment> {
#Override
public void completed(Integer result, Attachment att) {
att.writeBuffer.clear();
// check if msg needs to be sent
byte data[] = peer.getNextMsg(att.connectedPeerId);
att.writeBuffer.put(data);
att.writeBuffer.flip();
if(att.channel.isOpen())
att.channel.write(att.writeBuffer, att, this);
}
#Override
public void failed(Throwable exc, Attachment att) {
System.err.println(exc.getMessage());
}
}
Any help solving this issue is appreciated.

Telegram bot API sendPhoto / Documents | Java

I want to make a simple Telegram Bot. It does not work out with method - sendPhoto (URL). When using the online command, the bot should send a picture to the user. The picture itself is dynamic, so I use sendPhoto URL.
Code:
public class SimpleBot extends TelegramLongPollingBot {
public static void main(String[] args) {
ApiContextInitializer.init();
TelegramBotsApi telegramBotsApi = new TelegramBotsApi();
try {
telegramBotsApi.registerBot(new SimpleBot());
} catch (TelegramApiException e) {
e.printStackTrace();
}
}
#Override
public String getBotUsername() {
return "SavchukBot";
}
#Override
public String getBotToken() {
return "TOKEN";
}
#Override
public void onUpdateReceived(Update update) {
Message message = update.getMessage();
if (message != null && message.hasText()) {
if (message.getText().equals("/help"))
sendMsg(message, "Test");
}
if (message != null && message.hasText()) {
if (message.getText().equals("/команды"))
sendMsg(message, "TestV2.0");
}
if (message != null && message.hasText()) {
if (message.getText().equals("/online"))
sendImageFromUrl("http://samp-stats.ru/web/userbar-15377.png", "#SavchukBot" );
} }
public void sendImageFromUrl(String url, String chatId) {
SendPhoto sendPhotoRequest = new SendPhoto();
sendPhotoRequest.setChatId(chatId);
sendPhotoRequest.setPhoto("http://samp-stats.ru/web/userbar-15377.png");
try {
sendPhoto(sendPhotoRequest);
} catch (TelegramApiException e) {
e.printStackTrace();
}
}
private void sendMsg(Message message, String text) {
SendMessage sendMessage = new SendMessage();
sendMessage.enableMarkdown(true);
sendMessage.setChatId(message.getChatId().toString());
sendMessage.setReplyToMessageId(message.getMessageId());
sendMessage.setText(text);
try {
sendMessage(sendMessage);
} catch (TelegramApiException e) {
e.printStackTrace();
}
}
}
Errors that I get when running a command - /online:
org.telegram.telegrambots.exceptions.TelegramApiRequestException: Error sending photo: [400] Bad Request: chat not found
at org.telegram.telegrambots.api.methods.send.SendPhoto.deserializeResponse(SendPhoto.java:153)
at org.telegram.telegrambots.bots.DefaultAbsSender.sendPhoto(DefaultAbsSender.java:210)
at SimpleBot.sendImageFromUrl(SimpleBot.java:62)
at SimpleBot.onUpdateReceived(SimpleBot.java:52)
at java.util.ArrayList.forEach(ArrayList.java:1249)
at org.telegram.telegrambots.generics.LongPollingBot.onUpdatesReceived(LongPollingBot.java:27)
at org.telegram.telegrambots.updatesreceivers.DefaultBotSession$HandlerThread.run(DefaultBotSession.java:301)
Any thoughts how to solve this problem. Thank you =)
Parameter two chatId should be target chat ID, not bot name.
Try to pass message.getChatId().toString() as parameter.

java cometD + selenium. Client communication not stable

My scheme: ajax long polling to Tomcat. Tomcat executes selenium "operations".
Im trying to execute selenium scenario from tomcat.
Its working ok but i need to get logs back to js client.
Javascript client partially receives messages from server when selenium working.
Inside some selenium operations im using Thread.sleep(). Maybe mistakes because of this ?
Please tell me why messages partially received (i think) by client
Here is ServerInfoLogger. BaseLogger outputs messages to console and file
public class ServerInfoLogger extends BaseLogger {
public ServerSession clientServerSession;
protected void logToClient(String message) {
super.log(message);
sendMessage(message);
}
// Server.serverSession and Server.clientServerSession not null but messages partially not received by client
private void sendMessage(String message) {
// send message to client
if (Server.serverSession!=null && Server.clientServerSession!=null) {
Server.clientServerSession.deliver(Server.serverSession, "/message", message);
} else {
System.err.println("Server error. Server.serverSession=" + Server.serverSession + " clientServerSession=" + clientServerSession);
}
}
}
Here is selenium scenario
public class Task extends ServerInfoLogger {
public static boolean datesAvailable = false;
private TaskParser parser = new TaskParser();
protected ArrayList<Step> steps = new ArrayList<>();
private WebDriver webDriver;
protected int currentStepIndex = 0;
protected Step currentStep;
private WebDriverFactory webDriverFactory = new WebDriverFactory();
private int currentTryout = 1;
private int maxTryouts = 40;
public Task(ServerSession clientServerSession, String taskData) {
this.clientServerSession = clientServerSession;
logToClient("new task"); // client always receives this message
steps = parser.parse(taskData);
logToClient("steps parsed. total: "+steps.size()); // client always receives this message
start();
}
protected void start() {
createWebDriver();
startStep();
}
protected void startStep() {
currentStep = steps.get(currentStepIndex);
currentStep.setWebDriver(webDriver);
currentStep.clientServerSession = clientServerSession;
boolean stepComplete = false;
try {
stepComplete = currentStep.start();
} catch (StepException e) {
logToClient(e.getMessage()+" step id: "+e.getStepId());
e.printStackTrace();
}
log("step complete = "+stepComplete);
if (stepComplete) {
onStepComplete();
} else {
onStepError();
}
}
private void onStepError() {
currentTryout++;
if (currentTryout > maxTryouts) {
destroyWebDriver();
logToClient("Max tryouts reached"); // client never receives this message
} else {
logToClient("Step not complete. Restarting task. currentTryout=" + currentTryout); // client partially receives this message
restart();
}
}
private void onStepComplete() {
currentStepIndex++;
if (currentStepIndex < steps.size()) {
startStep();
} else {
destroyWebDriver();
taskComplete();
}
}
private void destroyWebDriver() {
webDriver.quit();
webDriver = null;
}
private void taskComplete() {
logToClient("Task complete !!!"); // client **never** receives this message
TaskEvent taskEvent = new TaskEvent(TaskEvent.TASK_COMPLETE);
EventDispatcher.getInstance().dispatchEvent(taskEvent);
}
public void restart() {
logToClient("Task restart");
try {
setTimeout(Application.baseOperationWaitSecondsUntil);
new SwitchToDefaultContentOperation().execute();
} catch(OperationException exception) {
logToClient("Cannot get default content"); // client partially receives this message
}
currentStepIndex = 0;
startStep();
}
private void setTimeout(int seconds) {
webDriver.manage().timeouts().implicitlyWait(seconds, TimeUnit.SECONDS);
}
private void createWebDriver() {
webDriver = webDriverFactory.getDriver(BrowserType.CHROME).getDriver();
}
public int getCurrentStepIndex() {
return currentStepIndex;
}
}
Here is creation of logger
private void createLogger() {
Date currentDate = new Date();
String logFilePostfix = currentDate.getMonth()+"_"+currentDate.getDate()+"-"+currentDate.getHours()+"_"+currentDate.getMinutes()+"_"+currentDate.getSeconds();
logger = Logger.getLogger(appName);
logger.setUseParentHandlers(false);
FileHandler fh;
SimplestFormatter formatter = new SimplestFormatter();
try {
fh = new FileHandler("C:\\consultant\\logs\\log_"+logFilePostfix+".txt");
logger.addHandler(fh);
fh.setFormatter(formatter);
} catch (SecurityException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
Selenium operation with Thread.sleep()
public class SwitchToMainFrameOperation extends BaseOperation {
private WebElement mainIframe;
private WebDriverWait wait;
#Override
public boolean execute() throws OperationException {
switchToRoot();
sleepThread();
log("switchToMainIFrame by xPath "+Page.getMainIframeXPath()); // log to console and file
wait = new WebDriverWait(webDriver, Application.baseOperationWaitSecondsUntil);
try {
mainIframe = wait.until(ExpectedConditions.presenceOfElementLocated(By.xpath(Page.getMainIframeXPath())));
webDriver.switchTo().frame(mainIframe);
log("main frame switch OK"); // log to console and file
} catch(StaleElementReferenceException exception) {
log("main frame switch error. StaleElementReferenceException - trying again"); // log to console and file
wait = null;
sleepThread();
execute();
}
return true;
}
private void switchToRoot() {
log("switch to root");
webDriver.switchTo().defaultContent();
}
private void sleepThread() {
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}

Why the roster isn't added on both the sides?

user-a sends a subscription request to user-b. Subscription mode has been set to accept_all. Also, packet listener has been registered for both the users.
When user-a sends a request to user-b this method is called :
private void searchUser(java.awt.event.ActionEvent evt) {
try {
String userToSearch = jTextField1.getText();
if(!xmppParamInit) {
initUXmppP();
xmppParamInit = true;
}
Presence subscribe = new Presence(Presence.Type.subscribe);
userToSearch += "#localhost";
subscribe.setTo(userToSearch);
ofConnection.sendPacket(subscribe); // Send the 'subscribe' packet
}catch(Exception exc) {
exc.printStackTrace();
}
}
Prior to this method, following are called :
private void startPLThread() { // start packet-listener-thread
Runnable r = new Runnable() {
#Override
public void run() {
startPL();
}
};
new Thread(r,"packet listener thread").start();
}
private void startPL() {
PacketListener pListener = new PacketListener() {
#Override
public void processPacket(Packet packet) {System.out.println("Inside process packet");
if(packet instanceof Presence) {
Presence presence = (Presence) packet;
Presence subscription = new Presence(Presence.Type.subscribe);
subscription.setTo(presence.getFrom());
System.out.println("presence.getFrom : " + presence.getFrom());
ofConnection.sendPacket(subscription);
}
}
};
PacketFilter pFilter = new PacketFilter() {
#Override
public boolean accept(Packet packet) {
return true;
}
};
ofConnection.addPacketListener(pListener, pFilter);
}
The problem is user-a can see user-b in his roster but user-b cannot see user-a in its roster. I do not understand the reason for this. What could be the problem ?
Subscription mode has been set to accept_all in this method that is called from within search user :
private void initUXmppP() { // Initialize user-xmpp-parameters
Roster roster = ofConnection.getRoster();
roster.setSubscriptionMode(Roster.SubscriptionMode.accept_all);
}
It is a GUI application and I tried keeping both the users online

Getting error while implement OutboundMessageListener in blackberry?

Getting error while using OutboundMessageListener and MessageListener by using this code:
public class MainClass extends UiApplication implements OutboundMessageListener,MessageListener
{
public static void main(String[] args)
{
MainClass mainClass = new MainClass();
mainClass.enterEventDispatcher();
}
public MainClass()
{
try
{
MessageConnection _mc = (MessageConnection)Connector.open("sms://");
_mc.setMessageListener(this);
}
catch (IOException e)
{
}
UiApplication.getUiApplication().pushScreen(new SmsCountScreen());
}
public void notifyIncomingMessage(MessageConnection conn)
{
UiApplication.getUiApplication().invokeAndWait(new Runnable()
{
public void run()
{
Dialog dialog = new Dialog(Dialog.D_OK, "Message Received!", 0, null, Dialog.FIELD_HCENTER);
Ui.getUiEngine().pushGlobalScreen(dialog, 1, UiEngine.GLOBAL_MODAL);
}
});
}
public void notifyOutgoingMessage(Message message)
{
UiApplication.getUiApplication().invokeAndWait(new Runnable()
{
public void run()
{
Dialog dialog = new Dialog(Dialog.D_OK, "Message Sent!", 0, null, Dialog.FIELD_HCENTER);
Ui.getUiEngine().pushGlobalScreen(dialog, 1, UiEngine.GLOBAL_MODAL);
}
});
}
}
using this code and getting error
IOException: operation not permitted on a client connection
Please help to solve this?
Looking at this example on the BlackBerry support forums, they use this code:
public class MyMessageListener implements OutboundMessageListener
{
public void notifyOutgoingMessage(javax.wireless.messaging.Message m)
{
try {
String msg = null;
msg = getMessage(m); // my call to convert Message to String
//... process msg
}
catch(Exception ex) {
// handle exception
}
}
public void notifyIncomingMessage(MessageConnection conn)
{
// handle received sms here
}
}
to register the listener
MyMessageListener ml = new MyMessageListener();
MessageConnection mc;
try {
mc = (MessageConnection)Connector.open("sms://:0");
mc.setMessageListener(el);
} catch (Exception e) {
// handle exception
}
Note that the port is specified in the Connection.open() URL. I'd also recommend testing this on a real device, not the simulators.

Categories