org.xmpp.packet.JID Java Examples

The following examples show how to use org.xmpp.packet.JID. 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 File: FlattenNestedGroupsTest.java    From Openfire with Apache License 2.0 6 votes vote down vote up
public void testFlattenGroupsOfUsers() throws GroupNotFoundException {
    LdapGroupProvider groupProvider = new LdapGroupProvider();

    assertThat(groupProvider.getGroupNames(new JID("j.bond", THIS_HOST_NAME, null)),
        containsInAnyOrder("admins"));

    assertThat(groupProvider.getGroupNames(new JID("a.schweis", THIS_HOST_NAME, null)),
        containsInAnyOrder("cycle1", "cycle2", "cycle3", "group1", "group2", "group3"));

    assertThat(groupProvider.getGroupNames(new JID("c.man", THIS_HOST_NAME, null)),
        containsInAnyOrder("cycle1", "cycle2", "cycle3", "group1"));

    assertThat(groupProvider.getGroupNames(new JID("h.wurst", THIS_HOST_NAME, null)),
        containsInAnyOrder("cycle1", "cycle2", "cycle3", "group1"));

    assertThat(groupProvider.getGroupNames(new JID("j.lopez", THIS_HOST_NAME, null)),
        containsInAnyOrder("admins", "cycle1", "cycle2", "group1", "group2", "cycle3", "group4"));

    assertThat(groupProvider.getGroupNames(new JID("l.densivillja", THIS_HOST_NAME, null)),
        containsInAnyOrder("cycle1", "cycle2", "cycle3", "group1", "group2"));

    assertThat(groupProvider.getGroupNames(new JID("p.silie", THIS_HOST_NAME, null)),
        containsInAnyOrder("cycle1", "cycle2", "cycle3", "group1", "group2"));
}
 
Example #2
Source File: EntityCapabilitiesManager.java    From Openfire with 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 #3
Source File: PublishedItem.java    From Openfire with Apache License 2.0 6 votes vote down vote up
/**
 * Returns the {@link LeafNode} where this item was published.
 *
 * @return the leaf node where this item was published.
 */
public LeafNode getNode() {
    if (node == null) {
        synchronized (this) {
            if (node == null) {
                if (XMPPServer.getInstance().getPubSubModule().getServiceID().equals(serviceId))
                {
                    node = (LeafNode) XMPPServer.getInstance().getPubSubModule().getNode(nodeId);
                }
                else
                {
                    PEPServiceManager serviceMgr = XMPPServer.getInstance().getIQPEPHandler().getServiceManager();
                    JID service = new JID( serviceId );
                    node = serviceMgr.hasCachedService(service) ? (LeafNode) serviceMgr.getPEPService(service).getNode(nodeId) : null;
                }
            }
        }
    }
    return node;
}
 
Example #4
Source File: PubSubServiceInfo.java    From Openfire with Apache License 2.0 6 votes vote down vote up
public JID getValidJID(String username) {
    if (username != null && !username.isEmpty()) {
        try {
            if (username.contains("@")) {
                JID jid = new JID(username);
                if (userManager.isRegisteredUser(jid)) {
                    return jid;
                }
            } else if (userManager.isRegisteredUser(username)) {
                return xmppServer.createJID(username, null);
            }
        } catch (IllegalArgumentException e) {
            Log.debug("Unable to parse value '{}' as a JID.", username);
        }
    }
    // Return null if JID is invalid or user not registered
    return null;
}
 
Example #5
Source File: UserNameManager.java    From Openfire with Apache License 2.0 6 votes vote down vote up
/**
 * Returns the name of the XMPP entity. If the entity is a local user then the User's name
 * will be returned. However, if the user is not a local user then check if there exists a
 * UserNameProvider that provides name for the specified domain. If none was found then
 * the vCard of the entity might be requested and if none was found then a string
 * representation of the entity's JID will be returned.
 *
 * @param entity      the JID of the entity to get its name.
 * @param defaultName default name to return when no name was found.
 * @return the name of the XMPP entity.
 * @throws UserNotFoundException if the jid belongs to the local server but no user was
 *                               found for that jid.
 */
