Exemplo n.º 1
0
  /**
   * Publish present status. We search for the highest value in the given interval.
   *
   * @param protocolProvider the protocol provider to which we change the status.
   * @param status the status tu publish.
   */
  public void publishStatus(
      ProtocolProviderService protocolProvider, PresenceStatus status, boolean rememberStatus) {
    OperationSetPresence presence = protocolProvider.getOperationSet(OperationSetPresence.class);

    LoginManager loginManager = GuiActivator.getUIService().getLoginManager();
    RegistrationState registrationState = protocolProvider.getRegistrationState();

    if (registrationState == RegistrationState.REGISTERED
        && presence != null
        && !presence.getPresenceStatus().equals(status)) {
      if (status.isOnline()) {
        new PublishPresenceStatusThread(protocolProvider, presence, status).start();
      } else {
        loginManager.setManuallyDisconnected(true);
        GuiActivator.getUIService().getLoginManager().logoff(protocolProvider);
      }
    } else if (registrationState != RegistrationState.REGISTERED
        && registrationState != RegistrationState.REGISTERING
        && registrationState != RegistrationState.AUTHENTICATING
        && status.isOnline()) {
      GuiActivator.getUIService().getLoginManager().login(protocolProvider);
    } else if (!status.isOnline() && !(registrationState == RegistrationState.UNREGISTERING)) {
      loginManager.setManuallyDisconnected(true);
      GuiActivator.getUIService().getLoginManager().logoff(protocolProvider);
    }

    if (rememberStatus) saveStatusInformation(protocolProvider, status.getStatusName());
  }
  /**
   * Indicates that the given protocol provider has been connected at the given time.
   *
   * @param protocolProvider the <tt>ProtocolProviderService</tt> corresponding to the connected
   *     account
   * @param date the date/time at which the account has connected
   */
  public void protocolProviderConnected(ProtocolProviderService protocolProvider, long date) {

    OperationSetPresence presence = AccountStatusUtils.getProtocolPresenceOpSet(protocolProvider);

    if (presence != null) {
      presence.setAuthorizationHandler(authorizationHandler);
    }

    updateGlobalStatus();
  }
  /**
   * Adds the user interface related to the given protocol provider.
   *
   * @param protocolProvider the protocol provider for which we add the user interface
   */
  public void addProtocolProviderUI(ProtocolProviderService protocolProvider) {
    OperationSetBasicTelephony<?> telOpSet =
        protocolProvider.getOperationSet(OperationSetBasicTelephony.class);

    if (telOpSet != null) {
      telOpSet.addCallListener(androidCallListener);
    }

    OperationSetPresence presenceOpSet =
        protocolProvider.getOperationSet(OperationSetPresence.class);

    if (presenceOpSet != null) {
      presenceOpSet.addProviderPresenceStatusListener(androidPresenceListener);
    }
  }
  /**
   * Send an instant message from the tested operation set and assert reception by the tester agent.
   */
  public void firstTestReceiveMessage() {
    String body = "This is an IM coming from the tester agent" + " on " + new Date().toString();

    ImEventCollector evtCollector = new ImEventCollector();

    // add a msg listener and register to the op set and send an instant
    // msg from the tester agent.
    opSetBasicIM1.addMessageListener(evtCollector);

    Contact testerAgentContact = opSetPresence2.findContactByID(fixture.userID1);

    logger.debug("Will send message " + body + " to: " + testerAgentContact);

    opSetBasicIM2.sendInstantMessage(testerAgentContact, opSetBasicIM2.createMessage(body));

    evtCollector.waitForEvent(10000);

    opSetBasicIM1.removeMessageListener(evtCollector);

    // assert reception of a message event
    assertTrue(
        "No events delivered upon a received message", evtCollector.collectedEvents.size() > 0);

    // assert event instance of Message Received Evt
    assertTrue(
        "Received evt was not an instance of " + MessageReceivedEvent.class.getName(),
        evtCollector.collectedEvents.get(0) instanceof MessageReceivedEvent);

    // assert source contact == testAgent.uin
    MessageReceivedEvent evt = (MessageReceivedEvent) evtCollector.collectedEvents.get(0);
    assertEquals("message sender ", evt.getSourceContact().getAddress(), fixture.userID2);

    // assert messageBody == body
    assertEquals("message body", body, evt.getSourceMessage().getContent());
  }
  /**
   * Removes the user interface related to the given protocol provider.
   *
   * @param protocolProvider the protocol provider to remove
   */
  public void removeProtocolProviderUI(ProtocolProviderService protocolProvider) {
    OperationSetBasicTelephony<?> telOpSet =
        protocolProvider.getOperationSet(OperationSetBasicTelephony.class);

    if (telOpSet != null) {
      telOpSet.removeCallListener(androidCallListener);
    }

    OperationSetPresence presenceOpSet =
        protocolProvider.getOperationSet(OperationSetPresence.class);

    if (presenceOpSet != null) {
      presenceOpSet.removeProviderPresenceStatusListener(androidPresenceListener);
    }

    // Removes all chat session for unregistered provider
    ChatSessionManager.removeAllChatsForProvider(protocolProvider);
  }
Exemplo n.º 6
0
  /**
   * Returns the last status that was stored in the configuration for the given protocol provider.
   *
   * @param protocolProvider the protocol provider
   * @return the last status that was stored in the configuration for the given protocol provider
   */
  public PresenceStatus getLastPresenceStatus(ProtocolProviderService protocolProvider) {
    String lastStatus = getLastStatusString(protocolProvider);

    if (lastStatus != null) {
      OperationSetPresence presence = protocolProvider.getOperationSet(OperationSetPresence.class);

      if (presence == null) return null;

      Iterator<PresenceStatus> i = presence.getSupportedStatusSet();
      PresenceStatus status;

      while (i.hasNext()) {
        status = i.next();
        if (status.getStatusName().equals(lastStatus)) return status;
      }
    }
    return null;
  }
