org.jivesoftware.smack.PacketListener Java Examples

The following examples show how to use org.jivesoftware.smack.PacketListener. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: ClientManagerImpl.java    From olat with Apache License 2.0 6 votes vote down vote up
/**
 * @param username
 */
@Override
public void addMessageListener(final String username) {
    final PacketListener packetListener = new PacketListener() {
        @Override
        public void processPacket(final Packet packet) {
            final Message jabbmessage = (Message) packet;
            // TODO:gs:b see issue: http://bugs.olat.org/jira/browse/OLAT-2966
            // filter <script> msg. out - security risk of cross site scripting!
            // or may user ext.util.strip script tag method on client side
            jabbmessage.setProperty("receiveTime", new Long(new Date().getTime()));
            final GenericEventListener listener = listeners.get(username);
            if (listener != null) {
                listener.event(new InstantMessagingEvent(packet, "message"));
                if (log.isDebugEnabled()) {
                    log.debug("routing message event to controller of: " + packet.getTo());
                }
            } else {
                log.warn("could not find listener for IM message for username: " + username, null);
            }
        }
    };
    getInstantMessagingClient(username).getConnection().addPacketListener(packetListener, new PacketTypeFilter(Message.class));
}
 
Example #2
Source File: GroupChatJoinTask.java    From olat with Apache License 2.0 6 votes vote down vote up
/**
 * listens to new messages for this chatroom
 */
void addMessageListener() {
    messageListener = new PacketListener() {

        @Override
        public void processPacket(final Packet packet) {
            final Message jabbmessage = (Message) packet;
            if (log.isDebugEnabled()) {
                log.debug("processPacket Msg: to=" + jabbmessage.getTo());
            }
            jabbmessage.setProperty("receiveTime", new Long(new Date().getTime()));
            if ((jabbmessage.getType() == Message.Type.groupchat) && jabbmessage.getBody() != null) {
                listeningController.event(new InstantMessagingEvent(jabbmessage, "groupchat"));
            }
        }
    };
    muc.addMessageListener(messageListener);
}
 
Example #3
Source File: GroupChatJoinTask.java    From olat with Apache License 2.0 6 votes vote down vote up
/**
 * listen to new people joining the room in realtime and and set the new content which sets the component to dirty which forces it to redraw
 */
void addParticipationsListener() {
    participationsListener = new PacketListener() {

        @Override
        public void processPacket(final Packet packet) {
            final Presence presence = (Presence) packet;
            if (log.isDebugEnabled()) {
                log.debug("processPacket Presence: to=" + presence.getTo() + " , ");
            }
            if (presence.getFrom() != null) {
                listeningController.event(new InstantMessagingEvent(presence, "participant"));
            }
        }
    };
    muc.addParticipantListener(participationsListener);

}
 
Example #4
Source File: ThreadedReceiver.java    From saros with GNU General Public License v2.0 6 votes vote down vote up
@Override
public void processPacket(final Packet packet) {
  for (Entry<PacketListener, PacketFilter> entry : listeners.entrySet()) {
    final PacketListener listener = entry.getKey();
    final PacketFilter filter = entry.getValue();

    if (filter == null || filter.accept(packet)) {
      listener.processPacket(packet);

      executor.submit(
          new Runnable() {

            @Override
            public void run() {
              try {
                listener.processPacket(packet);
              } catch (Throwable t) {
                t.printStackTrace();
              }
            }
          });
    }
  }
}
 
Example #5
Source File: XMPPReceiver.java    From saros with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Dispatches the packet to all registered listeners.
 *
 * @sarosThread must be called from the Dispatch Thread
 */
private void forwardPacket(Packet packet) {
  Map<PacketListener, PacketFilter> copy;

  synchronized (listeners) {
    copy = new HashMap<PacketListener, PacketFilter>(listeners);
  }
  for (Entry<PacketListener, PacketFilter> entry : copy.entrySet()) {
    PacketListener listener = entry.getKey();
    PacketFilter filter = entry.getValue();

    if (filter == null || filter.accept(packet)) {
      listener.processPacket(packet);
    }
  }
}
 
