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 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 401 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 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 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 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 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 585 586 587 588 589 590 591 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 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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
*
* https://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.apache.tomcat.dbcp.dbcp2;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
import java.time.Duration;
import java.util.Collection;
import java.util.Objects;
import java.util.concurrent.atomic.AtomicLong;
import javax.management.MalformedObjectNameException;
import javax.management.ObjectName;
import org.apache.juli.logging.Log;
import org.apache.juli.logging.LogFactory;
import org.apache.tomcat.dbcp.pool2.DestroyMode;
import org.apache.tomcat.dbcp.pool2.KeyedObjectPool;
import org.apache.tomcat.dbcp.pool2.ObjectPool;
import org.apache.tomcat.dbcp.pool2.PooledObject;
import org.apache.tomcat.dbcp.pool2.PooledObjectFactory;
import org.apache.tomcat.dbcp.pool2.impl.DefaultPooledObject;
import org.apache.tomcat.dbcp.pool2.impl.GenericKeyedObjectPool;
import org.apache.tomcat.dbcp.pool2.impl.GenericKeyedObjectPoolConfig;
/**
* A {@link PooledObjectFactory} that creates {@link PoolableConnection}s.
*
* @since 2.0
*/
public class PoolableConnectionFactory implements PooledObjectFactory<PoolableConnection> {
private static final Log log = LogFactory.getLog(PoolableConnectionFactory.class);
/**
* Internal constant to indicate the level is not set.
*/
static final int UNKNOWN_TRANSACTION_ISOLATION = -1;
private final ConnectionFactory connectionFactory;
private final ObjectName dataSourceJmxObjectName;
private volatile String validationQuery;
private volatile Duration validationQueryTimeoutDuration = Duration.ofSeconds(-1);
private Collection<String> connectionInitSqls;
private Collection<String> disconnectionSqlCodes;
private Collection<String> disconnectionIgnoreSqlCodes;
private volatile boolean fastFailValidation = true;
private volatile ObjectPool<PoolableConnection> pool;
private Boolean defaultReadOnly;
private Boolean defaultAutoCommit;
private volatile boolean autoCommitOnReturn = true;
private volatile boolean rollbackOnReturn = true;
private volatile int defaultTransactionIsolation = UNKNOWN_TRANSACTION_ISOLATION;
private String defaultCatalog;
private String defaultSchema;
private volatile boolean cacheState;
private volatile boolean poolStatements;
private volatile boolean clearStatementPoolOnReturn;
private volatile int maxOpenPreparedStatements = GenericKeyedObjectPoolConfig.DEFAULT_MAX_TOTAL_PER_KEY;
private Duration maxConnDuration = Duration.ofMillis(-1);
private final AtomicLong connectionIndex = new AtomicLong();
private Duration defaultQueryTimeoutDuration;
/**
* Creates a new {@link PoolableConnectionFactory}.
*
* @param connFactory
* the {@link ConnectionFactory} from which to obtain base {@link Connection}s
* @param dataSourceJmxObjectName
* The JMX object name, may be null.
*/
public PoolableConnectionFactory(final ConnectionFactory connFactory, final ObjectName dataSourceJmxObjectName) {
this.connectionFactory = connFactory;
this.dataSourceJmxObjectName = dataSourceJmxObjectName;
}
@Override
public void activateObject(final PooledObject<PoolableConnection> p) throws SQLException {
validateLifetime(p);
final PoolableConnection poolableConnection = p.getObject();
poolableConnection.activate();
if (defaultAutoCommit != null && poolableConnection.getAutoCommit() != defaultAutoCommit.booleanValue()) {
poolableConnection.setAutoCommit(defaultAutoCommit.booleanValue());
}
if (defaultTransactionIsolation != UNKNOWN_TRANSACTION_ISOLATION
&& poolableConnection.getTransactionIsolation() != defaultTransactionIsolation) {
poolableConnection.setTransactionIsolation(defaultTransactionIsolation);
}
if (defaultReadOnly != null && poolableConnection.isReadOnly() != defaultReadOnly.booleanValue()) {
poolableConnection.setReadOnly(defaultReadOnly.booleanValue());
}
if (defaultCatalog != null && !defaultCatalog.equals(poolableConnection.getCatalog())) {
poolableConnection.setCatalog(defaultCatalog);
}
if (defaultSchema != null && !defaultSchema.equals(Jdbc41Bridge.getSchema(poolableConnection))) {
Jdbc41Bridge.setSchema(poolableConnection, defaultSchema);
}
poolableConnection.setDefaultQueryTimeout(defaultQueryTimeoutDuration);
}
@Override
public void destroyObject(final PooledObject<PoolableConnection> p) throws SQLException {
p.getObject().reallyClose();
}
/**
* @since 2.9.0
*/
@Override
public void destroyObject(final PooledObject<PoolableConnection> p, final DestroyMode mode) throws SQLException {
if (mode == DestroyMode.ABANDONED) {
Jdbc41Bridge.abort(p.getObject().getInnermostDelegate(), Runnable::run);
} else {
p.getObject().reallyClose();
}
}
/**
* Gets the cache state to propagate in {@link #makeObject()}.
*
* @return The cache state.
* @since 2.6.0.
*/
public boolean getCacheState() {
return cacheState;
}
/**
* Gets the connection factory.
*
* @return The connection factory.
* @since 2.6.0.
*/
public ConnectionFactory getConnectionFactory() {
return connectionFactory;
}
/**
* Gets how many connections were created in {@link #makeObject()}.
*
* @return the connection count.
*/
protected AtomicLong getConnectionIndex() {
return connectionIndex;
}
/**
* Gets the collection of initialization SQL statements.
*
* @return The collection of initialization SQL statements.
* @since 2.6.0
*/
public Collection<String> getConnectionInitSqls() {
return connectionInitSqls;
}
/**
* Gets data source JMX ObjectName.
*
* @return The data source JMX ObjectName.
* @since 2.6.0.
*/
public ObjectName getDataSourceJmxName() {
return dataSourceJmxObjectName;
}
/**
* Gets the data source JMX ObjectName.
*
* @return The data source JMX ObjectName.
* @since 2.6.0
*/
public ObjectName getDataSourceJmxObjectName() {
return dataSourceJmxObjectName;
}
/**
* Gets the Default auto-commit value.
*
* @return The default auto-commit value.
* @since 2.6.0
*/
public Boolean getDefaultAutoCommit() {
return defaultAutoCommit;
}
/**
* Gets the default catalog.
*
* @return The default catalog.
* @since 2.6.0
*/
public String getDefaultCatalog() {
return defaultCatalog;
}
/**
* Gets the default query timeout in seconds.
*
* @return The default query timeout in seconds.
* @deprecated Use {@link #getDefaultQueryTimeoutDuration()}.
*/
@Deprecated
public Integer getDefaultQueryTimeout() {
return getDefaultQueryTimeoutSeconds();
}
/**
* Gets the default query timeout Duration.
*
* @return The default query timeout Duration.
* @since 2.10.0
*/
public Duration getDefaultQueryTimeoutDuration() {
return defaultQueryTimeoutDuration;
}
/**
* Gets the default query timeout in seconds.
*
* @return The default query timeout in seconds.
* @since 2.6.0
* @deprecated Use {@link #getDefaultQueryTimeoutDuration()}.
*/
@Deprecated
public Integer getDefaultQueryTimeoutSeconds() {
return defaultQueryTimeoutDuration == null ? null : Integer.valueOf((int) defaultQueryTimeoutDuration.getSeconds());
}
/**
* Gets the default read-only-value.
*
* @return The default read-only-value.
* @since 2.6.0
*/
public Boolean getDefaultReadOnly() {
return defaultReadOnly;
}
/**
* Gets the default schema.
*
* @return The default schema.
* @since 2.6.0
*/
public String getDefaultSchema() {
return defaultSchema;
}
/**
* Gets the default transaction isolation.
*
* @return The default transaction isolation.
* @since 2.6.0
*/
public int getDefaultTransactionIsolation() {
return defaultTransactionIsolation;
}
/**
* Gets the collection of SQL State codes that are not considered fatal disconnection codes.
* <p>
* This method returns the collection of SQL State codes that have been set to be ignored when
* determining if a {@link SQLException} signals a disconnection. These codes are excluded from
* being treated as fatal even if they match the typical disconnection criteria.
* </p>
*
* @return a {@link Collection} of SQL State codes that should be ignored for disconnection checks.
* @since 2.13.0
*/
public Collection<String> getDisconnectionIgnoreSqlCodes() {
return disconnectionIgnoreSqlCodes;
}
/**
* Gets SQL State codes considered to signal fatal conditions.
* <p>
* Overrides the defaults in {@link Utils#getDisconnectionSqlCodes()} (plus anything starting with
* {@link Utils#DISCONNECTION_SQL_CODE_PREFIX}). If this property is non-null and {@link #isFastFailValidation()} is
* {@code true}, whenever connections created by this factory generate exceptions with SQL State codes in this list,
* they will be marked as "fatally disconnected" and subsequent validations will fail fast (no attempt at isValid or
* validation query).
* </p>
* <p>
* If {@link #isFastFailValidation()} is {@code false} setting this property has no effect.
* </p>
*
* @return SQL State codes overriding defaults
* @since 2.1
*/
public Collection<String> getDisconnectionSqlCodes() {
return disconnectionSqlCodes;
}
/**
* Gets the Maximum connection duration.
*
* @return Maximum connection duration.
* @since 2.10.0
*/
public Duration getMaxConnDuration() {
return maxConnDuration;
}
/**
* Gets the Maximum connection lifetime in milliseconds.
*
* @return Maximum connection lifetime in milliseconds.
* @since 2.6.0
*/
public long getMaxConnLifetimeMillis() {
return maxConnDuration.toMillis();
}
/**
* Gets the maximum number of open prepared statements.
*
* @return The maximum number of open prepared statements.
*/
protected int getMaxOpenPreparedStatements() {
return maxOpenPreparedStatements;
}
/**
* Returns the {@link ObjectPool} in which {@link Connection}s are pooled.
*
* @return the connection pool
*/
public synchronized ObjectPool<PoolableConnection> getPool() {
return pool;
}
/**
* Tests whether to pool statements.
*
* @return Whether to pool statements.
* @since 2.6.0.
*/
public boolean getPoolStatements() {
return poolStatements;
}
/**
* Gets the validation query.
*
* @return Validation query.
* @since 2.6.0
*/
public String getValidationQuery() {
return validationQuery;
}
/**
* Gets the query timeout in seconds.
*
* @return Validation query timeout in seconds.
* @since 2.10.0
*/
public Duration getValidationQueryTimeoutDuration() {
return validationQueryTimeoutDuration;
}
/**
* Gets the query timeout in seconds.
*
* @return Validation query timeout in seconds.
* @since 2.6.0
* @deprecated Use {@link #getValidationQueryTimeoutDuration()}.
*/
@Deprecated
public int getValidationQueryTimeoutSeconds() {
return (int) validationQueryTimeoutDuration.getSeconds();
}
/**
* Initializes the given connection with the collection of SQL statements set in {@link #setConnectionInitSql(Collection)}.
*
* @param conn the connection to initialize.
* @throws SQLException if a database access error occurs or this method is called on a closed connection.
* @see #setConnectionInitSql(Collection)
*/
protected void initializeConnection(final Connection conn) throws SQLException {
final Collection<String> sqls = connectionInitSqls;
if (conn.isClosed()) {
throw new SQLException("initializeConnection: connection closed");
}
if (!Utils.isEmpty(sqls)) {
try (Statement statement = conn.createStatement()) {
for (final String sql : sqls) {
statement.execute(Objects.requireNonNull(sql, "null connectionInitSqls element"));
}
}
}
}
/**
* Tests whether to set auto-commit on {@link #passivateObject(PooledObject)}.
*
* @return Whether to set auto-commit on {@link #passivateObject(PooledObject)}.
* @since 2.6.0
*/
public boolean isAutoCommitOnReturn() {
return autoCommitOnReturn;
}
/**
* Tests whether to set auto-commit on {@link #passivateObject(PooledObject)}.
*
* @return Whether to set auto-commit on {@link #passivateObject(PooledObject)}.
* @deprecated Use {@link #isAutoCommitOnReturn()}.
*/
@Deprecated
public boolean isEnableAutoCommitOnReturn() {
return autoCommitOnReturn;
}
/**
* True means that validation will fail immediately for connections that have previously thrown SQLExceptions with
* SQL State indicating fatal disconnection errors.
*
* @return true if connections created by this factory will fast fail validation.
* @see #setDisconnectionSqlCodes(Collection)
* @since 2.1
* @since 2.5.0 Defaults to true, previous versions defaulted to false.
*/
public boolean isFastFailValidation() {
return fastFailValidation;
}
/**
* Tests whether to rollback on return.
*
* @return Whether to rollback on return.
*/
public boolean isRollbackOnReturn() {
return rollbackOnReturn;
}
@Override
public PooledObject<PoolableConnection> makeObject() throws SQLException {
Connection conn = connectionFactory.createConnection();
if (conn == null) {
throw new IllegalStateException("Connection factory returned null from createConnection");
}
try {
initializeConnection(conn);
} catch (final SQLException e) {
// Make sure the connection is closed
Utils.closeQuietly((AutoCloseable) conn);
// Rethrow original exception so it is visible to caller
throw e;
}
final long connIndex = connectionIndex.getAndIncrement();
if (poolStatements) {
conn = new PoolingConnection(conn);
final GenericKeyedObjectPoolConfig<DelegatingPreparedStatement> config = new GenericKeyedObjectPoolConfig<>();
config.setMaxTotalPerKey(-1);
config.setBlockWhenExhausted(false);
config.setMaxWait(Duration.ZERO);
config.setMaxIdlePerKey(1);
config.setMaxTotal(maxOpenPreparedStatements);
if (dataSourceJmxObjectName != null) {
final StringBuilder base = new StringBuilder(dataSourceJmxObjectName.toString());
base.append(Constants.JMX_CONNECTION_BASE_EXT);
base.append(connIndex);
config.setJmxNameBase(base.toString());
config.setJmxNamePrefix(Constants.JMX_STATEMENT_POOL_PREFIX);
} else {
config.setJmxEnabled(false);
}
final PoolingConnection poolingConn = (PoolingConnection) conn;
final KeyedObjectPool<PStmtKey, DelegatingPreparedStatement> stmtPool = new GenericKeyedObjectPool<>(poolingConn, config);
poolingConn.setStatementPool(stmtPool);
poolingConn.setClearStatementPoolOnReturn(clearStatementPoolOnReturn);
poolingConn.setCacheState(cacheState);
}
// Register this connection with JMX
final ObjectName connJmxName;
if (dataSourceJmxObjectName == null) {
connJmxName = null;
} else {
final String name = dataSourceJmxObjectName.toString() + Constants.JMX_CONNECTION_BASE_EXT + connIndex;
try {
connJmxName = new ObjectName(name);
} catch (final MalformedObjectNameException e) {
Utils.closeQuietly((AutoCloseable) conn);
throw new SQLException(name, e);
}
}
final PoolableConnection pc = new PoolableConnection(conn, pool, connJmxName,
disconnectionSqlCodes, disconnectionIgnoreSqlCodes, fastFailValidation);
pc.setCacheState(cacheState);
return new DefaultPooledObject<>(pc);
}
@Override
public void passivateObject(final PooledObject<PoolableConnection> p) throws SQLException {
validateLifetime(p);
final PoolableConnection conn = p.getObject();
Boolean connAutoCommit = null;
if (rollbackOnReturn) {
connAutoCommit = Boolean.valueOf(conn.getAutoCommit());
if (!connAutoCommit.booleanValue() && !conn.isReadOnly()) {
conn.rollback();
}
}
conn.clearWarnings();
// DBCP-97 / DBCP-399 / DBCP-351 Idle connections in the pool should
// have autoCommit enabled
if (autoCommitOnReturn) {
if (connAutoCommit == null) {
connAutoCommit = Boolean.valueOf(conn.getAutoCommit());
}
if (!connAutoCommit.booleanValue()) {
conn.setAutoCommit(true);
}
}
conn.passivate();
}
/**
* Sets whether to set auto-commit on {@link #passivateObject(PooledObject)}.
*
* @param autoCommitOnReturn whether to set auto-commit.
*/
public void setAutoCommitOnReturn(final boolean autoCommitOnReturn) {
this.autoCommitOnReturn = autoCommitOnReturn;
}
/**
* Sets the cache state to propagate in {@link #makeObject()}.
*
* @param cacheState the cache state to propagate.
*/
public void setCacheState(final boolean cacheState) {
this.cacheState = cacheState;
}
/**
* Sets whether the pool of statements (which was enabled with {@link #setPoolStatements(boolean)}) should
* be cleared when the connection is returned to its pool. Default is false.
*
* @param clearStatementPoolOnReturn clear or not
* @since 2.8.0
*/
public void setClearStatementPoolOnReturn(final boolean clearStatementPoolOnReturn) {
this.clearStatementPoolOnReturn = clearStatementPoolOnReturn;
}
/**
* Sets the SQL statements I use to initialize newly created {@link Connection}s. Using {@code null} turns off
* connection initialization.
*
* @param connectionInitSqls
* SQL statement to initialize {@link Connection}s.
*/
public void setConnectionInitSql(final Collection<String> connectionInitSqls) {
this.connectionInitSqls = connectionInitSqls;
}
/**
* Sets the default "auto commit" setting for borrowed {@link Connection}s
*
* @param defaultAutoCommit
* the default "auto commit" setting for borrowed {@link Connection}s
*/
public void setDefaultAutoCommit(final Boolean defaultAutoCommit) {
this.defaultAutoCommit = defaultAutoCommit;
}
/**
* Sets the default "catalog" setting for borrowed {@link Connection}s
*
* @param defaultCatalog
* the default "catalog" setting for borrowed {@link Connection}s
*/
public void setDefaultCatalog(final String defaultCatalog) {
this.defaultCatalog = defaultCatalog;
}
/**
* Sets the query timeout Duration.
*
* @param defaultQueryTimeoutDuration the query timeout Duration.
* @since 2.10.0
*/
public void setDefaultQueryTimeout(final Duration defaultQueryTimeoutDuration) {
this.defaultQueryTimeoutDuration = defaultQueryTimeoutDuration;
}
/**
* Sets the query timeout in seconds.
*
* @param defaultQueryTimeoutSeconds the query timeout in seconds.
* @deprecated Use {@link #setDefaultQueryTimeout(Duration)}.
*/
@Deprecated
public void setDefaultQueryTimeout(final Integer defaultQueryTimeoutSeconds) {
this.defaultQueryTimeoutDuration = defaultQueryTimeoutSeconds == null ? null : Duration.ofSeconds(defaultQueryTimeoutSeconds.longValue());
}
/**
* Sets the default "read only" setting for borrowed {@link Connection}s
*
* @param defaultReadOnly
* the default "read only" setting for borrowed {@link Connection}s
*/
public void setDefaultReadOnly(final Boolean defaultReadOnly) {
this.defaultReadOnly = defaultReadOnly;
}
/**
* Sets the default "schema" setting for borrowed {@link Connection}s
*
* @param defaultSchema
* the default "schema" setting for borrowed {@link Connection}s
* @since 2.5.0
*/
public void setDefaultSchema(final String defaultSchema) {
this.defaultSchema = defaultSchema;
}
/**
* Sets the default "Transaction Isolation" setting for borrowed {@link Connection}s
*
* @param defaultTransactionIsolation
* the default "Transaction Isolation" setting for returned {@link Connection}s
*/
public void setDefaultTransactionIsolation(final int defaultTransactionIsolation) {
this.defaultTransactionIsolation = defaultTransactionIsolation;
}
/**
* Sets the disconnection SQL codes to ignore.
*
* @param disconnectionIgnoreSqlCodes
* The collection of SQL State codes to be ignored.
* @see #getDisconnectionIgnoreSqlCodes()
* @throws IllegalArgumentException if any SQL state codes overlap with those in {@link #disconnectionSqlCodes}.
* @since 2.13.0
*/
public void setDisconnectionIgnoreSqlCodes(final Collection<String> disconnectionIgnoreSqlCodes) {
Utils.checkSqlCodes(disconnectionIgnoreSqlCodes, this.disconnectionSqlCodes);
this.disconnectionIgnoreSqlCodes = disconnectionIgnoreSqlCodes;
}
/**
* Sets the disconnection SQL codes.
*
* @param disconnectionSqlCodes
* The disconnection SQL codes.
* @see #getDisconnectionSqlCodes()
* @throws IllegalArgumentException if any SQL state codes overlap with those in {@link #disconnectionIgnoreSqlCodes}.
* @since 2.1
*/
public void setDisconnectionSqlCodes(final Collection<String> disconnectionSqlCodes) {
Utils.checkSqlCodes(disconnectionSqlCodes, this.disconnectionIgnoreSqlCodes);
this.disconnectionSqlCodes = disconnectionSqlCodes;
}
/**
* Sets whether to set auto-commit on {@link #passivateObject(PooledObject)}.
*
* @param autoCommitOnReturn whether to set auto-commit.
*/
@Deprecated
public void setEnableAutoCommitOnReturn(final boolean autoCommitOnReturn) {
this.autoCommitOnReturn = autoCommitOnReturn;
}
/**
* Sets whether connections created by this factory will fast fail validation.
*
* @param fastFailValidation true means connections created by this factory will fast fail validation
* @see #isFastFailValidation()
* @since 2.1
*/
public void setFastFailValidation(final boolean fastFailValidation) {
this.fastFailValidation = fastFailValidation;
}
/**
* Sets the maximum lifetime in milliseconds of a connection after which the connection will always fail activation,
* passivation and validation. A value of zero or less indicates an infinite lifetime. The default value is -1.
*
* @param maxConnDuration
* The maximum lifetime in milliseconds.
* @since 2.10.0
*/
public void setMaxConn(final Duration maxConnDuration) {
this.maxConnDuration = maxConnDuration;
}
/**
* Sets the maximum lifetime in milliseconds of a connection after which the connection will always fail activation,
* passivation and validation. A value of zero or less indicates an infinite lifetime. The default value is -1.
*
* @param maxConnLifetimeMillis
* The maximum lifetime in milliseconds.
* @deprecated Use {@link #setMaxConn(Duration)}.
*/
@Deprecated
public void setMaxConnLifetimeMillis(final long maxConnLifetimeMillis) {
this.maxConnDuration = Duration.ofMillis(maxConnLifetimeMillis);
}
/**
* Sets the maximum number of open prepared statements.
*
* @param maxOpenPreparedStatements
* The maximum number of open prepared statements.
*/
public void setMaxOpenPreparedStatements(final int maxOpenPreparedStatements) {
this.maxOpenPreparedStatements = maxOpenPreparedStatements;
}
/**
* Deprecated due to typo in method name.
*
* @param maxOpenPreparedStatements
* The maximum number of open prepared statements.
* @deprecated Use {@link #setMaxOpenPreparedStatements(int)}.
*/
@Deprecated // Due to typo in method name.
public void setMaxOpenPrepatedStatements(final int maxOpenPreparedStatements) {
setMaxOpenPreparedStatements(maxOpenPreparedStatements);
}
/**
* Sets the {@link ObjectPool} in which to pool {@link Connection}s.
*
* @param pool
* the {@link ObjectPool} in which to pool those {@link Connection}s
*/
public synchronized void setPool(final ObjectPool<PoolableConnection> pool) {
if (null != this.pool && pool != this.pool) {
Utils.closeQuietly(this.pool);
}
this.pool = pool;
}
/**
* Sets whether to pool statements.
*
* @param poolStatements whether to pool statements.
*/
public void setPoolStatements(final boolean poolStatements) {
this.poolStatements = poolStatements;
}
/**
* Sets whether to rollback on return.
*
* @param rollbackOnReturn whether to rollback on return.
*/
public void setRollbackOnReturn(final boolean rollbackOnReturn) {
this.rollbackOnReturn = rollbackOnReturn;
}
/**
* Sets the query I use to {@link #validateObject validate} {@link Connection}s. Should return at least one row. If
* not specified, {@link Connection#isValid(int)} will be used to validate connections.
*
* @param validationQuery
* a query to use to {@link #validateObject validate} {@link Connection}s.
*/
public void setValidationQuery(final String validationQuery) {
this.validationQuery = validationQuery;
}
/**
* Sets the validation query timeout, the amount of time, that connection validation will wait for a response from the
* database when executing a validation query. Use a value less than or equal to 0 for no timeout.
*
* @param validationQueryTimeoutDuration new validation query timeout duration.
* @since 2.10.0
*/
public void setValidationQueryTimeout(final Duration validationQueryTimeoutDuration) {
this.validationQueryTimeoutDuration = validationQueryTimeoutDuration;
}
/**
* Sets the validation query timeout, the amount of time, in seconds, that connection validation will wait for a
* response from the database when executing a validation query. Use a value less than or equal to 0 for no timeout.
*
* @param validationQueryTimeoutSeconds
* new validation query timeout value in seconds
* @deprecated {@link #setValidationQueryTimeout(Duration)}.
*/
@Deprecated
public void setValidationQueryTimeout(final int validationQueryTimeoutSeconds) {
this.validationQueryTimeoutDuration = Duration.ofSeconds(validationQueryTimeoutSeconds);
}
/**
* Validates the given connection if it is open.
*
* @param conn the connection to validate.
* @throws SQLException if the connection is closed or validate fails.
*/
public void validateConnection(final PoolableConnection conn) throws SQLException {
if (conn.isClosed()) {
throw new SQLException("validateConnection: connection closed");
}
conn.validate(validationQuery, validationQueryTimeoutDuration);
}
private void validateLifetime(final PooledObject<PoolableConnection> p) throws LifetimeExceededException {
Utils.validateLifetime(p, maxConnDuration);
}
@Override
public boolean validateObject(final PooledObject<PoolableConnection> p) {
try {
validateLifetime(p);
validateConnection(p.getObject());
return true;
} catch (final Exception e) {
if (log.isDebugEnabled()) {
log.debug(Utils.getMessage("poolableConnectionFactory.validateObject.fail"), e);
}
return false;
}
}
}
|