JDBCUserProvider.java 14.3 KB
Newer Older
1 2 3 4
/**
 * $Revision: $
 * $Date: $
 *
5
 * Copyright (C) 2005-2008 Jive Software. All rights reserved.
6 7
 *
 * This software is published under the terms of the GNU Public License (GPL),
8 9
 * a copy of which is included in this distribution, or a commercial license
 * agreement with Jive.
10 11
 */

12
package org.jivesoftware.openfire.user;
13 14

import org.jivesoftware.database.DbConnectionManager;
Gaston Dombiak's avatar
Gaston Dombiak committed
15
import org.jivesoftware.openfire.XMPPServer;
16 17 18
import org.jivesoftware.util.JiveGlobals;
import org.jivesoftware.util.Log;
import org.jivesoftware.util.StringUtils;
Gaston Dombiak's avatar
Gaston Dombiak committed
19
import org.xmpp.packet.JID;
20 21 22 23 24 25 26 27

import java.sql.*;
import java.util.*;
import java.util.Date;

/**
 * The JDBC user provider allows you to use an external database to define the users.
 * It is best used with the JDBCAuthProvider & JDBCGroupProvider to provide integration
28
 * between your external system and Openfire. All data is treated as read-only so any
29 30 31 32 33 34
 * set operations will result in an exception.<p/>
 *
 * For the seach facility, the SQL will be constructed from the SQL in the <i>search</i>
 * section below, as well as the <i>usernameField</i>, the <i>nameField</i> and the
 * <i>emailField</i>.<p/>
 *
35 36 37 38 39
 * To enable this provider, set the following in the system properties:<p/>
 *
 * <ul>
 * <li><tt>provider.user.className = org.jivesoftware.openfire.user.JDBCUserProvider</tt></li>
 * </ul>
40 41 42
 *
 * Then you need to set your driver, connection string and SQL statements:
 * <p/>
43 44 45 46 47 48 49 50 51 52 53
 * <ul>
 * <li><tt>jdbcProvider.driver = com.mysql.jdbc.Driver</tt></li>
 * <li><tt>jdbcProvider.connectionString = jdbc:mysql://localhost/dbname?user=username&amp;password=secret</tt></li>
 * <li><tt>jdbcUserProvider.loadUserSQL = SELECT name,email FROM myUser WHERE user = ?</tt></li>
 * <li><tt>jdbcUserProvider.userCountSQL = SELECT COUNT(*) FROM myUser</tt></li>
 * <li><tt>jdbcUserProvider.allUsersSQL = SELECT user FROM myUser</tt></li>
 * <li><tt>jdbcUserProvider.searchSQL = SELECT user FROM myUser WHERE</tt></li>
 * <li><tt>jdbcUserProvider.usernameField = myUsernameField</tt></li>
 * <li><tt>jdbcUserProvider.nameField = myNameField</tt></li>
 * <li><tt>jdbcUserProvider.emailField = mymailField</tt></li>
 * </ul>
54
 *
55 56 57 58 59 60 61 62
 * In order to use the configured JDBC connection provider do not use a JDBC
 * connection string, set the following property
 *
 * <ul>
 * <li><tt>jdbcUserProvider.useConnectionProvider = true</tt></li>
 * </ul>
 *
 *
63 64 65 66 67 68 69 70 71 72 73 74 75
 * @author Huw Richards huw.richards@gmail.com
 */
public class JDBCUserProvider implements UserProvider {

	private String connectionString;

	private String loadUserSQL;
	private String userCountSQL;
	private String allUsersSQL;
	private String searchSQL;
	private String usernameField;
	private String nameField;
	private String emailField;
76
	private boolean useConnectionProvider;
77 78 79 80 81