Exemplo n.º 7
0
  /**
   * Adds the account corresponding to the given protocol provider to this menu.
   *
   * @param protocolProvider the protocol provider corresponding to the account to add
   */
  private void addAccount(ProtocolProviderService protocolProvider) {
    OperationSetPresence presence =
        (OperationSetPresence) protocolProvider.getOperationSet(OperationSetPresence.class);

    if (presence == null) {
      StatusSimpleSelector simpleSelector =
          new StatusSimpleSelector(parentSystray, protocolProvider);

      this.accountSelectors.put(protocolProvider.getAccountID(), simpleSelector);
      this.add(simpleSelector);
    } else {
      StatusSelector statusSelector = new StatusSelector(parentSystray, protocolProvider, presence);

      this.accountSelectors.put(protocolProvider.getAccountID(), statusSelector);
      this.add(statusSelector);

      presence.addProviderPresenceStatusListener(new SystrayProviderPresenceStatusListener());
    }
  }
Exemplo n.º 8
0
    public Component getTableCellRendererComponent(
        JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
      ProtocolProviderService pps = (ProtocolProviderService) value;
      OperationSetPresence presence = pps.getOperationSet(OperationSetPresence.class);

      if (presence != null) {
        byte[] protocolStatusImage = presence.getPresenceStatus().getStatusIcon();

        if (protocolStatusImage != null) {
          this.setIcon(new ImageIcon(protocolStatusImage));
        } else {
          this.setIcon(null);
        }
      }

      this.setText(pps.getAccountID().getDisplayName());

      if (isSelected) this.setBackground(table.getSelectionBackground());
      else this.setBackground(UIManager.getColor("Table.background"));

      return this;
    }
  /**
   * Used by functions testing the queryContactStatus method of the presence operation set.
   *
   * @param taStatusLong the icq status as specified by FullUserInfo, that the tester agent should
   *     switch to.
   * @param expectedReturn the PresenceStatus that the presence operation set should see the tester
   *     agent in once it has switched to taStatusLong.
   * @throws java.lang.Exception if querying the status causes some exception.
   */
  public void subtestQueryContactStatus(long taStatusLong, PresenceStatus expectedReturn)
      throws Exception {
    if (!fixture.testerAgent.enterStatus(taStatusLong)) {
      throw new RuntimeException(
          "Tester UserAgent Failed to switch to the " + expectedReturn.getStatusName() + " state.");
    }

    PresenceStatus actualReturn =
        operationSetPresence.queryContactStatus(fixture.testerAgent.getIcqUIN());
    assertEquals(
        "Querying a " + expectedReturn.getStatusName() + " state did not return as expected",
        expectedReturn,
        actualReturn);
  }
  /**
   * Send an instant message from the tester agent and assert reception by the tested implementation
   */
  public void thenTestSendMessage() {
    String body =
        "This is an IM coming from the tested implementation" + " on " + new Date().toString();

    // create the message
    net.java.sip.communicator.service.protocol.Message msg = opSetBasicIM.createMessage(body);

    // register a listener in the op set
    ImEventCollector imEvtCollector = new ImEventCollector();
    opSetBasicIM.addMessageListener(imEvtCollector);

    // register a listener in the tester agent
    JoustSimMessageEventCollector jsEvtCollector = new JoustSimMessageEventCollector();
    fixture.testerAgent.addConversationListener(fixture.ourUserID, jsEvtCollector);

    Contact testerAgentContact = opSetPresence.findContactByID(fixture.testerAgent.getIcqUIN());

    opSetBasicIM.sendInstantMessage(testerAgentContact, msg);

    imEvtCollector.waitForEvent(10000);
    jsEvtCollector.waitForEvent(10000);

    fixture.testerAgent.removeConversationListener(fixture.ourUserID, jsEvtCollector);
    opSetBasicIM.removeMessageListener(imEvtCollector);

    // verify that the message delivered event was dispatched
    assertTrue(
        "No events delivered when sending a message", imEvtCollector.collectedEvents.size() > 0);

    assertTrue(
        "Received evt was not an instance of " + MessageDeliveredEvent.class.getName(),
        imEvtCollector.collectedEvents.get(0) instanceof MessageDeliveredEvent);

    MessageDeliveredEvent evt = (MessageDeliveredEvent) imEvtCollector.collectedEvents.get(0);
    assertEquals(
        "message destination ",
        evt.getDestinationContact().getAddress(),
        fixture.testerAgent.getIcqUIN());

    assertSame("source message", msg, evt.getSourceMessage());

    // verify that the message has successfully arived at the destination
    assertTrue(
        "No messages received by the tester agent", jsEvtCollector.collectedMessageInfo.size() > 0);
    String receivedBody =
        ((MessageInfo) jsEvtCollector.collectedMessageInfo.get(0)).getMessage().getMessageBody();

    assertEquals("received message body", msg.getContent(), receivedBody);
  }
