UserMultiProvider.java 14.3 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373
/*
 * Copyright 2016 IgniteRealtime.org
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.jivesoftware.openfire.user;

import org.jivesoftware.util.ClassUtils;
import org.jivesoftware.util.JiveGlobals;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.*;

/**
 * A {@link UserProvider} that delegates to one or more 'backing' UserProvider.
 *
 * @author GUus der Kinderen, guus@goodbytes.nl
 */
public abstract class UserMultiProvider implements UserProvider
{
    private final static Logger Log = LoggerFactory.getLogger( UserMultiProvider.class );

    /**
     * Instantiates a UserProvider based on a property value (that is expected to be a class name). When the property
     * is not set, this method returns null. When the property is set, but an exception occurs while instantiating
     * the class, this method logs the error and returns null.
     *
     * UserProvider classes are required to have a public, no-argument constructor.
     *
     * @param propertyName A property name (cannot ben ull).
     * @return A user provider (can be null).
     */
    public static UserProvider instantiate( String propertyName )
    {
        final String className = JiveGlobals.getProperty( propertyName );
        if ( className == null )
        {
            Log.debug( "Property '{}' is undefined. Skipping.", propertyName );
            return null;
        }
        Log.debug( "About to to instantiate an UserProvider '{}' based on the value of property '{}'.", className, propertyName );
        try
        {
            final Class c = ClassUtils.forName( className );
            final UserProvider provider = (UserProvider) c.newInstance();
            Log.debug( "Instantiated UserProvider '{}'", className );
            return provider;
        }
        catch ( Exception e )
        {
            Log.error( "Unable to load UserProvider '{}'. Users in this provider will be disabled.", className, e );
            return null;
        }
    }

    /**
     * Returns all UserProvider instances that serve as 'backing' providers.
     *
     * @return A collection of providers (never null).
     */
    abstract Collection<UserProvider> getUserProviders();

    /**
     * Returns the 'backing' provider that serves the provided user. Note that the user need not exist.
     *
     * Finds a suitable UserProvider for the user.
     *
     * Note that the provided username need not reflect a pre-existing user (the instance might be used to determine in
     * which provider a new user is to be created).
     *
     * Implementations are expected to be able to find a UserProvider for any username. If an implementation fails to do
     * so, such a failure is assumed to be the result of a problem in implementation or configuration.
     *
     * @param username A user identifier (cannot be null or empty).
     * @return A UserProvider for the user (never null).
     */
    abstract UserProvider getUserProvider( String username );

    @Override
    public int getUserCount()
    {
        int total = 0;
        // TODO Make calls concurrent for improved throughput.
        for ( final UserProvider provider : getUserProviders() )
        {
            total += provider.getUserCount();
        }

        return total;
    }

    @Override
    public Collection<User> getUsers()
    {
        final Collection<User> result = new ArrayList<>();
        for ( final UserProvider provider : getUserProviders() )
        {
            // TODO Make calls concurrent for improved throughput.
            result.addAll( provider.getUsers() );
        }

        return result;
    }

    @Override
    public Collection<String> getUsernames()
    {
        final Collection<String> result = new ArrayList<>();
        for ( final UserProvider provider : getUserProviders() )
        {
            // TODO Make calls concurrent for improved throughput.
            result.addAll( provider.getUsernames() );
        }

        return result;
    }

    @Override
    public Collection<User> getUsers( int startIndex, int numResults )
    {
        final List<User> userList = new ArrayList<>();
        int totalUserCount = 0;

        for ( final UserProvider provider : getUserProviders() )
        {
            final int providerStartIndex = Math.max( ( startIndex - totalUserCount ), 0 );
            totalUserCount += provider.getUserCount();
            if ( startIndex >= totalUserCount )
            {
                continue;
            }
            final int providerResultMax = numResults - userList.size();
            userList.addAll( provider.getUsers( providerStartIndex, providerResultMax ) );
            if ( userList.size() >= numResults )
            {
                break;
            }
        }
        return userList;
    }

    /**
     * Searches for users based on a set of fields and a query string. The fields must  be taken from the values
     * returned by {@link #getSearchFields()}. The query can  include wildcards. For example, a search on the field
     * "Name" with a query of "Ma*"  might return user's with the name "Matt", "Martha" and "Madeline".
     *
     * This method throws an UnsupportedOperationException when none of the backing providers support search.
     *
     * When fields are provided that are not supported by a particular provider, those fields are ignored by that
     * provider (but can still be used by other providers).
     *
     * @param fields the fields to search on.
     * @param query  the query string.
     * @return a Collection of users that match the search.
     * @throws UnsupportedOperationException When none of the providers support search.
     */
    @Override
    public Collection<User> findUsers( Set<String> fields, String query ) throws UnsupportedOperationException
    {
        final List<User> userList = new ArrayList<>();
        int supportSearch = getUserProviders().size();

        // TODO Make calls concurrent for improved throughput.
        for ( final UserProvider provider : getUserProviders() )
        {
            try
            {
                // Use only those fields that are supported by the provider.
                final Set<String> supportedFields = new HashSet<>( fields );
                supportedFields.retainAll( provider.getSearchFields() );

                userList.addAll( provider.findUsers( supportedFields, query ) );
            }
            catch ( UnsupportedOperationException uoe )
            {
                Log.warn( "UserProvider.findUsers is not supported by this UserProvider: {}. Its users are not returned as part of search queries.", provider.getClass().getName() );
                supportSearch--;
            }
        }

        if ( supportSearch == 0 )
        {
            throw new UnsupportedOperationException( "None of the backing providers support this operation." );
        }
        return userList;
    }

