Ejemplo n.º 1
0
  @Test
  public void isModeAwayTest() {
    Presence presence = getNewPresence();
    presence.setMode(Presence.Mode.away);
    assertTrue(presence.isAway());

    presence.setMode(Presence.Mode.chat);
    assertFalse(presence.isAway());
  }
Ejemplo n.º 2
0
  @Test
  public void isPresenceAvailableTest() {
    Presence presence = getNewPresence();
    presence.setType(Presence.Type.available);
    assertTrue(presence.isAvailable());

    presence.setType(Presence.Type.unavailable);
    assertFalse(presence.isAvailable());
  }
Ejemplo n.º 3
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);
 }
Ejemplo n.º 4
0
  /**
   * Returns true if the workgroup is available for receiving new requests. The workgroup will be
   * available only when agents are available for this workgroup.
   *
   * @return true if the workgroup is available for receiving new requests.
   * @throws XMPPException
   */
  public boolean isAvailable() throws XMPPException {
    Presence directedPresence = new Presence(Presence.Type.available);
    directedPresence.setTo(workgroupJID);
    PacketFilter typeFilter = new PacketTypeFilter(Presence.class);
    PacketFilter fromFilter = FromMatchesFilter.create(workgroupJID);
    PacketCollector collector =
        connection.createPacketCollector(new AndFilter(fromFilter, typeFilter));

    connection.sendPacket(directedPresence);

    Presence response = (Presence) collector.nextResultOrThrow();
    return Presence.Type.available == response.getType();
  }
Ejemplo n.º 5
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;
  }
Ejemplo n.º 6
0
  @Test
  public void setPresenceTypeTest() throws IOException, SAXException, ParserConfigurationException {
    Presence.Type type = Presence.Type.unavailable;
    Presence.Type type2 = Presence.Type.subscribe;

    StringBuilder controlBuilder = new StringBuilder();
    controlBuilder
        .append("<presence")
        .append(" type=\"")
        .append(type)
        .append("\">")
        .append("</presence>");
    String control = controlBuilder.toString();

    Presence presenceTypeInConstructor = new Presence(type);
    presenceTypeInConstructor.setPacketID(Packet.ID_NOT_AVAILABLE);
    assertEquals(type, presenceTypeInConstructor.getType());
    assertXMLEqual(control, presenceTypeInConstructor.toXML());

    controlBuilder = new StringBuilder();
    controlBuilder
        .append("<presence")
        .append(" type=\"")
        .append(type2)
        .append("\">")
        .append("</presence>");
    control = controlBuilder.toString();

    Presence presenceTypeSet = getNewPresence();
    presenceTypeSet.setType(type2);
    assertEquals(type2, presenceTypeSet.getType());
    assertXMLEqual(control, presenceTypeSet.toXML());
  }
Ejemplo n.º 7
0
  @Test
  public void presenceXmlLangTest() throws IOException, SAXException, ParserConfigurationException {
    final String lang = "sp";

    StringBuilder controlBuilder = new StringBuilder();
    controlBuilder
        .append("<presence")
        .append(" xml:lang=\"")
        .append(lang)
        .append("\">")
        .append("</presence>");
    String control = controlBuilder.toString();

    Presence presence = getNewPresence();
    presence.setLanguage(lang);

    assertXMLEqual(control, presence.toXML());
  }
Ejemplo n.º 8
0
  @Test
  public void setPresencePriorityTest()
      throws IOException, SAXException, ParserConfigurationException {
    final int priority = 10;

    StringBuilder controlBuilder = new StringBuilder();
    controlBuilder
        .append("<presence>")
        .append("<priority>")
        .append(priority)
        .append("</priority>")
        .append("</presence>");
    String control = controlBuilder.toString();

    Presence presence = getNewPresence();
    presence.setPriority(priority);

    assertEquals(priority, presence.getPriority());
    assertXMLEqual(control, presence.toXML());
  }
