Ejemplo n.º 1
0
 protected void createRoom(Map<String, Object> roomSpec, String serviceName) throws Exception {
   List<String> owners = (List) roomSpec.get("owners");
   JID owner = XMPPServer.getInstance().createJID("admin", null);
   if (owners != null && owners.size() > 0) {
     owner = new JID(owners.get(0));
   } else {
     owners = new ArrayList<String>();
     owners.add(owner.toBareJID());
     roomSpec.put("owners", owners);
   }
   String roomName = (String) roomSpec.get("roomName");
   Boolean isPersistent = (Boolean) roomSpec.get("persistent");
   MUCRoom room =
       XMPPServer.getInstance()
           .getMultiUserChatManager()
           .getMultiUserChatService(serviceName)
           .getChatRoom(roomName.toLowerCase(), owner);
   IntrospectionSupport.setProperties(room, roomSpec);
   room.setRolesToBroadcastPresence(new ArrayList<String>());
   setRoles(room, roomSpec);
   room.setCreationDate(new Date());
   room.setModificationDate(new Date());
   // Unlock the room, because the default configuration lock the room.
   room.unlock(room.getRole());
   System.out.println("isPersistent:" + isPersistent);
   if (isPersistent == null) {
     room.setPersistent(true);
   }
   if (room.isPersistent()) {
     room.saveToDB();
   }
 }
  /**
   * Adds the new user to others roster.
   *
   * @param newUser the new user
   * @param otherItem the other item
   * @param currentUser the current user
   * @throws ServiceException the service exception
   */
  private static void addNewUserToOthersRoster(
      User newUser, RosterItem otherItem, String currentUser) throws ServiceException {
    otherItem.getJid();
    UserManager userManager = UserManager.getInstance();

    // Is this user registered with our OF server?
    String username = otherItem.getJid().getNode();
    if (username != null
        && username.length() > 0
        && userManager.isRegisteredUser(username)
        && XMPPServer.getInstance()
            .isLocal(XMPPServer.getInstance().createJID(currentUser, null))) {
      try {
        User otherUser = userManager.getUser(username);
        Roster otherRoster = otherUser.getRoster();
        RosterItem oldUserOnOthersRoster =
            otherRoster.getRosterItem(XMPPServer.getInstance().createJID(currentUser, null));

        try {
          if (!oldUserOnOthersRoster.isOnlyShared()) {

            RosterItem justCreated =
                otherRoster.createRosterItem(
                    XMPPServer.getInstance().createJID(newUser.getUsername(), null),
                    oldUserOnOthersRoster.getNickname(),
                    oldUserOnOthersRoster.getGroups(),
                    true,
                    true);
            justCreated.setAskStatus(oldUserOnOthersRoster.getAskStatus());
            justCreated.setRecvStatus(oldUserOnOthersRoster.getRecvStatus());
            justCreated.setSubStatus(oldUserOnOthersRoster.getSubStatus());
            otherRoster.updateRosterItem(justCreated);
          }
        } catch (UserAlreadyExistsException e) {
          throw new ServiceException(
              "Could not create roster item for user ",
              newUser.getUsername(),
              ExceptionType.USER_ALREADY_EXISTS_EXCEPTION,
              Response.Status.CONFLICT,
              e);
        } catch (SharedGroupException e) {
          throw new ServiceException(
              "Could not create roster item, because it is a contact from a shared group",
              newUser.getUsername(),
              ExceptionType.USER_ALREADY_EXISTS_EXCEPTION,
              Response.Status.BAD_REQUEST,
              e);
        }
      } catch (UserNotFoundException e) {
        throw new ServiceException(
            "Could not create roster item for user "
                + newUser.getUsername()
                + "  because it is a contact from a shared group.",
            newUser.getUsername(),
            ExceptionType.USER_NOT_FOUND_EXCEPTION,
            Response.Status.NOT_FOUND,
            e);
      }
    }
  }
