Java Code Examples for org.jivesoftware.openfire.user.User

The following examples show how to use org.jivesoftware.openfire.user.User. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source Project: Openfire   Author: igniterealtime   File: UserProperties.java    License: Apache License 2.0 6 votes vote down vote up
private void populateResponseFields(DataForm form, List<String> accounts) {
    FormField jidField = form.addField();
    jidField.setVariable("accountjids");

    FormField emailField = form.addField();
    emailField.setVariable("email");

    FormField nameField = form.addField();
    nameField.setVariable("name");

    UserManager manager = UserManager.getInstance();
    for(String account : accounts) {
        User user;
        try {
            JID jid = new JID(account);
            user = manager.getUser(jid.getNode());
        }
        catch (Exception ex) {
            continue;
        }

        jidField.addValue(account);
        emailField.addValue(user.getEmail());
        nameField.addValue(user.getName());
    }
}
 
Example #2
Source Project: Openfire   Author: igniterealtime   File: GroupManager.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Deletes a user from all the groups where he/she belongs. The most probable cause
 * for this request is that the user has been deleted from the system.
 *
 * @param user the deleted user from the system.
 */
public void deleteUser(User user) {
    JID userJID = XMPPServer.getInstance().createJID(user.getUsername(), null);
    for (Group group : getGroups(userJID)) {
        if (group.getAdmins().contains(userJID)) {
            if (group.getAdmins().remove(userJID)) {
                // Remove the group from cache.
                groupCache.remove(group.getName());
            }
        }
        else {
            if (group.getMembers().remove(userJID)) {
                // Remove the group from cache.
                groupCache.remove(group.getName());
            }
        }
    }
    evictCachedUserForGroup(userJID.toBareJID());
}
 
Example #3
Source Project: Openfire   Author: igniterealtime   File: CrowdUserProvider.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public Collection<User> findUsers(Set<String> fields, String query, int startIndex, int numResults) throws UnsupportedOperationException {
    lock.readLock().lock();
    try {
        ArrayList<User> foundUsers = (ArrayList<User>) findUsers(fields, query);
        
        Collection<User> results = new ArrayList<>(foundUsers.size());
        
        for (int i = 0, j = startIndex; i < numResults && j < foundUsers.size(); ++i, ++j) {
            results.add(foundUsers.get(j));
        }
        
        return results;
        
    } finally {
        lock.readLock().unlock();
    }
}
 
Example #4
Source Project: Openfire   Author: igniterealtime   File: EntityCapabilitiesManager.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void userDeleting(User user, Map<String, Object> params) {
    // Delete this user's association in entityCapabilitiesUserMap.
    final JID bareJid = XMPPServer.getInstance().createJID(user.getUsername(), null, true);

    // Remember: Cache's are not regular maps. The EntrySet is immutable.
    // We'll first find the keys, then remove them in a separate call.
    final Set<JID> jidsToRemove = entityCapabilitiesUserMap.keySet().stream()
        .filter( jid -> jid.asBareJID().equals( bareJid ) )
        .collect( Collectors.toSet() );

    final Set<String> deletedUserVerHashes = new HashSet<>();
    for ( final JID jidToRemove : jidsToRemove )
    {
        deletedUserVerHashes.add( entityCapabilitiesUserMap.remove( jidToRemove ) );
    }

    // If there are no other references to the deleted user's 'ver' hash,
    // it is safe to remove that 'ver' hash's associated entity
    // capabilities from the entityCapabilitiesMap cache.
    deletedUserVerHashes.forEach( this::checkObsolete );
}
 
Example #5
Source Project: Openfire   Author: igniterealtime   File: PresenceManagerImpl.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public Presence getPresence(User user) {
    if (user == null) {
        return null;
    }
    Presence presence = null;

    for (ClientSession session : sessionManager.getSessions(user.getUsername())) {
        if (presence == null) {
            presence = session.getPresence();
        }
        else {
            // Get the ordinals of the presences to compare. If no ordinal is available then
            // assume a value of -1
            int o1 = presence.getShow() != null ? presence.getShow().ordinal() : -1;
            int o2 = session.getPresence().getShow() != null ?
                    session.getPresence().getShow().ordinal() : -1;
            // Compare the presences' show ordinals
            if (o1 > o2) {
                presence = session.getPresence();
            }
        }
    }
    return presence;
}
 
