DbConnectionManager.java 35.2 KB
Newer Older
Matt Tucker's avatar
Matt Tucker committed
1 2 3 4 5
/**
 * $RCSfile$
 * $Revision$
 * $Date$
 *
6
 * Copyright (C) 2004-2008 Jive Software. All rights reserved.
Matt Tucker's avatar
Matt Tucker committed
7
 *
8 9 10 11 12 13 14 15 16 17 18
 * 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.
Matt Tucker's avatar
Matt Tucker committed
19 20 21 22
 */

package org.jivesoftware.database;

23 24 25 26 27 28 29 30 31
import java.io.Reader;
import java.io.StringReader;
import java.io.StringWriter;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
32
import java.util.MissingResourceException;
33

Matt Tucker's avatar
Matt Tucker committed
34
import org.jivesoftware.util.ClassUtils;
35
import org.jivesoftware.util.JiveGlobals;
36 37
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
Matt Tucker's avatar
Matt Tucker committed
38 39 40 41

/**
 * Central manager of database connections. All methods are static so that they
 * can be easily accessed throughout the classes in the database package.<p>
42
 *
Matt Tucker's avatar
Matt Tucker committed
43 44 45 46 47
 * This class also provides a set of utility methods that abstract out
 * operations that may not work on all databases such as setting the max number
 * or rows that a query should return.
 *
 * @author Jive Software
48
 * @see ConnectionProvider
Matt Tucker's avatar
Matt Tucker committed
49 50 51
 */
public class DbConnectionManager {

52 53
	private static final Logger Log = LoggerFactory.getLogger(DbConnectionManager.class);

Matt Tucker's avatar
Matt Tucker committed
54
    private static ConnectionProvider connectionProvider;
55
    private static final Object providerLock = new Object();
Matt Tucker's avatar
Matt Tucker committed
56 57 58 59 60 61 62 63

    // True if connection profiling is turned on. Always false by default.
    private static boolean profilingEnabled = false;

    // True if the database support transactions.
    private static boolean transactionsSupported;
    // True if the database requires large text fields to be streamed.
    private static boolean streamTextRequired;
64
    /** True if the database supports the Statement.setMaxRows() method. */
Matt Tucker's avatar
Matt Tucker committed
65
    private static boolean maxRowsSupported;
66
    /** True if the database supports the rs.setFetchSize() method. */
Matt Tucker's avatar
Matt Tucker committed
67 68 69 70 71 72 73
    private static boolean fetchSizeSupported;
    // True if the database supports correlated subqueries.
    private static boolean subqueriesSupported;
    // True if the database supports scroll-insensitive results.
    private static boolean scrollResultsSupported;
    // True if the database supports batch updates.
    private static boolean batchUpdatesSupported;
74 75 76
    /** True if the database supports the Statement.setFetchSize()) method. */
    static boolean pstmt_fetchSizeSupported = true;

Matt Tucker's avatar
Matt Tucker committed
77

78
    private static DatabaseType databaseType = DatabaseType.unknown;
Matt Tucker's avatar
Matt Tucker committed
79

80 81
    private static SchemaManager schemaManager = new SchemaManager();

Matt Tucker's avatar
Matt Tucker committed
82 83
    /**
     * Returns a database connection from the currently active connection
Gaston Dombiak's avatar
Gaston Dombiak committed
84 85
     * provider. An exception will be thrown if no connection was found.
     * (auto commit is set to true).
86 87
     *
     * @return a connection.
Gaston Dombiak's avatar
Gaston Dombiak committed
88
     * @throws SQLException if a SQL exception occurs or no connection was found.
Matt Tucker's avatar
Matt Tucker committed
89 90 91 92 93 94 95
     */
    public static Connection getConnection() throws SQLException {
        if (connectionProvider == null) {
            synchronized (providerLock) {
                if (connectionProvider == null) {
                    // Attempt to load the connection provider classname as
                    // a Jive property.
96
                    String className = JiveGlobals.getXMLProperty("connectionProvider.className");
Matt Tucker's avatar
Matt Tucker committed
97 98 99 100 101 102 103
                    if (className != null) {
                        // Attempt to load the class.
                        try {
                            Class conClass = ClassUtils.forName(className);
                            setConnectionProvider((ConnectionProvider)conClass.newInstance());
                        }
                        catch (Exception e) {
104
                            Log.warn("Failed to create the " +
Matt Tucker's avatar
Matt Tucker committed
105 106 107 108 109 110 111 112 113 114 115
                                    "connection provider specified by connection" +
                                    "Provider.className. Using the default pool.", e);
                            setConnectionProvider(new DefaultConnectionProvider());
                        }
                    }
                    else {
                        setConnectionProvider(new DefaultConnectionProvider());
                    }
                }
            }
        }
116 117 118 119 120

        // TODO: May want to make these settings configurable
        Integer retryCnt = 0;
        Integer retryMax = 10;
        Integer retryWait = 250; // milliseconds
121 122
        Connection con = null;
        SQLException lastException = null;
123
        do {
124 125
            try {
            	con = connectionProvider.getConnection();
126 127 128 129 130 131 132 133 134 135 136 137
                if (con != null) {
                    // Got one, lets hand it off.
                    // Usually profiling is not enabled. So we return a normal 
                    // connection unless profiling is enabled. If yes, wrap the
                    // connection with a profiled connection.
                    if (!profilingEnabled) {
                        return con;
                    }
                    else {
                        return new ProfiledConnection(con); 
                    }
                }
138 139 140 141 142 143
            } catch (SQLException e) {
            	// TODO distinguish recoverable from non-recoverable exceptions.
            	lastException = e;
            	Log.info("Unable to get a connection from the database pool " +
            			"(attempt "+retryCnt+" out of "+retryMax+").", e);
			}
144 145 146 147 148 149
            try {
                Thread.sleep(retryWait);
            }
            catch (Exception e) {
                // Ignored
            }
150
            retryCnt++;
151
        } while (retryCnt <= retryMax);
152 153 154
        throw new SQLException("ConnectionManager.getConnection() " +
                "failed to obtain a connection after " + retryCnt +" retries. " +
                "The exception from the last attempt is as follows: "+lastException);
Matt Tucker's avatar
Matt Tucker committed
155 156 157 158 159
    }