Ejemplo n.º 3
0
 /**
  * Remove the roster item from the sender's roster (and possibly the recipient's). Actual roster
  * removal is done in the removeItem(Roster,RosterItem) method.
  *
  * @param roster The sender's roster.
  * @param sender The JID of the sender of the removal request
  * @param item The removal item element
  */
 private void removeItem(
     org.jivesoftware.openfire.roster.Roster roster, JID sender, org.xmpp.packet.Roster.Item item)
     throws SharedGroupException {
   JID recipient = item.getJID();
   // Remove recipient from the sender's roster
   roster.deleteRosterItem(item.getJID(), true);
   // Forward set packet to the subscriber
   if (localServer.isLocal(recipient)) { // Recipient is local so let's handle it here
     try {
       Roster recipientRoster = userManager.getUser(recipient.getNode()).getRoster();
       recipientRoster.deleteRosterItem(sender, true);
     } catch (UserNotFoundException e) {
       // Do nothing
     }
   } else {
     // Recipient is remote so we just forward the packet to them
     String serverDomain = localServer.getServerInfo().getXMPPDomain();
     // Check if the recipient may be hosted by this server
     if (!recipient.getDomain().contains(serverDomain)) {
       // TODO Implete when s2s is implemented
     } else {
       Packet removePacket = createRemoveForward(sender, recipient);
       router.route(removePacket);
     }
   }
 }
Ejemplo n.º 4
0
 /**
  * Returns the Clearspace user id the user by JID.
  *
  * @param user JID of user to retrieve ID of.
  * @return The ID number of the user in Clearspace.
  * @throws org.jivesoftware.openfire.user.UserNotFoundException If the user was not found.
  */
 protected long getUserID(JID user) throws UserNotFoundException {
   // User's id are only for local users
   XMPPServer server = XMPPServer.getInstance();
   if (!server.isLocal(user)) {
     throw new UserNotFoundException("Cannot load user of remote server: " + user.toString());
   }
   return getUserID(user.getNode());
 }
 @Override
 public void initialize(XMPPServer server) {
   super.initialize(server);
   infoHandler = server.getIQDiscoInfoHandler();
   itemsHandler = server.getIQDiscoItemsHandler();
   messageStore = server.getOfflineMessageStore();
   userManager = server.getUserManager();
   routingTable = server.getRoutingTable();
 }