public static String getUserName(JID entity, String defaultName) throws UserNotFoundException {
    if (server.isLocal(entity)) {
        // Contact is a local entity so search for his user name
        User localUser = UserManager.getInstance().getUser(entity.getNode());
        return !localUser.isNameVisible() || "".equals(localUser.getName()) ? entity.getNode() : localUser.getName();
    } else {
        UserNameProvider provider = providersByDomain.get(entity.getDomain());
        if (provider != null) {
            return provider.getUserName(entity);
        }
        // TODO Request vCard to the remote server/component and return the name as
        // TODO defined in the vCard. We might need to cache this information to avoid
        // TODO high traffic.

        // Return the jid itself as the username
        return defaultName;
    }
}
 
Example #6
Source File: PrivacyList.java    From Openfire with Apache License 2.0 6 votes vote down vote up
/**
 * Returns all JIDs that are on the blocklist (as defined in XEP-0191).
 *
 * @return a collection of JIDs (possibly empty, never null)
 */
public Set<JID> getBlockedJIDs()
{
    final Set<JID> result = new HashSet<>();

    for ( final PrivacyItem item : items )
    {
        if ( !item.isAllow() && item.isType( PrivacyItem.Type.jid ) )
        {
            if ( item.getJID() != null )
            {
                result.add( item.getJID() );
            }
        }
    }

    return result;
}
 