Ejemplo n.º 9
0
  public String getToolTipText(MouseEvent ev) {
    if (ev == null) return null;
    TreePath path = getPathForLocation(ev.getX(), ev.getY());
    if (path != null) {
      JIDStatus jidStatus = null;
      Object o = path.getLastPathComponent();
      if (o instanceof PrimaryJIDStatus) {
        jidStatus = ((PrimaryJIDStatus) o).getJIDPrimaryStatus();
      }
      if (o instanceof JIDStatus) {
        jidStatus = ((JIDStatus) o);
      } else {
        return null;
      }
      String statusMsg;
      if (jidStatus.getStatus() != null) {
        statusMsg =
            I18N.gettext("main.main.statusmenu.Status_message:")
                + " "
                + jidStatus.getStatus()
                + "</p><p>";
      } else {
        statusMsg = "";
      }

      String waitingStatus = jidStatus.getWaiting();
      if (jidStatus.getWaiting() != null) {
        waitingStatus =
            "<p>"
                + I18N.gettext("main.main.roster.Waiting_Status:")
                + " "
                + jidStatus.getWaiting()
                + "</p>";
      } else {
        waitingStatus = "";
      }
      return "<HTML><P>"
          + I18N.gettext("main.main.roster.Status:")
          + " "
          + Presence.toLongShow(jidStatus.getShow())
          + "</p><p>"
          + statusMsg
          + "JID: "
          + jidStatus.getCompleteJID()
          + "</p><p>"
          + I18N.gettext("main.main.roster.Subscription:")
          + " "
          + jidStatus.getSubscription()
          + "</p>"
          + waitingStatus
          + "</p></HTML>";
    }
    return null;
  }
Ejemplo n.º 10
0
  @Test
  public void setPresenceStatusTest()
      throws IOException, SAXException, ParserConfigurationException {
    final String status = "This is a test of the emergency broadcast system.";

    StringBuilder controlBuilder = new StringBuilder();
    controlBuilder
        .append("<presence>")
        .append("<status>")
        .append(status)
        .append("</status>")
        .append("</presence>");
    String control = controlBuilder.toString();

    Presence presence = getNewPresence();
    presence.setStatus(status);

    assertEquals(status, presence.getStatus());
    assertXMLEqual(control, presence.toXML());
  }
Ejemplo n.º 11
0
 private void process(Presence presence) {
   if (presence.getType() == Presence.Type.unavailable) {
     MUCRole mucRole = room.getOccupantByFullJID(realjid);
     if (mucRole != null) {
       room.leaveRoom(mucRole);
     }
   } else {
     throw new UnsupportedOperationException(
         "Cannot process Presence packets of remote users: " + presence);
   }
 }
Ejemplo n.º 12
0
  public void testProcessPacket_When_Packet_Send_To_Group_But_Group_No_Found() throws Exception {
    // Arrange
    final Presence packet = new Presence();
    packet.setFrom(userJid);
    packet.setTo(groupJid);
    groupService.initialize(serviceJid, null);

    new NonStrictExpectations() {
      {
        final GroupManager groupManager = getField(groupService, "groupManager");
        new NonStrictExpectations(groupManager) {
          {
            groupManager.getGroup(groupJid.getNode());
            result = null;
            times = 1;
          }
        };
      }
    };
    new NonStrictExpectations(groupService) {
      {
        groupService.routePacket(
            with(
                new Delegate<Packet>() {
                  public void validate(Packet packet) {
                    assertEquals(groupJid, packet.getFrom());
                    assertEquals(userJid, packet.getTo());
                    assertEquals(
                        PacketError.Condition.item_not_found, packet.getError().getCondition());
                    assertEquals(Presence.class, packet.getClass());
                  }
                }));
        times = 1;
      }
    };

    // Act
    groupService.processPacket(packet);
  }
Ejemplo n.º 13
0
 /**
  * Processes the packet in another thread if the packet has not been rejected.
  *
  * @param packet the received packet.
  */
 protected void processPresence(final Presence packet) throws UnauthorizedException {
   try {
     packetReceived(packet);
     // Process the packet in another thread
     threadPool.execute(
         new Runnable() {
           public void run() {
             try {
               ServerSocketReader.super.processPresence(packet);
             } catch (UnauthorizedException e) {
               Log.error("Error processing packet", e);
             }
           }
         });
   } catch (PacketRejectedException e) {
     Log.debug("Presence rejected: " + packet.toXML(), e);
   }
 }