Example #6
Source File: ClientManagerImpl.java    From olat with Apache License 2.0 6 votes vote down vote up
/**
 * @param username
 */
@Override
public void addMessageListener(final String username) {
    final PacketListener packetListener = new PacketListener() {
        @Override
        public void processPacket(final Packet packet) {
            final Message jabbmessage = (Message) packet;
            // TODO:gs:b see issue: http://bugs.olat.org/jira/browse/OLAT-2966
            // filter <script> msg. out - security risk of cross site scripting!
            // or may user ext.util.strip script tag method on client side
            jabbmessage.setProperty("receiveTime", new Long(new Date().getTime()));
            final GenericEventListener listener = listeners.get(username);
            if (listener != null) {
                listener.event(new InstantMessagingEvent(packet, "message"));
                if (log.isDebugEnabled()) {
                    log.debug("routing message event to controller of: " + packet.getTo());
                }
            } else {
                log.warn("could not find listener for IM message for username: " + username, null);
            }
        }
    };
    getInstantMessagingClient(username).getConnection().addPacketListener(packetListener, new PacketTypeFilter(Message.class));
}
 
Example #7
Source File: ClientManagerImpl.java    From olat with Apache License 2.0 6 votes vote down vote up
/**
 * @param username
 */
@Override
public void addPresenceListener(final String username) {
    final PacketListener packetListener = new PacketListener() {
        @Override
        public void processPacket(final Packet packet) {
            try {
                final GenericEventListener listener = listeners.get(username);
                if (listener == null) {
                    log.warn("could not route presence event as presence listener is null for user: " + username, null);
                } else {
                    listener.event(new InstantMessagingEvent(packet, "presence"));
                    final Presence presence = (Presence) packet;
                    if (log.isDebugEnabled()) {
                        log.debug("routing presence event to controller of: " + presence.getTo());
                    }
                }
            } catch (final Throwable th) {
                log.warn("Presence package", th);
            }
        }
    };
    getInstantMessagingClient(username).getConnection().addPacketListener(packetListener, new PacketTypeFilter(Presence.class));
}
 
Example #8
Source File: GroupChatJoinTask.java    From olat with Apache License 2.0 6 votes vote down vote up
/**
 * listens to new messages for this chatroom
 */
void addMessageListener() {
    messageListener = new PacketListener() {

        @Override
        public void processPacket(final Packet packet) {
            final Message jabbmessage = (Message) packet;
            if (log.isDebugEnabled()) {
                log.debug("processPacket Msg: to=" + jabbmessage.getTo());
            }
            jabbmessage.setProperty("receiveTime", new Long(new Date().getTime()));
            if ((jabbmessage.getType() == Message.Type.groupchat) && jabbmessage.getBody() != null) {
                listeningController.event(new InstantMessagingEvent(jabbmessage, "groupchat"));
            }
        }
    };
    muc.addMessageListener(messageListener);
}
 
Example #9
Source File: GroupChatJoinTask.java    From olat with Apache License 2.0 6 votes vote down vote up
/**
 * listen to new people joining the room in realtime and and set the new content which sets the component to dirty which forces it to redraw
 */
void addParticipationsListener() {
    participationsListener = new PacketListener() {

        @Override
        public void processPacket(final Packet packet) {
            final Presence presence = (Presence) packet;
            if (log.isDebugEnabled()) {
                log.debug("processPacket Presence: to=" + presence.getTo() + " , ");
            }
            if (presence.getFrom() != null) {
                listeningController.event(new InstantMessagingEvent(presence, "participant"));
            }
        }
    };
    muc.addParticipantListener(participationsListener);

}
 
