/**
   * Returns the index of the source contact, in the list of recent messages.
   *
   * @param messageSourceContact
   * @return
   */
  int getIndex(MessageSourceContact messageSourceContact) {
    synchronized (recentMessages) {
      for (int i = 0; i < recentMessages.size(); i++)
        if (recentMessages.get(i).equals(messageSourceContact)) return i;

      return -1;
    }
  }
示例#2
0
  /**
   * Fires a <tt>StreamSoundLevelEvent</tt> and notifies all registered listeners.
   *
   * @param level the new sound level
   */
  void fireStreamSoundLevelEvent(int level) {
    SoundLevelListener[] listeners;

    synchronized (soundLevelListeners) {
      listeners = soundLevelListeners.toArray(new SoundLevelListener[soundLevelListeners.size()]);
    }

    for (SoundLevelListener listener : listeners) listener.soundLevelChanged(this, level);
  }
    /**
     * Blocks until at least one event is received or until waitFor miliseconds pass (whichever
     * happens first).
     *
     * @param waitFor the number of miliseconds that we should be waiting for an event before simply
     *     bailing out.
     */
    public void waitForEvent(long waitFor) {
      synchronized (this) {
        if (collectedEvents.size() > 0) return;

        try {
          wait(waitFor);
        } catch (InterruptedException ex) {
          logger.debug("Interrupted while waiting for a message evt", ex);
        }
      }
    }
    /**
     * Blocks until at least one event is received or until waitFor miliseconds pass (whicever
     * happens first).
     *
     * @param waitFor the number of miliseconds that we should be waiting for an event before simply
     *     bailing out.
     */
    public void waitForEvent(long waitFor) {
      synchronized (this) {
        if (collectedMessageInfo.size() > 0) {
          logger.trace("evt already received. " + collectedMessageInfo);
          return;
        }

        try {
          wait(waitFor);
        } catch (InterruptedException ex) {
          logger.debug("Interrupted while waiting for a subscription evt", ex);
        }
      }
    }
  /**
   * Generate the display of the results of the Define command
   *
   * @param data the result of the Define command
   * @param word the queried word
   * @return the formatted result
   */
  private String retrieveDefine(List<Definition> data, String word) {
    StringBuffer res = new StringBuffer();
    Definition def;

    for (int i = 0; i < data.size(); i++) {
      def = data.get(i);

      if (i != 0 && data.size() > 0) {
        res.append("<hr>");
      }
      res.append(def.getDefinition().replaceAll("\n", "<br>"))
          .append("<div align=\"right\"><font size=\"-2\">-- From ")
          .append(def.getDictionary())
          .append("</font></div>");
    }

    String result = res.toString();
    result = formatResult(result, "\\\\", "<em>", "</em>");
    result = formatResult(result, "[\\[\\]]", "<cite>", "</cite>");
    result = formatResult(result, "[\\{\\}]", "<strong>", "</strong>");
    result = formatWordDefined(result, word);

    return result;
  }
