Example #1
0
  protected List<Roster> getRosters(String groupname) {
    List<Roster> childList = new ArrayList<Roster>();

    // 查询条件 group 和  owner(owner解决多用户登陆问题)
    String selectWhere = RosterConstants.GROUP + " = ?" + " AND " + RosterConstants.OWNER + " = ?";
    //	if (!mIsShowOffline)
    //		selectWhere += " AND " + OFFLINE_EXCLUSION;
    Cursor cursor =
        mContentResolver.query(
            RosterProvider.CONTENT_URI,
            ROSTER_QUERY,
            selectWhere,
            new String[] {
              groupname, PreferenceUtils.getPrefString(mContext, PreferenceConstants.ACCOUNT, "")
            },
            null);
    cursor.moveToFirst();
    while (!cursor.isAfterLast()) {
      Roster roster = new Roster();
      roster.setJid(cursor.getString(cursor.getColumnIndexOrThrow(RosterConstants.JID)));
      roster.setAlias(cursor.getString(cursor.getColumnIndexOrThrow(RosterConstants.ALIAS)));
      roster.setStatus_message(
          cursor.getString(cursor.getColumnIndexOrThrow(RosterConstants.STATUS_MESSAGE)));
      roster.setStatusMode(
          cursor.getString(cursor.getColumnIndexOrThrow(RosterConstants.STATUS_MODE)));
      childList.add(roster);
      cursor.moveToNext();
    }
    cursor.close();
    return childList;
  }
Example #2
0
  private void removeSharedGroupFromRoster(Group group, String username) {
    // Get the group users to remove from the user's roster
    Collection<String> users = new HashSet<String>(group.getMembers());
    users.addAll(group.getAdmins());

    // Get the roster of the user from which we need to remove the shared group users
    Roster userRoster = (Roster) CacheManager.getCache("username2roster").get(username);

    // Iterate on all the group users and update their rosters
    for (String userToRemove : users) {
      // Get the roster to update
      Roster roster = (Roster) CacheManager.getCache("username2roster").get(userToRemove);
      // Only update rosters in memory
      if (roster != null) {
        roster.deleteSharedUser(group, username);
      }
      // Update the roster of the user
      if (userRoster != null) {
        try {
          User user = UserManager.getInstance().getUser(userToRemove);
          Collection<Group> groups = GroupManager.getInstance().getGroups(user);
          userRoster.deleteSharedUser(userToRemove, groups, group);
        } catch (UserNotFoundException e) {
        }
      }
    }
  }
Example #3
0
  /**
   * Notification that a Group user has been added. Update the group users' roster accordingly.
   *
   * @param group the group where the user was added.
   * @param addedUser the username of the user that has been added to the group.
   */
  private void groupUserAdded(Group group, String addedUser) {
    // Get all the affected users
    Collection<String> users = getAffectedUsers(group);
    // Get the roster of the added user.
    Roster addedUserRoster = (Roster) CacheManager.getCache("username2roster").get(addedUser);

    // Iterate on all the affected users and update their rosters
    for (String userToUpdate : users) {
      if (!addedUser.equals(userToUpdate)) {
        // Get the roster to update
        Roster roster = (Roster) CacheManager.getCache("username2roster").get(userToUpdate);
        // Only update rosters in memory
        if (roster != null) {
          roster.addSharedUser(group, addedUser);
        }
        // Update the roster of the newly added group user.
        if (addedUserRoster != null) {
          try {
            User user = UserManager.getInstance().getUser(userToUpdate);
            Collection<Group> groups = GroupManager.getInstance().getGroups(user);
            addedUserRoster.addSharedUser(userToUpdate, groups, group);
          } catch (UserNotFoundException e) {
          }
        }
      }
    }
  }