Example #10
Source File: NonThreadedReceiver.java    From saros with GNU General Public License v2.0 5 votes vote down vote up
@Override
public void processPacket(Packet packet) {
  for (Entry<PacketListener, PacketFilter> entry : listeners.entrySet()) {
    PacketListener listener = entry.getKey();
    PacketFilter filter = entry.getValue();

    if (filter == null || filter.accept(packet)) {
      listener.processPacket(packet);
    }
  }
}
 
Example #11
Source File: InstantMessagingGroupChatController.java    From olat with Apache License 2.0 5 votes vote down vote up
/**
*/
  @Override
  protected void doDispose() {

      if (chatRoster.getMultiUserChat() != null && chatRoster.getMultiUserChat().isJoined() && connection.isConnected()) {
          try {

              chatRoster.getMultiUserChat().leave();
              final PacketListener msgListener = roomJoinTask.getMessageListener();
              if (msgListener != null) {
                  chatRoster.getMultiUserChat().removeMessageListener(msgListener);
              }
              final PacketListener pListener = roomJoinTask.getParticipationsListener();
              if (pListener != null) {
                  chatRoster.getMultiUserChat().removeParticipantListener(pListener);
              }
              chatRoster.setMultiUserChat(null);

          } catch (final Exception e) {
              log.warn("Error while leaving multiuserchat:", e);
          }

      }

      if (chatRoster.isChatWindowOpen()) {
          getWindowControl().getWindowBackOffice().sendCommandTo(getCloseCommand());
          allChats.remove(this);
          singleUserEventCenter.fireEventToListenersOf(new MultiUserEvent("ChatWindowClosed"), OresHelper.createOLATResourceableType(InstantMessaging.class));
      }
  }
 
Example #12
Source File: ClientManagerImpl.java    From olat with Apache License 2.0 5 votes vote down vote up
/**
 * @param username
 */
@Override
public void addPresenceListener(final String username) {
    final PacketListener packetListener = new PacketListener() {
        @Override
        public void processPacket(final Packet packet) {
            try {
                final GenericEventListener listener = listeners.get(username);
                if (listener == null) {
                    log.warn("could not route presence event as presence listener is null for user: " + username, null);
                } else {
                    listener.event(new InstantMessagingEvent(packet, "presence"));
                    final Presence presence = (Presence) packet;
                    if (log.isDebugEnabled()) {
                        log.debug("routing presence event to controller of: " + presence.getTo());
                    }
                }
            } catch (final Throwable th) {
                log.warn("Presence package", th);
            }
        }
    };
    getInstantMessagingClient(username).getConnection().addPacketListener(packetListener, new PacketTypeFilter(Presence.class));
}
 
Example #13
Source File: InstantMessagingGroupChatController.java    From olat with Apache License 2.0 5 votes vote down vote up
/**
*/
  @Override
  protected void doDispose() {

      if (chatRoster.getMultiUserChat() != null && chatRoster.getMultiUserChat().isJoined() && connection.isConnected()) {
          try {

              chatRoster.getMultiUserChat().leave();
              final PacketListener msgListener = roomJoinTask.getMessageListener();
              if (msgListener != null) {
                  chatRoster.getMultiUserChat().removeMessageListener(msgListener);
              }
              final PacketListener pListener = roomJoinTask.getParticipationsListener();
              if (pListener != null) {
                  chatRoster.getMultiUserChat().removeParticipantListener(pListener);
              }
              chatRoster.setMultiUserChat(null);

          } catch (final Exception e) {
              log.warn("Error while leaving multiuserchat:", e);
          }

      }

      if (chatRoster.isChatWindowOpen()) {
          getWindowControl().getWindowBackOffice().sendCommandTo(getCloseCommand());
          allChats.remove(this);
          singleUserEventCenter.fireEventToListenersOf(new MultiUserEvent("ChatWindowClosed"), OresHelper.createOLATResourceableType(InstantMessaging.class));
      }
  }
 