Exemplo n.º 11
0
  /**
   * Publish present status. We search for the highest value in the given interval.
   *
   * @param protocolProvider the protocol provider to which we change the status.
   * @param floorStatusValue the min status value.
   * @param ceilStatusValue the max status value.
   */
  private void publishStatus(
      ProtocolProviderService protocolProvider, int floorStatusValue, int ceilStatusValue) {
    if (!protocolProvider.isRegistered()) return;

    OperationSetPresence presence = protocolProvider.getOperationSet(OperationSetPresence.class);

    if (presence == null) return;

    Iterator<PresenceStatus> statusSet = presence.getSupportedStatusSet();

    PresenceStatus status = null;

    while (statusSet.hasNext()) {
      PresenceStatus currentStatus = statusSet.next();

      if (status == null
          && currentStatus.getStatus() < ceilStatusValue
          && currentStatus.getStatus() >= floorStatusValue) {
        status = currentStatus;
      }

      if (status != null) {
        if (currentStatus.getStatus() < ceilStatusValue
            && currentStatus.getStatus() >= floorStatusValue
            && currentStatus.getStatus() > status.getStatus()) {
          status = currentStatus;
        }
      }
    }

    if (status != null) {
      new PublishPresenceStatusThread(protocolProvider, presence, status).start();

      this.saveStatusInformation(protocolProvider, status.getStatusName());
    }
  }
  /**
   * Create the list to be sure that contacts exchanging messages exists in each other lists
   *
   * @throws Exception
   */
  public void prepareContactList() throws Exception {
    fixture.clearProvidersLists();

    Object o = new Object();
    synchronized (o) {
      o.wait(2000);
    }

    try {
      opSetPresence1.subscribe(fixture.userID2);
    } catch (OperationFailedException ex) {
      // the contact already exist its OK
    }

    try {
      opSetPresence2.subscribe(fixture.userID1);
    } catch (OperationFailedException ex1) {
      // the contact already exist its OK
    }

    synchronized (o) {
      o.wait(2000);
    }
  }
  /** 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);
  }
Exemplo n.º 14
0
  /**
   * Creates an instance of <tt>MetaContactChatTransport</tt> by specifying the parent
   * <tt>chatSession</tt> and the <tt>contact</tt> associated with the transport.
   *
   * @param chatSession the parent <tt>ChatSession</tt>
   * @param contact the <tt>Contact</tt> associated with this transport
   * @param contactResource the <tt>ContactResource</tt> associated with the contact
   * @param isDisplayResourceOnly indicates if only the resource name should be displayed
   */
  public MetaContactChatTransport(
      MetaContactChatSession chatSession,
      Contact contact,
      ContactResource contactResource,
      boolean isDisplayResourceOnly) {
    this.parentChatSession = chatSession;
    this.contact = contact;
    this.contactResource = contactResource;
    this.isDisplayResourceOnly = isDisplayResourceOnly;

    presenceOpSet = contact.getProtocolProvider().getOperationSet(OperationSetPresence.class);

    if (presenceOpSet != null) presenceOpSet.addContactPresenceStatusListener(this);

    // checking this can be slow so make
    // sure its out of our way
    new Thread(
            new Runnable() {
              public void run() {
                checkImCaps();
              }
            })
        .start();
  }
Exemplo n.º 15
0
    @Override
    public void run() {
      try {
        presence.publishPresenceStatus(status, "");
      } catch (IllegalArgumentException e1) {

        logger.error("Error - changing status", e1);
      } catch (IllegalStateException e1) {

        logger.error("Error - changing status", e1);
      } catch (OperationFailedException e1) {
        if (e1.getErrorCode() == OperationFailedException.GENERAL_ERROR) {
          String msgText =
              GuiActivator.getResources()
                  .getI18NString(
                      "service.gui.STATUS_CHANGE_GENERAL_ERROR",
                      new String[] {
                        protocolProvider.getAccountID().getUserID(),
                        protocolProvider.getAccountID().getService()
                      });

          new ErrorDialog(
                  null,
                  GuiActivator.getResources().getI18NString("service.gui.GENERAL_ERROR"),
                  msgText,
                  e1)
              .showDialog();
        } else if (e1.getErrorCode() == OperationFailedException.NETWORK_FAILURE) {
          String msgText =
              GuiActivator.getResources()
                  .getI18NString(
                      "service.gui.STATUS_CHANGE_NETWORK_FAILURE",
                      new String[] {
                        protocolProvider.getAccountID().getUserID(),
                        protocolProvider.getAccountID().getService()
                      });

          new ErrorDialog(
                  null,
                  msgText,
                  GuiActivator.getResources().getI18NString("service.gui.NETWORK_FAILURE"),
                  e1)
              .showDialog();
        } else if (e1.getErrorCode() == OperationFailedException.PROVIDER_NOT_REGISTERED) {
          String msgText =
              GuiActivator.getResources()
                  .getI18NString(
                      "service.gui.STATUS_CHANGE_NETWORK_FAILURE",
                      new String[] {
                        protocolProvider.getAccountID().getUserID(),
                        protocolProvider.getAccountID().getService()
                      });

          new ErrorDialog(
                  null,
                  GuiActivator.getResources().getI18NString("service.gui.NETWORK_FAILURE"),
                  msgText,
                  e1)
              .showDialog();
        }
        logger.error("Error - changing status", e1);
      }
    }