Example #4
0
  public synchronized Ticket bind(Endpoint endpoint) {
    EndOid oid = endpoint.endOid;
    registry.put(oid, endpoint);
    roster.addBuddies(oid, endpoint.buddyOids);
    roster.joinGroups(oid, endpoint.roomOids);

    Ticket ticket = new Ticket(oid.clazz, oid.name);
    Subscriber subscriber = new Subscriber(ticket);
    List<Subscriber> subscribers = routes.get(oid);
    if (subscribers == null) {
      subscribers = new ArrayList<Subscriber>();
    }
    subscribers.add(subscriber);
    routes.put(oid, subscribers);

    for (EndOid buddyOid : endpoint.buddyOids) {
      Presence presence = new Presence("online", endpoint.endOid, buddyOid);
      presence.setShow(endpoint.show);
      presence.setNick(endpoint.nick);
      presence.setStatus(endpoint.status);
      route(ticket, presence);
    }

    // join group presence
    for (EndOid grpOid : endpoint.roomOids) {
      Presence p = new Presence("grponline", endpoint.endOid, grpOid);
      p.setNick(endpoint.nick);
      p.setShow("available");
      p.setStatus(grpOid.name);
      route(ticket, p);
    }
    return ticket;
  }
    /**
     * <code>receivedPacket</code> of PacketListener handler, this filters for jabber:iq:auth
     * extensions, then broadcasts those events on a special RosterListener interface.
     *
     * @param p incoming <code>PacketEvent</code>
     */
    public void receivedPacket(PacketEvent p) {
      if (!(p.getPacket() instanceof InfoQuery)) return;
      Enumeration e = ((InfoQuery) p.getPacket()).Extensions();
      Extension ext;
      if ((e == null) || (!e.hasMoreElements())) return;

      ext = (Extension) e.nextElement();

      if (!(ext instanceof Roster)) return;

      // TODO: add code to modify current roster image based on
      // new data. Replacement is basically shown by if the type is not
      // 'result' of the IQ
      Roster rext = (Roster) ext;

      if (((InfoQuery) p.getPacket()).getType().equals("result")) {
        // the results of a get will be the results of a full fetch
        Enumeration enumx = rext.items();
        currentRoster.clear();
        while (enumx.hasMoreElements()) {
          RosterItem ri = (RosterItem) enumx.nextElement();
          currentRoster.put(ri.getJID(), ri);
        }
        fireUserRosterReplaced(rext);
      } else {
        Enumeration enumx = rext.items();
        while (enumx.hasMoreElements()) {
          RosterItem ri = (RosterItem) enumx.nextElement();
          currentRoster.put(ri.getJID(), ri);
        }

        fireUserRosterChanged(rext);
      }
    }
  @Override
  public void disconnected(boolean onError) {
    final XMPPConnection connection = myFacade.getConnection();

    LOG.info("Jabber disconnected: " + connection.getUser());
    connection.removePacketListener(mySubscribeListener);
    mySubscribeListener = null;
    connection.removePacketListener(myMessageListener);
    myMessageListener = null;

    final Roster roster = connection.getRoster();
    if (roster != null) {
      roster.removeRosterListener(myRosterListener);
    }
    myRosterListener = null;

    myIDEtalkUsers.clear();
    myUser2Presence.clear();
    myUser2Thread.clear();

    if (onError && reconnectEnabledAndNotStarted()) {
      LOG.warn(getMsg("jabber.server.was.disconnected", myReconnectTimeout / 1000));
      myReconnectProcess = myIdeFacade.runOnPooledThread(new MyReconnectRunnable());
    }
  }
    @Override
    public void actionPerformed(ActionEvent evt) {
      if (pluginModel.isDownloadingList()) return;

      boolean downloadSource = jEdit.getBooleanProperty("plugin-manager.downloadSource");
      boolean installUser = jEdit.getBooleanProperty("plugin-manager.installUser");
      Roster roster = new Roster();
      String installDirectory;
      if (installUser) {
        installDirectory = MiscUtilities.constructPath(jEdit.getSettingsDirectory(), "jars");
      } else {
        installDirectory = MiscUtilities.constructPath(jEdit.getJEditHome(), "jars");
      }

      int length = pluginModel.entries.size();
      int instcount = 0;
      for (int i = 0; i < length; i++) {
        Entry entry = (Entry) pluginModel.entries.get(i);
        if (entry.install) {
          entry.plugin.install(roster, installDirectory, downloadSource);
          if (updates)
            entry
                .plugin
                .getCompatibleBranch()
                .satisfyDependencies(roster, installDirectory, downloadSource);
          instcount++;
        }
      }

      if (roster.isEmpty()) return;

      boolean cancel = false;
      if (updates && roster.getOperationCount() > instcount)
        if (GUIUtilities.confirm(
                window,
                "install-plugins.depend",
                null,
                JOptionPane.OK_CANCEL_OPTION,
                JOptionPane.WARNING_MESSAGE)
            == JOptionPane.CANCEL_OPTION) cancel = true;

      if (!cancel) {
        new PluginManagerProgress(window, roster);

        roster.performOperationsInAWTThread(window);
        pluginModel.update();
      }
    }
  public void actionPerformed(ActionEvent e) {

    // --SEND/GET UPDATE(s) FROM SERVER-- Called whenever timer goes off (every 5 sec.)

    // ==== SEND ALL OF THE MESSAGES WE HAVE ====
    comm.sendOutboxMessages();
    // ==== SEND A REQUEST FOR A UNIVERSAL UPDATE ====
    comm.sendMessage("REQUEST");
    // ==== RECIEVE THE UNIVERSE/ROSTER/MARKET UPDATES ====
    ArrayList<String> responses = comm.getAllMessages();
    // ==== HERE IS WHERE WE UNPACK THE UPDATES FROM THE SERVER ====
    for (int q = 0; q < responses.size(); q++) {
      String header = responses.get(q).substring(0, 4);

      if (header.equals("UNIV")) {
        theUniverse.unpack(responses.get(q));
        Debug.msg("Unpacked a Universe");
        theDisplay.updateDisplay();
      } else if (header.equals("ROST")) {
        Roster.unpack(responses.get(q));
      } else if (header.equals("MARK")) {
        theMarket.unpack(responses.get(q));
      } else if (header.equals("SERV")) {
        Vector inParsed = ParseUtil.parseStringBySign(responses.get(q), '-');
        myPlayerNum = Integer.parseInt((String) inParsed.elementAt(1));
      } else Debug.msg("Unknown header recieved in ClientMain.actionPerformed() ");
    }
  }
