#617 - Refactor - tidy up DataSource internals, reduce method visibility

This commit is contained in:
Robin Bygrave committed 2016-03-23 20:51:32 +13:00
1 parent 406b7304ad
commit 84b2ffa971
11 files changed
+63 -214

No files matched your search

@@ -97,10 +97,8 @@ class BusyConnectionBuffer {
/**
* Collect the load statistics from all the busy connections.
*
* @param reset
*/
protected void collectStatistics(LoadValues values, boolean reset) {
void collectStatistics(LoadValues values, boolean reset) {
for (int i = 0; i < slots.length; i++) {
if (slots[i] != null) {
@@ -112,7 +110,7 @@ class BusyConnectionBuffer {
/**
* Close connections that should be considered leaked.
*/
protected void closeBusyConnections(long leakTimeMinutes) {
void closeBusyConnections(long leakTimeMinutes) {
long olderThanTime = System.currentTimeMillis() - (leakTimeMinutes * 60000);
@@ -152,7 +150,7 @@ class BusyConnectionBuffer {
/**
* Returns information describing connections that are currently being used.
*/
protected String getBusyConnectionInformation(boolean toLogger) {
String getBusyConnectionInformation(boolean toLogger) {
if (toLogger) {
logger.info("Dumping [{}] busy connections: (Use datasource.xxx.capturestacktrace=true ... to get stackTraces)", size());
@@ -25,21 +25,10 @@ public class DataSourcePoolStatistics {
private final long totalMicros;
/**
* No statistics collected.
*/
public DataSourcePoolStatistics() {
this.collectionStart = 0;
this.count = 0;
this.errorCount = 0;
this.hwmMicros = 0;
this.totalMicros = 0;
}
/**
* Construct with statistics collected.
*/
public DataSourcePoolStatistics(long collectionStart, long count, long errorCount, long hwmMicros, long totalMicros) {
DataSourcePoolStatistics(long collectionStart, long count, long errorCount, long hwmMicros, long totalMicros) {
this.collectionStart = collectionStart;
this.count = count;
this.errorCount = errorCount;
@@ -47,14 +47,10 @@ public class ExtendedPreparedStatement extends ExtendedStatement implements Prep
this.cacheKey = cacheKey;
}
public PreparedStatement getDelegate() {
return pstmt;
}
/**
* Return the key used to cache this on the Connection.
*/
public String getCacheKey() {
String getCacheKey() {
return cacheKey;
}
@@ -69,7 +65,7 @@ public class ExtendedPreparedStatement extends ExtendedStatement implements Prep
* Fully close the underlying PreparedStatement. After this we can no longer
* reuse the PreparedStatement.
*/
public void closeDestroy() throws SQLException {
void closeDestroy() throws SQLException {
pstmt.close();
}
@@ -16,12 +16,12 @@ import com.avaje.ebeaninternal.jdbc.PreparedStatementDelegator;
* for the case where someone uses the Statement api on an ExtendedPreparedStatement.
* </p>
*/
public abstract class ExtendedStatement extends PreparedStatementDelegator {
abstract class ExtendedStatement extends PreparedStatementDelegator {
/**
* The pooled connection this Statement belongs to.
*/
protected final PooledConnection pooledConnection;
final PooledConnection pooledConnection;
/**
* The underlying Statement that this object wraps.
@@ -31,7 +31,7 @@ public abstract class ExtendedStatement extends PreparedStatementDelegator {
/**
* Create the ExtendedStatement for a given pooledConnection.
*/
public ExtendedStatement(PooledConnection pooledConnection, PreparedStatement pstmt) {
ExtendedStatement(PooledConnection pooledConnection, PreparedStatement pstmt) {
super(pstmt);
this.pooledConnection = pooledConnection;
@@ -25,7 +25,7 @@ class FreeConnectionBuffer {
*/
private final LinkedList<PooledConnection> freeBuffer = new LinkedList<PooledConnection>();
protected FreeConnectionBuffer() {
FreeConnectionBuffer() {
}
protected int size() {
@@ -53,7 +53,7 @@ class FreeConnectionBuffer {
/**
* Close all connections in this buffer.
*/
protected void closeAll(boolean logErrors) {
void closeAll(boolean logErrors) {
// create a temporary list
List<PooledConnection> tempList = new ArrayList<PooledConnection>(freeBuffer.size());
@@ -97,7 +97,7 @@ class FreeConnectionBuffer {
/**
* Collect the load statistics from all the free connections.
*/
protected void collectStatistics(LoadValues values, boolean reset) {
void collectStatistics(LoadValues values, boolean reset) {
for (PooledConnection c : freeBuffer) {
values.plus(c.getStatistics().getValues(reset));
@@ -179,7 +179,7 @@ public class PooledConnection extends ConnectionDelegator {
this.pool = pool;
this.connection = connection;
this.name = pool.getName() + "." + uniqueId;
this.pstmtCache = new PstmtCache(name, pool.getPstmtCacheSize());
this.pstmtCache = new PstmtCache(pool.getPstmtCacheSize());
this.maxStackTrace = pool.getMaxStackTraceSize();
this.creationTime = System.currentTimeMillis();
this.lastUseTime = creationTime;
@@ -202,14 +202,14 @@ public class PooledConnection extends ConnectionDelegator {
/**
* Return the slot position in the busy buffer.
*/
public int getSlotId() {
int getSlotId() {
return slotId;
}
/**
* Set the slot position in the busy buffer.
*/
public void setSlotId(int slotId) {
void setSlotId(int slotId) {
this.slotId = slotId;
}
@@ -220,7 +220,7 @@ public class PooledConnection extends ConnectionDelegator {
return name;
}
public String getNameSlot() {
private String getNameSlot() {
return name + ":" + slotId;
}
@@ -228,7 +228,7 @@ public class PooledConnection extends ConnectionDelegator {
return getDescription();
}
public long getBusySeconds() {
private long getBusySeconds() {
return (System.currentTimeMillis() - startUseTime) / 1000;
}
@@ -236,7 +236,7 @@ public class PooledConnection extends ConnectionDelegator {
return "name[" + name + "] slot[" + slotId + "] startTime[" + getStartUseTime() + "] busySeconds[" + getBusySeconds() + "] createdBy[" + getCreatedByMethod() + "] stmt[" + getLastStatement() + "]";
}
public String getFullDescription() {
String getFullDescription() {
return "name[" + name + "] slot[" + slotId + "] startTime[" + getStartUseTime() + "] busySeconds[" + getBusySeconds() + "] stackTrace[" + getStackTraceAsString() + "] stmt[" + getLastStatement() + "]";
}
@@ -247,7 +247,7 @@ public class PooledConnection extends ConnectionDelegator {
/**
* Return true if the connection should be treated as long running (skip connection pool leak check).
*/
public boolean isLongRunning() {
boolean isLongRunning() {
return longRunning;
}
@@ -268,7 +268,7 @@ public class PooledConnection extends ConnectionDelegator {
*
* @param logErrors if false then don't log errors when closing
*/
public void closeConnectionFully(boolean logErrors) {
void closeConnectionFully(boolean logErrors) {
if (pool != null) {
// allow collection of load statistics
@@ -345,7 +345,7 @@ public class PooledConnection extends ConnectionDelegator {
/**
* Return a PreparedStatement back into the cache.
*/
protected void returnPreparedStatement(ExtendedPreparedStatement pstmt) {
void returnPreparedStatement(ExtendedPreparedStatement pstmt) {
synchronized (pstmtMonitor) {
if (!pstmtCache.returnStatement(pstmt)) {
@@ -429,7 +429,7 @@ public class PooledConnection extends ConnectionDelegator {
* Reset the connection for returning to the client. Resets the status,
* startUseTime and hadErrors.
*/
protected void resetForUse() {
void resetForUse() {
this.status = STATUS_ACTIVE;
this.startUseTime = System.currentTimeMillis();
this.exeStartNanos = System.nanoTime();
@@ -446,7 +446,7 @@ public class PooledConnection extends ConnectionDelegator {
* before it is placed back into the connection pool.
* </p>
*/
public void addError(Throwable throwable) {
void addError(Throwable throwable) {
hadErrors = true;
}
@@ -532,7 +532,7 @@ public class PooledConnection extends ConnectionDelegator {
/**
* Return true if the connection is too old.
*/
public boolean exceedsMaxAge(long maxAgeMillis) {
private boolean exceedsMaxAge(long maxAgeMillis) {
if (maxAgeMillis > 0 && (creationTime < (System.currentTimeMillis() - maxAgeMillis))) {
this.closeReason = REASON_MAXAGE;
return true;
@@ -540,7 +540,7 @@ public class PooledConnection extends ConnectionDelegator {
return false;
}
public boolean shouldTrimOnReturn(long lastResetTime, long maxAgeMillis) {
boolean shouldTrimOnReturn(long lastResetTime, long maxAgeMillis) {
if (creationTime <= lastResetTime) {
this.closeReason = REASON_RESET;
return true;
@@ -551,7 +551,7 @@ public class PooledConnection extends ConnectionDelegator {
/**
* Return true if the connection has been idle for too long or is too old.
*/
public boolean shouldTrim(long usedSince, long createdSince) {
boolean shouldTrim(long usedSince, long createdSince) {
if (lastUseTime < usedSince) {
// been idle for too long so trim it
this.closeReason = REASON_IDLE;
@@ -571,7 +571,7 @@ public class PooledConnection extends ConnectionDelegator {
* Used to detect busy connections that could be leaks.
* </p>
*/
public long getStartUseTime() {
private long getStartUseTime() {
return startUseTime;
}
@@ -582,14 +582,14 @@ public class PooledConnection extends ConnectionDelegator {
* minutes.
* </p>
*/
public long getLastUsedTime() {
long getLastUsedTime() {
return lastUseTime;
}
/**
* Returns the last sql statement executed.
*/
public String getLastStatement() {
private String getLastStatement() {
return lastStatement;
}
@@ -599,7 +599,7 @@ public class PooledConnection extends ConnectionDelegator {
* Note with addBatch() this will not really work.
* </p>
*/
protected void setLastStatement(String lastStatement) {
void setLastStatement(String lastStatement) {
this.lastStatement = lastStatement;
if (logger.isTraceEnabled()) {
logger.trace(".setLastStatement[" + lastStatement + "]");
@@ -889,7 +889,7 @@ public class PooledConnection extends ConnectionDelegator {
* Used to help finding connection pool leaks.
* </p>
*/
public String getCreatedByMethod() {
private String getCreatedByMethod() {
if (createdByMethod != null) {
return createdByMethod;
}
@@ -934,7 +934,7 @@ public class PooledConnection extends ConnectionDelegator {
/**
* Return the stackTrace as a String for logging purposes.
*/
public String getStackTraceAsString() {
private String getStackTraceAsString() {
StackTraceElement[] stackTrace = getStackTrace();
if (stackTrace == null) {
return "";
@@ -130,7 +130,7 @@ public class PooledConnectionQueue {
/**
* Collect statistics of a connection that is fully closing
*/
protected void reportClosingConnection(PooledConnection pooledConnection) {
void reportClosingConnection(PooledConnection pooledConnection) {
collectedStats.add(pooledConnection.getStatistics());
}
@@ -173,7 +173,7 @@ public class PooledConnectionQueue {
}
}
public void setMinSize(int minSize) {
void setMinSize(int minSize) {
final ReentrantLock lock = this.lock;
lock.lock();
try {
@@ -186,7 +186,7 @@ public class PooledConnectionQueue {
}
}
public void setMaxSize(int maxSize) {
void setMaxSize(int maxSize) {
final ReentrantLock lock = this.lock;
lock.lock();
try {
@@ -200,7 +200,7 @@ public class PooledConnectionQueue {
}
}
public void setWarningSize(int warningSize) {
void setWarningSize(int warningSize) {
final ReentrantLock lock = this.lock;
lock.lock();
try {
@@ -217,7 +217,7 @@ public class PooledConnectionQueue {
return freeList.size() + busyList.size();
}
public void ensureMinimumConnections() throws SQLException {
void ensureMinimumConnections() throws SQLException {
final ReentrantLock lock = this.lock;
lock.lock();
try {
@@ -238,7 +238,7 @@ public class PooledConnectionQueue {
/**
* Return a PooledConnection.
*/
protected void returnPooledConnection(PooledConnection c, boolean forceClose) {
void returnPooledConnection(PooledConnection c, boolean forceClose) {
final ReentrantLock lock = this.lock;
lock.lock();
@@ -264,7 +264,7 @@ public class PooledConnectionQueue {
return c;
}
public PooledConnection getPooledConnection() throws SQLException {
PooledConnection getPooledConnection() throws SQLException {
try {
PooledConnection pc = _getPooledConnection();
@@ -448,7 +448,7 @@ public class PooledConnectionQueue {
/**
* Close all the connections that are in the free list.
*/
public void closeFreeConnections(boolean logErrors) {
private void closeFreeConnections(boolean logErrors) {
final ReentrantLock lock = this.lock;
lock.lock();
try {
@@ -470,7 +470,7 @@ public class PooledConnectionQueue {
* closed and put back into the pool.
* </p>
*/
public void closeBusyConnections(long leakTimeMinutes) {
void closeBusyConnections(long leakTimeMinutes) {
final ReentrantLock lock = this.lock;
lock.lock();
@@ -504,11 +504,11 @@ public class PooledConnectionQueue {
}
}
public String getBusyConnectionInformation() {
String getBusyConnectionInformation() {
return getBusyConnectionInformation(false);
}
public void dumpBusyConnectionInformation() {
void dumpBusyConnectionInformation() {
getBusyConnectionInformation(true);
}
@@ -6,7 +6,7 @@ import java.util.concurrent.atomic.AtomicLong;
/**
* Collects load statistics for a PooledConnection.
*/
public class PooledConnectionStatistics {
class PooledConnectionStatistics {
private final AtomicLong count = new AtomicLong();
@@ -18,7 +18,7 @@ public class PooledConnectionStatistics {
private final AtomicLong collectionStart;
public PooledConnectionStatistics() {
PooledConnectionStatistics() {
this.collectionStart = new AtomicLong(System.currentTimeMillis());
}
@@ -67,22 +67,22 @@ public class PooledConnectionStatistics {
return count.get();
}
public long getErrorCount() {
private long getErrorCount() {
return errorCount.get();
}
public long getTotalMicros() {
private long getTotalMicros() {
return TimeUnit.MICROSECONDS.convert(totalNanos.get(), TimeUnit.NANOSECONDS);
}
public long getHwmMicros() {
private long getHwmMicros() {
return TimeUnit.MICROSECONDS.convert(hwmNanos.get(), TimeUnit.NANOSECONDS);
}
/**
* Get the current values and reset the statistics if necessary.
*/
public LoadValues getValues(boolean reset) {
LoadValues getValues(boolean reset) {
LoadValues value = new LoadValues(collectionStart.get(), count.get(), errorCount.get(), getHwmMicros(), getTotalMicros());
if (reset) {
count.set(0);
@@ -100,7 +100,7 @@ public class PooledConnectionStatistics {
* These are aggregated up to get a total for the DataSourcePool.
* </p>
*/
public static class LoadValues {
static class LoadValues {
private long collectionStart;
private long count;
@@ -108,10 +108,10 @@ public class PooledConnectionStatistics {
private long hwmMicros;
private long totalMicros;
public LoadValues() {
LoadValues() {
}
public LoadValues(long collectionStart, long count, long errorCount, long hwmMicros, long totalMicros) {
LoadValues(long collectionStart, long count, long errorCount, long hwmMicros, long totalMicros) {
this.collectionStart = collectionStart;
this.count = count;
this.errorCount = errorCount;
@@ -131,7 +131,7 @@ public class PooledConnectionStatistics {
return "count[" + count + "] errors[" + errorCount + "] totalMicros[" + totalMicros + "] hwmMicros[" + hwmMicros + "] avgMicros[" + getAvgMicros() + "]";
}
public long getCollectionStart() {
long getCollectionStart() {
return collectionStart;
}
@@ -139,19 +139,19 @@ public class PooledConnectionStatistics {
return count;
}
public long getErrorCount() {
long getErrorCount() {
return errorCount;
}
public long getHwmMicros() {
long getHwmMicros() {
return hwmMicros;
}
public long getTotalMicros() {
long getTotalMicros() {
return totalMicros;
}
public long getAvgMicros() {
long getAvgMicros() {
return (count == 0) ? 0 : totalMicros / count;
}
}
@@ -1,98 +0,0 @@
package com.avaje.ebeaninternal.server.lib.sql;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Random;
/**
* Security mechanisim.
*/
public class Prefix {
private static final Logger logger = LoggerFactory.getLogger(Prefix.class);
private static final int[] oa = {50, 12, 4, 6, 8, 10, 7, 23, 45, 23, 6, 9, 12, 2, 8, 34};
public static String getProp(String prop) {
String v = dec(prop);
int p = v.indexOf(":");
return v.substring(1, p);
}
public static void main(String[] args) {
String m = e(args[0]);
logger.info("[" + m + "]");
String o = getProp(m);
logger.info("[" + o + "]");
}
public static String e(String msg) {
msg = elen(msg, 40);
return enc(msg);
}
public static byte az(byte c, int offset) {
int z = c + offset;
if (z > 122) {
// dp("z> "+z);
z = z - 122 + 48 - 1;
}
// dp("z="+z+" c:"+(int)c);
return (byte) z;
}
public static byte bz(byte c, int offset) {
int z = c - offset;
if (z < (48)) {
// dp("z< "+z);
z = z + 122 - 48 + 1;
}
return (byte) z;
}
public static String enc(String msg) {
byte[] msgbytes = msg.getBytes();
byte[] encbytes = new byte[msgbytes.length + 1];
Random r = new Random();
int key = r.nextInt(70);
char k = (char) (key + 48);
encbytes[0] = az((byte) k, oa[0]);
// dp("key:"+key+" encbytes[0]:"+(byte)encbytes[0]);
for (int i = 1; i < (msgbytes.length + 1); i++) {
encbytes[i] = az(msgbytes[i - 1], (oa[(i + key) % oa.length]));
}
return new String(encbytes);
}
public static String dec(String msg) {
byte[] msgbytes = msg.getBytes();
byte[] encbytes = new byte[msgbytes.length];
encbytes[0] = bz(msgbytes[0], oa[0]);
byte key = encbytes[0];
int ios = (key - 48);
for (int i = 1; i < msgbytes.length; i++) {
encbytes[i] = bz(msgbytes[i], oa[(i + ios) % oa.length]);
}
return new String(encbytes);
}
public static String elen(String msg, int len) {
Random r = new Random();
if (msg.length() < len) {
int max = len - msg.length();
StringBuilder sb = new StringBuilder();
sb.append(msg).append(":");
for (int i = 1; i < max; i++) {
int bc = r.nextInt(122 - 48);
sb.append(Character.toString((char) (bc + 48)));
}
return sb.toString();
}
return msg;
}
}
@@ -10,17 +10,12 @@ import java.util.Map;
/**
* A LRU based cache for PreparedStatements.
*/
public class PstmtCache extends LinkedHashMap<String, ExtendedPreparedStatement> {
class PstmtCache extends LinkedHashMap<String, ExtendedPreparedStatement> {
private static final Logger logger = LoggerFactory.getLogger(PstmtCache.class);
static final long serialVersionUID = -3096406924865550697L;
/**
* The name of the cache, for tracing purposes.
*/
protected final String cacheName;
/**
* The maximum size of the cache. When this is exceeded the oldest entry is removed.
*/
@@ -46,11 +41,9 @@ public class PstmtCache extends LinkedHashMap<String, ExtendedPreparedStatement>
*/
private int putCounter;
public PstmtCache(String cacheName, int maxCacheSize) {
PstmtCache(int maxCacheSize) {
// note = access ordered list. This is what gives it the LRU order
super(maxCacheSize * 3, 0.75f, true);
this.cacheName = cacheName;
this.maxSize = maxCacheSize;
}
@@ -72,7 +65,7 @@ public class PstmtCache extends LinkedHashMap<String, ExtendedPreparedStatement>
* Gets the hit ratio. A number between 0 and 100 indicating the number of
* hits to misses. A number approaching 100 is desirable.
*/
public int getHitRatio() {
private int getHitRatio() {
if (hitCounter == 0) {
return 0;
} else {
@@ -106,7 +99,7 @@ public class PstmtCache extends LinkedHashMap<String, ExtendedPreparedStatement>
* matching ExtendedPreparedStatement in the cache return false else add
* the statement to the cache and return true.
*/
public boolean returnStatement(ExtendedPreparedStatement pstmt) {
boolean returnStatement(ExtendedPreparedStatement pstmt) {
ExtendedPreparedStatement alreadyInCache = super.get(pstmt.getCacheKey());
if (alreadyInCache != null) {
@@ -5,36 +5,7 @@ import java.sql.Connection;
/**
* Helper object that can convert between transaction isolation descriptions and values.
*/
public class TransactionIsolation {
/**
* return the isolation level for a given string description.
*/
public static int getLevel(String level) {
level = level.toUpperCase();
if (level.startsWith("TRANSACTION")) {
level = level.substring("TRANSACTION".length());
}
level = level.replace("_", "");
if ("NONE".equalsIgnoreCase(level)) {
return Connection.TRANSACTION_NONE;
}
if ("READCOMMITTED".equalsIgnoreCase(level)) {
return Connection.TRANSACTION_READ_COMMITTED;
}
if ("READUNCOMMITTED".equalsIgnoreCase(level)) {
return Connection.TRANSACTION_READ_UNCOMMITTED;
}
if ("REPEATABLEREAD".equalsIgnoreCase(level)) {
return Connection.TRANSACTION_REPEATABLE_READ;
}
if ("SERIALIZABLE".equalsIgnoreCase(level)) {
return Connection.TRANSACTION_SERIALIZABLE;
}
throw new RuntimeException("Transaction Isolaction level [" + level + "] is not known.");
}
class TransactionIsolation {
/**
* Return the string description of the transaction isolation level specified.
@@ -44,7 +15,7 @@ public class TransactionIsolation {
* @param level the transaction isolation level as per java.sql.Connection
* @return the level description as a string.
*/
public static String getLevelDescription(int level) {
static String getLevelDescription(int level) {
switch (level) {
case Connection.TRANSACTION_NONE:
return "NONE";