示例#6
0
  /**
   * Fires a <tt>StreamSoundLevelEvent</tt> and notifies all registered listeners.
   *
   * @param levels the new sound levels
   */
  void fireConferenceMembersSoundLevelEvent(Map<ConferenceMember, Integer> levels) {
    ConferenceMembersSoundLevelEvent event = new ConferenceMembersSoundLevelEvent(this, levels);

    ConferenceMembersSoundLevelListener[] ls;

    synchronized (confMemebrSoundLevelListeners) {
      ls =
          confMemebrSoundLevelListeners.toArray(
              new ConferenceMembersSoundLevelListener[confMemebrSoundLevelListeners.size()]);
    }

    for (ConferenceMembersSoundLevelListener listener : ls) {
      listener.soundLevelChanged(event);
    }
  }
  /**
   * Generate the display of the results of the Match command
   *
   * @param data the result of the Match command
   * @param word the queried word
   * @return the formatted result
   */
  private String retrieveMatch(List<MatchWord> data, String word) {
    StringBuffer result = new StringBuffer();
    boolean isStart = true;

    result.append(
        DictActivator.getResources()
            .getI18NString("plugin.dictaccregwizz.MATCH_RESULT", new String[] {word}));

    for (int i = 0; i < data.size(); i++) {
      if (isStart) isStart = false;
      else result.append(", ");

      result.append(data.get(i).getWord());
    }

    return result.toString();
  }
  /**
   * Searches for entries in cached recent messages in history.
   *
   * @param provider the provider which contact messages we will search
   * @param isStatusChanged is the search because of status changed
   * @return entries in cached recent messages in history.
   */
  private List<ComparableEvtObj> getCachedRecentMessages(
      ProtocolProviderService provider, boolean isStatusChanged) {
    String providerID = provider.getAccountID().getAccountUniqueID();
    List<String> recentMessagesContactIDs =
        getRecentContactIDs(
            providerID, recentMessages.size() < numberOfMessages ? null : oldestRecentMessage);

    List<ComparableEvtObj> cachedRecentMessages = new ArrayList<ComparableEvtObj>();

    for (String contactID : recentMessagesContactIDs) {
      Collection<EventObject> res =
          messageHistoryService.findRecentMessagesPerContact(
              numberOfMessages, providerID, contactID, isSMSEnabled);

      processEventObjects(res, cachedRecentMessages, isStatusChanged);
    }

    return cachedRecentMessages;
  }
    /**
     * Blocks until an event notifying us of the awaited state change is received or until waitFor
     * miliseconds pass (whichever happens first).
     *
     * @param waitFor the number of miliseconds that we should be waiting for an event before simply
     *     bailing out.
     */
    public void waitForEvent(long waitFor) {
      logger.trace("Waiting for a RegistrationStateChangeEvent ");

      synchronized (this) {
        if (collectedNewStates.contains(RegistrationState.REGISTERED)) {
          logger.trace("Event already received. " + collectedNewStates);
          return;
        }

        try {
          wait(waitFor);

          if (collectedNewStates.size() > 0)
            logger.trace("Received a RegistrationStateChangeEvent.");
          else logger.trace("No RegistrationStateChangeEvent received for " + waitFor + "ms.");

        } catch (InterruptedException ex) {
          logger.debug("Interrupted while waiting for a " + "RegistrationStateChangeEvent", ex);
        }
      }
    }
  /** Verifies that all necessary ICQ test states are supported by the implementation. */
  public void testSupportedStatusSetForCompleteness() {
    // first create a local list containing the presence status instances
    // supported by the underlying implementation.
    Iterator<PresenceStatus> supportedStatusSetIter = operationSetPresence.getSupportedStatusSet();

    List<PresenceStatus> supportedStatusSet = new LinkedList<PresenceStatus>();
    while (supportedStatusSetIter.hasNext()) {
      supportedStatusSet.add(supportedStatusSetIter.next());
    }

    // create a copy of the MUST status set and remove any matching status
    // that is also present in the supported set.
    List<?> requiredStatusSetCopy = (List<?>) IcqStatusEnum.icqStatusSet.clone();

    requiredStatusSetCopy.removeAll(supportedStatusSet);

    // if we have anything left then the implementation is wrong.
    int unsupported = requiredStatusSetCopy.size();
    assertTrue(
        "There are " + unsupported + " statuses as follows:" + requiredStatusSetCopy,
        unsupported == 0);
  }