Example #9
0
  Collection<String> getSharedUsersForRoster(Group group, Roster roster) {
    String showInRoster = group.getProperties().get("sharedRoster.showInRoster");
    String groupNames = group.getProperties().get("sharedRoster.groupList");

    // Answer an empty collection if the group is not being shown in users' rosters
    if (!"onlyGroup".equals(showInRoster) && !"everybody".equals(showInRoster)) {
      return new ArrayList<String>();
    }

    // Add the users of the group
    Collection<String> users = new HashSet<String>(group.getMembers());
    users.addAll(group.getAdmins());

    // Check if anyone can see this shared group
    if ("everybody".equals(showInRoster)) {
      // If the user of the roster belongs to the public group then we should return all users
      // in the system since they all need to be in the roster with subscription "from"
      if (group.isUser(roster.getUsername())) {
        // Add all users in the system
        for (User user : UserManager.getInstance().getUsers()) {
          users.add(user.getUsername());
        }
      }
    } else {
      // Add the users that may see the group
      Collection<Group> groupList = parseGroups(groupNames);
      for (Group groupInList : groupList) {
        users.addAll(groupInList.getMembers());
        users.addAll(groupInList.getAdmins());
      }
    }
    return users;
  }
  public void commandAction(Command c, Displayable d) {
    if (c == cmdOk) {
      String jid = getString(tJid);
      if (jid != null) {
        String name = getString(tNick);
        String group = group(tGrpList.getSelectedIndex());
        if (group == null) group = getString(tGroup);

        try {
          int gSel = tGrpList.getSelectedIndex();
          if (gSel != tGrpList.size() - 1) {
            group = (gSel > 0) ? tGrpList.getString(gSel) : null; // nokia fix
          }
        } catch (Exception e) {
        } // nokia fix

        // сохранение контакта
        boolean ask[] = new boolean[1];
        tAskSubscrCheckBox.getSelectedFlags(ask);
        roster.storeContact(jid, name, group, ask[0]);
        destroyView();
        return;
      }
    }

    if (c == cmdCancel) destroyView();
  }
  public Roster getRoster() {
    // synchronize against login()
    synchronized (this) {
      // if connection is authenticated the roster is already set by login()
      // or a previous call to getRoster()
      if (!isAuthenticated() || isAnonymous()) {
        if (roster == null) {
          roster = new Roster(this);
        }
        return roster;
      }
    }

    if (!config.isRosterLoadedAtLogin()) {
      if (roster == null) {
        roster = new Roster(this);
      }
      roster.reload();
    }
    // If this is the first time the user has asked for the roster after calling
    // login, we want to wait for the server to send back the user's roster. This
    // behavior shields API users from having to worry about the fact that roster
    // operations are asynchronous, although they'll still have to listen for
    // changes to the roster. Note: because of this waiting logic, internal
    // Smack code should be wary about calling the getRoster method, and may need to
    // access the roster object directly.
    if (!roster.rosterInitialized) {
      try {
        synchronized (roster) {
          long waitTime = SmackConfiguration.getPacketReplyTimeout();
          long start = System.currentTimeMillis();
          while (!roster.rosterInitialized) {
            if (waitTime <= 0) {
              break;
            }
            roster.wait(waitTime);
            long now = System.currentTimeMillis();
            waitTime -= now - start;
            start = now;
          }
        }
      } catch (InterruptedException ie) {
        // Ignore.
      }
    }
    return roster;
  }