Ejemplo n.º 6
0
 public PubSubService getService() {
   if (XMPPServer.getInstance().getPubSubModule().getServiceID().equals(serviceId))
     return XMPPServer.getInstance().getPubSubModule();
   else {
     PEPServiceManager serviceMgr = XMPPServer.getInstance().getIQPEPHandler().getServiceManager();
     return serviceMgr.hasCachedService(new JID(serviceId))
         ? serviceMgr.getPEPService(serviceId)
         : null;
   }
 }
  /**
   * Login to the XMPP server and establish a non-anonymous user session using the given username
   * and resource. When <tt>createIfNotExist</tt> is <tt>true</tt>, a new user with the username
   * will be created and stored in the database if it does not exist. When <tt>false</tt>, and the
   * user does not exist, the method will not attempt the login. Whenever there's an error, the bot
   * will not login.
   *
   * @param username Username to login with.
   * @param resource The resource the user will bind to.
   * @param createIfNotExist When specified as <tt>true</tt>, a new user will be created and stored
   *     in the database if it does not exist.
   * @throws SessionAlreadyExistsException If the bot's session already exists.
   * @throws UserNotFoundException If it fails to create the user.
   */
  public void login(String username, String resource, boolean createIfNotExist)
      throws SessionAlreadyExistsException, UserNotFoundException {
    LOGGER.debug("Bot login with username:{} with resource:{}", username, resource);

    if (isClosed()) throw new SessionAlreadyExistsException();

    JID jid =
        new JID(
            username.toLowerCase(),
            XMPPServer.getInstance().getServerInfo().getXMPPDomain(),
            resource);
    ClientSession oldSession = SessionManager.getInstance().getSession(jid);

    // Check for session conflict
    if (oldSession != null) {
      try {
        int count = oldSession.incrementConflictCount();
        int conflictLimit = SessionManager.getInstance().getConflictKickLimit();
        if (conflictLimit != SessionManager.NEVER_KICK && count > conflictLimit) {
          // Kick out the old connection that is conflicting with the
          // new one
          StreamError error = new StreamError(StreamError.Condition.conflict);
          oldSession.deliverRawText(error.toXML());
          oldSession.close();
        } else throw new SessionAlreadyExistsException();
      } catch (Exception e) {
        LOGGER.error("Error during login", e);
      }
    }

    if (!XMPPServer.getInstance().getUserManager().isRegisteredUser(jid.getNode())) {
      if (createIfNotExist) {
        try {
          // Bot doesn't care of whatever password it is.
          XMPPServer.getInstance()
              .getUserManager()
              .createUser(jid.getNode(), StringUtils.randomString(15), null, null);
        } catch (UserAlreadyExistsException e) {
          // Ignore
        }
      } else {
        throw new UserNotFoundException();
      }
    }

    localClientSession = SessionManager.getInstance().createClientSession(this);

    localClientSession.setAuthToken(new AuthToken(jid.getNode()), jid.getResource());

    if (packetProcessor != null) {
      packetProcessor.initialize(this);
      initProcessor = true;
    }
  }
Ejemplo n.º 8
0
 @Override
 public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
   byte[] bytes = ExternalizableUtil.getInstance().readByteArray(in);
   // Retrieve the NodeID but try to use the singleton instance
   if (XMPPServer.getInstance().getNodeID().equals(bytes)) {
     nodeID = XMPPServer.getInstance().getNodeID();
   } else {
     nodeID = NodeID.getInstance(bytes);
   }
   available = ExternalizableUtil.getInstance().readBoolean(in);
 }
Ejemplo n.º 9
0
  @Override
  public void start() {
    // Set this ComponentManager as the current component manager
    ComponentManagerFactory.setComponentManager(instance);

    XMPPServer server = XMPPServer.getInstance();
    serverDomain = server.getServerInfo().getXMPPDomain();
    // Set the address of this internal service. component.[domain]
    serviceAddress = new JID(null, "component." + serverDomain, null);
    if (!server.isSetupMode()) {
      // Add a route to this service
      server.getRoutingTable().addComponentRoute(getAddress(), this);
    }
  }
Ejemplo n.º 10
0
  public void createChatRoom(
      String domain,
      String ownerJid,
      String roomName,
      boolean listRoomInDirectory,
      boolean makeRoomModerated,
      boolean makeRoomMembersOnly,
      boolean allowOccupantsToInviteOthers,
      boolean isPublicRoom,
      boolean logRoomConversations,
      boolean isPersistent,
      String password,
      String description,
      String conferenceExtension)
      throws Exception {
    MultiUserChatService mucService =
        XMPPServer.getInstance().getMultiUserChatManager().getMultiUserChatService(domain);
    if (mucService == null) {
      mucService =
          XMPPServer.getInstance()
              .getMultiUserChatManager()
              .createMultiUserChatService(domain, description, false);
      Collection<JID> admins = XMPPServer.getInstance().getAdmins();
      JID admin = admins.iterator().next();
      mucService.addUserAllowedToCreate(admin.toBareJID());
    }
    MUCRoom mucRoom = mucService.getChatRoom(roomName, new JID(ownerJid));

    mucRoom.setPersistent(isPersistent);
    mucRoom.setCanAnyoneDiscoverJID(true);
    mucRoom.setChangeNickname(true);
    mucRoom.setModerated(makeRoomModerated);
    mucRoom.setMembersOnly(makeRoomMembersOnly);
    mucRoom.setRegistrationEnabled(true);
    mucRoom.setPublicRoom(isPublicRoom);
    mucRoom.setCanAnyoneDiscoverJID(true);
    mucRoom.setCanOccupantsInvite(allowOccupantsToInviteOthers);
    mucRoom.setDescription(description);
    mucRoom.setPassword(password);
    mucRoom.setCanOccupantsChangeSubject(true);
    mucRoom.setChangeNickname(true);
    mucRoom.setLogEnabled(logRoomConversations);

    mucRoom.setDescription(description);

    mucRoom.setPassword(password);
    /* The conference extension is the voice conf bridge extension */
    this.roomNameToConferenceExtensionMap.put(domain + "." + roomName, conferenceExtension);
  }