Ejemplo n.º 14
0
  @Test
  public void setPresenceModeTest() throws IOException, SAXException, ParserConfigurationException {
    Presence.Mode mode1 = Presence.Mode.dnd;
    final int priority = 10;
    final String status = "This is a test of the emergency broadcast system.";
    Presence.Mode mode2 = Presence.Mode.chat;

    StringBuilder controlBuilder = new StringBuilder();
    controlBuilder
        .append("<presence>")
        .append("<status>")
        .append(status)
        .append("</status>")
        .append("<priority>")
        .append(priority)
        .append("</priority>")
        .append("<show>")
        .append(mode1)
        .append("</show>")
        .append("</presence>");
    String control = controlBuilder.toString();

    Presence presenceModeInConstructor =
        new Presence(Presence.Type.available, status, priority, mode1);
    presenceModeInConstructor.setPacketID(Packet.ID_NOT_AVAILABLE);
    assertEquals(mode1, presenceModeInConstructor.getMode());
    assertXMLEqual(control, presenceModeInConstructor.toXML());

    controlBuilder = new StringBuilder();
    controlBuilder
        .append("<presence>")
        .append("<show>")
        .append(mode2)
        .append("</show>")
        .append("</presence>");
    control = controlBuilder.toString();

    Presence presenceModeSet = getNewPresence();
    presenceModeSet.setMode(mode2);
    assertEquals(mode2, presenceModeSet.getMode());
    assertXMLEqual(control, presenceModeSet.toXML());
  }
  /**
   * Sends a file transfer request to the given <tt>toContact</tt>.
   *
   * @return the transfer object
   * @param toContact the contact that should receive the file
   * @param file file to send
   * @param gw special gateway to be used for receiver if its jid misses the domain part
   */
  FileTransfer sendFile(Contact toContact, File file, String gw)
      throws IllegalStateException, IllegalArgumentException, OperationNotSupportedException {
    OutgoingFileTransferJabberImpl outgoingTransfer = null;

    try {
      assertConnected();

      if (file.length() > getMaximumFileLength())
        throw new IllegalArgumentException("File length exceeds the allowed one for this protocol");

      String fullJid = null;
      // Find the jid of the contact which support file transfer
      // and is with highest priority if more than one found
      // if we have equals priorities
      // choose the one that is more available
      OperationSetMultiUserChat mucOpSet =
          jabberProvider.getOperationSet(OperationSetMultiUserChat.class);
      if (mucOpSet != null && mucOpSet.isPrivateMessagingContact(toContact.getAddress())) {
        fullJid = toContact.getAddress();
      } else {
        Iterator<Presence> iter =
            jabberProvider.getConnection().getRoster().getPresences(toContact.getAddress());
        int bestPriority = -1;

        PresenceStatus jabberStatus = null;

        while (iter.hasNext()) {
          Presence presence = iter.next();

          if (jabberProvider.isFeatureListSupported(
              presence.getFrom(),
              new String[] {
                "http://jabber.org/protocol/si",
                "http://jabber.org/protocol/si/profile/file-transfer"
              })) {

            int priority =
                (presence.getPriority() == Integer.MIN_VALUE) ? 0 : presence.getPriority();

            if (priority > bestPriority) {
              bestPriority = priority;
              fullJid = presence.getFrom();
              jabberStatus =
                  OperationSetPersistentPresenceJabberImpl.jabberStatusToPresenceStatus(
                      presence, jabberProvider);
            } else if (priority == bestPriority && jabberStatus != null) {
              PresenceStatus tempStatus =
                  OperationSetPersistentPresenceJabberImpl.jabberStatusToPresenceStatus(
                      presence, jabberProvider);
              if (tempStatus.compareTo(jabberStatus) > 0) {
                fullJid = presence.getFrom();
                jabberStatus = tempStatus;
              }
            }
          }
        }
      }

      // First we check if file transfer is at all supported for this
      // contact.
      if (fullJid == null) {
        throw new OperationNotSupportedException(
            "Contact client or server does not support file transfers.");
      }

      if (gw != null && !fullJid.contains("@") && !fullJid.endsWith(gw)) {
        fullJid = fullJid + "@" + gw;
      }

      OutgoingFileTransfer transfer = manager.createOutgoingFileTransfer(fullJid);

      outgoingTransfer =
          new OutgoingFileTransferJabberImpl(toContact, file, transfer, jabberProvider);

      // Notify all interested listeners that a file transfer has been
      // created.
      FileTransferCreatedEvent event = new FileTransferCreatedEvent(outgoingTransfer, new Date());

      fireFileTransferCreated(event);

      // Send the file through the Jabber file transfer.
      transfer.sendFile(file, "Sending file");

      // Start the status and progress thread.
      new FileTransferProgressThread(transfer, outgoingTransfer).start();
    } catch (XMPPException e) {
      logger.error("Failed to send file.", e);
    }

    return outgoingTransfer;
  }