Example #12
0
  private List<ContactSortModel> queryData(String groupname) {
    // mSortList = new ArrayList<SortModel>();
    if (mContactList == null) {
      mContactList = new ArrayList<ContactSortModel>();
    } else {
      mContactList.clear();
    }

    List<Roster> rosters = getRosters(groupname);

    if (mIsContact) {
      ContactSortModel sm1 = new ContactSortModel();
      Roster roster = new Roster();
      roster.setAlias("添加好友");
      sm1.setRoster(roster);
      sm1.setSortLetters("@");
      mContactList.add(sm1);

      ContactSortModel sm2 = new ContactSortModel();
      Roster roster2 = new Roster();
      roster2.setAlias("新朋友");
      sm2.setRoster(roster2);
      sm2.setSortLetters("@");
      mContactList.add(sm2);
    }

    for (int i = 0; i < rosters.size(); i++) {
      ContactSortModel sortModel = new ContactSortModel();

      sortModel.setRoster(rosters.get(i));
      // 取roster的alias昵称,并将汉字转换成拼音
      String pinyin = mCharacterParser.getSelling(rosters.get(i).getAlias());
      String sortString = pinyin.substring(0, 1).toUpperCase();

      // 正则表达式,判断首字母是否是英文字母
      if (sortString.matches("[A-Z]")) {
        sortModel.setSortLetters(sortString.toUpperCase());
      } else {
        sortModel.setSortLetters("#");
      }

      mContactList.add(sortModel);
    }

    return filterData(mFilterString, mContactList);
  }
Example #13
0
  /**
   * Removes the entire roster of a given user. This is necessary when a user account is being
   * deleted from the server.
   *
   * @param user the user.
   */
  public void deleteRoster(JID user) {
    try {
      String username = user.getNode();
      // Get the roster of the deleted user
      Roster roster = (Roster) CacheManager.getCache("username2roster").get(username);
      if (roster == null) {
        // Not in cache so load a new one:
        roster = new Roster(username);
      }
      // Remove each roster item from the user's roster
      for (RosterItem item : roster.getRosterItems()) {
        try {
          roster.deleteRosterItem(item.getJid(), false);
        } catch (SharedGroupException e) {
          // Do nothing. We shouldn't have this exception since we disabled the checkings
        }
      }
      // Remove the cached roster from memory
      CacheManager.getCache("username2roster").remove(username);

      // Get the rosters that have a reference to the deleted user
      RosterItemProvider rosteItemProvider = RosterItemProvider.getInstance();
      Iterator<String> usernames = rosteItemProvider.getUsernames(user.toBareJID());
      while (usernames.hasNext()) {
        username = usernames.next();
        // Get the roster that has a reference to the deleted user
        roster = (Roster) CacheManager.getCache("username2roster").get(username);
        if (roster == null) {
          // Not in cache so load a new one:
          roster = new Roster(username);
        }
        // Remove the deleted user reference from this roster
        try {
          roster.deleteRosterItem(user, false);
        } catch (SharedGroupException e) {
          // Do nothing. We shouldn't have this exception since we disabled the checkings
        }
      }
    } catch (UnsupportedOperationException e) {
      // Do nothing
    }
  }
Example #14
0
 public void leave(EndOid grpOid, EndOid userOid) {
   roster.leave(grpOid, userOid);
   Presence p = new Presence("leave", userOid, grpOid);
   Endpoint ep = lookup(userOid);
   if (ep != null) {
     p.setNick(ep.nick);
     p.setShow("available");
     p.setStatus(grpOid.name);
   }
   route(null, p);
 }
Example #15
0
 /**
  * Returns an unmodifiable collection of the roster groups that this entry belongs to.
  *
  * @return an iterator for the groups this entry belongs to.
  */
 public Collection<RosterGroup> getGroups() {
   List<RosterGroup> results = new ArrayList<RosterGroup>();
   // Loop through all roster groups and find the ones that contain this
   // entry. This algorithm should be fine
   for (RosterGroup group : roster.getGroups()) {
     if (group.contains(this)) {
       results.add(group);
     }
   }
   return Collections.unmodifiableCollection(results);
 }
  public Object coerceToUi(java.lang.Object val, org.zkoss.zk.ui.Component comp) {

    DaoRoster daoRoster = new DaoRoster();

    if (val instanceof Jugador) {
      jugador = ((Jugador) val);
      roster = daoRoster.buscarRoster(jugador.getCedulaRif());
      if (roster == null) return valorRetornado = "";
      else valorRetornado = roster.getEquipo().getNombre();
    }
    return valorRetornado;
  }
  public void drawShip(Graphics g, int X, int Y, int Scale, int fleetNum) // Stolen from Riehle
      {

    // Determine if yours, ally or enemy for coloring
    if (ClientMain.myPlayerNum == playerNum) g.setColor(Color.GREEN);
    else if (Roster.getPlayer(ClientMain.myPlayerNum).getAlliances().isAllied(playerNum))
      g.setColor(Color.YELLOW);
    else g.setColor(Color.RED);

    // Display numbers and ships
    g.drawString("" + numShips, Scale * 2 + X + Scale * 3 * fleetNum, Scale * 2 + Y);
    //             g.fillRect(Scale*2 + X,Scale*2 + Y, Scale*3, Scale*3);
    g.drawRect(Scale * 2 + X + Scale * 3 * fleetNum, Scale * 2 + Y, Scale * 3, Scale * 3);
  }