Exemplo n.º 16
0
  /**
   * Publish present status. We search for the highest value in the given interval.
   *
   * <p>change the status.
   *
   * @param globalStatus
   */
  public void publishStatus(GlobalStatusEnum globalStatus) {
    String itemName = globalStatus.getStatusName();

    Iterator<ProtocolProviderService> pProviders =
        GuiActivator.getUIService().getMainFrame().getProtocolProviders();

    while (pProviders.hasNext()) {
      ProtocolProviderService protocolProvider = pProviders.next();

      if (itemName.equals(GlobalStatusEnum.ONLINE_STATUS)) {
        if (!protocolProvider.isRegistered()) {
          saveStatusInformation(protocolProvider, itemName);

          GuiActivator.getUIService().getLoginManager().login(protocolProvider);
        } else {
          OperationSetPresence presence =
              protocolProvider.getOperationSet(OperationSetPresence.class);

          if (presence == null) {
            saveStatusInformation(protocolProvider, itemName);

            continue;
          }

          Iterator<PresenceStatus> statusSet = presence.getSupportedStatusSet();

          while (statusSet.hasNext()) {
            PresenceStatus status = statusSet.next();

            if (status.getStatus() < PresenceStatus.EAGER_TO_COMMUNICATE_THRESHOLD
                && status.getStatus() >= PresenceStatus.AVAILABLE_THRESHOLD) {
              new PublishPresenceStatusThread(protocolProvider, presence, status).start();

              this.saveStatusInformation(protocolProvider, status.getStatusName());

              break;
            }
          }
        }
      } else if (itemName.equals(GlobalStatusEnum.OFFLINE_STATUS)) {
        if (!protocolProvider.getRegistrationState().equals(RegistrationState.UNREGISTERED)
            && !protocolProvider.getRegistrationState().equals(RegistrationState.UNREGISTERING)) {
          OperationSetPresence presence =
              protocolProvider.getOperationSet(OperationSetPresence.class);

          if (presence == null) {
            saveStatusInformation(protocolProvider, itemName);

            GuiActivator.getUIService().getLoginManager().logoff(protocolProvider);

            continue;
          }

          Iterator<PresenceStatus> statusSet = presence.getSupportedStatusSet();

          while (statusSet.hasNext()) {
            PresenceStatus status = statusSet.next();

            if (status.getStatus() < PresenceStatus.ONLINE_THRESHOLD) {
              this.saveStatusInformation(protocolProvider, status.getStatusName());

              break;
            }
          }

          try {
            protocolProvider.unregister();
          } catch (OperationFailedException e1) {
            logger.error(
                "Unable to unregister the protocol provider: "
                    + protocolProvider
                    + " due to the following exception: "
                    + e1);
          }
        }
      } else if (itemName.equals(GlobalStatusEnum.FREE_FOR_CHAT_STATUS)) {
        // we search for highest available status here
        publishStatus(
            protocolProvider, PresenceStatus.AVAILABLE_THRESHOLD, PresenceStatus.MAX_STATUS_VALUE);
      } else if (itemName.equals(GlobalStatusEnum.DO_NOT_DISTURB_STATUS)) {
        // status between online and away is DND
        publishStatus(
            protocolProvider, PresenceStatus.ONLINE_THRESHOLD, PresenceStatus.AWAY_THRESHOLD);
      } else if (itemName.equals(GlobalStatusEnum.AWAY_STATUS)) {
        // a status in the away interval
        publishStatus(
            protocolProvider, PresenceStatus.AWAY_THRESHOLD, PresenceStatus.AVAILABLE_THRESHOLD);
      }
    }
  }
  /**
   * We unsubscribe from presence notification deliveries concerning IcqTesterAgent's presence
   * status and verify that we receive the subscription removed event. We then make the tester agent
   * change status and make sure that no notifications are delivered.
   *
   * @throws java.lang.Exception in case unsubscribing fails.
   */
  public void postTestUnsubscribe() throws Exception {
    logger.debug("Testing Unsubscribe and unsubscription event dispatch.");

    // First create a subscription and verify that it really gets created.
    SubscriptionEventCollector subEvtCollector = new SubscriptionEventCollector();
    operationSetPresence.addSubscriptionListener(subEvtCollector);

    Contact icqTesterAgentContact =
        operationSetPresence.findContactByID(fixture.testerAgent.getIcqUIN());

    assertNotNull(
        "Failed to find an existing subscription for the tester agent", icqTesterAgentContact);

    synchronized (subEvtCollector) {
      operationSetPresence.unsubscribe(icqTesterAgentContact);
      subEvtCollector.waitForEvent(40000);
      // don't want any more events
      operationSetPresence.removeSubscriptionListener(subEvtCollector);
    }

    assertEquals(
        "Subscription event dispatching failed.", 1, subEvtCollector.collectedEvents.size());
    SubscriptionEvent subEvt = (SubscriptionEvent) subEvtCollector.collectedEvents.get(0);

    assertEquals("SubscriptionEvent Source:", icqTesterAgentContact, subEvt.getSource());

    assertEquals(
        "SubscriptionEvent Source Contact:", icqTesterAgentContact, subEvt.getSourceContact());

    assertSame("SubscriptionEvent Source Provider:", fixture.provider, subEvt.getSourceProvider());

    subEvtCollector.collectedEvents.clear();

    // make the user agent tester change its states and make sure we don't
    // get notifications as we're now unsubscribed.
    logger.debug("Testing (lack of) presence notifications.");
    IcqStatusEnum testerAgentOldStatus = fixture.testerAgent.getPresneceStatus();
    IcqStatusEnum testerAgentNewStatus = IcqStatusEnum.FREE_FOR_CHAT;
    long testerAgentNewStatusLong = FullUserInfo.ICQSTATUS_FFC;

    // in case we are by any chance already in a FREE_FOR_CHAT status, we'll
    // be changing to something else
    if (testerAgentOldStatus.equals(testerAgentNewStatus)) {
      testerAgentNewStatus = IcqStatusEnum.DO_NOT_DISTURB;
      testerAgentNewStatusLong = FullUserInfo.ICQSTATUS_DND;
    }

    // now do the actual status notification testing
    ContactPresenceEventCollector contactPresEvtCollector =
        new ContactPresenceEventCollector(fixture.testerAgent.getIcqUIN(), null);
    operationSetPresence.addContactPresenceStatusListener(contactPresEvtCollector);

    synchronized (contactPresEvtCollector) {
      if (!fixture.testerAgent.enterStatus(testerAgentNewStatusLong)) {
        throw new RuntimeException(
            "Tester UserAgent Failed to switch to the "
                + testerAgentNewStatus.getStatusName()
                + " state.");
      }
      // we may already have the event, but it won't hurt to check.
      contactPresEvtCollector.waitForEvent(10000);
      operationSetPresence.removeContactPresenceStatusListener(contactPresEvtCollector);
    }

    assertEquals(
        "Presence Notifications were received after unsubscibing.",
        0,
        contactPresEvtCollector.collectedEvents.size());
  }
  /**
   * The method would add a subscription for a contact, wait for a subscription event confirming the
   * subscription, then change the status of the newly added contact (which is actually the
   * IcqTesterAgent) and make sure that the corresponding notification events have been generated.
   *
   * @throws java.lang.Exception if an exception occurs during testing.
   */
  public void postTestSubscribe() throws Exception {
    logger.debug("Testing Subscription and Subscription Event Dispatch.");

    // First create a subscription and verify that it really gets created.
    SubscriptionEventCollector subEvtCollector = new SubscriptionEventCollector();

    logger.trace("set Auth Handler");
    operationSetPresence.setAuthorizationHandler(authEventCollector);

    synchronized (authEventCollector) {
      authEventCollector.authorizationRequestReason = "Please deny my request!";
      fixture.testerAgent.getAuthCmdFactory().responseReasonStr =
          "First authorization I will Deny!!!";
      fixture.testerAgent.getAuthCmdFactory().ACCEPT = false;
      operationSetPresence.subscribe(fixture.testerAgent.getIcqUIN());

      // this one collects event that the buddy has been added
      // to the list as awaiting
      SubscriptionEventCollector moveEvtCollector = new SubscriptionEventCollector();
      operationSetPresence.addSubscriptionListener(moveEvtCollector);

      logger.debug("Waiting for authorization error and authorization response...");
      authEventCollector.waitForAuthResponse(15000);
      assertTrue(
          "Error adding buddy not recieved or the buddy("
              + fixture.testerAgent.getIcqUIN()
              + ") doesn't require authorization",
          authEventCollector.isAuthorizationRequestSent);

      assertNotNull(
          "Agent haven't received any reason for authorization",
          fixture.testerAgent.getAuthCmdFactory().requestReasonStr);
      assertEquals(
          "Error sent request reason is not as the received one",
          authEventCollector.authorizationRequestReason,
          fixture.testerAgent.getAuthCmdFactory().requestReasonStr);

      logger.debug(
          "authEventCollector.isAuthorizationResponseReceived "
              + authEventCollector.isAuthorizationResponseReceived);

      assertTrue("Response not received!", authEventCollector.isAuthorizationResponseReceived);

      boolean isAcceptedAuthReuest =
          authEventCollector.response.getResponseCode().equals(AuthorizationResponse.ACCEPT);
      assertEquals(
          "Response is not as the sent one",
          fixture.testerAgent.getAuthCmdFactory().ACCEPT,
          isAcceptedAuthReuest);
      assertNotNull(
          "We didn't receive any reason! ", authEventCollector.authorizationResponseString);

      assertEquals(
          "The sent response reason is not as the received one",
          fixture.testerAgent.getAuthCmdFactory().responseReasonStr,
          authEventCollector.authorizationResponseString);

      // here we must wait for server to move the awaiting buddy
      // to the first specified  group
      synchronized (moveEvtCollector) {
        moveEvtCollector.waitForEvent(20000);
        // don't want any more events
        operationSetPresence.removeSubscriptionListener(moveEvtCollector);
      }

      Contact c = operationSetPresence.findContactByID(fixture.testerAgent.getIcqUIN());
      logger.debug("I will remove " + c + " from group : " + c.getParentContactGroup());

      UnsubscribeWait unsubscribeEvtCollector = new UnsubscribeWait();
      operationSetPresence.addSubscriptionListener(unsubscribeEvtCollector);

      synchronized (unsubscribeEvtCollector) {
        operationSetPresence.unsubscribe(c);
        logger.debug("Waiting to be removed...");
        unsubscribeEvtCollector.waitForUnsubscribre(20000);

        logger.debug("Received unsubscribed ok or we lost patients!");

        // don't want any more events
        operationSetPresence.removeSubscriptionListener(unsubscribeEvtCollector);
      }

      // so we haven't asserted so everithing is fine lets try to be authorized
      authEventCollector.authorizationRequestReason = "Please accept my request!";
      fixture.testerAgent.getAuthCmdFactory().responseReasonStr =
          "Second authorization I will Accept!!!";
      fixture.testerAgent.getAuthCmdFactory().ACCEPT = true;

      // clear some things
      authEventCollector.isAuthorizationRequestSent = false;
      authEventCollector.isAuthorizationResponseReceived = false;
      authEventCollector.authorizationResponseString = null;

      logger.debug(
          "I will add buddy does it exists ?  "
              + (operationSetPresence.findContactByID(fixture.testerAgent.getIcqUIN()) != null));
      // add the listener beacuse now our authorization will be accepted
      // and so the buddy will be finally added to the list
      operationSetPresence.addSubscriptionListener(subEvtCollector);
      // subscribe again so we can trigger again the authorization procedure
      operationSetPresence.subscribe(fixture.testerAgent.getIcqUIN());

      logger.debug(
          "Waiting ... Subscribe must fail and the authorization process "
              + "to be trigered again so waiting for auth response ...");
      authEventCollector.waitForAuthResponse(15000);

      assertTrue(
          "Error adding buddy not recieved or the buddy("
              + fixture.testerAgent.getIcqUIN()
              + ") doesn't require authorization",
          authEventCollector.isAuthorizationRequestSent);

      assertNotNull(
          "Agent haven't received any reason for authorization",
          fixture.testerAgent.getAuthCmdFactory().requestReasonStr);

      // not working for now
      assertEquals(
          "Error sent request reason",
          authEventCollector.authorizationRequestReason,
          fixture.testerAgent.getAuthCmdFactory().requestReasonStr);

      // wait for authorization process to be finnished
      // the modification of buddy (server will inform us
      // that he removed - awaiting authorization flag)
      Object obj = new Object();
      synchronized (obj) {
        logger.debug("wait for authorization process to be finnished");
        obj.wait(10000);
        logger.debug("Stop waiting!");
      }

      subEvtCollector.waitForEvent(10000);
      // don't want any more events
      operationSetPresence.removeSubscriptionListener(subEvtCollector);
    }

    // after adding awaitingAuthorization group here are catched 3 events
    // 1 - creating unresolved contact
    // 2 - move of the contact to awaitingAuthorization group
    // 3 - move of the contact from awaitingAuthorization group to original group
    assertTrue(
        "Subscription event dispatching failed.", subEvtCollector.collectedEvents.size() > 0);

    EventObject evt = null;

    Iterator<EventObject> events = subEvtCollector.collectedEvents.iterator();
    while (events.hasNext()) {
      EventObject elem = events.next();
      if (elem instanceof SubscriptionEvent) {
        if (((SubscriptionEvent) elem).getEventID() == SubscriptionEvent.SUBSCRIPTION_CREATED)
          evt = (SubscriptionEvent) elem;
      }
    }

    Object source = null;
    Contact srcContact = null;
    ProtocolProviderService srcProvider = null;

    // the event can be SubscriptionEvent and the new added one
    // SubscriptionMovedEvent

    if (evt instanceof SubscriptionEvent) {
      SubscriptionEvent subEvt = (SubscriptionEvent) evt;

      source = subEvt.getSource();
      srcContact = subEvt.getSourceContact();
      srcProvider = subEvt.getSourceProvider();
    }

    assertEquals(
        "SubscriptionEvent Source:",
        fixture.testerAgent.getIcqUIN(),
        ((Contact) source).getAddress());
    assertEquals(
        "SubscriptionEvent Source Contact:",
        fixture.testerAgent.getIcqUIN(),
        srcContact.getAddress());
    assertSame("SubscriptionEvent Source Provider:", fixture.provider, srcProvider);

    subEvtCollector.collectedEvents.clear();

    // make the user agent tester change its states and make sure we are
    // notified
    logger.debug("Testing presence notifications.");
    IcqStatusEnum testerAgentOldStatus = fixture.testerAgent.getPresneceStatus();
    IcqStatusEnum testerAgentNewStatus = IcqStatusEnum.FREE_FOR_CHAT;
    long testerAgentNewStatusLong = FullUserInfo.ICQSTATUS_FFC;

    // in case we are by any chance already in a FREE_FOR_CHAT status, we'll
    // be changing to something else
    if (testerAgentOldStatus.equals(testerAgentNewStatus)) {
      testerAgentNewStatus = IcqStatusEnum.DO_NOT_DISTURB;
      testerAgentNewStatusLong = FullUserInfo.ICQSTATUS_DND;
    }

    // now do the actual status notification testing
    ContactPresenceEventCollector contactPresEvtCollector =
        new ContactPresenceEventCollector(fixture.testerAgent.getIcqUIN(), testerAgentNewStatus);
    operationSetPresence.addContactPresenceStatusListener(contactPresEvtCollector);

    synchronized (contactPresEvtCollector) {
      if (!fixture.testerAgent.enterStatus(testerAgentNewStatusLong)) {
        throw new RuntimeException(
            "Tester UserAgent Failed to switch to the "
                + testerAgentNewStatus.getStatusName()
                + " state.");
      }
      // we may already have the event, but it won't hurt to check.
      contactPresEvtCollector.waitForEvent(12000);
      operationSetPresence.removeContactPresenceStatusListener(contactPresEvtCollector);
    }

    if (contactPresEvtCollector.collectedEvents.size() == 0) {
      logger.info(
          "PROBLEM. Authorisation process doesn't have finnished "
              + "Server doesn't report us for changing authorization flag! Will try to authorize once again");

      fixture.testerAgent.sendAuthorizationReplay(
          fixture.icqAccountID.getUserID(),
          fixture.testerAgent.getAuthCmdFactory().responseReasonStr,
          fixture.testerAgent.getAuthCmdFactory().ACCEPT);

      Object obj = new Object();
      synchronized (obj) {
        logger.debug("wait for authorization process to be finnished for second time");
        obj.wait(10000);
        logger.debug("Stop waiting!");
      }

      testerAgentOldStatus = fixture.testerAgent.getPresneceStatus();
      testerAgentNewStatusLong = FullUserInfo.ICQSTATUS_FFC;

      // in case we are by any chance already in a FREE_FOR_CHAT status, we'll
      // be changing to something else
      if (testerAgentOldStatus.equals(testerAgentNewStatus)) {
        testerAgentNewStatus = IcqStatusEnum.OCCUPIED;
        testerAgentNewStatusLong = FullUserInfo.ICQSTATUS_OCCUPIED;
      }

      contactPresEvtCollector =
          new ContactPresenceEventCollector(fixture.testerAgent.getIcqUIN(), testerAgentNewStatus);
      operationSetPresence.addContactPresenceStatusListener(contactPresEvtCollector);

      synchronized (contactPresEvtCollector) {
        if (!fixture.testerAgent.enterStatus(testerAgentNewStatusLong)) {
          throw new RuntimeException(
              "Tester UserAgent Failed to switch to the "
                  + testerAgentNewStatus.getStatusName()
                  + " state.");
        }
        // we may already have the event, but it won't hurt to check.
        contactPresEvtCollector.waitForEvent(12000);
        operationSetPresence.removeContactPresenceStatusListener(contactPresEvtCollector);
      }
    }

    assertEquals(
        "Presence Notif. event dispatching failed.",
        1,
        contactPresEvtCollector.collectedEvents.size());
    ContactPresenceStatusChangeEvent presEvt =
        (ContactPresenceStatusChangeEvent) contactPresEvtCollector.collectedEvents.get(0);

    assertEquals(
        "Presence Notif. event  Source:",
        fixture.testerAgent.getIcqUIN(),
        ((Contact) presEvt.getSource()).getAddress());
    assertEquals(
        "Presence Notif. event  Source Contact:",
        fixture.testerAgent.getIcqUIN(),
        presEvt.getSourceContact().getAddress());
    assertSame(
        "Presence Notif. event  Source Provider:", fixture.provider, presEvt.getSourceProvider());

    PresenceStatus reportedNewStatus = presEvt.getNewStatus();
    PresenceStatus reportedOldStatus = presEvt.getOldStatus();

    assertEquals("Reported new PresenceStatus: ", testerAgentNewStatus, reportedNewStatus);

    // don't require equality between the reported old PresenceStatus and
    // the actual presence status of the tester agent because a first
    // notification is not supposed to have the old status as it really was.
    assertNotNull("Reported old PresenceStatus: ", reportedOldStatus);

    /** @todo tester agent changes status message we see the new message */
    /** @todo we should see the alias of the tester agent. */
    Object obj = new Object();
    synchronized (obj) {
      logger.debug("wait a moment. give time to server");
      obj.wait(4000);
    }
  }