Ejemplo n.º 16
0
  /**
   * Handles presence stanzas
   *
   * @param presence
   */
  private void handlePresence(Presence presence) {
    // unavailable is sent when user leaves the room
    if (!presence.isAvailable()) {
      return;
    }

    String from = presence.getFrom();
    JitsiMeetConference conference = getConferenceForMucJid(from);

    if (conference == null) {
      if (logger.isDebugEnabled()) {
        logger.debug("Room not found for JID: " + from);
      }
      return;
    }

    ChatRoomMemberRole role = conference.getRoleForMucJid(from);

    if (role != null && role.compareTo(ChatRoomMemberRole.MODERATOR) < 0) {
      StartMutedPacketExtension ext =
          (StartMutedPacketExtension)
              presence.getExtension(
                  StartMutedPacketExtension.ELEMENT_NAME, StartMutedPacketExtension.NAMESPACE);

      if (ext != null) {
        boolean[] startMuted = {ext.getAudioMuted(), ext.getVideoMuted()};

        conference.setStartMuted(startMuted);
      }
    }

    Participant participant = conference.findParticipantForRoomJid(from);
    ColibriConference colibriConference = conference.getColibriConference();

    if (participant != null && colibriConference != null) {
      // Check if this conference is valid
      String conferenceId = colibriConference.getConferenceId();
      if (StringUtils.isNullOrEmpty(conferenceId)) {
        logger.error("Unable to send DisplayNameChanged event" + " - no conference id");
        return;
      }

      // Check for changes to the display name
      String oldDisplayName = participant.getDisplayName();
      String newDisplayName = null;
      for (PacketExtension pe : presence.getExtensions()) {
        if (pe instanceof Nick) {
          newDisplayName = ((Nick) pe).getName();
          break;
        }
      }

      if (!Objects.equals(oldDisplayName, newDisplayName)) {
        participant.setDisplayName(newDisplayName);

        EventAdmin eventAdmin = FocusBundleActivator.getEventAdmin();
        if (eventAdmin != null) {
          // Prevent NPE when adding to event hashtable
          if (newDisplayName == null) {
            newDisplayName = "";
          }
          eventAdmin.sendEvent(
              EventFactory.endpointDisplayNameChanged(
                  conferenceId, participant.getEndpointId(), newDisplayName));
        }
      }
    }
  }
Ejemplo n.º 17
0
 private static Presence getNewPresence() {
   Presence presence = new Presence(Presence.Type.available);
   presence.setPacketID(Packet.ID_NOT_AVAILABLE);
   return presence;
 }
Ejemplo n.º 18
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);
      }
    }
  }
Ejemplo n.º 19
0
  /**
   * Parses a presence packet.
   *
   * @param parser the XML parser, positioned at the start of a presence packet.
   * @return a Presence packet.
   * @throws Exception if an exception occurs while parsing the packet.
   */
  public static Presence parsePresence(XmlPullParser parser) throws Exception {
    Presence.Type type = Presence.Type.available;
    String typeString = parser.getAttributeValue("", "type");
    if (typeString != null && !typeString.equals("")) {
      try {
        type = Presence.Type.valueOf(typeString);
      } catch (IllegalArgumentException iae) {
        LOGGER.log(Level.SEVERE, "Found invalid presence type " + typeString);
      }
    }
    Presence presence = new Presence(type);
    presence.setTo(parser.getAttributeValue("", "to"));
    presence.setFrom(parser.getAttributeValue("", "from"));
    String id = parser.getAttributeValue("", "id");
    presence.setPacketID(id == null ? Packet.ID_NOT_AVAILABLE : id);

    String language = getLanguageAttribute(parser);
    if (language != null && !"".equals(language.trim())) {
      presence.setLanguage(language);
    }
    presence.setPacketID(id == null ? Packet.ID_NOT_AVAILABLE : id);

    // Parse sub-elements
    boolean done = false;
    while (!done) {
      int eventType = parser.next();
      if (eventType == XmlPullParser.START_TAG) {
        String elementName = parser.getName();
        String namespace = parser.getNamespace();
        if (elementName.equals("status")) {
          try {
            presence.setStatus(parser.nextText());
          } catch (Throwable t) {
            LOGGER.log(Level.SEVERE, "Error parsing presence status", t);
          }
        } else if (elementName.equals("priority")) {
          try {
            int priority = Integer.parseInt(parser.nextText());
            presence.setPriority(priority);
          } catch (NumberFormatException nfe) {
            // Ignore.
          } catch (IllegalArgumentException iae) {
            // Presence priority is out of range so assume priority to be zero
            presence.setPriority(0);
          }
        } else if (elementName.equals("show")) {
          String modeText = parser.nextText();
          try {
            presence.setMode(Presence.Mode.valueOf(modeText));
          } catch (IllegalArgumentException iae) {
            LOGGER.log(Level.SEVERE, "Found invalid presence mode " + modeText);
          }
        } else if (elementName.equals("error")) {
          presence.setError(parseError(parser));
        } else if (elementName.equals("properties") && namespace.equals(PROPERTIES_NAMESPACE)) {
          Map<String, Object> properties = parseProperties(parser);
          // Set packet properties.
          for (String name : properties.keySet()) {
            presence.setProperty(name, properties.get(name));
          }
        }
        // Otherwise, it must be a packet extension.
        else {
          presence.addExtension(
              PacketParserUtils.parsePacketExtension(elementName, namespace, parser));
        }
      } else if (eventType == XmlPullParser.END_TAG) {
        if (parser.getName().equals("presence")) {
          done = true;
        }
      }
    }
    return presence;
  }