Example #18
0
  /**
   * Notification that a Group user has been deleted. Update the group users' roster accordingly.
   *
   * @param group the group from where the user was deleted.
   * @param users the users to update their rosters
   * @param deletedUser the username of the user that has been deleted from the group.
   */
  private void groupUserDeleted(Group group, Collection<String> users, String deletedUser) {
    // Get the roster of the deleted user.
    Roster deletedUserRoster = (Roster) CacheManager.getCache("username2roster").get(deletedUser);

    // Iterate on all the affected users and update their rosters
    for (String userToUpdate : users) {
      // Get the roster to update
      Roster roster = (Roster) CacheManager.getCache("username2roster").get(userToUpdate);
      // Only update rosters in memory
      if (roster != null) {
        roster.deleteSharedUser(group, deletedUser);
      }
      // Update the roster of the newly deleted group user.
      if (deletedUserRoster != null) {
        try {
          User user = UserManager.getInstance().getUser(userToUpdate);
          Collection<Group> groups = GroupManager.getInstance().getGroups(user);
          deletedUserRoster.deleteSharedUser(userToUpdate, groups, group);
        } catch (UserNotFoundException e) {
        }
      }
    }
  }
Example #19
0
  public void route(Ticket ticket, Packet packet) {
    if (packet instanceof Presence) {
      update((Presence) packet);
    }
    if (isGrpMessage(packet)) {
      List<Member> members = roster.members(packet.toOid);
      for (Member member : members) {
        if (!packet.fromOid.equals(member.userOid)) {
          route(ticket, member.userOid, packet);
        }
      }
    } else if (isGrpPresence(packet)) {
      List<Member> members = roster.members(packet.toOid);
      for (Member member : members) {
        String type = ((Presence) packet).type;
        if (("join".equals(type) || "leave".equals(type)) && packet.fromOid.equals(member.userOid))
          continue;
        route(ticket, member.userOid, packet);
      }

    } else {
      route(ticket, packet.toOid, packet);
    }
  }
Example #20
0
 // test 3 of 3 - has giver given to givee in past X years?
 static boolean giveeNotRepeat(String giverCode, String giveeCode, Roster roster, int thisYear) {
   final int PAST_X_YEARS = 4;
   int counter;
   String giveeInYear;
   boolean result = true;
   for (counter = thisYear - 1;
       (counter >= 0) && (counter >= (thisYear - PAST_X_YEARS));
       counter--) {
     giveeInYear = roster.getGiveeCode(giverCode, counter);
     if (giveeCode.equals(giveeInYear)) {
       result = false;
     }
   }
   return result;
 }
  public JabberTransport(
      JabberUI UI,
      JabberFacade facade,
      UserModel userModel,
      AsyncMessageDispatcher messageDispatcher,
      JabberUserFinder userFinder) {
    Roster.setDefaultSubscriptionMode(Roster.SubscriptionMode.manual);

    // XMPPConnection.DEBUG_ENABLED = true;
    JDOMExtension.init();

    myUI = UI;
    myFacade = facade;
    myUserModel = userModel;
    myDispatcher = messageDispatcher;
    myUserFinder = userFinder;
    myIdeFacade = messageDispatcher.getIdeFacade();
    myIgnoreList = new IgnoreList(myIdeFacade);

    myFacade.addConnectionListener(this);
    getBroadcaster().addListener(myUserModelListener);
  }
  public void disconnect(Presence unavailablePresence) {
    // If not connected, ignore this request.
    PacketReader packetReader = this.packetReader;
    PacketWriter packetWriter = this.packetWriter;
    if (packetReader == null || packetWriter == null) {
      return;
    }

    shutdown(unavailablePresence);

    if (roster != null) {
      roster.cleanup();
      roster = null;
    }
    chatManager = null;

    wasAuthenticated = false;

    packetWriter.cleanup();
    this.packetWriter = null;
    packetReader.cleanup();
    this.packetReader = null;
  }