示例#11
0
  /**
   * A provider has been removed.
   *
   * @param provider the ProtocolProviderService that has been unregistered.
   */
  void handleProviderRemoved(ProtocolProviderService provider) {
    // lets remove the recent messages for this provider, and update
    // with recent messages for the available providers
    synchronized (recentMessages) {
      if (provider != null) {
        List<ComparableEvtObj> removedItems = new ArrayList<ComparableEvtObj>();
        for (ComparableEvtObj msc : recentMessages) {
          if (msc.getProtocolProviderService().equals(provider)) removedItems.add(msc);
        }

        recentMessages.removeAll(removedItems);
        if (!recentMessages.isEmpty())
          oldestRecentMessage = recentMessages.get(recentMessages.size() - 1).getTimestamp();
        else oldestRecentMessage = null;

        if (recentQuery != null) {
          for (ComparableEvtObj msc : removedItems) {
            recentQuery.fireContactRemoved(msc);
          }
        }
      }

      // handleProviderRemoved can be invoked due to stopped
      // history service, if this is the case we do not want to
      // update messages
      if (!this.messageHistoryService.isHistoryLoggingEnabled()) return;

      // lets do the same as we enable provider
      // for all registered providers and finally fire events
      List<ComparableEvtObj> contactsToAdd = new ArrayList<ComparableEvtObj>();
      for (ProtocolProviderService pps : messageHistoryService.getCurrentlyAvailableProviders()) {
        contactsToAdd.addAll(getCachedRecentMessages(pps, true));
      }

      addNewRecentMessages(contactsToAdd);
    }
  }
  /** Initializes "select account" spinner with existing accounts. */
  private void initAccountSpinner() {
    Spinner accountsSpiner = (Spinner) findViewById(R.id.selectAccountSpinner);

    Iterator<ProtocolProviderService> providers = AccountUtils.getRegisteredProviders().iterator();

    List<AccountID> accounts = new ArrayList<AccountID>();

    int selectedIdx = -1;
    int idx = 0;

    while (providers.hasNext()) {
      ProtocolProviderService provider = providers.next();

      OperationSet opSet = provider.getOperationSet(OperationSetPresence.class);

      if (opSet == null) continue;

      AccountID account = provider.getAccountID();
      accounts.add(account);
      idx++;

      if (account.isPreferredProvider()) {
        selectedIdx = idx;
      }
    }

    AccountsListAdapter accountsAdapter =
        new AccountsListAdapter(
            this, R.layout.select_account_row, R.layout.select_account_dropdown, accounts, true);
    accountsSpiner.setAdapter(accountsAdapter);

    // if we have only select account option and only one account
    // select the available account
    if (accounts.size() == 1) accountsSpiner.setSelection(0);
    else accountsSpiner.setSelection(selectedIdx);
  }
  /**
   * Retrieves a server stored contact list and checks whether it contains all contacts that have
   * been added there during the initialization phase by the testerAgent.
   */
  public void testRetrievingServerStoredContactList() {
    ContactGroup rootGroup = opSetPersPresence1.getServerStoredContactListRoot();

    logger.debug("=========== Server Stored Contact List =================");

    logger.debug(
        "rootGroup="
            + rootGroup.getGroupName()
            + " rootGroup.childContacts="
            + rootGroup.countContacts()
            + "rootGroup.childGroups="
            + rootGroup.countSubgroups()
            + "Printing rootGroupContents=\n"
            + rootGroup.toString());

    Hashtable<String, List<String>> expectedContactList =
        GibberishSlickFixture.preInstalledBuddyList;

    logger.debug("============== Expected Contact List ===================");
    logger.debug(expectedContactList);

    // Go through the contact list retrieved by the persistence presence set
    // and remove the name of every contact and group that we find there from
    // the expected contct list hashtable.
    Iterator<ContactGroup> groups = rootGroup.subgroups();
    while (groups.hasNext()) {
      ContactGroup group = groups.next();

      List<String> expectedContactsInGroup = expectedContactList.get(group.getGroupName());

      // When sending the offline message
      // the sever creates a group NotInContactList,
      // because the buddy we are sending message to is not in
      // the contactlist. So this group must be ignored
      if (!group.getGroupName().equals("NotInContactList")) {
        assertNotNull(
            "Group "
                + group.getGroupName()
                + " was returned by "
                + "the server but was not in the expected contact list.",
            expectedContactsInGroup);

        Iterator<Contact> contactsIter = group.contacts();
        while (contactsIter.hasNext()) {
          String contactID = contactsIter.next().getAddress();
          expectedContactsInGroup.remove(contactID);
        }

        // If we've removed all the sub contacts, remove the group too.
        if (expectedContactsInGroup.size() == 0) expectedContactList.remove(group.getGroupName());
      }
    }

    // whatever we now have in the expected contact list snapshot are groups,
    // that have been added by the testerAgent but that were not retrieved
    // by the persistent presence operation set.
    assertTrue(
        "The following contacts were on the server sidec contact "
            + "list, but were not returned by the pers. pres. op. set"
            + expectedContactList.toString(),
        expectedContactList.isEmpty());
  }