Example #7
Source File: JDBCAdminProvider.java    From Openfire with Apache License 2.0 6 votes vote down vote up
@Override
public void setAdmins(List<JID> newAdmins) {
    if (isReadOnly()) {
        // Reject the operation since the provider is read-only
        throw new UnsupportedOperationException();
    }

    synchronized (getAdminsSQL) {
        final List<JID> currentAdmins = getAdmins();
        // Get a list of everyone in the new list not in the current list
        final List<JID> adminsToAdd = new ArrayList<>(newAdmins);
        adminsToAdd.removeAll(currentAdmins);
        // Get a list of everyone in the current list not in the new list
        currentAdmins.removeAll(newAdmins);
        try (final Connection con = getConnection()) {
            changeAdmins(con, insertAdminsSQL, adminsToAdd);
            changeAdmins(con, deleteAdminsSQL, currentAdmins);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }
}
 
Example #8
Source File: RoutingTableImpl.java    From Openfire with Apache License 2.0 6 votes vote down vote up
/**
 * Remove local or remote component route.
 *
 * @param route the route of the component to be removed.
 * @param nodeID The node to which the to-be-removed component was connected to.
 */
private boolean removeComponentRoute(JID route, NodeID nodeID) {
    String address = route.getDomain();
    boolean removed = false;
    Lock lock = componentsCache.getLock(address);
    try {
        lock.lock();
        HashSet<NodeID> nodes = componentsCache.get(address);
        if (nodes != null) {
            removed = nodes.remove(nodeID);
            if (nodes.isEmpty()) {
                componentsCache.remove(address);
            }
            else {
                componentsCache.put(address, nodes);
            }
        }
    } finally {
        lock.unlock();
    }
    localRoutingTable.removeRoute(new DomainPair("", address));
    return removed;
}
 
Example #9
Source File: RosterManager.java    From Openfire with Apache License 2.0 6 votes vote down vote up
@Override
public void memberRemoved(Group group, Map params) {
    String member = (String) params.get("member");
    if (member == null) {
        return;
    }
    JID deletedUser = new JID(member);
    // Do nothing if the user is still an admin
    if (group.getAdmins().contains(deletedUser)) {
        return;
    }
    if (!isSharedGroup(group)) {
        for (Group visibleGroup : getVisibleGroups(group)) {
            // Get the list of affected users
            Collection<JID> users = new HashSet<>(visibleGroup.getMembers());
            users.addAll(visibleGroup.getAdmins());
            groupUserDeleted(visibleGroup, users, deletedUser);
        }
    }
    else {
        groupUserDeleted(group, deletedUser);
    }
}
 
Example #10
Source File: EntityCapabilitiesListenerTest.java    From Openfire with Apache License 2.0 6 votes vote down vote up
/**
 * Asserts that removing the registration of an user-specific listener causes that listener to no longer receive events.
 */
@Test
public void testDeregisterUserSpecificListener() throws Exception
{
    // Setup fixture.
    final JID entity = new JID( "john", "example.org", "mobile" );
    final EntityCapabilities caps = new EntityCapabilities();
    caps.setVerAttribute( "test-ver" );
    caps.setHashAttribute( "test-hash" );
    manager.addListener( entity, userSpecific );
    manager.removeListener( entity, userSpecific );

    // Execute system under test.
    manager.registerCapabilities( entity, caps );

    // Verify results.
    verify( userSpecific, never() ).entityCapabilitiesChanged( entity, caps, Collections.emptySet(), Collections.emptySet(), Collections.emptySet(), Collections.emptySet() );
}
 
Example #11
Source File: SessionManager.java    From Openfire with Apache License 2.0 6 votes vote down vote up
/**
 * Sends the presences of other connected resources to the resource that just connected.
 *
 * @param session the newly created session.
 */
private void broadcastPresenceOfOtherResource(LocalClientSession session) {
    if (!SessionManager.isOtherResourcePresenceEnabled()) {
        return;
    }
    Presence presence;
    // Get list of sessions of the same user
    JID searchJID = new JID(session.getAddress().getNode(), session.getAddress().getDomain(), null);
    List<JID> addresses = routingTable.getRoutes(searchJID, null);
    for (JID address : addresses) {
        if (address.equals(session.getAddress())) {
            continue;
        }
        // Send the presence of an existing session to the session that has just changed
        // the presence
        ClientSession userSession = routingTable.getClientRoute(address);
        presence = userSession.getPresence().createCopy();
        presence.setTo(session.getAddress());
        session.process(presence);
    }
}
 
Example #12
Source File: MUCEventDispatcher.java    From Openfire with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("deprecation")
public static void occupantLeft(JID roomJID, JID user, String nickname) {
    for (MUCEventListener listener : listeners) {
        try {
            // We call both two and three argument methods to support
            // older API clients
            listener.occupantLeft(roomJID, user);
            listener.occupantLeft(roomJID, user, nickname);
        } catch (Exception e) {
            Log.warn("An exception occurred while dispatching a 'occupantLeft' event!", e);
        } 
    }
}
 
Example #13
Source File: JDBCAdminProvider.java    From Openfire with Apache License 2.0 5 votes vote down vote up
private void changeAdmins(final Connection con, final String sql, final List<JID> admins) throws SQLException {
    if (!admins.isEmpty()) {
        try (final PreparedStatement pstmt = con.prepareStatement(sql)) {
            for (final JID jid : admins) {
                // OF-1837: When the database does not hold escaped data, our query should use unescaped values in the 'where' clause.
                final String queryValue = assumePersistedDataIsEscaped() ? jid.getNode() : JID.unescapeNode( jid.getNode() );
                pstmt.setString(1, queryValue);
                pstmt.execute();
            }
        }
    }
}
 
Example #14
Source File: GcmPlugin.java    From Openfire-GCM with 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 #15
Source File: IQPEPHandler.java    From Openfire with Apache License 2.0 5 votes vote down vote up
/**
 * Process an IQ set stanza that was addressed to the a node/user.
 *
 * @param packet The stanza to process.
 * @return A response (can be null).
 */
private IQ handleIQRequestToUser(IQ packet)
{
    final JID jidTo = packet.getTo().asBareJID();
    final PEPService pepService = pepServiceManager.getPEPService(jidTo);
    pepServiceManager.process(pepService, packet);
    return null;
}
 
Example #16
Source File: AdHocCommandHandler.java    From Openfire with Apache License 2.0 5 votes vote down vote up
@Override
public boolean hasInfo(String name, String node, JID senderJID) {
    if (NAMESPACE.equals(node)) {
        return true;
    }
    else {
        // Only include commands that the sender can execute
        AdHocCommand command = manager.getCommand(node);
        return command != null && command.hasPermission(senderJID);
    }
}
 
Example #17
Source File: SocketPacketWriteHandler.java    From Openfire with Apache License 2.0 5 votes vote down vote up
@Override
 public void process(Packet packet) throws UnauthorizedException, PacketException {
    try {
        JID recipient = packet.getTo();
        // Check if the target domain belongs to a remote server or a component
        if (server.matchesComponent(recipient) || server.isRemote(recipient)) {
            routingTable.routePacket(recipient, packet, false);
        }
        // The target domain belongs to the local server
        else if (recipient == null || (recipient.getNode() == null && recipient.getResource() == null)) {
            // no TO was found so send back the packet to the sender
            routingTable.routePacket(packet.getFrom(), packet, false);
        }
        else if (recipient.getResource() != null || !(packet instanceof Presence)) {
            // JID is of the form <user@domain/resource>
            routingTable.routePacket(recipient, packet, false);
        }
        else {
            // JID is of the form <user@domain>
            for (JID route : routingTable.getRoutes(recipient, null)) {
                routingTable.routePacket(route, packet, false);
            }
        }
    }
    catch (Exception e) {
        Log.error(LocaleUtils.getLocalizedString("admin.error.deliver") + "\n" + packet.toString(), e);
    }
}
 
Example #18
Source File: SessionManager.java    From Openfire with Apache License 2.0 5 votes vote down vote up
public Collection<ClientSession> getSessions(String username) {
    List<ClientSession> sessionList = new ArrayList<>();
    if (username != null && serverName != null) {
        List<JID> addresses = routingTable.getRoutes(new JID(username, serverName, null, true), null);
        for (JID address : addresses) {
            sessionList.add(routingTable.getClientRoute(address));
        }
    }
    return sessionList;
}
 
Example #19
Source File: LdapVCardProvider.java    From Openfire with Apache License 2.0 5 votes vote down vote up
/**
 * Loads the avatar from LDAP, based off the vcard template.
 *
 * If enabled, will replace a blank PHOTO element with one from a DB stored vcard.
 *
 * @param username User we are loading the vcard for.
 * @return The loaded vcard element, or null if none found.
 */
@Override
public Element loadVCard(String username) {
    // Un-escape username.
    username = JID.unescapeNode(username);
    Map<String, String> map = getLdapAttributes(username);
    Log.debug("LdapVCardProvider: Getting mapped vcard for " + username);
    Element vcard = new VCard(template).getVCard(map);
    // If we have a vcard from ldap, but it doesn't have an avatar filled in, then we
    // may fill it with a locally stored vcard element.
    if (dbStorageEnabled && vcard != null && (vcard.element("PHOTO") == null || vcard.element("PHOTO").element("BINVAL") == null || vcard.element("PHOTO").element("BINVAL").getText().matches("\\s*"))) {
        Element avatarElement = loadAvatarFromDatabase(username);
        if (avatarElement != null) {
            Log.debug("LdapVCardProvider: Adding avatar element from local storage");
            Element currentElement = vcard.element("PHOTO");
            if (currentElement != null) {
                vcard.remove(currentElement);
            }
            vcard.add(avatarElement);
        }
    }

    if ( JiveGlobals.getBooleanProperty( PhotoResizer.PROPERTY_RESIZE_ON_LOAD, PhotoResizer.PROPERTY_RESIZE_ON_LOAD_DEFAULT ) )
    {
        PhotoResizer.resizeAvatar( vcard );
    }

    Log.debug("LdapVCardProvider: Returning vcard");
    return vcard;
}
 
Example #20
Source File: LocalMUCRoom.java    From Openfire with Apache License 2.0 5 votes vote down vote up
public void affiliationAdded(AddAffiliation affiliation) {
    JID affiliationJID = affiliation.getBareJID();
    switch(affiliation.getAffiliation()) {
        case owner:
            removeMember(affiliationJID);
            removeAdmin(affiliationJID);
            removeOutcast(affiliationJID);
            owners.add(affiliationJID);
            break;
        case admin:
            removeMember(affiliationJID);
            removeOwner(affiliationJID);
            removeOutcast(affiliationJID);
            admins.add(affiliationJID);
            break;
        case outcast:
            removeMember(affiliationJID);
            removeAdmin(affiliationJID);
            removeOwner(affiliationJID);
            outcasts.add(affiliationJID);
            break;
        case none:
        default:
            removeMember(affiliationJID);
            removeAdmin(affiliationJID);
            removeOwner(affiliationJID);
            removeOutcast(affiliationJID);
            break;
    }
}
 
Example #21
Source File: PacketsNotification.java    From Openfire with Apache License 2.0 5 votes vote down vote up
@Override
public void execute(SessionData data, Element command) {
    boolean presenceEnabled = false;
    boolean messageEnabled = false;
    boolean iqEnabled = false;
    for (String packet_type : data.getData().get("packet_type")) {
        if ("presence".equals(packet_type)) {
            presenceEnabled = true;
        }
        else if ("iq".equals(packet_type)) {
            iqEnabled = true;
        }
        else if ("message".equals(packet_type)) {
            messageEnabled = true;
        }
    }

    boolean incoming = "incoming".equals(data.getData().get("direction").get(0));
    boolean processed = "true".equals(data.getData().get("processed").get(0));

    JID componentJID = data.getOwner();
    // Create or update subscription of the component to receive packet notifications
    PacketCopier.getInstance()
            .addSubscriber(componentJID, iqEnabled, messageEnabled, presenceEnabled, incoming, processed);

    // Inform that everything went fine
    Element note = command.addElement("note");
    note.addAttribute("type", "info");
    note.setText("Operation finished successfully");
}
 
Example #22
Source File: Node.java    From Openfire with Apache License 2.0 5 votes vote down vote up
/**
 * Sends an event notification to the specified subscriber. The event notification may
 * include information about the affected subscriptions.
 *
 * @param subscriberJID the subscriber JID that will get the notification.
 * @param notification the message to send to the subscriber.
 * @param subIDs the list of affected subscription IDs or null when node does not
 *        allow multiple subscriptions.
 */
protected void sendEventNotification(JID subscriberJID, Message notification,
        Collection<String> subIDs) {
    Element headers = null;
    if (subIDs != null) {
        // Notate the event notification with the ID of the affected subscriptions
        headers = notification.addChildElement("headers", "http://jabber.org/protocol/shim");
        for (String subID : subIDs) {
            Element header = headers.addElement("header");
            header.addAttribute("name", "SubID");
            header.setText(subID);
        }
    }
    
    // Verify that the subscriber JID is currently available to receive notification
    // messages. This is required because the message router will deliver packets via 
    // the bare JID if a session for the full JID is not available. The "isActiveRoute"
    // condition below will prevent inadvertent delivery of multiple copies of each
    // event notification to the user, possibly multiple times (e.g. route.all-resources). 
    // (Refer to http://issues.igniterealtime.org/browse/OF-14 for more info.)
    //
    // This approach is informed by the following XEP-0060 implementation guidelines:
    //   12.2 "Intended Recipients for Notifications" - only deliver to subscriber JID
    //   12.4 "Not Routing Events to Offline Storage" - no offline storage for notifications
    //
    // Note however that this may be somewhat in conflict with the following:
    //   12.3 "Presence-Based Delivery of Events" - automatically detect user's presence
    //
    if (subscriberJID.getResource() == null ||
        SessionManager.getInstance().getSession(subscriberJID) != null) {
        getService().sendNotification(this, notification, subscriberJID);
    }

    if (headers != null) {
        // Remove the added child element that includes subscription IDs information
        notification.getElement().remove(headers);
    }
}
 
Example #23
Source File: LeafNode.java    From Openfire with Apache License 2.0 5 votes vote down vote up
public LeafNode(PubSubService.UniqueIdentifier serviceId, CollectionNode parentNode, String nodeID, JID creator, DefaultNodeConfiguration defaultConfiguration) {
    super(serviceId, parentNode, nodeID, creator, defaultConfiguration);
    this.persistPublishedItems = defaultConfiguration.isPersistPublishedItems();
    this.maxPublishedItems = defaultConfiguration.getMaxPublishedItems();
    this.maxPayloadSize = defaultConfiguration.getMaxPayloadSize();
    this.sendItemSubscribe = defaultConfiguration.isSendItemSubscribe();
}
 
Example #24
Source File: DestroyRoomRequest.java    From Openfire with Apache License 2.0 5 votes vote down vote up
@Override
public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
    super.readExternal(in);
    if (ExternalizableUtil.getInstance().readBoolean(in)) {
        alternateJID = (JID) ExternalizableUtil.getInstance().readSerializable(in);
    }
    if (ExternalizableUtil.getInstance().readBoolean(in)) {
        reason = ExternalizableUtil.getInstance().readSafeUTF(in);
    }
}
 