Example #23
0
  public static void main(String[] args) {
    Scanner inputReader = new Scanner(System.in);
    XMPPConnection connection = null;
    System.out.println("Welcome to the Multi User Chat Desktop Application.");
    boolean notConnected = true;
    while (notConnected) {
      System.out.println("Enter the XMPP server you would like to connect to (e.g. myserver.org):");
      String xmppServer = inputReader.nextLine();
      try {
        System.out.println("Processing... Please wait");
        connection = new XMPPConnection(xmppServer); // connects to server address provided
        connection.connect();
        System.out.println("Connection Successful!\n");
        notConnected = false;
      } catch (Exception e) {
        System.out.println(
            "There was an issue connecting to the XMPP server '"
                + xmppServer
                + "' (We recommend jabber.org)");
      }
    }
    boolean validUserAndPass = false;
    String userName = null;
    while (!validUserAndPass) {
      System.out.println("Please enter your username: "******"Please enter your password: "******"Validating your information...");
        connection.login(userName, password); // attempts to login to the server
        validUserAndPass = true;
        System.out.println("Login Successful!\n");
      } catch (Exception e) {
        System.out.println(
            "Error logging into server - Your username or password may be incorrect");
      }
    }
    Connection connection2 = new XMPPConnection("jabber.org");
    MultiUserChat groupChat2 = null;
    try {
      connection2.connect();
      connection2.login("*****@*****.**", "opencommdesign");
    } catch (XMPPException e1) {
      System.out.println("Hardcoded opencommdesign failed to log in");
    }
    System.out.println("Enter a command to begin (or 'help' to see available commands)");
    MultiUserChat groupChat = null;
    ArrayList<RosterEntry> onlineUsersInRoom =
        new ArrayList<RosterEntry>(); // updated when a user accepts the chat invitation
    boolean chatRoomGenerated =
        false; // checked against to make sure room is not regenerated each time a user is invited
    ChatManager chatmanager = null;
    Chat chat = null;
    boolean programTerminated = false;
    while (!programTerminated) {
      String input = inputReader.nextLine();
      input =
          input
              .trim(); // ignores spaces before and after the command if the command itself is
                       // correct - does not remove spaces mixed into the command
      if (input.startsWith(HELP_VERB) && input.length() == HELP_VERB.length()) {
        System.out.println(COMMAND_OPTIONS); // prints list of available commands
      } else if (input.equals(VIEW_ROOM_VERB)) {
        if (groupChat == null) {
          System.out.println("You are not currently in any chat rooms");
        } else {
          System.out.println("You are currently in the '" + DEFAULT_ROOM_NAME + "' chatroom");
        }
      } else if (input.startsWith(INVITATION_VERB)) {
        String userToInvite =
            input.substring(
                INVITATION_VERB.length()
                    + 1); // +1 accounts for space after verb, isolates the username

        try {
          if (!chatRoomGenerated) {
            System.out.println("Initializing a default chat room...");
            groupChat = new MultiUserChat(connection, DEFAULT_ROOM_NAME + "@conference.jabber.org");
            groupChat.create(
                DEFAULT_ROOM_NAME); // initializes a default instant room, automatically placing the
                                    // user in it
            groupChat.sendConfigurationForm(new Form(Form.TYPE_SUBMIT));
            System.out.println("Default chat room initialized!");
            // listen for invitation rejections
            groupChat.addInvitationRejectionListener(
                new InvitationRejectionListener() {
                  public void invitationDeclined(String invitee, String reason) {
                    System.out.println("User '" + invitee + "' declined your chat invitation.");
                    System.out.println("Reason: " + reason);
                  }
                });
            groupChat2 =
                new MultiUserChat(connection, DEFAULT_ROOM_NAME + "@conference.jabber.org");
            groupChat2.join(DEFAULT_ROOM_NAME); // hardcoded second user joins the room
            chatRoomGenerated = true;
            chatmanager = connection.getChatManager();
            chat =
                chatmanager.createChat(
                    userToInvite,
                    new MessageListener() {
                      public void processMessage(Chat chat, Message message) {
                        System.out.println("Received message: " + message);
                      }
                    });
          }
          groupChat.invite(
              userToInvite, "User '" + userName + "' has invited you to join a chat room");

        } catch (XMPPException e) {
          System.out.println("Error occured in creating the chat room");
        }
      } else if (input.equals(VIEW_BUDDY_VERB)) { // if user enters viewBuddyList
        Roster roster = connection.getRoster(); // gets other users on this connection
        Collection<RosterEntry> entries = roster.getEntries();
        ArrayList<RosterEntry> onlineUsers = new ArrayList<RosterEntry>();
        ArrayList<RosterEntry> offlineUsers = new ArrayList<RosterEntry>();
        for (RosterEntry entry : entries) {
          if (entry
              .toString()
              .contains(
                  "[Buddies]")) { // if other users are marked as buddies, print them to the list
            String user = entry.getUser();
            if (roster.getPresence(user) == null) { // if user is offline, add them to offlineUsers
              offlineUsers.add(entry);
            } else {
              onlineUsers.add(entry);
            }
          }
        }

        System.out.println("Online Buddies in your chat room:");
        if (groupChat.getOccupantsCount() == 1) {
          System.out.println("There are 0 buddies in your chat room");
        } else {
          @SuppressWarnings("unchecked")
          Collection<String> users = (Collection<String>) groupChat.getOccupants();
          for (@SuppressWarnings("unused") String user : users) {
            System.out.println(user);
          }
        }
        System.out.println("Online Buddies:");
        if (onlineUsers.size() == 0) {
          System.out.println("There are 0 buddies online");
        } else {
          for (RosterEntry entry : onlineUsers) {
            String user = entry.toString().substring(0, entry.toString().indexOf("[Buddies]"));
            System.out.println(user);
          }
        }
        System.out.println("Offline Buddies:");
        if (offlineUsers.size() == 0) {
          System.out.println("There are 0 buddies offline");
        } else {
          for (RosterEntry entry : offlineUsers) {
            String user = entry.toString().substring(0, entry.toString().indexOf("[Buddies]"));
            System.out.println(user);
          }
        }
        System.out.println("");
      } else {
        System.out.println(
            "Command not recognized.  Type 'help' to see a list of available commands");
      }

      if (!programTerminated) {
        System.out.println("Enter a command: ");
      }
    }
  }