    /**
     * Searches for users based on a set of fields and a query string. The fields must  be taken from the values
     * returned by {@link #getSearchFields()}. The query can  include wildcards. For example, a search on the field
     * "Name" with a query of "Ma*"  might return user's with the name "Matt", "Martha" and "Madeline".
     *
     * This method throws an UnsupportedOperationException when none of the backing providers support search.
     *
     * When fields are provided that are not supported by a particular provider, those fields are ignored by that
     * provider (but can still be used by other providers).
     *
     * The startIndex and numResults parameters are used to page through search results. For example, if the startIndex
     * is 0 and numResults is 10, the first  10 search results will be returned. Note that numResults is a request for
     * the number of results to return and that the actual number of results returned may be fewer.
     *
     * @param fields     the fields to search on.
     * @param query      the query string.
     * @param startIndex the starting index in the search result to return.
     * @param numResults the number of users to return in the search result.
     * @return a Collection of users that match the search.
     * @throws UnsupportedOperationException When none of the providers support search.
     */
    @Override
    public Collection<User> findUsers( Set<String> fields, String query, int startIndex, int numResults ) throws UnsupportedOperationException
    {
        final List<User> userList = new ArrayList<>();
        int supportSearch = getUserProviders().size();
        int totalMatchedUserCount = 0;

        for ( final UserProvider provider : getUserProviders() )
        {
            try
            {
                // Use only those fields that are supported by the provider.
                final Set<String> supportedFields = new HashSet<>( fields );
                supportedFields.retainAll( provider.getSearchFields() );

                // Query the provider for sub-results.
                final Collection<User> providerResults = provider.findUsers( fields, query );

                // Keep track of how many hits we have had so far.
                totalMatchedUserCount += providerResults.size();

                // Check if this sub-result contains the start of the page of data that is searched for.
                if ( startIndex >= totalMatchedUserCount )
                {
                    continue;
                }

                // From the sub-results, take those that are of interest.
                final int providerStartIndex = Math.max( 0, startIndex - totalMatchedUserCount );
                final int providerResultMax = numResults - userList.size();
                final List<User> providerList = providerResults instanceof List<?> ?
                        (List<User>) providerResults : new ArrayList<>( providerResults );
                userList.addAll( providerList.subList( providerStartIndex, providerResultMax ) );

                // Check if we have enough results.
                if ( userList.size() >= numResults )
                {
                    break;
                }
            }
            catch ( UnsupportedOperationException uoe )
            {
                Log.warn( "UserProvider.findUsers is not supported by this UserProvider: " + provider.getClass().getName() );
                supportSearch--;
            }
        }

        if ( supportSearch == 0 )
        {
            throw new UnsupportedOperationException( "None of the backing providers support this operation." );
        }
        return userList;
    }

    /**
     * Returns the combination of search fields supported by the backing providers. Note that the returned fields might
     * not be supported by every backing provider.
     *
     * @throws UnsupportedOperationException If no search fields are returned, or when at least one of the providers throws UnsupportedOperationException when its #getSearchField() is invoked.
     */
    @Override
    public Set<String> getSearchFields() throws UnsupportedOperationException
    {
        int supportSearch = getUserProviders().size();
        final Set<String> result = new HashSet<>();

        // TODO Make calls concurrent for improved throughput.
        for ( final UserProvider provider : getUserProviders() )
        {
            try
            {
                result.addAll( provider.getSearchFields() );
            }
            catch ( UnsupportedOperationException uoe )
            {
                Log.warn( "getSearchFields is not supported by this UserProvider: " + provider.getClass().getName() );
                supportSearch--;
            }
        }

        if ( supportSearch == 0 )
        {
            throw new UnsupportedOperationException( "None of the backing providers support this operation." );
        }
        return result;
    }

    /**
     * Returns whether <em>all</em> backing providers are read-only. When read-only, users can not be created, deleted,
     * or modified. If at least one provider is not read-only, this method returns false.
     *
     * @return true when all backing providers are read-only, otherwise false.
     */
    @Override
    public boolean isReadOnly()
    {
        // TODO Make calls concurrent for improved throughput.
        for ( final UserProvider provider : getUserProviders() )
        {
            // If at least one provider is not readonly, neither is this proxy.
            if ( !provider.isReadOnly() )
            {
                return false;
            }
        }

        return true;
    }

    /**
     * Returns whether <em>all</em> backing providers require a name to be set on User objects. If at least one proivder
     * does not, this method returns false.
     *
     * @return true when all backing providers require a name to be set on User objects, otherwise false.
     */
    @Override
    public boolean isNameRequired()
    {
        // TODO Make calls concurrent for improved throughput.
        for ( final UserProvider provider : getUserProviders() )
        {
            // If at least one provider does not require a name, neither is this proxy.
            if ( !provider.isNameRequired() )
            {
                return false;
            }
        }

        return true;
    }

    /**
     * Returns whether <em>all</em> backing providers require an email address to be set on User objects. If at least
     * one proivder does not, this method returns false.
     *
     * @return true when all backing providers require an email address to be set on User objects, otherwise false.
     */
    @Override
    public boolean isEmailRequired()
    {
        // TODO Make calls concurrent for improved throughput.
        for ( final UserProvider provider : getUserProviders() )
        {
            // If at least one provider does not require an email, neither is this proxy.
            if ( !provider.isEmailRequired() )
            {
                return false;
            }
        }

        return true;
    }
}