示例#14
0
 /**
  * Returns <tt>true</tt> if <tt>list1</tt> and <tt>list2</tt> contain the same elements where
  * items order is not relevant.
  *
  * @param list1 the first list of <tt>String</tt> to be compared against the second list.
  * @param list2 the second list of <tt>String</tt> to be compared against the first list.
  */
 public static boolean areTheSame(List<String> list1, List<String> list2) {
   return list1.size() == list2.size() && list2.containsAll(list1);
 }
示例#15
0
  /**
   * Find the <tt>ProtocolProviderServiceSipImpl</tt> (one of our "candidate recipient" listeners)
   * which this <tt>request</tt> should be dispatched to. The strategy is to look first at the
   * request URI, and then at the To field to find a matching candidate for dispatching. Note that
   * this method takes a <tt>Request</tt> as param, and not a <tt>ServerTransaction</tt>, because
   * sometimes <tt>RequestEvent</tt>s have no associated <tt>ServerTransaction</tt>.
   *
   * @param request the <tt>Request</tt> to find a recipient for.
   * @return a suitable <tt>ProtocolProviderServiceSipImpl</tt>.
   */
  private ProtocolProviderServiceSipImpl findTargetFor(Request request) {
    if (request == null) {
      logger.error("request shouldn't be null.");
      return null;
    }

    List<ProtocolProviderServiceSipImpl> currentListenersCopy =
        new ArrayList<ProtocolProviderServiceSipImpl>(this.getSipListeners());

    // Let's first narrow down candidate choice by comparing
    // addresses and ports (no point in delivering to a provider with a
    // non matching IP address  since they will reject it anyway).
    filterByAddress(currentListenersCopy, request);

    if (currentListenersCopy.size() == 0) {
      logger.error("no listeners");
      return null;
    }

    URI requestURI = request.getRequestURI();

    if (requestURI.isSipURI()) {
      String requestUser = ((SipURI) requestURI).getUser();

      List<ProtocolProviderServiceSipImpl> candidates =
          new ArrayList<ProtocolProviderServiceSipImpl>();

      // check if the Request-URI username is
      // one of ours usernames
      for (ProtocolProviderServiceSipImpl listener : currentListenersCopy) {
        String ourUserID = listener.getAccountID().getUserID();
        // logger.trace(ourUserID + " *** " + requestUser);
        if (ourUserID.equals(requestUser)) {
          if (logger.isTraceEnabled())
            logger.trace("suitable candidate found: " + listener.getAccountID());
          candidates.add(listener);
        }
      }

      // the perfect match
      // every other case is approximation
      if (candidates.size() == 1) {
        ProtocolProviderServiceSipImpl perfectMatch = candidates.get(0);

        if (logger.isTraceEnabled())
          logger.trace("Will dispatch to \"" + perfectMatch.getAccountID() + "\"");
        return perfectMatch;
      }

      // more than one account match
      if (candidates.size() > 1) {
        // check if a custom param exists in the contact
        // address (set for registrar accounts)
        for (ProtocolProviderServiceSipImpl candidate : candidates) {
          String hostValue =
              ((SipURI) requestURI).getParameter(SipStackSharing.CONTACT_ADDRESS_CUSTOM_PARAM_NAME);
          if (hostValue == null) continue;
          if (hostValue.equals(candidate.getContactAddressCustomParamValue())) {
            if (logger.isTraceEnabled())
              logger.trace(
                  "Will dispatch to \""
                      + candidate.getAccountID()
                      + "\" because "
                      + "\" the custom param was set");
            return candidate;
          }
        }

        // Past this point, our guess is not reliable. We try to find
        // the "least worst" match based on parameters like the To field

        // check if the To header field host part
        // matches any of our SIP hosts
        for (ProtocolProviderServiceSipImpl candidate : candidates) {
          URI fromURI = ((FromHeader) request.getHeader(FromHeader.NAME)).getAddress().getURI();
          if (fromURI.isSipURI() == false) continue;
          SipURI ourURI = (SipURI) candidate.getOurSipAddress((SipURI) fromURI).getURI();
          String ourHost = ourURI.getHost();

          URI toURI = ((ToHeader) request.getHeader(ToHeader.NAME)).getAddress().getURI();
          if (toURI.isSipURI() == false) continue;
          String toHost = ((SipURI) toURI).getHost();

          // logger.trace(toHost + "***" + ourHost);
          if (toHost.equals(ourHost)) {
            if (logger.isTraceEnabled())
              logger.trace(
                  "Will dispatch to \""
                      + candidate.getAccountID()
                      + "\" because "
                      + "host in the To: is the same as in our AOR");
            return candidate;
          }
        }

        // fallback on the first candidate
        ProtocolProviderServiceSipImpl target = candidates.iterator().next();
        logger.info(
            "Will randomly dispatch to \""
                + target.getAccountID()
                + "\" because there is ambiguity on the username from"
                + " the Request-URI");
        if (logger.isTraceEnabled()) logger.trace("\n" + request);
        return target;
      }

      // fallback on any account
      ProtocolProviderServiceSipImpl target = currentListenersCopy.iterator().next();
      if (logger.isDebugEnabled())
        logger.debug(
            "Will randomly dispatch to \""
                + target.getAccountID()
                + "\" because the username in the Request-URI "
                + "is unknown or empty");
      if (logger.isTraceEnabled()) logger.trace("\n" + request);
      return target;
    } else {
      logger.error("Request-URI is not a SIP URI, dropping");
    }
    return null;
  }