Example #6
Source Project: Openfire   Author: igniterealtime   File: PresenceManagerImpl.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public String getLastPresenceStatus(User user) {
    String username = user.getUsername();
    String presenceStatus = null;
    String presenceXML = offlinePresenceCache.get(username);
    if (presenceXML == null) {
        loadOfflinePresence(username);
    }
    presenceXML = offlinePresenceCache.get(username);
    if (presenceXML != null) {
        // If the cached answer is no data, return null.
        if (presenceXML.equals(NULL_STRING)) {
            return null;
        }
        // Otherwise, parse out the status from the XML.
        try {
            // Parse the element
            Document element = DocumentHelper.parseText(presenceXML);
            presenceStatus = element.getRootElement().elementTextTrim("status");
        }
        catch (DocumentException e) {
            Log.error(LocaleUtils.getLocalizedString("admin.error"), e);
        }
    }
    return presenceStatus;
}
 
Example #7
Source Project: Openfire   Author: igniterealtime   File: PresenceManagerImpl.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public long getLastActivity(User user) {
    String username = user.getUsername();
    long lastActivity = NULL_LONG;
    Long offlineDate = lastActivityCache.get(username);
    if (offlineDate == null) {
        loadOfflinePresence(username);
    }
    offlineDate = lastActivityCache.get(username);
    if (offlineDate != null) {
        // If the cached answer is no data, return -1.
        if (offlineDate == NULL_LONG) {
            return NULL_LONG;
        }
        else {
            try {
                lastActivity = (System.currentTimeMillis() - offlineDate);
            }
            catch (NumberFormatException e) {
                Log.error(LocaleUtils.getLocalizedString("admin.error"), e);
            }
        }
    }
    return lastActivity;
}
 
Example #8
Source Project: Openfire   Author: igniterealtime   File: UserEventDispatcher.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Dispatches an event to all listeners.
 *
 * @param user the user.
 * @param eventType the event type.
 * @param params event parameters.
 */
public static void dispatchEvent(User user, EventType eventType, Map<String,Object> params) {
    for (UserEventListener listener : listeners) {
        try {
            switch (eventType) {
                case user_created: {
                    listener.userCreated(user, params);
                    break;
                }
                case user_deleting: {
                    listener.userDeleting(user, params);
                    break;
                }
                case user_modified: {
                    listener.userModified(user, params);
                    break;
                }
                default:
                    break;
            }
        }
        catch (Exception e) {
            Log.error(e.getMessage(), e);
        }
    }
}
 
Example #9
Source Project: Openfire   Author: igniterealtime   File: IQDiscoItemsHandler.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public Iterator<Element> getUserItems(String name, JID senderJID) {
    List<Element> answer = new ArrayList<>();
    try {
        User user = UserManager.getInstance().getUser(name);
        RosterItem item = user.getRoster().getRosterItem(senderJID);
        // If the requesting entity is subscribed to the account's presence then
        // answer the user's "available resources"
        if (item.getSubStatus() == RosterItem.SUB_FROM ||
                item.getSubStatus() == RosterItem.SUB_BOTH) {
            for (Session session : SessionManager.getInstance().getSessions(name)) {
                Element element = DocumentHelper.createElement("item");
                element.addAttribute("jid", session.getAddress().toString());
                answer.add(element);
            }
        }
        return answer.iterator();
    }
    catch (UserNotFoundException e) {
        return answer.iterator();
    }
}
 
Example #10
Source Project: Openfire   Author: igniterealtime   File: WebManager.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * @return the page user or {@code null} if one is not found.
 */