Ejemplo n.º 11
0
 public void authenticate(String username, String token, String digest)
     throws UnauthorizedException {
   if (username == null || token == null || digest == null) {
     throw new UnauthorizedException();
   }
   username = username.trim().toLowerCase();
   if (username.contains("@")) {
     // Check that the specified domain matches the server's domain
     int index = username.indexOf("@");
     String domain = username.substring(index + 1);
     if (domain.equals(XMPPServer.getInstance().getServerInfo().getXMPPDomain())) {
       username = username.substring(0, index);
     } else {
       // Unknown domain. Return authentication failed.
       throw new UnauthorizedException();
     }
   }
   try {
     String password = getPassword(username);
     String anticipatedDigest = AuthFactory.createDigest(token, password);
     if (!digest.equalsIgnoreCase(anticipatedDigest)) {
       throw new UnauthorizedException();
     }
   } catch (UserNotFoundException unfe) {
     throw new UnauthorizedException();
   }
   // Got this far, so the user must be authorized.
 }
Ejemplo n.º 12
0
  @Override
  public IQ query(Component component, IQ packet, long timeout) throws ComponentException {
    final LinkedBlockingQueue<IQ> answer = new LinkedBlockingQueue<>(8);
    XMPPServer.getInstance()
        .getIQRouter()
        .addIQResultListener(
            packet.getID(),
            new IQResultListener() {
              @Override
              public void receivedAnswer(IQ packet) {
                answer.offer(packet);
              }

              @Override
              public void answerTimeout(String packetId) {
                Log.warn(
                    "An answer to a previously sent IQ stanza was never received. Packet id: "
                        + packetId);
              }
            });
    sendPacket(component, packet);
    IQ reply = null;
    try {
      reply = answer.poll(timeout, TimeUnit.MILLISECONDS);
    } catch (InterruptedException e) {
      // Ignore
    }
    return reply;
  }
  @Override
  public String getAvailableStreamFeatures() {
    // Offer authenticate and registration only if TLS was not required or if required
    // then the connection is already secured
    if (conn.getTlsPolicy() == Connection.TLSPolicy.required && !conn.isSecure()) {
      return null;
    }

    StringBuilder sb = new StringBuilder(200);

    // Include Stream Compression Mechanism
    if (conn.getCompressionPolicy() != Connection.CompressionPolicy.disabled
        && !conn.isCompressed()) {
      sb.append(
          "<compression xmlns=\"http://jabber.org/features/compress\"><method>zlib</method></compression>");
    }

    if (getAuthToken() == null) {
      // Advertise that the server supports Non-SASL Authentication
      sb.append("<auth xmlns=\"http://jabber.org/features/iq-auth\"/>");
      // Advertise that the server supports In-Band Registration
      if (XMPPServer.getInstance().getIQRegisterHandler().isInbandRegEnabled()) {
        sb.append("<register xmlns=\"http://jabber.org/features/iq-register\"/>");
      }
    } else {
      // If the session has been authenticated then offer resource binding
      // and session establishment
      sb.append("<bind xmlns=\"urn:ietf:params:xml:ns:xmpp-bind\"/>");
      sb.append("<session xmlns=\"urn:ietf:params:xml:ns:xmpp-session\"/>");
    }
    return sb.toString();
  }