Example #25
Source File: DefaultPubSubPersistenceProvider.java    From Openfire with Apache License 2.0 5 votes vote down vote up
@Override
public PublishedItem getLastPublishedItem(LeafNode node) {
    Connection con = null;
    PreparedStatement pstmt = null;
    ResultSet rs = null;
    PublishedItem item = null;

    try {
        con = DbConnectionManager.getConnection();
        // Get published items of the specified node
        pstmt = con.prepareStatement(LOAD_LAST_ITEM);
        pstmt.setFetchSize(1);
        pstmt.setMaxRows(1);
        pstmt.setString(1, node.getUniqueIdentifier().getServiceIdentifier().getServiceId());
        pstmt.setString(2, encodeNodeID(node.getNodeID()));
        rs = pstmt.executeQuery();
        // Rebuild loaded published items
        if (rs.next()) {
            String itemID = rs.getString(1);
            JID publisher = new JID(rs.getString(2));
            Date creationDate = new Date(Long.parseLong(rs.getString(3).trim()));
            // Create the item
            item = new PublishedItem(node, publisher, itemID, creationDate);
            // Add the extra fields to the published item
            if (rs.getString(4) != null) {
            	item.setPayloadXML(rs.getString(4));
            }
        }
    }
    catch (Exception sqle) {
        log.error(sqle.getMessage(), sqle);
    }
    finally {
        DbConnectionManager.closeConnection(rs, pstmt, con);
    }
    return item;
}
 