public User getUser() {
    User pageUser = null;
    try {
        final AuthToken authToken = getAuthToken();
        if (authToken == null )
        {
            Log.debug( "Unable to get user: no auth token on session." );
            return null;
        }
        if (authToken instanceof AuthToken.OneTimeAuthToken) {
            return new User(authToken.getUsername(), "Recovery via One Time Auth Token", null, new Date(), new Date());
        }
        final String username = authToken.getUsername();
        if (username == null || username.isEmpty())
        {
            Log.debug( "Unable to get user: no username in auth token on session." );
            return null;
        }
        pageUser = getUserManager().getUser(username);
    }
    catch (Exception ex) {
        Log.debug("Unexpected exception (which is ignored) while trying to obtain user.", ex);
    }
    return pageUser;
}
 
Example #11
Source Project: Openfire   Author: igniterealtime   File: WebManager.java    License: Apache License 2.0 6 votes vote down vote up
public int getPageProperty(String pageName, String property, int defaultValue) {
    User user = getUser();
    if (user != null) {
        String values = user.getProperties().get(property);
        if (values != null) {
            StringTokenizer tokens = new StringTokenizer(values, ",=");
            while (tokens.hasMoreTokens()) {
                String page = tokens.nextToken().trim();
                String rows = tokens.nextToken().trim();
                if  (pageName.equals(page)) {
                    try {
                        return Integer.parseInt(rows);
                    }
                    catch (NumberFormatException e) {
                        return defaultValue;
                    }
                }
            }
        }
    }
    return defaultValue;
}
 