    /**
     * Constructs a new JDBC user provider.
     */
    public JDBCUserProvider() {
82 83 84 85 86 87 88 89 90 91 92
        // Convert XML based provider setup to Database based
        JiveGlobals.migrateProperty("jdbcProvider.driver");
        JiveGlobals.migrateProperty("jdbcProvider.connectionString");
        JiveGlobals.migrateProperty("jdbcUserProvider.loadUserSQL");
        JiveGlobals.migrateProperty("jdbcUserProvider.userCountSQL");
        JiveGlobals.migrateProperty("jdbcUserProvider.allUsersSQL");
        JiveGlobals.migrateProperty("jdbcUserProvider.searchSQL");
        JiveGlobals.migrateProperty("jdbcUserProvider.usernameField");
        JiveGlobals.migrateProperty("jdbcUserProvider.nameField");
        JiveGlobals.migrateProperty("jdbcUserProvider.emailField");

93 94 95 96 97 98 99 100 101 102 103 104 105
        useConnectionProvider = JiveGlobals.getBooleanProperty("jdbcUserProvider.useConnectionProvider");

            // Load the JDBC driver and connection string.
		if (!useConnectionProvider) {
			String jdbcDriver = JiveGlobals.getProperty("jdbcProvider.driver");
			try {
				Class.forName(jdbcDriver).newInstance();
			}
			catch (Exception e) {
				Log.error("Unable to load JDBC driver: " + jdbcDriver, e);
				return;
			}
			connectionString = JiveGlobals.getProperty("jdbcProvider.connectionString");
106 107 108
		}

        // Load database statements for user data.
109 110 111 112 113 114 115
        loadUserSQL = JiveGlobals.getProperty("jdbcUserProvider.loadUserSQL");
		userCountSQL = JiveGlobals.getProperty("jdbcUserProvider.userCountSQL");
		allUsersSQL = JiveGlobals.getProperty("jdbcUserProvider.allUsersSQL");
		searchSQL = JiveGlobals.getProperty("jdbcUserProvider.searchSQL");
		usernameField = JiveGlobals.getProperty("jdbcUserProvider.usernameField");
		nameField = JiveGlobals.getProperty("jdbcUserProvider.nameField");
		emailField = JiveGlobals.getProperty("jdbcUserProvider.emailField");
116 117 118
	}

	public User loadUser(String username) throws UserNotFoundException {
119
        if(username.contains("@")) {
Gaston Dombiak's avatar
Gaston Dombiak committed
120 121 122
            if (!XMPPServer.getInstance().isLocal(new JID(username))) {
                throw new UserNotFoundException("Cannot load user of remote server: " + username);
            }
123 124
            username = username.substring(0,username.lastIndexOf("@"));
        }
125 126 127 128
		Connection con = null;
		PreparedStatement pstmt = null;
		ResultSet rs = null;
        try {
129
			con = getConnection();
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
			pstmt = con.prepareStatement(loadUserSQL);
			pstmt.setString(1, username);
			rs = pstmt.executeQuery();
			if (!rs.next()) {
				throw new UserNotFoundException();
			}
			String name = rs.getString(1);
			String email = rs.getString(2);

			return new User(username, name, email, new Date(), new Date());
		}
		catch (Exception e) {
			throw new UserNotFoundException(e);
		}
		finally {
			DbConnectionManager.closeConnection(rs, pstmt, con);
		}
	}

	public int getUserCount() {
		int count = 0;
		Connection con = null;
		PreparedStatement pstmt = null;
		ResultSet rs = null;
        try {
155
			con = getConnection();
156 157 158 159 160 161 162 163 164 165 166 167 168 169 170
			pstmt = con.prepareStatement(userCountSQL);
			rs = pstmt.executeQuery();
			if (rs.next()) {
				count = rs.getInt(1);
			}
		}
		catch (SQLException e) {
			Log.error(e);
		}
		finally {
			DbConnectionManager.closeConnection(rs, pstmt, con);
		}
		return count;
	}

171 172 173 174 175 176
	private Connection getConnection() throws SQLException {
		if (useConnectionProvider)
			return DbConnectionManager.getConnection();
		return DriverManager.getConnection(connectionString);
	}

177 178 179 180 181 182 183 184 185 186 187
	public Collection<User> getUsers() {
		Collection<String> usernames = getUsernames();
		return new UserCollection(usernames.toArray(new String[usernames.size()]));
	}