示例#16
0
  /**
   * Handles new events.
   *
   * @param obj the event object
   * @param provider the provider
   * @param id the id of the source of the event
   */
  private void handle(EventObject obj, ProtocolProviderService provider, String id) {
    // check if provider - contact exist update message content
    synchronized (recentMessages) {
      ComparableEvtObj existingMsc = null;
      for (ComparableEvtObj msc : recentMessages) {
        if (msc.getProtocolProviderService().equals(provider)
            && msc.getContactAddress().equals(id)) {
          // update
          msc.update(obj);
          updateRecentMessageToHistory(msc);

          existingMsc = msc;
        }
      }

      if (existingMsc != null) {
        Collections.sort(recentMessages);
        oldestRecentMessage = recentMessages.get(recentMessages.size() - 1).getTimestamp();

        if (recentQuery != null) {
          recentQuery.updateContact(existingMsc, existingMsc.getEventObject());
          recentQuery.fireContactChanged(existingMsc);
        }

        return;
      }

      // if missing create source contact
      // and update recent messages, trim and sort
      MessageSourceContact newSourceContact =
          new MessageSourceContact(obj, MessageSourceService.this);
      newSourceContact.initDetails(obj);
      // we have already checked for duplicate
      ComparableEvtObj newMsg = new ComparableEvtObj(obj);
      recentMessages.add(newMsg);

      Collections.sort(recentMessages);
      oldestRecentMessage = recentMessages.get(recentMessages.size() - 1).getTimestamp();

      // trim
      List<ComparableEvtObj> removedItems = null;
      if (recentMessages.size() > numberOfMessages) {
        removedItems =
            new ArrayList<ComparableEvtObj>(
                recentMessages.subList(numberOfMessages, recentMessages.size()));

        recentMessages.removeAll(removedItems);
      }

      // save
      saveRecentMessageToHistory(newMsg);

      // no query nothing to fire
      if (recentQuery == null) return;

      // now fire
      if (removedItems != null) {
        for (ComparableEvtObj msc : removedItems) {
          recentQuery.fireContactRemoved(msc);
        }
      }

      recentQuery.addQueryResult(newSourceContact);
    }
  }