Example #26
Source File: IQBlockingHandler.java    From Openfire with 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 File: IQBlockingHandler.java    From Openfire with 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 #28
Source File: LocalIncomingServerSession.java    From Openfire with Apache License 2.0 5 votes vote down vote up
/**
 * Adds a new validated domain, subdomain or virtual host to the list of
 * validated domains for the remote server.
 *
 * @param domain the new validated domain, subdomain or virtual host to add.
 */
public void addValidatedDomain(String domain) {
    if (validatedDomains.add(domain)) {
        // Set the first validated domain as the address of the session
        if (validatedDomains.size() < 2) {
            setAddress(new JID(null, domain, null));
        }
        // Register the new validated domain for this server session in SessionManager
        SessionManager.getInstance().registerIncomingServerSession(domain, this);
    }
}
 
Example #29
Source File: IQBlockingHandler.java    From Openfire with 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 #30
Source File: FileTransferProxy.java    From Openfire with Apache License 2.0 5 votes vote down vote up
@Override
public Iterator<Element> getIdentities(String name, String node, JID senderJID) {
    // Answer the identity of the proxy
    Element identity = DocumentHelper.createElement("identity");
    identity.addAttribute("category", "proxy");
    identity.addAttribute("name", "SOCKS5 Bytestreams Service");
    identity.addAttribute("type", "bytestreams");

    return Collections.singleton(identity).iterator();
}