    /**
     * Returns a Connection from the currently active connection provider that
     * is ready to participate in transactions (auto commit is set to false).
160 161 162
     *
     * @return a connection with transactions enabled.
     * @throws SQLException if a SQL exception occurs.
Matt Tucker's avatar
Matt Tucker committed
163 164 165 166 167 168 169 170 171
     */
    public static Connection getTransactionConnection() throws SQLException {
        Connection con = getConnection();
        if (isTransactionsSupported()) {
            con.setAutoCommit(false);
        }
        return con;
    }

172 173 174
    /**
     * Closes a PreparedStatement and Connection. However, it first rolls back the transaction or
     * commits it depending on the value of <code>abortTransaction</code>.
175 176 177 178
     *
     * @param pstmt the prepared statement to close.
     * @param con the connection to close.
     * @param abortTransaction true if the transaction should be rolled back.
179 180 181 182
     */
    public static void closeTransactionConnection(PreparedStatement pstmt, Connection con,
            boolean abortTransaction)
    {
183
        closeStatement(pstmt);
184 185 186
        closeTransactionConnection(con, abortTransaction);
    }

Matt Tucker's avatar
Matt Tucker committed
187 188 189
    /**
     * Closes a Connection. However, it first rolls back the transaction or
     * commits it depending on the value of <code>abortTransaction</code>.
190 191 192
     *
     * @param con the connection to close.
     * @param abortTransaction true if the transaction should be rolled back.
Matt Tucker's avatar
Matt Tucker committed
193 194 195 196 197 198 199 200 201 202 203 204 205
     */
    public static void closeTransactionConnection(Connection con, boolean abortTransaction) {
        // Rollback or commit the transaction
        if (isTransactionsSupported()) {
            try {
                if (abortTransaction) {
                    con.rollback();
                }
                else {
                    con.commit();
                }
            }
            catch (Exception e) {
206
                Log.error(e.getMessage(), e);
Matt Tucker's avatar
Matt Tucker committed
207 208
            }
            // Reset the connection to auto-commit mode.
209 210 211 212 213
            try {
                con.setAutoCommit(true);              
            }
            catch (Exception e) {
                Log.error(e.getMessage(), e);
Matt Tucker's avatar
Matt Tucker committed
214 215
            }
        }
216
        closeConnection(con);
Matt Tucker's avatar
Matt Tucker committed
217 218
    }

219 220
    /**
     * Closes a result set. This method should be called within the finally section of
221 222 223 224 225 226 227 228 229 230 231 232
     * your database logic, as in the following example:
     *
     * <pre>
     *  public void doSomething(Connection con) {
     *      ResultSet rs = null;
     *      PreparedStatement pstmt = null;
     *      try {
     *          pstmt = con.prepareStatement("select * from blah");
     *          rs = pstmt.executeQuery();
     *          ....
     *      }
     *      catch (SQLException sqle) {
233
     *          Log.error(sqle.getMessage(), sqle);
234 235 236 237 238 239
     *      }
     *      finally {
     *          ConnectionManager.closeResultSet(rs);
     *          ConnectionManager.closePreparedStatement(pstmt);
     *      }
     * } </pre>
240 241
     *
     * @param rs the result set to close.
242 243
     */
    public static void closeResultSet(ResultSet rs) {
244 245 246 247 248 249
        if (rs != null) {
            try {
                    rs.close();
                }
            catch (SQLException e) {
                Log.error(e.getMessage(), e);
250 251 252 253 254
            }
        }
    }