Example #24
0
 // test 2 of 3 - is givee giving to giver?
 static boolean giveeNotRecip(String giverCode, String giveeCode, Roster roster, int thisYear) {
   String giveeGivingTo;
   giveeGivingTo = roster.getGiveeCode(giveeCode, thisYear);
   return !giverCode.equals(giveeGivingTo);
 }
Example #25
0
 /** 登陆XMPP服务器 */
 public boolean login() throws RemoteException {
   // 未建立XMPP连接
   if (!connection.isConnected()) {
     return false;
   }
   // 应经登陆过
   if (connection.isAuthenticated()) {
     return true;
   } else {
     // 开始登陆
     try {
       connection.login(account, password, imService.getString(R.string.app_name));
       if (messageListener == null) {
         messageListener = new MessageListener();
       }
       // 添加消息监听器
       connection.addPacketListener(messageListener, new PacketTypeFilter(Message.class));
       Roster roster = connection.getRoster();
       if (rosterListener == null) {
         rosterListener = new IMClientRosterListener();
       }
       // 添加花名册监听器
       roster.addRosterListener(rosterListener);
       // 获取花名册
       if (roster != null && roster.getEntries().size() > 0) {
         Uri uri = null;
         for (RosterEntry entry : roster.getEntries()) {
           // 获取联系人名片信息
           VCard vCard = new VCard();
           vCard.load(connection, entry.getUser());
           // 用户名称
           String userName = StringUtils.parseName(entry.getUser());
           // 用户备注
           String remarks = entry.getName();
           // 通讯录的名称
           String name = "";
           // 名称与备注判断
           if (userName.equals(remarks) && vCard != null) {
             // 使用联系人的昵称
             name = vCard.getNickName();
           } else {
             // 使用备注
             name = remarks;
           }
           if (vCard != null) {
             IM.saveAvatar(vCard.getAvatar(), StringUtils.parseName(entry.getUser()));
           }
           ContentValues values = new ContentValues();
           values.put(ContactsProvider.ContactColumns.ACCOUNT, entry.getUser());
           values.put(ContactsProvider.ContactColumns.NAME, name);
           String sortStr = PinYin.getPinYin(name);
           values.put(ContactsProvider.ContactColumns.SORT, sortStr);
           values.put(
               ContactsProvider.ContactColumns.SECTION,
               sortStr.substring(0, 1).toUpperCase(Locale.ENGLISH));
           // 储存联系人
           if (imService
                   .getContentResolver()
                   .update(
                       ContactsProvider.CONTACT_URI,
                       values,
                       ContactsProvider.ContactColumns.ACCOUNT + " = ?",
                       new String[] {entry.getUser()})
               == 0) {
             uri = imService.getContentResolver().insert(ContactsProvider.CONTACT_URI, values);
           }
         }
         // 发生改变,通知刷新
         if (uri != null) {
           imService.getContentResolver().notifyChange(uri, null);
         }
       }
     } catch (XMPPException e) {
       e.printStackTrace();
     } catch (SmackException e) {
       e.printStackTrace();
     } catch (IOException e) {
       e.printStackTrace();
     }
     return true;
   }
 }