	public Collection<String> getUsernames() {
		List<String> usernames = new ArrayList<String>(500);
		Connection con = null;
		PreparedStatement pstmt = null;
        ResultSet rs = null;
        try {
188
			con = getConnection();
189 190 191 192 193 194
			pstmt = con.prepareStatement(allUsersSQL);
			rs = pstmt.executeQuery();
			// Set the fetch size. This will prevent some JDBC drivers from trying
			// to load the entire result set into memory.
			DbConnectionManager.setFetchSize(rs, 500);
			while (rs.next()) {
195
				Log.debug("JDBCUserProvider: "+rs.getString(1));
196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213
				usernames.add(rs.getString(1));
			}
		}
		catch (SQLException e) {
			Log.error(e);
		}
		finally {
			DbConnectionManager.closeConnection(rs, pstmt, con);
		}
		return usernames;
	}

	public Collection<User> getUsers(int startIndex, int numResults) {
		List<String> usernames = new ArrayList<String>(numResults);
		Connection con = null;
		PreparedStatement pstmt = null;
		ResultSet rs = null;
        try {
214
			con = getConnection();
215 216 217 218 219 220
			pstmt = DbConnectionManager.createScrollablePreparedStatement(con, allUsersSQL);
			rs = pstmt.executeQuery();
			DbConnectionManager.setFetchSize(rs, startIndex + numResults);
			DbConnectionManager.scrollResultSet(rs, startIndex);
			int count = 0;
			while (rs.next() && count < numResults) {
221
				Log.debug("JDBCUserProvider: "+rs.getString(1));
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
				usernames.add(rs.getString(1));
				count++;
			}
		}
		catch (SQLException e) {
			Log.error(e);
		}
		finally {
			DbConnectionManager.closeConnection(rs, pstmt, con);
		}
		return new UserCollection(usernames.toArray(new String[usernames.size()]));
	}

	public User createUser(String username, String password, String name, String email)
			throws UserAlreadyExistsException {
		// Reject the operation since the provider is read-only
		throw new UnsupportedOperationException();
	}

	public void deleteUser(String username) {
		// Reject the operation since the provider is read-only
		throw new UnsupportedOperationException();
	}

	public void setName(String username, String name) throws UserNotFoundException {
		// Reject the operation since the provider is read-only
		throw new UnsupportedOperationException();
	}

	public void setEmail(String username, String email) throws UserNotFoundException {
		// Reject the operation since the provider is read-only
		throw new UnsupportedOperationException();
	}

	public void setCreationDate(String username, Date creationDate) throws UserNotFoundException {
		// Reject the operation since the provider is read-only
		throw new UnsupportedOperationException();
	}

	public void setModificationDate(String username, Date modificationDate) throws UserNotFoundException {
		// Reject the operation since the provider is read-only
		throw new UnsupportedOperationException();
	}

	public Collection<User> findUsers(Set<String> fields, String query)
			throws UnsupportedOperationException
    {
		if (searchSQL == null) {
            throw new UnsupportedOperationException();
        }
        if (fields.isEmpty()) {
			return Collections.emptyList();
		}
		if (!getSearchFields().containsAll(fields)) {
			throw new IllegalArgumentException("Search fields " + fields + " are not valid.");
		}
		if (query == null || "".equals(query)) {
			return Collections.emptyList();
		}
		// SQL LIKE queries don't map directly into a keyword/wildcard search like we want.
		// Therefore, we do a best approximiation by replacing '*' with '%' and then
		// surrounding the whole query with two '%'. This will return more data than desired,
		// but is better than returning less data than desired.
		query = "%" + query.replace('*', '%') + "%";
		if (query.endsWith("%%")) {
			query = query.substring(0, query.length() - 1);
		}

		List<String> usernames = new ArrayList<String>(50);
		Connection con = null;
		Statement stmt = null;
		ResultSet rs = null;
        try {
295
			con = getConnection();
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
			stmt = con.createStatement();
			StringBuilder sql = new StringBuilder();
			sql.append(searchSQL);
			boolean first = true;
			if (fields.contains("Username")) {
				sql.append(" ")
						.append(usernameField)
						.append(" LIKE '")
						.append(StringUtils.escapeForSQL(query)).append("'");
				first = false;
			}
			if (fields.contains("Name")) {
				if (!first) {
					sql.append(" AND ");
				}
				sql.append(" ")
						.append(nameField)
						.append(" LIKE '")
						.append(StringUtils.escapeForSQL(query)).append("'");
				first = false;
			}
			if (fields.contains("Email")) {
				if (!first) {
					sql.append(" AND ");
				}
				sql.append(" ")
						.append(emailField)
						.append(" LIKE '")
						.append(StringUtils.escapeForSQL(query)).append("'");
			}
326
			Log.debug("JDBCUserProvider: "+sql.toString());
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
			rs = stmt.executeQuery(sql.toString());
			while (rs.next()) {
				usernames.add(rs.getString(1));
			}
		}
		catch (SQLException e) {
			Log.error(e);
		}
		finally {
			DbConnectionManager.closeConnection(rs, stmt, con);
		}
		return new UserCollection(usernames.toArray(new String[usernames.size()]));
	}