Exemplo n.º 19
0
 /** Removes all previously added listeners. */
 public void dispose() {
   if (presenceOpSet != null) presenceOpSet.removeContactPresenceStatusListener(this);
 }
  /**
   * Send an instant message from the tester agent and assert reception by the tested implementation
   */
  public void thenTestSendMessage() {
    logger.debug(
        "Printing Server Stored list to see if message fails are contacts in each other lists");
    ContactGroup rootGroup1 =
        ((OperationSetPersistentPresence) opSetPresence1).getServerStoredContactListRoot();

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

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

    ContactGroup rootGroup2 =
        ((OperationSetPersistentPresence) opSetPresence2).getServerStoredContactListRoot();

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

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

    String body =
        "This is an IM coming from the tested implementation" + " on " + new Date().toString();

    // create the message
    net.java.sip.communicator.service.protocol.Message msg = opSetBasicIM1.createMessage(body);

    // register a listener in the op set
    ImEventCollector imEvtCollector1 = new ImEventCollector();
    opSetBasicIM1.addMessageListener(imEvtCollector1);

    // register a listener in the tester agent
    ImEventCollector imEvtCollector2 = new ImEventCollector();
    opSetBasicIM2.addMessageListener(imEvtCollector2);

    Contact testerAgentContact = opSetPresence1.findContactByID(fixture.userID2);

    opSetBasicIM1.sendInstantMessage(testerAgentContact, msg);

    imEvtCollector1.waitForEvent(10000);
    imEvtCollector2.waitForEvent(10000);

    opSetBasicIM1.removeMessageListener(imEvtCollector1);
    opSetBasicIM2.removeMessageListener(imEvtCollector2);

    // verify that the message delivered event was dispatched
    assertTrue(
        "No events delivered when sending a message", imEvtCollector1.collectedEvents.size() > 0);

    assertTrue(
        "Received evt was not an instance of " + MessageDeliveredEvent.class.getName(),
        imEvtCollector1.collectedEvents.get(0) instanceof MessageDeliveredEvent);

    MessageDeliveredEvent evt = (MessageDeliveredEvent) imEvtCollector1.collectedEvents.get(0);
    assertEquals("message destination ", evt.getDestinationContact().getAddress(), fixture.userID2);

    assertSame("source message", msg, evt.getSourceMessage());

    // verify that the message has successfully arived at the destination
    assertTrue(
        "No messages received by the tester agent", imEvtCollector2.collectedEvents.size() > 0);

    assertFalse(
        "Message was unable to deliver !",
        imEvtCollector2.collectedEvents.get(0) instanceof MessageDeliveryFailedEvent);

    String receivedBody =
        ((MessageReceivedEvent) imEvtCollector2.collectedEvents.get(0))
            .getSourceMessage()
            .getContent();

    assertEquals("received message body", msg.getContent(), receivedBody);
  }