Example #14
Source File: XMPPReceiver.java    From saros with GNU General Public License v2.0 4 votes vote down vote up
@Override
public void removePacketListener(PacketListener listener) {
  listeners.remove(listener);
}
 
Example #15
Source File: NonThreadedReceiver.java    From saros with GNU General Public License v2.0 4 votes vote down vote up
@Override
public void addPacketListener(PacketListener listener, PacketFilter filter) {
  listeners.put(listener, filter);
}
 
Example #16
Source File: SarosSessionTest.java    From saros with GNU General Public License v2.0 4 votes vote down vote up
@Override
public synchronized void removePacketListener(PacketListener listener) {
  currentListeners--;
}
 
Example #17
Source File: XMPPReceiver.java    From saros with GNU General Public License v2.0 4 votes vote down vote up
@Override
public void addPacketListener(PacketListener listener, PacketFilter filter) {
  listeners.put(listener, filter);
}
 
Example #18
Source File: ConsoleDebugger.java    From AndroidPNClient with Apache License 2.0 4 votes vote down vote up
public PacketListener getReaderListener() {
    return listener;
}
 
Example #19
Source File: NonThreadedReceiver.java    From saros with GNU General Public License v2.0 4 votes vote down vote up
@Override
public void removePacketListener(PacketListener listener) {
  listeners.remove(listener);
}
 
Example #20
Source File: ThreadedReceiver.java    From saros with GNU General Public License v2.0 4 votes vote down vote up
@Override
public void addPacketListener(PacketListener listener, PacketFilter filter) {
  listeners.put(listener, filter);
}
 
Example #21
Source File: ThreadedReceiver.java    From saros with GNU General Public License v2.0 4 votes vote down vote up
@Override
public void removePacketListener(PacketListener listener) {
  listeners.remove(listener);
}
 
Example #22
Source File: XmppManager.java    From android-demo-xmpp-androidpn with Apache License 2.0 4 votes vote down vote up
public PacketListener getNotificationPacketListener() {
    return notificationPacketListener;
}
 
Example #23
Source File: XmppManager.java    From android-demo-xmpp-androidpn with Apache License 2.0 4 votes vote down vote up
public void run() {
    Log.i(LOGTAG, "RegisterTask.run()...");

    if (!xmppManager.isRegistered()) {
        final String newUsername = newRandomUUID();
        final String newPassword = newRandomUUID();
        //客户端发送到服务器注册的数据包,Packet的子类
        Registration registration = new Registration();

        /**
         * 数据包的ID和类型的过滤器
         */
        PacketFilter packetFilter = new AndFilter(new PacketIDFilter(
                registration.getPacketID()), new PacketTypeFilter(
                IQ.class));
        /**
         * 数据包的监听
         */
        PacketListener packetListener = new PacketListener() {

            public void processPacket(Packet packet) {
                Log.d("RegisterTask.PacketListener",
                        "processPacket().....");
                Log.d("RegisterTask.PacketListener", "packet="
                        + packet.toXML());
                //服务器回复客户端
                if (packet instanceof IQ) {
                    IQ response = (IQ) packet;
                    if (response.getType() == IQ.Type.ERROR) {		//注册失败
                        if (!response.getError().toString().contains(
                                "409")) {
                            Log.e(LOGTAG,
                                    "Unknown error while registering XMPP account! "
                                            + response.getError()
                                                    .getCondition());
                        }
                    } else if (response.getType() == IQ.Type.RESULT) {  //注册成功
                        xmppManager.setUsername(newUsername);
                        xmppManager.setPassword(newPassword);
                        Log.d(LOGTAG, "username=" + newUsername);
                        Log.d(LOGTAG, "password=" + newPassword);
                        //把用户名和密码保存到共享引用
                        Editor editor = sharedPrefs.edit();
                        editor.putString(Constants.XMPP_USERNAME,
                                newUsername);
                        editor.putString(Constants.XMPP_PASSWORD,
                                newPassword);
                        editor.commit();
                        Log.i(LOGTAG,
                        		"Account registered successfully");
                        xmppManager.runTask();
                    }
                }
            }
        };
        // 给注册的Packet设置Listener,因为只有等到正真注册成功后,我们才可以交流  
        connection.addPacketListener(packetListener, packetFilter);

        registration.setType(IQ.Type.SET);
        // registration.setTo(xmppHost);
        // Map<String, String> attributes = new HashMap<String, String>();
        // attributes.put("username", rUsername);
        // attributes.put("password", rPassword);
        // registration.setAttributes(attributes);
        registration.addAttribute("username", newUsername);
        registration.addAttribute("password", newPassword);
        
        registration.addAttribute("imsi", "460000001232300");
        registration.addAttribute("imei", "324234343434434");
        
        // 向服务器端,发送注册Packet包,注意其中Registration是Packet的子类 
        connection.sendPacket(registration);

    } else {
        Log.i(LOGTAG, "Account registered already");
        xmppManager.runTask();
    }
}
 
