SMACK: how do I listen for user availability status changes? - smack

How do I subscribe to listen to user availability status changes in SMACK?
To get the availability status for a user I use the following:
XMPPConnection.getRoster().getPresence(name).isAvailable();
But how can I subscribe so I receive some notifications whenever the status changes? (So I don't have to poll).

You set up a listener for Roster and Presence changes.

this code may help you :
roster.addRosterListener(new RosterListener() {
// Ignored events public void entriesAdded(Collection<String> addresses) {}
public void entriesDeleted(Collection<String> addresses) {}
public void entriesUpdated(Collection<String> addresses) {}
public void presenceChanged(Presence presence) {
System.out.println("Presence changed: " + presence.getFrom() + " " + presence);
}
#Override
public void entriesAdded(Collection<String> arg0) {
// TODO Auto-generated method stub
}
});

roster.addRosterListener(new RosterListener() {
// Ignored events public void entriesAdded(Collection<String> addresses) {}
public void entriesDeleted(Collection<String> addresses) {}
public void entriesUpdated(Collection<String> addresses) {}
public void presenceChanged(Presence presence) {
Log.e(TAG, presence.getStatus());
Log.e(TAG,presence.getFrom());
Log.e(TAG, presence.getLanguage());
Log.e(TAG,presence.getDefaultLanguage());
Log.e(TAG, presence.getType().toString());
}
#Override
public void entriesAdded(Collection<String> arg0) {
// TODO Auto-generated method stub
}
});

Related

Perform Action in MQTT Subscriber

This mqtt subscriber code works fine. I can easily subscribe to messages which are published at broker.hivemq.com with respective topic.
public class AccelerometerSubscriber implements MqttCallback,
IMqttActionListener {
public static void main(String[] args) throws MqttException {
int QUALITY_OF_SERVICE = 2;
MqttClient client=new MqttClient("tcp://broker.hivemq.com:1883",
MqttClient.generateClientId());
client.setCallback( new SimpleMqttCallBack() );
client.connect();
System.out.println("Subscribing ....");
client.subscribe("MQTT Examples"); }
System.out.println("some action"); //------------right here--------------
public void connectionLost(Throwable throwable) {
System.out.println("Connection to MQTT broker lost!"); }
public void messageArrived(String s, MqttMessage mqttMessage) throws Exception {
System.out.println("Message received:\n\t"+ new String(mqttMessage.getPayload()) );
}
public void deliveryComplete(IMqttDeliveryToken iMqttDeliveryToken) {
// not used in this example
}}
Now I want to perform action only when a message is received. I'm unable to do that.
You have a class (AccelerometerSubscriber) that implements the interface MqttCallback, use an instance of it instead of doing client.setCallback( new SimpleMqttCallBack() );
public class AccelerometerSubscriber implements MqttCallback, IMqttActionListener {
public static void main(String[] args) throws MqttException {
AccelerometerSubscriber as = new AccelerometerSubscriber();
int QUALITY_OF_SERVICE = 2;
MqttClient client = new MqttClient("tcp://broker.hivemq.com:1883", MqttClient.generateClientId());
client.setCallback(as);
client.connect();
System.out.println("Subscribing ....");
client.subscribe("MQTT Examples");
}
#Override
public void connectionLost(Throwable throwable) {
System.out.println("Connection to MQTT broker lost!");
}
#Override
public void messageArrived(String s, MqttMessage mqttMessage) throws Exception {
//message is received is here!!!
System.out.println("Message received:\n\t" + new String(mqttMessage.getPayload()));
}
#Override
public void deliveryComplete(IMqttDeliveryToken iMqttDeliveryToken) {
System.out.println("deliveryComplete");
}
#Override
public void onFailure(IMqttToken arg0, Throwable arg1) {
System.out.println("onFailure");
}
#Override
public void onSuccess(IMqttToken arg0) {
System.out.println("onSuccess");
}
}

In Akka how do you know which request timed out?

This is how a callback is assigned for failure
future.onFailure(new FailureHandler(), context().system().dispatcher());
In the method FailureHandler()
public final class FailureHandler extends OnFailure {
public void onFailure(Throwable throwable) throws Throwable {
System.out.println(throwable.toString());
}
}
I can't figure out a way to find out which request failed. This is a common requirement and I believe I am missing something trivial.
It was trivial indeed, need to declare a class level variable to hold the transactionId onFailure
public final class FailureHandler extends OnFailure {
String transactionId;
public FailureHandler(String transactionId){
this.transactionId = transactionId;
}
#Override
public void onFailure(Throwable throwable) throws Throwable {
logger.error(transactionId + " failed");
}
}

Custom Listeners with detach() method error

I would like to know about Vaadin's detach() method. How can I understand below definition from API ?
Called before the UI is removed from the session.
I got a problem when creating custom listener such as BroadCaster .
MyCustomListener.java
public interface MyCustomListener {
void fireEvent(MyCustomEvent event);
}
MyCustomEvent.java
public class MyCustomEvent {
private String message;
public MyCustomEvent(final String message) {
this.message = message;
}
public final String getMessage() {
return message;
}
}
MyCustomDispatcher.java
public final class MyCustomDispatcher {
private static LinkedList<MyCustomListener> customListeners = new LinkedList<MyCustomListener>();
private static ExecutorService executorService = Executors.newSingleThreadExecutor();
private MyCustomDispatcher() {
}
public static synchronized void register(final MyCustomListener listener) {
customListeners.add(listener);
}
public static synchronized void unregister(final MyCustomListener listener) {
customListeners.remove(listener);
}
public static synchronized void invokeMyCustomEvent(final String message) {
if (message == null || message.trim().length() <= 0) {
return;
}
for (final MyCustomListener listener : customListeners) {
executorService.execute(new Runnable() {
public void run() {
listener.fireEvent(new MyCustomEvent(message));
}
});
}
}
}
I call this listener from my UI class as ...
public class HelloWorldUI extends UI implements MyCustomListener {
#Override
protected void init(VaadinRequest request) {
System.out.println("Getting initialized !");
MyCustomDispatcher.register(this);
final VerticalLayout layout = new VerticalLayout();
layout.setMargin(true);
setContent(layout);
setSizeFull();
layout.addComponent(new Label("Hello World !"));
}
#Override
public void detach() {
System.out.println("Listener was Unregister !");
MyCustomDispatcher.unregister(this);
super.detach();
}
#Override
public void fireEvent(MyCustomEvent event) {
// Do Something
}
}
I call unregister() method of my custom listener inside detach() method for
from some examples for custom listener
to avoid receiving messages for UIs no longer in use (and ensuring that the detached UI can be garbage collected).
Cleaning up resources in a UI
My problem was due to detach() method because when I refreshed my browser , my listener instance was deleted (from detach() method). So , I can't get fireEvent() anymore. I debugged , detach() method was called after init() method of my UI when refreshing browser. But if I remove calling unregister(MyCustomListener listener) from detach() method , that may cause nesting events (previous listeners were still alive).
What am I wrong ? How can I fix it ? Any suggestions ?
Sorry ! this is stupid question . Vaadin's component were server-side codes and I should avoid using static as I much as I can. When I am using my custom listeners as static-resources , these events were share all others. If someone invokes one event , every users will get same.
Static collection of listeners (sharing events) may only suitable for server-push.
I shouldn't create custom listeners as like this.
Thanks #HenriKerola for explanation of using static fields in vaadin and about the creating new UI instance when browser was refresh.

WiFi Direct Create Group null pointer

I want to create a group to make the current device tablet as the access point, however in the callback method onGroupInfoAvailable() I got a null pointer of group. Why?
manager = (WifiP2pManager) getSystemService(Context.WIFI_P2P_SERVICE);
channel = manager.initialize(this, getMainLooper(), null);
manager.createGroup(channel, new ActionListener() {
#Override
public void onSuccess() {
manager.requestGroupInfo(channel, new GroupInfoListener() {
public void onGroupInfoAvailable(WifiP2pGroup group) {
if(group != null)
Toast.makeText(SasetBladderPadActivity.this, "Group Passphrase: "
+ group.getPassphrase(), Toast.LENGTH_LONG).show();
else
Toast.makeText(SasetBladderPadActivity.this, "Group is null ",
Toast.LENGTH_LONG).show();
}
});
}
#Override
public void onFailure(int arg0) {
// TODO Auto-generated method stub
Toast.makeText(SasetBladderPadActivity.this, "Create group failed: " + arg0, \
Toast.LENGTH_LONG).show();
}
});
I think you need to implement the grouplistener and then #override the ongroupinfoavailable method. On success is just the asyn call. Actual callback needs to be modified.
Yes, the group is created but not shown. I will suggest to do it with the trick of implementing countdowntimer(or you may use any other timer) to start the requestGroupInfo() after a second. The modified code will be:
manager = (WifiP2pManager) getSystemService(Context.WIFI_P2P_SERVICE);
channel = manager.initialize(this, getMainLooper(), null);
manager.createGroup(channel, new ActionListener() {
#Override
public void onSuccess() {
new CountDownTimer(1000, 1000) {
public void onTick(long millisUntilFinished) {}
public void onFinish() {
manager.requestGroupInfo(channel, new GroupInfoListener() {
public void onGroupInfoAvailable(WifiP2pGroup group) {
if(group != null)
Toast.makeText(SasetBladderPadActivity.this, "Group Passphrase: "
+ group.getPassphrase(), Toast.LENGTH_LONG).show();
else
Toast.makeText(SasetBladderPadActivity.this, "Group is null ",
Toast.LENGTH_LONG).show();
}
});
}
}.start();
}
#Override
public void onFailure(int arg0) {
...

How to use twitter4j along with storm

I use the twitter4j query interface to filter tweets http://twitter4j.org/javadoc/twitter4j/Query.html. But the twitter spout in https://github.com/nathanmarz/storm-starter/blob/master/src/jvm/storm/starter/spout/TwitterSampleSpout.java:43 uses queue.offer(status). I don't have a reference to Status, how do I integrate these API(s) to process live tweets.
This is what we have been using successfully to filter tweets:
public void open(Map conf, TopologyContext context, SpoutOutputCollector collector) {
queue = new LinkedBlockingQueue<Status>(1000);
_collector = collector;
StatusListener listener = new StatusListener() {
public void onStatus(Status status) {
queue.offer(status);
}
public void onDeletionNotice(StatusDeletionNotice sdn) {
}
public void onTrackLimitationNotice(int i) {
}
public void onScrubGeo(long l, long l1) {
}
public void onException(Exception e) {
}
};
TwitterStreamFactory fact = new TwitterStreamFactory(new ConfigurationBuilder().setUser(_username).setPassword(_pwd).build());
_twitterStream = fact.getInstance();
_twitterStream.addListener(listener);
_twitterStream.filter(new FilterQuery().track(TERMS_TO_TRACK).setIncludeEntities(true));
}

Resources