Ejemplo n.º 14
0
 public PrivacyList(String username, String name, boolean isDefault, Element listElement) {
   this.userJID = XMPPServer.getInstance().createJID(username, null, true);
   this.name = name;
   this.isDefault = isDefault;
   // Set the new list items
   updateList(listElement);
 }
Ejemplo n.º 15
0
  /**
   * Create a new role.
   *
   * @param chatserver the server hosting the role.
   * @param chatroom the room the role is valid in.
   * @param nickname the nickname of the user in the role.
   * @param role the role of the user in the room.
   * @param affiliation the affiliation of the user in the room.
   * @param chatuser the user on the chat server.
   * @param presence the presence sent by the user to join the room.
   * @param packetRouter the packet router for sending messages from this role.
   */
  public LocalMUCRole(
      MultiUserChatService chatserver,
      LocalMUCRoom chatroom,
      String nickname,
      MUCRole.Role role,
      MUCRole.Affiliation affiliation,
      LocalMUCUser chatuser,
      Presence presence,
      PacketRouter packetRouter) {
    this.room = chatroom;
    this.nick = nickname;
    this.user = chatuser;
    this.server = chatserver;
    this.router = packetRouter;
    this.role = role;
    this.affiliation = affiliation;
    // Cache the user's session (will only work for local users)
    this.session = XMPPServer.getInstance().getSessionManager().getSession(presence.getFrom());

    extendedInformation =
        DocumentHelper.createElement(QName.get("x", "http://jabber.org/protocol/muc#user"));
    calculateExtendedInformation();
    rJID = new JID(room.getName(), server.getServiceDomain(), nick);
    setPresence(presence);
    // Check if new occupant wants to be a deaf occupant
    Element element =
        presence.getElement().element(QName.get("x", "http://jivesoftware.org/protocol/muc"));
    if (element != null) {
      voiceOnly = element.element("deaf-occupant") != null;
    }
    // Add the new role to the list of roles
    user.addRole(room.getName(), this);
  }
Ejemplo n.º 16
0
 /**
  * Retrieves the last n conversations from the system that were created after the given
  * conversationID.
  *
  * @param count the count of conversations to return.
  * @param mostRecentConversationID the last conversationID that has been retrieved.
  * @return a List of Map objects.
  */
 public List<Map<String, Long>> getNLatestConversations(int count, long mostRecentConversationID) {
   // TODO Fix plugin name 2 lines below and missing classes
   List<Map<String, Long>> cons = new ArrayList<Map<String, Long>>();
   MonitoringPlugin plugin =
       (MonitoringPlugin)
           XMPPServer.getInstance().getPluginManager().getPlugin(MonitoringConstants.NAME);
   ConversationManager conversationManager =
       (ConversationManager) plugin.getModule(ConversationManager.class);
   Collection<Conversation> conversations = conversationManager.getConversations();
   List<Conversation> lConversations =
       Arrays.asList(conversations.toArray(new Conversation[conversations.size()]));
   Collections.sort(lConversations, conversationComparator);
   int counter = 0;
   for (Iterator<Conversation> i = lConversations.iterator(); i.hasNext() && counter < count; ) {
     Conversation con = i.next();
     if (mostRecentConversationID == con.getConversationID()) {
       break;
     } else {
       Map mCon = new HashMap();
       mCon.put("conversationid", con.getConversationID());
       String users[];
       int usersIdx = 0;
       if (con.getRoom() == null) {
         users = new String[con.getParticipants().size()];
         for (JID jid : con.getParticipants()) {
           String identifier = jid.toBareJID();
           try {
             identifier = UserNameManager.getUserName(jid, jid.toBareJID());
           } catch (UserNotFoundException e) {
             // Ignore
           }
           users[usersIdx++] = StringUtils.abbreviate(identifier, 20);
         }
       } else {
         users = new String[2];
         users[0] =
             LocaleUtils.getLocalizedString(
                 "dashboard.group_conversation", MonitoringConstants.NAME);
         try {
           users[1] =
               "(<i>"
                   + LocaleUtils.getLocalizedString("muc.room.summary.room")
                   + ": <a href='../../muc-room-occupants.jsp?roomName="
                   + URLEncoder.encode(con.getRoom().getNode(), "UTF-8")
                   + "'>"
                   + con.getRoom().getNode()
                   + "</a></i>)";
         } catch (UnsupportedEncodingException e) {
           Log.error(e.getMessage(), e);
         }
       }
       mCon.put("users", users);
       mCon.put("lastactivity", formatTimeLong(con.getLastActivity()));
       mCon.put("messages", con.getMessageCount());
       cons.add(0, mCon);
       counter++;
     }
   }
   return cons;
 }