    /**
255
     * Closes a statement. This method should be called within the finally section of
256 257 258 259 260 261 262 263 264 265
     * your database logic, as in the following example:
     *
     * <pre>
     *  public void doSomething(Connection con) {
     *      PreparedStatement pstmt = null;
     *      try {
     *          pstmt = con.prepareStatement("select * from blah");
     *          ....
     *      }
     *      catch (SQLException sqle) {
266
     *          Log.error(sqle.getMessage(), sqle);
267 268
     *      }
     *      finally {
269
     *          ConnectionManager.closeStatement(pstmt);
270 271 272
     *      }
     * } </pre>
     *
273
     * @param stmt the statement.
274
     */
275
    public static void closeStatement(Statement stmt) {
276 277
        if (stmt != null) {
            try {
278
                stmt.close();
279 280 281
            }       
            catch (Exception e) {
                Log.error(e.getMessage(), e);
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
    
    /**
     * Closes a statement and a result set. This method should be called within the finally section of
     * your database logic, as in the following example:
     *
     * <pre>
     *  public void doSomething(Connection con) {
     *      PreparedStatement pstmt = null;
     *      ResultSet rs = null;
     *      try {
     *          pstmt = con.prepareStatement("select * from blah");
     *          rs = ...
     *          ....
     *      }
     *      catch (SQLException sqle) {
     *          Log.error(sqle.getMessage(), sqle);
     *      }
     *      finally {
     *          ConnectionManager.closeStatement(rs, pstmt);
     *      }
     * } </pre>
     *
     * @param stmt the statement.
     */
    public static void closeStatement(ResultSet rs, Statement stmt) {
        closeResultSet(rs);
        closeStatement(stmt);
    }
    /**
     * Closes a statement. This method should be called within the try section of
     * your database logic when you reuse a statement. It may throws an exception,
     * so don't place it in the finally section.<br>
     * Example:
     *
     * <pre>
     *  public void doSomething(Connection con) {
     *      PreparedStatement pstmt = null;
     *      try {
     *          pstmt = con.prepareStatement("select * from dual");
     *          pstmt.executeUpdate();
     *          ...
     *          <b>ConnectionManager.fastcloseStmt(pstmt);</b>
     *          pstmt = con.prepareStatement("select * from blah");
     *          ...
     *      }
     *      ...
     * } </pre>
     *
333
     * @param pstmt the statement to close.
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
     */
    public static void fastcloseStmt(PreparedStatement pstmt) throws SQLException
    {
        pstmt.close();
    }
        
    /**
     * Closes a statement and a result set. This method should be called within the try section of
     * your database logic when you reuse a statement. It may throw an exception,
     * so don't place it in the finally section.<br>
     * Example:
     *
     * <pre>
     *  public void doSomething(Connection con) {
     *      PreparedStatement pstmt = null;
     *      try {
     *          pstmt = con.prepareStatement("select * from blah");
     *          rs = pstmt.executeQuery();
     *          ...
     *          ConnectionManager.fastcloseStmt(rs, pstmt);
     *          pstmt = con.prepareStatement("select * from blah");
     *          ...
     *      }
     *      ...
     * } </pre>
     *
360
     * @param pstmt the statement to close.
361 362 363 364 365 366
     */
    public static void fastcloseStmt(ResultSet rs, PreparedStatement pstmt) throws SQLException
    {
        rs.close();
        pstmt.close();
    }
367 368

    /**
369
     * Closes a result set, statement and database connection (returning the connection to
370 371 372 373 374 375 376 377 378 379 380 381 382 383
     * the connection pool). This method should be called within the finally section of
     * your database logic, as in the following example:
     *
     * <pre>
     * Connection con = null;
     * PrepatedStatment pstmt = null;
     * ResultSet rs = null;
     * try {
     *     con = ConnectionManager.getConnection();
     *     pstmt = con.prepareStatement("select * from blah");
     *     rs = psmt.executeQuery();
     *     ....
     * }
     * catch (SQLException sqle) {
384
     *     Log.error(sqle.getMessage(), sqle);
385 386 387 388 389
     * }
     * finally {
     *     ConnectionManager.closeConnection(rs, pstmt, con);
     * }</pre>
     *
390
     * @param rs the result set.
391
     * @param stmt the statement.
392 393
     * @param con the connection.
     */
394
    public static void closeConnection(ResultSet rs, Statement stmt, Connection con) {
395
        closeResultSet(rs);
396
        closeStatement(stmt);
397 398 399
        closeConnection(con);
    }

400
    /**
401
     * Closes a statement and database connection (returning the connection to
402 403 404 405 406 407 408 409 410 411 412
     * the connection pool). This method should be called within the finally section of
     * your database logic, as in the following example:
     * <pre>
     * Connection con = null;
     * PrepatedStatment pstmt = null;
     * try {
     *     con = ConnectionManager.getConnection();
     *     pstmt = con.prepareStatement("select * from blah");
     *     ....
     * }
     * catch (SQLException sqle) {
413
     *     Log.error(sqle.getMessage(), sqle);
414 415 416 417 418
     * }
     * finally {
     *     DbConnectionManager.closeConnection(pstmt, con);
     * }</pre>
     *
419 420
     * @param stmt the statement.
     * @param con the connection.
421
     */
422
    public static void closeConnection(Statement stmt, Connection con) {
423
        closeStatement(stmt);
424 425 426 427 428 429 430 431 432 433 434 435 436 437 438
        closeConnection(con);
    }

    /**
     * Closes a database connection (returning the connection to the connection pool). Any
     * statements associated with the connection should be closed before calling this method.
     * This method should be called within the finally section of your database logic, as
     * in the following example:
     * <pre>
     * Connection con = null;
     * try {
     *     con = ConnectionManager.getConnection();
     *     ....
     * }
     * catch (SQLException sqle) {
439
     *     Log.error(sqle.getMessage(), sqle);
440 441 442 443 444 445 446 447
     * }
     * finally {
     *     DbConnectionManager.closeConnection(con);
     * }</pre>
     *
     * @param con the connection.
     */
    public static void closeConnection(Connection con) {
448 449 450 451 452 453
        if (con != null) {
            try {
               con.close();
            }
            catch (Exception e) {
                Log.error(e.getMessage(), e);
454 455 456 457
            }
        }
    }

Matt Tucker's avatar
Matt Tucker committed
458 459 460 461 462 463 464 465
    /**
     * Creates a scroll insensitive Statement if the JDBC driver supports it, or a normal
     * Statement otherwise.
     *
     * @param con the database connection.
     * @return a Statement
     * @throws SQLException if an error occurs.
     */
466
    @Deprecated
Matt Tucker's avatar
Matt Tucker committed
467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497
    public static Statement createScrollableStatement(Connection con) throws SQLException {
        if (isScrollResultsSupported()) {
            return con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
                    ResultSet.CONCUR_READ_ONLY);
        }
        else {
            return con.createStatement();
        }
    }

    /**
     * Creates a scroll insensitive PreparedStatement if the JDBC driver supports it, or a normal
     * PreparedStatement otherwise.
     *
     * @param con the database connection.
     * @param sql the SQL to create the PreparedStatement with.
     * @return a PreparedStatement
     * @throws java.sql.SQLException if an error occurs.
     */
    public static PreparedStatement createScrollablePreparedStatement(Connection con, String sql)
            throws SQLException {
        if (isScrollResultsSupported()) {
            return con.prepareStatement(sql, ResultSet.TYPE_SCROLL_INSENSITIVE,
                    ResultSet.CONCUR_READ_ONLY);
        }
        else {
            return con.prepareStatement(sql);
        }
    }

    /**
498 499 500
     * Scrolls forward in a result set the specified number of rows. If the JDBC driver
     * supports the feature, the cursor will be moved directly. Otherwise, we scroll
     * through results one by one manually by calling <tt>rs.next()</tt>.
Matt Tucker's avatar
Matt Tucker committed
501
     *
502
     * @param rs the ResultSet object to scroll.
Matt Tucker's avatar
Matt Tucker committed
503 504 505 506 507 508 509
     * @param rowNumber the row number to scroll forward to.
     * @throws SQLException if an error occurs.
     */
    public static void scrollResultSet(ResultSet rs, int rowNumber) throws SQLException {
        // If the driver supports scrollable result sets, use that feature.
        if (isScrollResultsSupported()) {
            if (rowNumber > 0) {
510 511 512 513 514
                // We will attempt to do a relative fetch. This may fail in SQL Server if
                // <resultset-navigation-strategy> is set to absolute. It would need to be
                // set to looping to work correctly.
                // If so, manually scroll to the correct row.
                try {
515
                    rs.setFetchDirection(ResultSet.FETCH_FORWARD);
516 517 518
                    rs.relative(rowNumber);
                }
                catch (SQLException e) {
519 520 521 522
                    // TODO change "Error ..." to "Disabling ..."
                    Log.error("Error in JDBC method rs.relative(rowNumber).", e);
                    //Log.error("Disabling JDBC method rs.relative(rowNumber).", e);
                    //scrollResultsSupported = false;
523 524 525 526
                    for (int i = 0; i < rowNumber; i++) {
                        rs.next();
                    }
                }
Matt Tucker's avatar
Matt Tucker committed
527 528 529 530 531 532 533 534 535 536
            }
        }
        // Otherwise, manually scroll to the correct row.
        else {
            for (int i = 0; i < rowNumber; i++) {
                rs.next();
            }
        }
    }

537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584
    /**
     * Limits the number of the results in a result set (to startIndex + numResults).
     * Sets the fetch size depending on the features of the JDBC driver and make
     * sure that the size is not bigger than 500. 
     * @param pstmt the PreparedStatement
     * @param startIndex the first row with interesting data
     * @param numResults the number of interesting results
     */
    public static void limitRowsAndFetchSize(PreparedStatement pstmt, int startIndex, int numResults) {
        final int MAX_FETCHRESULTS = 500;
        final int maxRows = startIndex + numResults;
        setMaxRows(pstmt, maxRows);
        if (pstmt_fetchSizeSupported)
        {
            if (scrollResultsSupported) {
                setFetchSize(pstmt, Math.min(MAX_FETCHRESULTS, numResults));
            }
            else {
                setFetchSize(pstmt, Math.min(MAX_FETCHRESULTS, maxRows));            
            }
        }
    }
    
    /**
     * Sets the number of rows that the JDBC driver should buffer at a time.
     * The operation is automatically bypassed if Openfire knows that the
     * the JDBC driver or database doesn't support it.
     *
     * @param pstmt the PreparedStatement to set the fetch size for.
     * @param fetchSize the fetchSize.
     */
    public static void setFetchSize(PreparedStatement pstmt, int fetchSize) {
        if (pstmt_fetchSizeSupported) {
            try {
                pstmt.setFetchSize(fetchSize);
            }
            catch (Throwable t) {
                // Ignore. Exception may happen if the driver doesn't support
                // this operation and we didn't set meta-data correctly.
                // However, it is a good idea to update the meta-data so that
                // we don't have to incur the cost of catching an exception
                // each time.
                Log.error("Disabling JDBC method pstmt.setFetchSize(fetchSize).", t);
                pstmt_fetchSizeSupported = false;
            }
        }
    }

Matt Tucker's avatar
Matt Tucker committed
585 586 587 588 589
    /**
     * Returns the current connection provider. The only case in which this
     * method should be called is if more information about the current
     * connection provider is needed. Database connections should always be
     * obtained by calling the getConnection method of this class.
590 591
     *
     * @return the connection provider.
Matt Tucker's avatar
Matt Tucker committed
592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618
     */
    public static ConnectionProvider getConnectionProvider() {
        return connectionProvider;
    }

    /**
     * Sets the connection provider. The old provider (if it exists) is shut
     * down before the new one is started. A connection provider <b>should
     * not</b> be started before being passed to the connection manager
     * because the manager will call the start() method automatically.
     *
     * @param provider the ConnectionProvider that the manager should obtain
     *                 connections from.
     */
    public static void setConnectionProvider(ConnectionProvider provider) {
        synchronized (providerLock) {
            if (connectionProvider != null) {
                connectionProvider.destroy();
                connectionProvider = null;
            }
            connectionProvider = provider;
            connectionProvider.start();
            // Now, get a connection to determine meta data.
            Connection con = null;
            try {
                con = connectionProvider.getConnection();
                setMetaData(con);
619 620

                // Check to see if the database schema needs to be upgraded.
621
                schemaManager.checkOpenfireSchema(con);
Matt Tucker's avatar
Matt Tucker committed
622
            }
623 624 625
            catch (MissingResourceException mre) {
                Log.error(mre.getMessage());
            }
Matt Tucker's avatar
Matt Tucker committed
626
            catch (Exception e) {
627
                Log.error(e.getMessage(), e);
Matt Tucker's avatar
Matt Tucker committed
628 629
            }
            finally {
630
                closeConnection(con);
Matt Tucker's avatar
Matt Tucker committed
631 632 633
            }
        }
        // Remember what connection provider we want to use for restarts.
634
        JiveGlobals.setXMLProperty("connectionProvider.className", provider.getClass().getName());
Matt Tucker's avatar
Matt Tucker committed
635 636
    }

637 638 639 640 641 642 643 644 645 646 647 648 649 650 651
    /**
     * Destroys the currennt connection provider. Future calls to
     * {@link #getConnectionProvider()} will return <tt>null</tt> until a new
     * ConnectionProvider is set, or one is automatically loaded by a call to
     * {@link #getConnection()}.
     */
    public static void destroyConnectionProvider() {
        synchronized (providerLock) {
            if (connectionProvider != null) {
                connectionProvider.destroy();
                connectionProvider = null;
            }
        }
    }

Matt Tucker's avatar
Matt Tucker committed
652 653 654 655 656 657
    /**
     * Retrives a large text column from a result set, automatically performing
     * streaming if the JDBC driver requires it. This is necessary because
     * different JDBC drivers have different capabilities and methods for
     * retrieving large text values.
     *
658
     * @param rs the ResultSet to retrieve the text field from.
Matt Tucker's avatar
Matt Tucker committed
659 660
     * @param columnIndex the column in the ResultSet of the text field.
     * @return the String value of the text field.
661
     * @throws SQLException if an SQL exception occurs.
Matt Tucker's avatar
Matt Tucker committed
662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681
     */
    public static String getLargeTextField(ResultSet rs, int columnIndex) throws SQLException {
        if (isStreamTextRequired()) {
            Reader bodyReader = null;
            String value = null;
            try {
                bodyReader = rs.getCharacterStream(columnIndex);
                if (bodyReader == null) {
                    return null;
                }
                char[] buf = new char[256];
                int len;
                StringWriter out = new StringWriter(256);
                while ((len = bodyReader.read(buf)) >= 0) {
                    out.write(buf, 0, len);
                }
                value = out.toString();
                out.close();
            }
            catch (Exception e) {
682
                Log.error(e.getMessage(), e);
Matt Tucker's avatar
Matt Tucker committed
683 684 685 686
                throw new SQLException("Failed to load text field");
            }
            finally {
                try {
687 688 689
                    if (bodyReader != null) {
                        bodyReader.close();
                    }
Matt Tucker's avatar
Matt Tucker committed
690 691
                }
                catch (Exception e) {
692
                    // Ignore.
Matt Tucker's avatar
Matt Tucker committed
693 694 695 696 697 698 699 700 701 702 703 704 705 706 707
                }
            }
            return value;
        }
        else {
            return rs.getString(columnIndex);
        }
    }

    /**
     * Sets a large text column in a result set, automatically performing
     * streaming if the JDBC driver requires it. This is necessary because
     * different JDBC drivers have different capabilities and methods for
     * setting large text values.
     *
708
     * @param pstmt the PreparedStatement to set the text field in.
Matt Tucker's avatar
Matt Tucker committed
709
     * @param parameterIndex the index corresponding to the text field.
710
     * @param value the String to set.
711
     * @throws SQLException if an SQL exception occurs.
Matt Tucker's avatar
Matt Tucker committed
712
     */
713
    public static void setLargeTextField(PreparedStatement pstmt, int parameterIndex,
714
                                         String value) throws SQLException {
Matt Tucker's avatar
Matt Tucker committed
715
        if (isStreamTextRequired()) {
716
            Reader bodyReader;
Matt Tucker's avatar
Matt Tucker committed
717 718 719 720 721
            try {
                bodyReader = new StringReader(value);
                pstmt.setCharacterStream(parameterIndex, bodyReader, value.length());
            }
            catch (Exception e) {
722
                Log.error(e.getMessage(), e);
Matt Tucker's avatar
Matt Tucker committed
723 724 725 726 727 728 729 730 731 732 733 734 735 736 737
                throw new SQLException("Failed to set text field.");
            }
            // Leave bodyReader open so that the db can read from it. It *should*
            // be garbage collected after it's done without needing to call close.
        }
        else {
            pstmt.setString(parameterIndex, value);
        }
    }

    /**
     * Sets the max number of rows that should be returned from executing a
     * statement. The operation is automatically bypassed if Jive knows that the
     * the JDBC driver or database doesn't support it.
     *
738
     * @param stmt    the Statement to set the max number of rows for.
Matt Tucker's avatar
Matt Tucker committed
739 740 741 742 743 744 745 746 747 748 749 750 751
     * @param maxRows the max number of rows to return.
     */
    public static void setMaxRows(Statement stmt, int maxRows) {
        if (isMaxRowsSupported()) {
            try {
                stmt.setMaxRows(maxRows);
            }
            catch (Throwable t) {
                // Ignore. Exception may happen if the driver doesn't support
                // this operation and we didn't set meta-data correctly.
                // However, it is a good idea to update the meta-data so that
                // we don't have to incur the cost of catching an exception
                // each time.
752
                Log.error("Disabling JDBC method stmt.setMaxRows(maxRows).", t);
Matt Tucker's avatar
Matt Tucker committed
753 754 755 756 757 758 759 760 761 762
                maxRowsSupported = false;
            }
        }
    }

    /**
     * Sets the number of rows that the JDBC driver should buffer at a time.
     * The operation is automatically bypassed if Jive knows that the
     * the JDBC driver or database doesn't support it.
     *
763
     * @param rs the ResultSet to set the fetch size for.
Matt Tucker's avatar
Matt Tucker committed
764 765 766 767 768 769 770 771 772 773 774 775 776
     * @param fetchSize the fetchSize.
     */
    public static void setFetchSize(ResultSet rs, int fetchSize) {
        if (isFetchSizeSupported()) {
            try {
                rs.setFetchSize(fetchSize);
            }
            catch (Throwable t) {
                // Ignore. Exception may happen if the driver doesn't support
                // this operation and we didn't set meta-data correctly.
                // However, it is a good idea to update the meta-data so that
                // we don't have to incur the cost of catching an exception
                // each time.
777
                Log.error("Disabling JDBC method rs.setFetchSize(fetchSize).", t);
Matt Tucker's avatar
Matt Tucker committed
778 779 780 781 782
                fetchSizeSupported = false;
            }
        }
    }

783 784
    /**
     * Returns a SchemaManager instance, which can be used to manage the database
785
     * schema information for Openfire and plugins.
786 787 788 789 790 791 792
     *
     * @return a SchemaManager instance.
     */
    public static SchemaManager getSchemaManager() {
        return schemaManager;
    }

Matt Tucker's avatar
Matt Tucker committed
793 794 795
    /**
     * Uses a connection from the database to set meta data information about
     * what different JDBC drivers and databases support.
796 797 798
     *
     * @param con the connection.
     * @throws SQLException if an SQL exception occurs.
Matt Tucker's avatar
Matt Tucker committed
799 800 801 802 803 804 805
     */
    private static void setMetaData(Connection con) throws SQLException {
        DatabaseMetaData metaData = con.getMetaData();
        // Supports transactions?
        transactionsSupported = metaData.supportsTransactions();
        // Supports subqueries?
        subqueriesSupported = metaData.supportsCorrelatedSubqueries();
806 807 808 809 810 811 812 813 814 815
        // Supports scroll insensitive result sets? Try/catch block is a
        // workaround for DB2 JDBC driver, which throws an exception on
        // the method call.
        try {
            scrollResultsSupported = metaData.supportsResultSetType(
                    ResultSet.TYPE_SCROLL_INSENSITIVE);
        }
        catch (Exception e) {
            scrollResultsSupported = false;
        }
Matt Tucker's avatar
Matt Tucker committed
816 817 818 819 820 821 822 823 824 825 826 827 828 829
        // Supports batch updates
        batchUpdatesSupported = metaData.supportsBatchUpdates();

        // Set defaults for other meta properties
        streamTextRequired = false;
        maxRowsSupported = true;
        fetchSizeSupported = true;

        // Get the database name so that we can perform meta data settings.
        String dbName = metaData.getDatabaseProductName().toLowerCase();
        String driverName = metaData.getDriverName().toLowerCase();

        // Oracle properties.
        if (dbName.indexOf("oracle") != -1) {
830
            databaseType = DatabaseType.oracle;
Matt Tucker's avatar
Matt Tucker committed
831
            streamTextRequired = true;
832
            scrollResultsSupported = false; /* TODO comment and test this, it should be supported since 10g */
Matt Tucker's avatar
Matt Tucker committed
833 834 835 836 837 838 839 840 841
            // The i-net AUGURO JDBC driver
            if (driverName.indexOf("auguro") != -1) {
                streamTextRequired = false;
                fetchSizeSupported = true;
                maxRowsSupported = false;
            }
        }
        // Postgres properties
        else if (dbName.indexOf("postgres") != -1) {
842
            databaseType = DatabaseType.postgresql;
Matt Tucker's avatar
Matt Tucker committed
843 844 845 846 847 848
            // Postgres blows, so disable scrolling result sets.
            scrollResultsSupported = false;
            fetchSizeSupported = false;
        }
        // Interbase properties
        else if (dbName.indexOf("interbase") != -1) {
849
            databaseType = DatabaseType.interbase;
Matt Tucker's avatar
Matt Tucker committed
850 851 852
            fetchSizeSupported = false;
            maxRowsSupported = false;
        }
853 854
        // SQLServer
        else if (dbName.indexOf("sql server") != -1) {
855
            databaseType = DatabaseType.sqlserver;
856 857 858 859 860
            // JDBC driver i-net UNA properties
            if (driverName.indexOf("una") != -1) {
                fetchSizeSupported = true;
                maxRowsSupported = false;
            }
Matt Tucker's avatar
Matt Tucker committed
861 862 863
        }
        // MySQL properties
        else if (dbName.indexOf("mysql") != -1) {
864
            databaseType = DatabaseType.mysql;
865
            transactionsSupported = false; /* TODO comment and test this, it should be supported since 5.0 */
Matt Tucker's avatar
Matt Tucker committed
866
        }
867 868
        // HSQL properties
        else if (dbName.indexOf("hsql") != -1) {
869
            databaseType = DatabaseType.hsqldb;
870
            // scrollResultsSupported = false; /* comment and test this, it should be supported since 1.7.2 */
871
        }
872 873 874 875
        // DB2 properties.
        else if (dbName.indexOf("db2") != 1) {
            databaseType = DatabaseType.db2;
        }
Matt Tucker's avatar
Matt Tucker committed
876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933
    }

    /**
     * Returns the database type. The possible types are constants of the
     * DatabaseType class. Any database that doesn't have its own constant
     * falls into the "Other" category.
     *
     * @return the database type.
     */
    public static DatabaseType getDatabaseType() {
        return databaseType;
    }

    /**
     * Returns true if connection profiling is turned on. You can collect
     * profiling statistics by using the static methods of the ProfiledConnection
     * class.
     *
     * @return true if connection profiling is enabled.
     */
    public static boolean isProfilingEnabled() {
        return profilingEnabled;
    }

    /**
     * Turns connection profiling on or off. You can collect profiling
     * statistics by using the static methods of the ProfiledConnection
     * class.
     *
     * @param enable true to enable profiling; false to disable.
     */
    public static void setProfilingEnabled(boolean enable) {
        // If enabling profiling, call the start method on ProfiledConnection
        if (!profilingEnabled && enable) {
            ProfiledConnection.start();
        }
        // Otherwise, if turning off, call stop method.
        else if (profilingEnabled && !enable) {
            ProfiledConnection.stop();
        }
        profilingEnabled = enable;
    }

    public static boolean isTransactionsSupported() {
        return transactionsSupported;
    }

    public static boolean isStreamTextRequired() {
        return streamTextRequired;
    }

    public static boolean isMaxRowsSupported() {
        return maxRowsSupported;
    }

    public static boolean isFetchSizeSupported() {
        return fetchSizeSupported;
    }
934 935 936 937
    
    public static boolean isPstmtFetchSizeSupported() {
        return pstmt_fetchSizeSupported;
    }
Matt Tucker's avatar
Matt Tucker committed
938 939 940 941 942 943 944 945 946 947 948 949 950

    public static boolean isSubqueriesSupported() {
        return subqueriesSupported;
    }

    public static boolean isScrollResultsSupported() {
        return scrollResultsSupported;
    }

    public static boolean isBatchUpdatesSupported() {
        return batchUpdatesSupported;
    }

951 952 953 954
    public static boolean isEmbeddedDB() {
        return connectionProvider != null && connectionProvider instanceof EmbeddedConnectionProvider;
    }

955 956 957 958 959 960 961 962 963 964 965 966 967 968 969
    public static String getTestSQL(String driver) {
        if (driver == null) {
            return "select 1";
        }
        else if (driver.contains("db2")) {
            return "select 1 from sysibm.sysdummy1";
        }
        else if (driver.contains("oracle")) {
            return "select 1 from dual";
        }
        else {
            return "select 1";
        }
    }

Matt Tucker's avatar
Matt Tucker committed
970 971 972 973 974 975 976
    /**
     * A class that identifies the type of the database that Jive is connected
     * to. In most cases, we don't want to make any database specific calls
     * and have no need to know the type of database we're using. However,
     * there are certain cases where it's critical to know the database for
     * performance reasons.
     */
977
    @SuppressWarnings({"UnnecessarySemicolon"}) // Support for QDox parsing
978 979 980
    public static enum DatabaseType {

        oracle,
Matt Tucker's avatar
Matt Tucker committed
981

982
        postgresql,
Matt Tucker's avatar
Matt Tucker committed
983

984 985 986 987 988 989 990 991 992 993
        mysql,

        hsqldb,

        db2,

        sqlserver,

        interbase,

994
        unknown;
995 996 997 998
    }

    private DbConnectionManager() {
        // Not instantiable.
Matt Tucker's avatar
Matt Tucker committed
999
    }
1000
}