示例#17
0
 /**
  * Returns the number of <tt>Contact</tt> members of this <tt>ContactGroup</tt>
  *
  * @return an int indicating the number of <tt>Contact</tt>s, members of this
  *     <tt>ContactGroup</tt>.
  */
 public int countContacts() {
   return contacts.size();
 }
示例#18
0
  /**
   * Add the ComparableEvtObj, newly added will fire new, for existing fire update and when trimming
   * the list to desired length fire remove for those that were removed
   *
   * @param contactsToAdd
   */
  private void addNewRecentMessages(List<ComparableEvtObj> contactsToAdd) {
    // now find object to fire new, and object to fire remove
    // let us find duplicates and fire update
    List<ComparableEvtObj> duplicates = new ArrayList<ComparableEvtObj>();
    for (ComparableEvtObj msgToAdd : contactsToAdd) {
      if (recentMessages.contains(msgToAdd)) {
        duplicates.add(msgToAdd);

        // save update
        updateRecentMessageToHistory(msgToAdd);
      }
    }
    recentMessages.removeAll(duplicates);

    // now contacts to add has no duplicates, add them all
    boolean changed = recentMessages.addAll(contactsToAdd);

    if (changed) {
      Collections.sort(recentMessages);

      if (recentQuery != null) {
        for (ComparableEvtObj obj : duplicates)
          recentQuery.updateContact(obj, obj.getEventObject());
      }
    }

    if (!recentMessages.isEmpty())
      oldestRecentMessage = recentMessages.get(recentMessages.size() - 1).getTimestamp();

    // trim
    List<ComparableEvtObj> removedItems = null;
    if (recentMessages.size() > numberOfMessages) {
      removedItems =
          new ArrayList<ComparableEvtObj>(
              recentMessages.subList(numberOfMessages, recentMessages.size()));

      recentMessages.removeAll(removedItems);
    }

    if (recentQuery != null) {
      // now fire, removed for all that were in the list
      // and now are removed after trim
      if (removedItems != null) {
        for (ComparableEvtObj msc : removedItems) {
          if (!contactsToAdd.contains(msc)) recentQuery.fireContactRemoved(msc);
        }
      }

      // fire new for all that were added, and not removed after trim
      for (ComparableEvtObj msc : contactsToAdd) {
        if ((removedItems == null || !removedItems.contains(msc)) && !duplicates.contains(msc)) {
          MessageSourceContact newSourceContact =
              new MessageSourceContact(msc.getEventObject(), MessageSourceService.this);
          newSourceContact.initDetails(msc.getEventObject());

          recentQuery.addQueryResult(newSourceContact);
        }
      }

      // if recent messages were changed, indexes have change lets
      // fire event for the last element which will reorder the whole
      // group if needed.
      if (changed) recentQuery.fireContactChanged(recentMessages.get(recentMessages.size() - 1));
    }
  }
示例#19
0
 /**
  * Returns the number of subgroups contained by this <tt>ContactGroup</tt>.
  *
  * @return the number of subGroups currently added to this group.
  */
 public int countSubgroups() {
   return subGroups.size();
 }
示例#20
0
 @Override
 public int getMembersCount() {
   return members.size();
 }