Example #24
Source File: SarosSessionTest.java    From saros with GNU General Public License v2.0 4 votes vote down vote up
@Override
public synchronized void addPacketListener(PacketListener listener, PacketFilter filter) {
  currentListeners++;
}
 
Example #25
Source File: JingleManagerTest.java    From Smack with Apache License 2.0 4 votes vote down vote up
/**
 * Test for the session request detection. Here, we use the same filter we
 * use in the JingleManager...
 */
public void testInitJingleSessionRequestListeners() {

    resetCounter();

    ProviderManager.getInstance().addIQProvider("jingle", "http://jabber.org/protocol/jingle", new JingleProvider());

    PacketFilter initRequestFilter = new PacketFilter() {
        // Return true if we accept this packet
        public boolean accept(Packet pin) {
            if (pin instanceof IQ) {
                System.out.println("packet: " + pin.toXML());
                IQ iq = (IQ) pin;
                if (iq.getType().equals(IQ.Type.set)) {
                    System.out.println("packet");
                    if (iq instanceof Jingle) {
                        Jingle jin = (Jingle) pin;
                        if (jin.getAction().equals(JingleActionEnum.SESSION_INITIATE)) {
                            System.out.println("Session initiation packet accepted... ");
                            return true;
                        }
                    }
                }
            }
            return false;
        }
    };

    // Start a packet listener for session initiation requests
    getConnection(0).addAsyncPacketListener(new PacketListener() {
        public void processStanza(final Packet packet) {
            System.out.println("Packet detected... ");
            incCounter();
        }
    }, initRequestFilter);

    // Create a dummy packet for testing...
    IQfake iqSent = new IQfake(" <jingle xmlns='http://jabber.org/protocol/jingle'" + " initiator=\"user1@thiago\""
            + " responder=\"user0@thiago\"" + " action=\"session-initiate\" sid=\"08666555\">" + "</jingle>");

    iqSent.setTo(getFullJID(0));
    iqSent.setFrom(getFullJID(0));
    iqSent.setType(IQ.Type.set);

    System.out.println("Sending packet and waiting... ");
    getConnection(1).sendStanza(iqSent);
    try {
        Thread.sleep(10000);
    } catch (InterruptedException e) {
    }

    System.out.println("Awake... " + valCounter());
    assertTrue(valCounter() > 0);
}
 
Example #26
Source File: XmppManager.java    From AndroidPNClient with Apache License 2.0 4 votes vote down vote up
public PacketListener getPacketListener() {
    return packetListener;
}
 
Example #27
Source File: ConsoleDebugger.java    From AndroidPNClient with Apache License 2.0 4 votes vote down vote up
public PacketListener getWriterListener() {
    return null;
}
 