Ejemplo n.º 17
0
  private Collection<JID> getGroupMembers(String groupName) {
    Cache<String, Collection<JID>> groupMembershipCache =
        CacheFactory.createLocalCache(GROUP_MEMBERSHIP_CACHE_NAME);
    Collection<JID> members = groupMembershipCache.get(groupName);
    if (members != null) {
      return members;
    }

    try {
      List<String> users = manager.getGroupMembers(groupName);
      Collection<JID> results = new ArrayList<JID>();

      for (String username : users) {
        results.add(server.createJID(username, null));
      }

      groupMembershipCache.put(groupName, results);
      return results;

    } catch (RemoteException re) {
      LOG.error("Failure to get the members of crowd group:" + String.valueOf(groupName), re);
    }

    groupMembershipCache.put(groupName, new ArrayList<JID>());
    return Collections.emptyList();
  }
Ejemplo n.º 18
0
  /**
   * Retrieves user properties for a Clearspace user in XML format.
   *
   * @param username Username to look up.
   * @return XML Element including information about the user.
   * @throws UserNotFoundException The user was not found in the Clearspace database or there was an
   *     error.
   */
  private Element getUserByUsername(String username) throws UserNotFoundException {
    // Checks if the user is local
    if (username.contains("@")) {
      if (!XMPPServer.getInstance().isLocal(new JID(username))) {
        throw new UserNotFoundException("Cannot load user of remote server: " + username);
      }
      username = username.substring(0, username.lastIndexOf("@"));
    }

    try {
      // Un-escape username.
      username = JID.unescapeNode(username);
      // Encode potentially non-ASCII characters
      username = URLUTF8Encoder.encode(username);
      // Requests the user
      String path = USER_URL_PREFIX + "users/" + username;
      // return the response
      return ClearspaceManager.getInstance().executeRequest(GET, path);
    } catch (UserNotFoundException e) {
      throw e;
    } catch (Exception e) {
      // It is not supported exception, wrap it into an UserNotFoundException
      throw new UserNotFoundException("Error loading the user from Clearspace: ", e);
    }
  }
Ejemplo n.º 19
0
  /**
   * Returns true if Clearspce is connected to Openfire.
   *
   * @return true if Clearspce is connected to Openfire.
   */
  public Boolean isClearspaceConnected() {
    XMPPServer server = XMPPServer.getInstance();
    if (server == null) {
      return false;
    }

    Collection<ComponentSession> componentSessions =
        server.getSessionManager().getComponentSessions();
    for (ComponentSession cs : componentSessions) {
      // All Clearspace sessions start with "clearspace"
      if (cs.getAddress().getDomain().startsWith("clearspace")) {
        return true;
      }
    }
    return false;
  }