	public Collection<User> findUsers(Set<String> fields, String query, int startIndex,
            int numResults) throws UnsupportedOperationException
    {
		if (searchSQL == null) {
            throw new UnsupportedOperationException();
        }
        if (fields.isEmpty()) {
			return Collections.emptyList();
		}
		if (!getSearchFields().containsAll(fields)) {
			throw new IllegalArgumentException("Search fields " + fields + " are not valid.");
		}
		if (query == null || "".equals(query)) {
			return Collections.emptyList();
		}
		// SQL LIKE queries don't map directly into a keyword/wildcard search like we want.
		// Therefore, we do a best approximiation by replacing '*' with '%' and then
		// surrounding the whole query with two '%'. This will return more data than desired,
		// but is better than returning less data than desired.
		query = "%" + query.replace('*', '%') + "%";
		if (query.endsWith("%%")) {
			query = query.substring(0, query.length() - 1);
		}

		List<String> usernames = new ArrayList<String>(50);
		Connection con = null;
		Statement stmt = null;
        ResultSet rs = null;
        try {
370
			con = getConnection();
371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400
			stmt = con.createStatement();
			StringBuilder sql = new StringBuilder();
			sql.append(searchSQL);
			boolean first = true;
			if (fields.contains("Username")) {
				sql.append(" ")
						.append(usernameField)
						.append(" LIKE '")
						.append(StringUtils.escapeForSQL(query)).append("'");
				first = false;
			}
			if (fields.contains("Name")) {
				if (!first) {
					sql.append(" AND ");
				}
				sql.append(" ")
						.append(nameField)
						.append("LIKE '")
						.append(StringUtils.escapeForSQL(query)).append("'");
				first = false;
			}
			if (fields.contains("Email")) {
				if (!first) {
					sql.append(" AND ");
				}
				sql.append(" ")
						.append(emailField)
						.append(" LIKE '")
						.append(StringUtils.escapeForSQL(query)).append("'");
			}
401
			Log.debug("JDBCUserProvider: "+sql.toString());
402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427
			rs = stmt.executeQuery(sql.toString());
			// Scroll to the start index.
			DbConnectionManager.scrollResultSet(rs, startIndex);
			while (rs.next()) {
				usernames.add(rs.getString(1));
			}
		}
		catch (SQLException e) {
			Log.error(e);
		}
		finally {
			DbConnectionManager.closeConnection(rs, stmt, con);
		}
		return new UserCollection(usernames.toArray(new String[usernames.size()]));
	}

	public Set<String> getSearchFields() throws UnsupportedOperationException {
        if (searchSQL == null) {
            throw new UnsupportedOperationException();
        }
        return new LinkedHashSet<String>(Arrays.asList("Username", "Name", "Email"));
	}

	public boolean isReadOnly() {
		return true;
	}
428 429 430 431 432 433 434 435

    public boolean isNameRequired() {
        return false;
    }

    public boolean isEmailRequired() {
        return false;
    }
436
}