Example #28
Source File: XmppService.java    From xmpp with Apache License 2.0 4 votes vote down vote up
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    if (null != con && con.isConnected()) {


        con.addPacketListener(new PacketListener() {

            @Override
            public void processPacket(Packet packet) {

                if (packet instanceof Presence) {
                    Presence presence = (Presence) packet;
                    s1 = presence.getFrom().toUpperCase().split("@");// 发送方
                    s2 = presence.getTo().toUpperCase().split("@");// 接收方
                    // Presence.Type有7中状态
                    if (presence.getType().equals(Presence.Type.subscribe)) {// 好友申请

                        Log.i("service", s1[0] + "\t好友申请加为好友\t type="
                                + presence.getType().toString());
                        sendBroad("add");

                    } else if (presence.getType().equals(Presence.Type.subscribed)) {// 同意添加好友

                        Log.i("service", s1[0] + "\t同意添加好友\t type="
                                + presence.getType().toString());
                        sendBroad("tongyi");

                    } else if (presence.getType().equals(Presence.Type.unsubscribe)) {// 删除好友

                        Log.i("service", s1[0] + "\t 删除好友");


                    } else if (presence.getType().equals(Presence.Type.unsubscribed)) {// 拒绝对放的添加请求

                        Log.i("service", s1[0] + "\t 拒绝添加好友");
                        sendBroad("jujue");

                    } else if (presence.getType().equals(Presence.Type.unavailable)) {// 好友下线
                        Log.i("service", s1[0] + "\t 下线了");
                        sendBroad("status", 6);
                    } else if (presence.getType().equals(Presence.Type.available)) {// 好友上线
                        //0.在线 1.Q我吧 2.忙碌 3.勿扰 4.离开 5.隐身 6.离线
                        if (presence.getMode() == Presence.Mode.chat) {//Q我吧
                            Log.i("service", s1[0] + "\t 的状态改为了 Q我吧");
                            sendBroad("status", 1);
                        } else if (presence.getMode() == Presence.Mode.dnd) {//忙碌
                            Log.i("service", s1[0] + "\t 的状态改为了 忙碌了");
                            sendBroad("status", 2);
                        } else if (presence.getMode() == Presence.Mode.xa) {//忙碌
                            Log.i("service", s1[0] + "\t 的状态改为了 勿扰了");
                            sendBroad("status", 3);
                        } else if (presence.getMode() == Presence.Mode.away) {//离开
                            Log.i("service", s1[0] + "\t 的状态改为了 离开了");
                            sendBroad("status", 4);
                        } else {
                            Log.i("service", s1[0] + "\t 的状态改为了 上线了");
                            sendBroad("status", 0);
                        }


                    }
                } else if (packet instanceof Message) {
                    Message msg = (Message) packet;
                    Log.i("service", msg.getFrom() + " 说:" + msg.getBody() + " 字符串长度:" + msg.getBody().length());
                    int viewType;
                    if (msg.getBody().length() > 3 && msg.getBody().toString().substring(0, 4).equals("http")) {
                        viewType = 2;
                    } else {
                        viewType = 1;
                    }
                    List<XmppUser> list_xu = XmppTool.getInstance().searchUsers(msg.getFrom().split("@")[0]);
                    User users = new Gson().fromJson(list_xu.get(0).getName(), User.class);
                    Log.i("serviceeeeee", list_xu.get(0).getName());
                    XmppChat xc = new XmppChat(user + users.getUser(), users.getUser(), users.getNickname(), users.getIcon(), 2, msg.getBody().toString(), users.getSex(), user, viewType, new Date().getTime());
                    XmppFriendMessageProvider.add_message(xc);
                    sendBroad("chat", xc);

                }

            }
        }, null);


    }

    // TODO Auto-generated method stub
    return super.onStartCommand(intent, flags, startId);
}
 
Example #29
Source File: AndroidDebugger.java    From AndroidPNClient with Apache License 2.0 4 votes vote down vote up
public PacketListener getWriterListener() {
    return null;
}
 
Example #30
Source File: AndroidDebugger.java    From AndroidPNClient with Apache License 2.0 4 votes vote down vote up
public PacketListener getReaderListener() {
    return listener;
}