Ejemplo n.º 20
0
  public User loadUser(String username) throws UserNotFoundException {
    if (username.contains("@")) {
      if (!XMPPServer.getInstance().isLocal(new JID(username))) {
        throw new UserNotFoundException("Cannot load user of remote server: " + username);
      }
      username = username.substring(0, username.lastIndexOf("@"));
    }
    Connection con = null;
    PreparedStatement pstmt = null;
    ResultSet rs = null;
    try {
      con = DbConnectionManager.getConnection();
      pstmt = con.prepareStatement(LOAD_USER);
      pstmt.setString(1, username);
      rs = pstmt.executeQuery();
      if (!rs.next()) {
        throw new UserNotFoundException();
      }
      String name = rs.getString(1);
      String email = rs.getString(2);
      Date creationDate = new Date(Long.parseLong(rs.getString(3).trim()));
      Date modificationDate = new Date(Long.parseLong(rs.getString(4).trim()));

      return new User(username, name, email, creationDate, modificationDate);
    } catch (Exception e) {
      throw new UserNotFoundException(e);
    } finally {
      DbConnectionManager.closeConnection(rs, pstmt, con);
    }
  }
Ejemplo n.º 21
0
  /**
   * The packet is a typical 'set' or 'get' update targeted at the server. Notice that the set could
   * be a roster removal in which case we have to generate a local roster removal update as well as
   * a new roster removal to send to the the roster item's owner.
   *
   * @param packet The packet that triggered this update
   * @return Either a response to the roster update or null if the packet is corrupt and the session
   *     was closed down
   */
  private IQ manageRoster(org.xmpp.packet.Roster packet)
      throws UnauthorizedException, UserAlreadyExistsException, SharedGroupException {

    IQ returnPacket = null;
    JID sender = packet.getFrom();
    IQ.Type type = packet.getType();

    try {
      if ((sender.getNode() == null
              || !RosterManager.isRosterServiceEnabled()
              || !userManager.isRegisteredUser(sender.getNode()))
          && IQ.Type.get == type) {
        // If anonymous user asks for his roster or roster service is disabled then
        // return an empty roster
        IQ reply = IQ.createResultIQ(packet);
        reply.setChildElement("query", "jabber:iq:roster");
        return reply;
      }
      if (!localServer.isLocal(sender)) {
        // Sender belongs to a remote server so discard this IQ request
        Log.warn("Discarding IQ roster packet of remote user: " + packet);
        return null;
      }

      Roster cachedRoster = userManager.getUser(sender.getNode()).getRoster();
      if (IQ.Type.get == type) {
        returnPacket = cachedRoster.getReset();
        returnPacket.setType(IQ.Type.result);
        returnPacket.setTo(sender);
        returnPacket.setID(packet.getID());
        // Force delivery of the response because we need to trigger
        // a presence probe from all contacts
        deliverer.deliver(returnPacket);
        returnPacket = null;
      } else if (IQ.Type.set == type) {

        for (org.xmpp.packet.Roster.Item item : packet.getItems()) {
          if (item.getSubscription() == org.xmpp.packet.Roster.Subscription.remove) {
            removeItem(cachedRoster, packet.getFrom(), item);
          } else {
            if (cachedRoster.isRosterItem(item.getJID())) {
              // existing item
              RosterItem cachedItem = cachedRoster.getRosterItem(item.getJID());
              cachedItem.setAsCopyOf(item);
              cachedRoster.updateRosterItem(cachedItem);
            } else {
              // new item
              cachedRoster.createRosterItem(item);
            }
          }
        }
        returnPacket = IQ.createResultIQ(packet);
      }
    } catch (UserNotFoundException e) {
      throw new UnauthorizedException(e);
    }

    return returnPacket;
  }
Ejemplo n.º 22
0
  @Override
  public void init(ServletConfig servletConfig) throws ServletException {
    super.init(servletConfig);
    plugin = (WixatPlugin) XMPPServer.getInstance().getPluginManager().getPlugin("wixat");

    // Exclude this servlet from requering the user to login
    AuthCheckFilter.addExclude("wixat/check");
  }