Example #12
Source Project: Openfire-GCM   Author: meisterfuu   File: GcmPlugin.java    License: Apache License 2.0 5 votes vote down vote up
private boolean checkTarget(Message msg) throws UserNotFoundException {
	if(msg.getBody() == null || msg.getBody().equals("")){
		return false;
	}
	
	JID toJID = msg.getTo().asBareJID();
	if(mDebug)Log.info("GCM Plugin check() called");

	if(!toJID.getDomain().contains(mServer.getServerInfo().getXMPPDomain())){
		return false;
	}
	
	if (mMode.equalsIgnoreCase(GcmPlugin.MODE_ALL)) {
		return true;
	} else if (mMode.equalsIgnoreCase(GcmPlugin.MODE_OFFLINE)) {
		
		String y = UserNameManager.getUserName(toJID);
		if(mDebug)Log.info("GCM Plugin getUserName(...) = " + y);
		User x = mUserManager.getUser(y);
		if(mDebug)Log.info("GCM Plugin getUser(...) = " + x.toString());
		try{
			Presence z = mPresenceManager.getPresence(x);
			if(z == null) return true;
			if(mDebug)Log.info("GCM Plugin getPresence(...) = " + z.toString());
			return !z.isAvailable();
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
	} else if (mMode.equalsIgnoreCase(GcmPlugin.MODE_NO_MOBILE)) {
		
	} else if (mMode.equalsIgnoreCase(GcmPlugin.MODE_EXCEPTION)) {

	}

	return true;
}
 
Example #13
Source Project: Openfire   Author: igniterealtime   File: ChangeUserPassword.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void execute(SessionData data, Element command) {
    Element note = command.addElement("note");
    // Check if groups cannot be modified (backend is read-only)
    if (UserManager.getUserProvider().isReadOnly()) {
        note.addAttribute("type", "error");
        note.setText("Users are read only. Changing password is not allowed.");
        return;
    }
    JID account = new JID(data.getData().get("accountjid").get(0));
    String newPassword = data.getData().get("password").get(0);
    if (!XMPPServer.getInstance().isLocal(account)) {
        note.addAttribute("type", "error");
        note.setText("Cannot change password of remote user.");
        return;
    }
    // Get requested group
    User user;
    try {
        user = UserManager.getInstance().getUser(account.getNode());
    } catch (UserNotFoundException e) {
        // Group not found
        note.addAttribute("type", "error");
        note.setText("User does not exists.");
        return;
    }
    // Set the new passowrd of the user
    user.setPassword(newPassword);
    // Answer that the operation was successful
    note.addAttribute("type", "info");
    note.setText("Operation finished successfully");
}
 
Example #14
Source Project: Openfire   Author: igniterealtime   File: UserDeleting.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void execute(SessionData sessionData, Element command) {
    Element note = command.addElement("note");

    Map<String, List<String>> data = sessionData.getData();

    // Gets the username
    String username;
    try {
        username = get(data, "username", 0);
    }
    catch (NullPointerException npe) {
        note.addAttribute("type", "error");
        note.setText("Username required parameter.");
        return;
    }

    // Sends the event
    User user;
    try {
        // Gets current user
        user = UserManager.getInstance().getUser(username);
        
        Map<String, Object> params = Collections.emptyMap();
        UserEventDispatcher.dispatchEvent(user, UserEventDispatcher.EventType.user_deleting, params);
    } catch (UserNotFoundException e) {
        // It's ok, user doesn't exist, so deleting it is nothing
    }

    // Answer that the operation was successful
    note.addAttribute("type", "info");
    note.setText("Operation finished successfully");
}
 
Example #15
Source Project: Openfire   Author: igniterealtime   File: UserCreated.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void execute(SessionData sessionData, Element command) {
    Element note = command.addElement("note");

    Map<String, List<String>> data = sessionData.getData();

    // Get the username
    String username;
    try {
        username = get(data, "username", 0);
    }
    catch (NullPointerException npe) {
        note.addAttribute("type", "error");
        note.setText("Username required parameter.");
        return;
    }

    // Sends the event
    User user;
    try {
        // Loads the new user            
        user = UserManager.getUserProvider().loadUser(username);

        // Fire event.
        Map<String, Object> params = Collections.emptyMap();
        UserEventDispatcher.dispatchEvent(user, UserEventDispatcher.EventType.user_created, params);

    } catch (UserNotFoundException e) {
        note.addAttribute("type", "error");
        note.setText("User not found.");
    }

    // Answer that the operation was successful
    note.addAttribute("type", "info");
    note.setText("Operation finished successfully");
}
 
Example #16
Source Project: Openfire   Author: igniterealtime   File: MultiUserChatManager.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void userDeleting(User user, Map<String, Object> params) {
    // Delete any affiliation of the user to any room of any MUC service
    MUCPersistenceManager
            .removeAffiliationFromDB(XMPPServer.getInstance().createJID(user.getUsername(), null, true));
    // TODO Delete any user information from the rooms loaded into memory
}
 
Example #17
Source Project: Openfire   Author: igniterealtime   File: CrowdUserProvider.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public User loadUser(String username) throws UserNotFoundException {
    lock.readLock().lock();
    try {
        return getCrowdUser(username).getOpenfireUser();
    } finally {
        lock.readLock().unlock();
    }
}
 
Example #18
Source Project: Openfire   Author: igniterealtime   File: CrowdUserProvider.java    License: Apache License 2.0 5 votes vote down vote up
public org.jivesoftware.openfire.crowd.jaxb.User getCrowdUser(String username) throws UserNotFoundException {
    lock.readLock().lock();
    try {
        if (usersCache.containsKey(username)) {
            return usersCache.get(username);
        } else {
            throw new UserNotFoundException("User : '" + String.valueOf(username) + "'");
        }
    } finally {
        lock.readLock().unlock();
    }
}
 
Example #19
Source Project: Openfire   Author: igniterealtime   File: CrowdUserProvider.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public Collection<User> getUsers() {
    lock.readLock().lock();
    try {
        Collection<User> results = new ArrayList<>();
        for (org.jivesoftware.openfire.crowd.jaxb.User user : usersCache.values()) {
            results.add(user.getOpenfireUser());
        }
        return results;
    } finally {
        lock.readLock().unlock();
    }
}
 
Example #20
Source Project: Openfire   Author: igniterealtime   File: CrowdUserProvider.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public Collection<User> getUsers(int startIndex, int numResults) {
    lock.readLock().lock();
    try {
        Collection<User> results = new ArrayList<>(numResults);
        
        for (int i = 0, j = startIndex; i < numResults && j < users.size(); ++i, ++j) {
            results.add(users.get(j).getOpenfireUser());
        }
        
        return results;
    } finally {
        lock.readLock().unlock();
    }
}
 
Example #21
Source Project: Openfire   Author: igniterealtime   File: CrowdUserProvider.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void run() {
    LOG.info("running synch with crowd...");
    CrowdManager manager = null;
    try {
        manager = CrowdManager.getInstance();
    } catch (Exception e) {
        LOG.error("Failure to load the Crowd manager", e);
        return;
    }
    
    List<org.jivesoftware.openfire.crowd.jaxb.User> allUsers = null;
    try {
        allUsers = manager.getAllUsers();
    } catch (RemoteException re) {
        LOG.error("Failure to fetch all crowd users", re);
        return;
    }

    if (allUsers != null && allUsers.size() > 0) {
        
        Map<String, org.jivesoftware.openfire.crowd.jaxb.User> usersMap = new TreeMap<>();
        for (org.jivesoftware.openfire.crowd.jaxb.User user : allUsers) {
            usersMap.put(user.name, user);
        }
        
        userProvider.lock.writeLock().lock();
        try {
            userProvider.users = allUsers;
            userProvider.usersCache = usersMap;
        } finally {
            userProvider.lock.writeLock().unlock();
        }
    }
    
    LOG.info("crowd synch done, returned " + allUsers.size() + " users");
    
}
 
Example #22
Source Project: Openfire   Author: igniterealtime   File: PresenceManagerImpl.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void userDeleting(User user, Map<String, Object> params) {
    // Delete user information
    deleteOfflinePresenceFromDB(user.getUsername());
    offlinePresenceCache.remove(user.getUsername());
    lastActivityCache.remove(user.getUsername());
}
 
Example #23
Source Project: Openfire   Author: igniterealtime   File: RosterManager.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * A new user has been created so members of public shared groups need to have
 * their rosters updated. Members of public shared groups need to have a roster
 * item with subscription FROM for the new user since the new user can see them.
 *
 * @param newUser the newly created user.
 * @param params event parameters.
 */
@Override
public void userCreated(User newUser, Map<String,Object> params) {
    JID newUserJID = server.createJID(newUser.getUsername(), null);
    // Shared public groups that are public should have a presence subscription
    // of type FROM for the new user
    for (Group group : getPublicSharedGroups()) {
        // Get group members of public group
        Collection<JID> users = new HashSet<>(group.getMembers());
        users.addAll(group.getAdmins());
        // Update the roster of each group member to include a subscription of type FROM
        for (JID userToUpdate : users) {
            // Get the roster to update
            Roster roster = null;
            if (server.isLocal(userToUpdate)) {
                // Check that the user exists, if not then continue with the next user
                try {
                    UserManager.getInstance().getUser(userToUpdate.getNode());
                }
                catch (UserNotFoundException e) {
                    continue;
                }
                roster = rosterCache.get(userToUpdate.getNode());
            }
            // Only update rosters in memory
            if (roster != null) {
                roster.addSharedUser(group, newUserJID);
            }
            if (!server.isLocal(userToUpdate)) {
                // Susbcribe to the presence of the remote user. This is only necessary for
                // remote users and may only work with remote users that **automatically**
                // accept presence subscription requests
                sendSubscribeRequest(newUserJID, userToUpdate, true);
            }
        }
    }
}
 
Example #24
Source Project: Openfire   Author: igniterealtime   File: RosterManager.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void userDeleting(User user, Map<String,Object> params) {
    // Shared public groups that have a presence subscription of type FROM
    // for the deleted user should no longer have a reference to the deleted user
    JID userJID = server.createJID(user.getUsername(), null);
    // Shared public groups that are public should have a presence subscription
    // of type FROM for the new user
    for (Group group : getPublicSharedGroups()) {
        // Get group members of public group
        Collection<JID> users = new HashSet<>(group.getMembers());
        users.addAll(group.getAdmins());
        // Update the roster of each group member to include a subscription of type FROM
        for (JID userToUpdate : users) {
            // Get the roster to update
            Roster roster = null;
            if (server.isLocal(userToUpdate)) {
                // Check that the user exists, if not then continue with the next user
                try {
                    UserManager.getInstance().getUser(userToUpdate.getNode());
                }
                catch (UserNotFoundException e) {
                    continue;
                }
                roster = rosterCache.get(userToUpdate.getNode());
            }
            // Only update rosters in memory
            if (roster != null) {
                roster.deleteSharedUser(group, userJID);
            }
            if (!server.isLocal(userToUpdate)) {
                // Unsusbcribe from the presence of the remote user. This is only necessary for
                // remote users and may only work with remote users that **automatically**
                // accept presence subscription requests
                sendSubscribeRequest(userJID, userToUpdate, false);
            }
        }
    }

    deleteRoster(userJID);
}
 
Example #25
Source Project: Openfire   Author: igniterealtime   File: RosterManager.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void userModified(User user, Map<String,Object> params) {
    if ("nameModified".equals(params.get("type"))) {

        for (Group group : getSharedGroups(user.getUsername())) {
            ArrayList<JID> groupUsers = new ArrayList<>();
            groupUsers.addAll(group.getAdmins());
            groupUsers.addAll(group.getMembers());

            for (JID groupUser : groupUsers) {
                rosterCache.remove(groupUser.getNode());
            }
        }
    }
}
 
Example #26
Source Project: Openfire   Author: igniterealtime   File: IQBlockingHandler.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Retrieves all of the JIDs that are on the blocklist of the provided user.
 *
 * @param user The use for which to retrieve the blocklist (cannot be null).
 * @return The JIDs that are on the blocklist (possibly empty, but never null).
 */
protected Set<JID> getBlocklist( User user )
{
    Log.debug( "Retrieving all JIDs that are on the blocklist of user '{}'.", user.getUsername() );
    final PrivacyList defaultPrivacyList = PrivacyListManager.getInstance().getDefaultPrivacyList( user.getUsername() );
    if ( defaultPrivacyList == null )
    {
        return Collections.emptySet();
    }

    return defaultPrivacyList.getBlockedJIDs();
}
 
Example #27
Source Project: Openfire   Author: igniterealtime   File: IQBlockingHandler.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Sends current presence information of the local user to the a collection of JIDs, if appropriate.
 *
 * @param user       The use for which to send presence (cannot be null).
 * @param recipients The entities to which information is send (cannot be null, can be empty)
 */
private void sendPresence( User user, Set<JID> recipients )
{
    if ( recipients.isEmpty() )
    {
        return;
    }

    final PresenceManager presenceManager = XMPPServer.getInstance().getPresenceManager();
    final Presence presence = presenceManager.getPresence( user );
    if ( presence == null )
    {
        return;
    }

    for ( final JID recipient : recipients )
    {
        try
        {
            if ( presenceManager.canProbePresence( recipient, user.getUsername() ) )
            {
                presenceManager.probePresence( recipient.asBareJID(), XMPPServer.getInstance().createJID( user.getUsername(), null ) );
            }
        }
        catch ( UserNotFoundException e )
        {
            Log.error( "Unable to send presence information of user '{}' to unblocked entity '{}' as local user is not found.", user.getUsername(), recipient );
        }
    }
}
 
Example #28
Source Project: Openfire   Author: igniterealtime   File: IQBlockingHandler.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Sends an IQ-set with the newly blocked JIDs to all resources of the user that have requested the blocklist.
 *
 * @param user      The for which updates are to be broadcasted (cannot be null).
 * @param newBlocks The JIDs for which an update needs to be sent (cannot be null, can be empty).
 */
protected void pushBlocklistUpdates( User user, List<JID> newBlocks )
{
    if ( newBlocks.isEmpty() )
    {
        return;
    }

    Log.debug( "Pushing blocklist updates to all resources of user '{}' that have previously requested the blocklist.", user.getUsername() );

    final Collection<ClientSession> sessions = sessionManager.getSessions( user.getUsername() );
    for ( final ClientSession session : sessions )
    {
        if ( session.hasRequestedBlocklist() )
        {
            final IQ iq = new IQ( IQ.Type.set );
            iq.setTo( session.getAddress() );
            final Element block = iq.setChildElement( "block", NAMESPACE );
            for ( final JID newBlock : newBlocks )
            {
                block.addElement( "item" ).addAttribute( "jid", newBlock.toString() );
            }

            XMPPServer.getInstance().getPacketRouter().route( iq );
        }
    }
}
 
Example #29
Source Project: Openfire   Author: igniterealtime   File: IQBlockingHandler.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Removes all JIDs from the blocklist of the provided user.
 *
 * This method removes the JIDs to the default privacy list. When no default privacy list exists for this user, this
 * method does nothing.
 *
 * @param user The owner of the blocklist to which JIDs are to be added (cannot be null).
 * @return The JIDs that are removed (never null, possibly empty).
 */
private Set<JID> removeAllFromBlocklist( User user )
{
    Log.debug( "Obtain the default privacy list for '{}'", user.getUsername() );
    final Set<JID> result = new HashSet<>();
    PrivacyList defaultPrivacyList = PrivacyListManager.getInstance().getDefaultPrivacyList( user.getUsername() );
    if ( defaultPrivacyList == null )
    {
        return result;
    }

    Log.debug( "Removing all JIDs from blocklist '{}' (belonging to '{}')", defaultPrivacyList.getName(), user.getUsername() );
    final Element listElement = defaultPrivacyList.asElement();
    final Set<Element> toRemove = new HashSet<>();
    for ( final Element element : listElement.elements( "item" ) )
    {
        if ( "jid".equals( element.attributeValue( "type" ) )
            && "deny".equals( element.attributeValue( "action" ) ) )
        {
            toRemove.add( element );
            result.add( new JID( element.attributeValue( "value" ) ) );
        }
    }

    if ( !toRemove.isEmpty() )
    {
        for ( final Element remove : toRemove )
        {
            listElement.remove( remove );
        }

        defaultPrivacyList.updateList( listElement );
        PrivacyListProvider.getInstance().updatePrivacyList( user.getUsername(), defaultPrivacyList );
    }
    return result;
}
 
Example #30
Source Project: Openfire   Author: igniterealtime   File: IQBlockingHandler.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Sends an IQ-set with the newly blocked JIDs to all resources of the user that have requested the blocklist.
 *
 * @param user      The for which updates are to be broadcasted (cannot be null).
 * @param newBlocks The JIDs for which an update needs to be sent (cannot be null, can be empty).
 */
protected void pushBlocklistUpdates( User user, Collection<JID> newBlocks )
{
    if ( newBlocks.isEmpty() )
    {
        return;
    }

    Log.debug( "Pushing blocklist updates to all resources of user '{}' that have previously requested the blocklist.", user.getUsername() );

    final Collection<ClientSession> sessions = sessionManager.getSessions( user.getUsername() );
    for ( final ClientSession session : sessions )
    {
        if ( session.hasRequestedBlocklist() )
        {
            final IQ iq = new IQ( IQ.Type.set );
            iq.setTo( session.getAddress() );
            final Element block = iq.setChildElement( "unblock", NAMESPACE );
            for ( final JID newBlock : newBlocks )
            {
                block.addElement( "item" ).addAttribute( "jid", newBlock.toString() );
            }

            XMPPServer.getInstance().getPacketRouter().route( iq );
        }
    }
}