Example #26
0
  protected synchronized void clean() {
    long now = System.currentTimeMillis();

    //		System.out.println("begin to clean: " + now);
    // clean subscribers
    Set<EndOid> keys = routes.keySet();
    for (EndOid key : keys) {
      List<Subscriber> subscribers = routes.get(key);
      Iterator<Subscriber> it = subscribers.iterator();
      while (it.hasNext()) {
        Subscriber sub = it.next();
        if ((sub.continuation == null || sub.continuation.isExpired())
            && ((sub.lastActive + 8000) < now)) {
          System.out.println("Clean NoTimeout Sub: " + sub);
          it.remove();
        } else if ((sub.lastActive + 28000) < now) {
          System.out.println("Clean Timeout Sub: " + sub);
          // TODO: when continuation cannot be expired
          if (sub.continuation != null && sub.continuation.isSuspended()) {
            sub.continuation.resume();
            sub.continuation = null;
          }
          it.remove();
        }
      }
      if (subscribers.size() == 0) {
        Endpoint ep = registry.get(key);
        if (ep != null && !ep.idle) {
          ep.idle = true;
          ep.idleTime = System.currentTimeMillis();
        }
      }
      routes.put(key, subscribers);
    }
    // clean endpoints
    Iterator<EndOid> keysIter = registry.keySet().iterator();

    //		for (EndOid key : keys) {
    while (keysIter.hasNext()) {
      EndOid key = keysIter.next();
      Endpoint ep = registry.get(key);
      if (ep.idle && (ep.idleTime + 8000) < now) {
        // System.out.println("Clean Endpoint: " + key);
        // presence
        List<Buddy> buddies = roster.buddies(key);
        for (Buddy b : buddies) {
          Presence p = new Presence("offline", key, b.fid);
          p.setNick(ep.nick);
          p.setShow("unavailable");
          p.setStatus(ep.status);
          // TODO:
          route(null, p);
        }
        // leave group presences
        for (EndOid grpOid : roster.groups(key)) {
          Presence p = new Presence("grpoffline", ep.endOid, grpOid);
          p.setNick(ep.nick);
          p.setShow("unavailable");
          p.setStatus(grpOid.name);
          route(null, p);
        }
        // remove
        //				registry.remove(key);
        keysIter.remove();
        routes.remove(key);
        roster.clean(key);
      }
    }
  }
Example #27
0
  public void groupModified(Group group, Map params) {
    // Do nothing if no group property has been modified
    if (!"propertyModified".equals(params.get("type"))) {
      return;
    }
    String keyChanged = (String) params.get("propertyKey");
    String originalValue = (String) params.get("originalValue");

    if ("sharedRoster.showInRoster".equals(keyChanged)) {
      String currentValue = group.getProperties().get("sharedRoster.showInRoster");
      // Nothing has changed so do nothing.
      if (currentValue.equals(originalValue)) {
        return;
      }
      // Get the users of the group
      Collection<String> users = new HashSet<String>(group.getMembers());
      users.addAll(group.getAdmins());
      // Get the users whose roster will be affected
      Collection<String> affectedUsers =
          getAffectedUsers(
              group, originalValue, group.getProperties().get("sharedRoster.groupList"));
      // Remove the group members from the affected rosters
      for (String deletedUser : users) {
        groupUserDeleted(group, affectedUsers, deletedUser);
      }

      // Simulate that the group users has been added to the group. This will cause to push
      // roster items to the "affected" users for the group users
      // Collection<Group> visibleGroups = getVisibleGroups(group);
      for (String user : users) {
        groupUserAdded(group, user);
        /*for (Group visibleGroup : visibleGroups) {
            addSharedGroupToRoster(visibleGroup, user);
        }*/
      }
    } else if ("sharedRoster.groupList".equals(keyChanged)) {
      String currentValue = group.getProperties().get("sharedRoster.groupList");
      // Nothing has changed so do nothing.
      if (currentValue.equals(originalValue)) {
        return;
      }
      // Get the users of the group
      Collection<String> users = new HashSet<String>(group.getMembers());
      users.addAll(group.getAdmins());
      // Get the users whose roster will be affected
      Collection<String> affectedUsers =
          getAffectedUsers(
              group, group.getProperties().get("sharedRoster.showInRoster"), originalValue);
      // Remove the group members from the affected rosters
      for (String deletedUser : users) {
        groupUserDeleted(group, affectedUsers, deletedUser);
      }

      // Simulate that the group users has been added to the group. This will cause to push
      // roster items to the "affected" users for the group users
      // Collection<Group> visibleGroups = getVisibleGroups(group);
      for (String user : users) {
        groupUserAdded(group, user);
        /*for (Group visibleGroup : visibleGroups) {
            addSharedGroupToRoster(visibleGroup, user);
        }*/
      }
    } else if ("sharedRoster.displayName".equals(keyChanged)) {
      String currentValue = group.getProperties().get("sharedRoster.displayName");
      // Nothing has changed so do nothing.
      if (currentValue.equals(originalValue)) {
        return;
      }
      // Do nothing if the group is not being shown in users' rosters
      if (!isSharedGroup(group)) {
        return;
      }
      // Get all the affected users
      Collection<String> users = getAffectedUsers(group);
      // Iterate on all the affected users and update their rosters
      for (String updatedUser : users) {
        // Get the roster to update.
        Roster roster = (Roster) CacheManager.getCache("username2roster").get(updatedUser);
        if (roster != null) {
          // Update the roster with the new group display name
          roster.shareGroupRenamed(users);
        }
      }
    }
  }