Ejemplo n.º 23
0
 public ClientSessionConnection(
     String connectionManagerName, String hostName, String hostAddress) {
   this.connectionManagerName = connectionManagerName;
   multiplexerManager = ConnectionMultiplexerManager.getInstance();
   serverName = XMPPServer.getInstance().getServerInfo().getXMPPDomain();
   this.hostName = hostName;
   this.hostAddress = hostAddress;
 }
Ejemplo n.º 24
0
 /**
  * Returns the user's roster. A roster is a list of users that the user wishes to know if they are
  * online. Rosters are similar to buddy groups in popular IM clients.
  *
  * @return the user's roster.
  */
 public Roster getRoster() {
   try {
     return XMPPServer.getInstance().getRosterManager().getRoster(username);
   } catch (UserNotFoundException unfe) {
     Log.error(unfe.getMessage(), unfe);
     return null;
   }
 }
Ejemplo n.º 25
0
  @Override
  public void destroyPlugin() {
    // Degister HistoryPacketInterceptor
    final HistoryPacketInterceptor historyPacketInterceptor = HistoryPacketInterceptor.singleton();
    final InterceptorManager interceptorManager = InterceptorManager.getInstance();
    interceptorManager.removeInterceptor(historyPacketInterceptor);

    // Deregister PredictionIQHandler
    final XMPPServer xmppServer = XMPPServer.getInstance();
    final IQRouter iqRouter = xmppServer.getIQRouter();
    final PredictionIQHandler predictionIQHandler = PredictionIQHandler.singleton();
    iqRouter.removeHandler(predictionIQHandler);

    // Deregister LocationRepository
    final LocationRepository locationRepo = LocationRepository.singleton();
    iqRouter.removeHandler(locationRepo);
  }
Ejemplo n.º 26
0
 private Roster getRoster() {
   try {
     return XMPPServer.getInstance().getRosterManager().getRoster(userJID.getNode());
   } catch (UserNotFoundException e) {
     Log.warn("Roster not found for user: " + userJID);
   }
   return null;
 }
Ejemplo n.º 27
0
 @Override
 public void stop() {
   super.stop();
   if (getAddress() != null) {
     // Remove the route to this service
     XMPPServer.getInstance().getRoutingTable().removeComponentRoute(getAddress());
   }
 }
 /**
  * Copy to groups.
  *
  * @param currentUser the current user
  * @param newUser the new user
  */
 private static void copyToGroups(String currentUser, String newUser) {
   GroupManager groupManager = GroupManager.getInstance();
   for (Group group : groupManager.getGroups()) {
     if (group.isUser(currentUser)) {
       group.getMembers().add(XMPPServer.getInstance().createJID(newUser, null));
     }
   }
 }
Ejemplo n.º 29
0
  @Override
  public void initializePlugin(final PluginManager pluginManager, final File pluginDirectory) {
    initialize();

    // Register HistoryPacketInterceptor
    final HistoryPacketInterceptor historyPacketInterceptor = HistoryPacketInterceptor.singleton();
    InterceptorManager.getInstance().addInterceptor(historyPacketInterceptor);

    // Register PredictionIQHandler
    final XMPPServer xmppServer = XMPPServer.getInstance();
    final IQRouter iqRouter = xmppServer.getIQRouter();
    final PredictionIQHandler predictionIQHandler = PredictionIQHandler.singleton();
    iqRouter.addHandler(predictionIQHandler);

    // Register LocationRepository
    final LocationRepository locationRepo = LocationRepository.singleton();
    iqRouter.addHandler(locationRepo);
  }
 @Override
 public void addHostname(String hostname) {
   synchronized (hostnames) {
     hostnames.add(hostname);
   }
   // Add a new route for this new session
   XMPPServer.getInstance()
       .getRoutingTable()
       .addServerRoute(new JID(null, hostname, null, true), this);
 }