Exemplo n.º 21
0
  /** Initializes the <tt>NewStatusMessageDialog</tt> by adding the buttons, fields, etc. */
  private void init() {
    JLabel messageLabel =
        new JLabel(GuiActivator.getResources().getI18NString("service.gui.NEW_STATUS_MESSAGE"));

    JPanel dataPanel = new TransparentPanel(new BorderLayout(5, 5));

    JTextArea infoArea =
        new JTextArea(GuiActivator.getResources().getI18NString("service.gui.STATUS_MESSAGE_INFO"));

    JLabel infoTitleLabel =
        new JLabel(GuiActivator.getResources().getI18NString("service.gui.NEW_STATUS_MESSAGE"));

    JPanel labelsPanel = new TransparentPanel(new GridLayout(0, 1));

    JButton okButton = new JButton(GuiActivator.getResources().getI18NString("service.gui.OK"));

    JPanel buttonsPanel = new TransparentPanel(new FlowLayout(FlowLayout.RIGHT));

    this.setTitle(GuiActivator.getResources().getI18NString("service.gui.NEW_STATUS_MESSAGE"));

    this.getRootPane().setDefaultButton(okButton);

    this.setPreferredSize(new Dimension(500, 200));

    infoArea.setEditable(false);
    infoArea.setLineWrap(true);
    infoArea.setWrapStyleWord(true);
    infoArea.setOpaque(false);

    dataPanel.add(messageLabel, BorderLayout.WEST);

    messageTextField.setText(presenceOpSet.getCurrentStatusMessage());
    dataPanel.add(messageTextField, BorderLayout.CENTER);

    infoTitleLabel.setHorizontalAlignment(JLabel.CENTER);
    infoTitleLabel.setFont(infoTitleLabel.getFont().deriveFont(Font.BOLD, 18.0f));

    labelsPanel.add(infoTitleLabel);
    labelsPanel.add(infoArea);
    labelsPanel.add(dataPanel);

    messagePanel = new TransparentPanel(new GridBagLayout());
    GridBagConstraints messagePanelConstraints = new GridBagConstraints();
    messagePanelConstraints.anchor = GridBagConstraints.NORTHWEST;
    messagePanelConstraints.fill = GridBagConstraints.NONE;
    messagePanelConstraints.gridx = 0;
    messagePanelConstraints.gridy = 0;
    messagePanelConstraints.insets = new Insets(5, 0, 5, 10);
    messagePanelConstraints.weightx = 0;
    messagePanelConstraints.weighty = 0;
    messagePanel.add(
        new ImageCanvas(ImageLoader.getImage(ImageLoader.RENAME_DIALOG_ICON)),
        messagePanelConstraints);

    messagePanelConstraints.anchor = GridBagConstraints.NORTH;
    messagePanelConstraints.fill = GridBagConstraints.HORIZONTAL;
    messagePanelConstraints.gridx = 1;
    messagePanelConstraints.insets = new Insets(0, 0, 0, 0);
    messagePanelConstraints.weightx = 1;
    messagePanel.add(labelsPanel, messagePanelConstraints);

    okButton.setName("ok");
    cancelButton.setName("cancel");

    okButton.setMnemonic(GuiActivator.getResources().getI18nMnemonic("service.gui.OK"));
    cancelButton.setMnemonic(GuiActivator.getResources().getI18nMnemonic("service.gui.CANCEL"));

    okButton.addActionListener(this);
    cancelButton.addActionListener(this);

    buttonsPanel.add(okButton);
    buttonsPanel.add(cancelButton);

    JPanel mainPanel = new TransparentPanel(new GridBagLayout());
    mainPanel.setBorder(BorderFactory.createEmptyBorder(5, 10, 0, 10));

    GridBagConstraints mainPanelConstraints = new GridBagConstraints();
    mainPanelConstraints.anchor = GridBagConstraints.NORTH;
    mainPanelConstraints.fill = GridBagConstraints.BOTH;
    mainPanelConstraints.gridx = 0;
    mainPanelConstraints.gridy = 0;
    mainPanelConstraints.weightx = 1;
    mainPanelConstraints.weighty = 1;
    mainPanel.add(messagePanel, mainPanelConstraints);

    mainPanelConstraints.anchor = GridBagConstraints.SOUTHEAST;
    mainPanelConstraints.fill = GridBagConstraints.NONE;
    mainPanelConstraints.gridy = 1;
    mainPanelConstraints.weightx = 0;
    mainPanelConstraints.weighty = 0;
    mainPanel.add(buttonsPanel, mainPanelConstraints);

    this.getContentPane().add(mainPanel);
  }
  /**
   * Used by methods testing state transiotions
   *
   * @param newStatus the IcqStatusEnum field corresponding to the status that we'd like the
   *     opeation set to enter.
   * @throws Exception in case changing the state causes an exception
   */
  public void subtestStateTransition(IcqStatusEnum newStatus) throws Exception {
    logger.trace(" --=== beginning state transition test ===--");

    PresenceStatus oldStatus = operationSetPresence.getPresenceStatus();
    String oldStatusMessage = operationSetPresence.getCurrentStatusMessage();
    String newStatusMessage = statusMessageRoot + newStatus;

    logger.debug(
        "old status is=" + oldStatus.getStatusName() + " new status=" + newStatus.getStatusName());

    // First register a listener to make sure that all corresponding
    // events have been generated.
    PresenceStatusEventCollector statusEventCollector = new PresenceStatusEventCollector();
    operationSetPresence.addProviderPresenceStatusListener(statusEventCollector);

    // change the status
    operationSetPresence.publishPresenceStatus(newStatus, newStatusMessage);

    // test event notification.
    statusEventCollector.waitForPresEvent(10000);
    statusEventCollector.waitForStatMsgEvent(10000);

    // sometimes we don't get response from the server for the
    // changed status. we will query it once again.
    // and wait for the response
    if (statusEventCollector.collectedPresEvents.size() == 0) {
      logger.trace("Will query again status as we haven't received one");
      operationSetPresence.queryContactStatus(fixture.icqAccountID.getUserID());
      statusEventCollector.waitForPresEvent(10000);
    }

    operationSetPresence.removeProviderPresenceStatusListener(statusEventCollector);

    assertEquals(
        "Events dispatched during an event transition.",
        1,
        statusEventCollector.collectedPresEvents.size());
    assertEquals(
        "A status changed event contained wrong old status.",
        oldStatus,
        ((ProviderPresenceStatusChangeEvent) statusEventCollector.collectedPresEvents.get(0))
            .getOldStatus());
    assertEquals(
        "A status changed event contained wrong new status.",
        newStatus,
        ((ProviderPresenceStatusChangeEvent) statusEventCollector.collectedPresEvents.get(0))
            .getNewStatus());

    // verify that the operation set itself is aware of the status change
    assertEquals(
        "opSet.getPresenceStatus() did not return properly.",
        newStatus,
        operationSetPresence.getPresenceStatus());

    IcqStatusEnum actualStatus =
        fixture.testerAgent.getBuddyStatus(fixture.icqAccountID.getUserID());
    assertEquals(
        "The underlying implementation did not switch to the " + "requested presence status.",
        newStatus,
        actualStatus);

    // check whether the server returned the status message that we've set.
    assertEquals(
        "No status message events.", 1, statusEventCollector.collectedStatMsgEvents.size());
    assertEquals(
        "A status message event contained wrong old value.",
        oldStatusMessage,
        ((PropertyChangeEvent) statusEventCollector.collectedStatMsgEvents.get(0)).getOldValue());
    assertEquals(
        "A status message event contained wrong new value.",
        newStatusMessage,
        ((PropertyChangeEvent) statusEventCollector.collectedStatMsgEvents.get(0)).getNewValue());

    // verify that the operation set itself is aware of the new status msg.
    assertEquals(
        "opSet.getCurrentStatusMessage() did not return properly.",
        newStatusMessage,
        operationSetPresence.getCurrentStatusMessage());

    logger.trace(" --=== finished test ===--");
    // make it sleep a bit cause the aol server gets mad otherwise.
    pauseBetweenStateChanges();
  }