Java Code Examples for org.xmpp.packet.JID

The following examples show how to use org.xmpp.packet.JID. 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   Source File: RoutingTableImpl.java    License: 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 2
Source Project: Openfire   Source File: UserNameManager.java    License: 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 3
Source Project: Openfire   Source File: PublishedItem.java    License: 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 Project: Openfire   Source File: PrivacyList.java    License: 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 5
Source Project: Openfire   Source File: JDBCAdminProvider.java    License: 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 6
Source Project: Openfire   Source File: RosterManager.java    License: 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 7
Source Project: Openfire   Source File: FlattenNestedGroupsTest.java    License: 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 8
Source Project: Openfire   Source File: SessionManager.java    License: 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 9
Source Project: Openfire   Source File: PubSubServiceInfo.java    License: 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 10
Source Project: Openfire   Source 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 11
Source Project: Openfire   Source File: EntityCapabilitiesListenerTest.java    License: 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 12
Source Project: Openfire   Source File: Node.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Returns a collection with the JID of the node owners. Entities that are node owners have
 * an affiliation of {@link NodeAffiliate.Affiliation#owner}. Owners are allowed to purge
 * and delete the node. Moreover, owners may also get The collection can be modified
 * since it represents a snapshot.
 *
 * @return a collection with the JID of the node owners.
 */
public Collection<JID> getOwners() {
    Collection<JID> jids = new ArrayList<>();
    for (NodeAffiliate affiliate : affiliates) {
        if (NodeAffiliate.Affiliation.owner == affiliate.getAffiliation()) {
            jids.add(affiliate.getJID());
        }
    }
    return jids;
}
 
Example 13
Source Project: Openfire-GCM   Source 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 14
Source Project: Openfire   Source File: LocalMUCRoom.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Removes the role of the occupant from all the internal occupants collections. The role will
 * also be removed from the user's roles.
 *
 * @param leaveRole the role to remove.
 */
void removeOccupantRole(MUCRole leaveRole) {
    Log.trace( "Remove occupant from room {}: {}", this.getJID(), leaveRole );
    JID userAddress = leaveRole.getUserAddress();
    // Notify the user that he/she is no longer in the room
    leaveRole.destroy();
    // Update the tables of occupants based on the bare and full JID
    JID bareJID = userAddress.asBareJID();

    String nickname = leaveRole.getNickname();
    lock.writeLock().lock();
    try {
        occupantsByNickname.computeIfPresent(nickname.toLowerCase(), (n, occupants) -> {
            occupants.remove(leaveRole);
            return occupants.isEmpty() ? null : occupants;
        });

        occupantsByBareJID.computeIfPresent(bareJID,(jid, occupants) -> {
            occupants.remove(leaveRole);
            return occupants.isEmpty() ? null : occupants;
        });

        occupantsByFullJID.remove(userAddress);
    }
    finally {
        lock.writeLock().unlock();
    }
}
 
Example 15
Source Project: Openfire   Source File: AdHocCommandHandler.java    License: 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 16
Source Project: Openfire   Source File: SessionManager.java    License: 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 17
Source Project: Openfire   Source File: AbstractGroupProvider.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public Collection<String> getSharedGroupNames(JID user) {
    Set<String> answer = new HashSet<>();
    Collection<String> userGroups = getGroupNames(user);
    answer.addAll(userGroups);
    for (String userGroup : userGroups) {
        answer.addAll(getVisibleGroupNames(userGroup));
    }
    answer.addAll(getPublicSharedGroupNames());
    return answer;
}
 
Example 18
Source Project: Openfire   Source File: MediaProxyService.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public Iterator<Element> getIdentities(String name, String node, JID senderJID) {
    List<Element> identities = new ArrayList<>();
    // Answer the identity of the proxy
    Element identity = DocumentHelper.createElement("identity");
    identity.addAttribute("category", "proxy");
    identity.addAttribute("name", "Media Proxy Service");
    identity.addAttribute("type", "rtpbridge");

    identities.add(identity);

    return identities.iterator();
}
 
Example 19
Source Project: Openfire   Source File: SocketPacketWriteHandler.java    License: 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 <[email protected]/resource>
            routingTable.routePacket(recipient, packet, false);
        }
        else {
            // JID is of the form <[email protected]>
            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 20
Source Project: Openfire   Source File: PacketsNotification.java    License: 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 21
Source Project: Openfire   Source File: DestroyRoomRequest.java    License: 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 22
Source Project: Openfire   Source File: LocalIncomingServerSession.java    License: 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 23
Source Project: Openfire   Source 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 24
Source Project: Openfire   Source File: FileTransferProxy.java    License: 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();
}
 
Example 25
Source Project: Openfire   Source 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 26
Source Project: Openfire   Source File: MUCEventDispatcher.java    License: 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 27
Source Project: Openfire   Source 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 28
Source Project: Openfire   Source File: DefaultPubSubPersistenceProvider.java    License: 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 29
Source Project: Openfire   Source File: LeafNode.java    License: 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 30
Source Project: Openfire   Source File: Roster.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Returns the list of users that belong ONLY to a shared group of this user. If the contact
 * belongs to the personal roster and a shared group then it wont' be included in the answer.
 *
 * @param sharedGroups the shared groups of this user.
 * @return the list of users that belong ONLY to a shared group of this user.
 */
private Map<JID, List<Group>> getSharedUsers(Collection<Group> sharedGroups) {
    final RosterManager rosterManager = XMPPServer.getInstance().getRosterManager();
    // Get the users to process from the shared groups. Users that belong to different groups
    // will have one entry in the map associated with all the groups
    Map<JID, List<Group>> sharedGroupUsers = new HashMap<>();
    for (Group group : sharedGroups) {
        // Get all the users that should be in this roster
        Collection<JID> users = rosterManager.getSharedUsersForRoster(group, this);
        // Add the users of the group to the general list of users to process
        JID userJID = getUserJID();
        for (JID jid : users) {
            // Add the user to the answer if the user doesn't belong to the personal roster
            // (since we have already added the user to the answer)
            boolean isRosterItem = rosterItems.containsKey(jid.toBareJID());
            if (!isRosterItem && !userJID.equals(jid)) {
                List<Group> groups = sharedGroupUsers.get(jid);
                if (groups == null) {
                    groups = new ArrayList<>();
                    sharedGroupUsers.put(jid, groups);
                }
                groups.add(group);
            }
        }
    }
    return sharedGroupUsers;
}