diff --git a/src/main/java/com/alibaba/druid/filter/FilterAdapter.java b/src/main/java/com/alibaba/druid/filter/FilterAdapter.java index bcb284114e..32804f030a 100644 --- a/src/main/java/com/alibaba/druid/filter/FilterAdapter.java +++ b/src/main/java/com/alibaba/druid/filter/FilterAdapter.java @@ -2429,11 +2429,6 @@ public abstract class FilterAdapter extends NotificationBroadcasterSupport imple chain.statement_clearBatch(statement); } - @Override - public void statement_clearWarnings(FilterChain chain, StatementProxy statement) throws SQLException { - chain.statement_clearWarnings(statement); - } - @Override public void statement_close(FilterChain chain, StatementProxy statement) throws SQLException { chain.statement_close(statement); @@ -2543,6 +2538,11 @@ public abstract class FilterAdapter extends NotificationBroadcasterSupport imple return chain.statement_getQueryTimeout(statement); } + @Override + public void statement_setQueryTimeout(FilterChain chain, StatementProxy statement, int seconds) throws SQLException { + chain.statement_setQueryTimeout(statement, seconds); + } + @Override public ResultSetProxy statement_getResultSet(FilterChain chain, StatementProxy statement) throws SQLException { return chain.statement_getResultSet(statement); @@ -2573,6 +2573,11 @@ public abstract class FilterAdapter extends NotificationBroadcasterSupport imple return chain.statement_getWarnings(statement); } + @Override + public void statement_clearWarnings(FilterChain chain, StatementProxy statement) throws SQLException { + chain.statement_clearWarnings(statement); + } + @Override public boolean statement_isClosed(FilterChain chain, StatementProxy statement) throws SQLException { return chain.statement_isClosed(statement); @@ -2621,11 +2626,6 @@ public abstract class FilterAdapter extends NotificationBroadcasterSupport imple chain.statement_setPoolable(statement, poolable); } - @Override - public void statement_setQueryTimeout(FilterChain chain, StatementProxy statement, int seconds) throws SQLException { - chain.statement_setQueryTimeout(statement, seconds); - } - @Override public T unwrap(FilterChain chain, Wrapper wrapper, Class iface) throws SQLException { return chain.unwrap(wrapper, iface); diff --git a/src/main/java/com/alibaba/druid/pool/DruidAbstractDataSource.java b/src/main/java/com/alibaba/druid/pool/DruidAbstractDataSource.java index e86956c2d2..844211f849 100644 --- a/src/main/java/com/alibaba/druid/pool/DruidAbstractDataSource.java +++ b/src/main/java/com/alibaba/druid/pool/DruidAbstractDataSource.java @@ -1127,7 +1127,7 @@ public abstract class DruidAbstractDataSource extends WrapperAdapter implements } return true; - } catch (SQLException ex) { + } catch (Exception ex) { // skip return false; } @@ -1137,10 +1137,6 @@ public abstract class DruidAbstractDataSource extends WrapperAdapter implements return this.activeConnections.keySet(); } - void removeActiveConnection(DruidPooledConnection conn) { - activeConnections.remove(conn); - } - public List getActiveConnectionStackTrace() { List list = new ArrayList(); for (ActiveConnectionTraceInfo traceInfo : this.activeConnections.values()) { @@ -1227,11 +1223,13 @@ public abstract class DruidAbstractDataSource extends WrapperAdapter implements String password = getPassword(); PasswordCallback passwordCallback = getPasswordCallback(); - if (passwordCallback instanceof DruidPasswordCallback) { - DruidPasswordCallback druidPasswordCallback = (DruidPasswordCallback) passwordCallback; + if (passwordCallback != null) { + if (passwordCallback instanceof DruidPasswordCallback) { + DruidPasswordCallback druidPasswordCallback = (DruidPasswordCallback) passwordCallback; - druidPasswordCallback.setUrl(url); - druidPasswordCallback.setProperties(connectProperties); + druidPasswordCallback.setUrl(url); + druidPasswordCallback.setProperties(connectProperties); + } char[] chars = passwordCallback.getPassword(); if (chars != null) { @@ -1312,6 +1310,8 @@ public abstract class DruidAbstractDataSource extends WrapperAdapter implements } } + public abstract int getActivePeak(); + public CompositeDataSupport getCompositeData() throws JMException { JdbcDataSourceStat stat = this.getDataSourceStat(); @@ -1330,20 +1330,19 @@ public abstract class DruidAbstractDataSource extends WrapperAdapter implements map.put("Properties", getProperties()); // 0 - 4 - map.put("ConnectionActiveCount", stat.getConnectionActiveCount()); - map.put("ConnectionActiveCountMax", stat.getConnectionStat().getActiveMax()); - map.put("ConnectionCloseCount", stat.getConnectionStat().getCloseCount()); - map.put("ConnectionCommitCount", stat.getConnectionStat().getCommitCount()); - map.put("ConnectionRollbackCount", stat.getConnectionStat().getRollbackCount()); + map.put("ConnectionActiveCount", (long) getActiveCount()); + map.put("ConnectionActiveCountMax", getActivePeak()); + map.put("ConnectionCloseCount", getCloseCount()); + map.put("ConnectionCommitCount", getCommitCount()); + map.put("ConnectionRollbackCount", getRollbackCount()); // 5 - 9 map.put("ConnectionConnectLastTime", stat.getConnectionStat().getConnectLastTime()); - map.put("ConnectionConnectErrorCount", stat.getConnectionStat().getConnectErrorCount()); - Throwable lastConnectionConnectError = stat.getConnectionStat().getConnectErrorLast(); - if (lastConnectionConnectError != null) { - map.put("ConnectionConnectErrorLastTime", stat.getConnectionStat().getErrorLastTime()); - map.put("ConnectionConnectErrorLastMessage", lastConnectionConnectError.getMessage()); - map.put("ConnectionConnectErrorLastStackTrace", IOUtils.getStackTrace(lastConnectionConnectError)); + map.put("ConnectionConnectErrorCount", this.getCreateCount()); + if (createError != null) { + map.put("ConnectionConnectErrorLastTime", getLastCreateErrorTime()); + map.put("ConnectionConnectErrorLastMessage", createError.getMessage()); + map.put("ConnectionConnectErrorLastStackTrace", IOUtils.getStackTrace(createError)); } else { map.put("ConnectionConnectErrorLastTime", null); map.put("ConnectionConnectErrorLastMessage", null); diff --git a/src/main/java/com/alibaba/druid/pool/DruidPooledStatement.java b/src/main/java/com/alibaba/druid/pool/DruidPooledStatement.java index 629d8bf274..e402d1472f 100644 --- a/src/main/java/com/alibaba/druid/pool/DruidPooledStatement.java +++ b/src/main/java/com/alibaba/druid/pool/DruidPooledStatement.java @@ -18,6 +18,7 @@ package com.alibaba.druid.pool; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; +import java.sql.SQLFeatureNotSupportedException; import java.sql.SQLWarning; import java.sql.Statement; import java.util.ArrayList; @@ -65,10 +66,6 @@ public class DruidPooledStatement extends PoolableWrapper implements Statement { return conn; } - public void setPoolableConnection(DruidPooledConnection conn) { - this.conn = conn; - } - public Statement getStatement() { return stmt; } @@ -603,11 +600,11 @@ public class DruidPooledStatement extends PoolableWrapper implements Statement { } public void closeOnCompletion() throws SQLException { - + throw new SQLFeatureNotSupportedException(); } public boolean isCloseOnCompletion() throws SQLException { - return false; + throw new SQLFeatureNotSupportedException(); } @SuppressWarnings("unchecked") diff --git a/src/main/java/com/alibaba/druid/pool/StatementCacheAlgorithm.java b/src/main/java/com/alibaba/druid/pool/StatementCacheAlgorithm.java deleted file mode 100644 index cc2445dbe9..0000000000 --- a/src/main/java/com/alibaba/druid/pool/StatementCacheAlgorithm.java +++ /dev/null @@ -1,20 +0,0 @@ -/* - * Copyright 1999-2011 Alibaba Group Holding Ltd. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.alibaba.druid.pool; - -public enum StatementCacheAlgorithm { - LRU, Fixed -} diff --git a/src/main/java/com/alibaba/druid/support/jconsole/DruidDataSourcePanel.java b/src/main/java/com/alibaba/druid/support/jconsole/DruidDataSourcePanel.java index 8caac6e11c..8dee034f71 100644 --- a/src/main/java/com/alibaba/druid/support/jconsole/DruidDataSourcePanel.java +++ b/src/main/java/com/alibaba/druid/support/jconsole/DruidDataSourcePanel.java @@ -1,22 +1,71 @@ -/* - * Copyright 1999-2011 Alibaba Group Holding Ltd. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.alibaba.druid.support.jconsole; - -public class DruidDataSourcePanel extends DruidPanel { - - private static final long serialVersionUID = 1L; - -} +/* + * Copyright 1999-2011 Alibaba Group Holding Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alibaba.druid.support.jconsole; + +import java.util.ArrayList; +import java.util.LinkedHashMap; + +import com.alibaba.druid.support.jconsole.model.DruidTableModel; +import com.alibaba.druid.support.jconsole.model.RowHeaderTable; +import com.alibaba.druid.support.jconsole.util.TableDataProcessor; +import com.alibaba.druid.support.jconsole.util.TableDataProcessor.ColumnData; + +/** + * 请求地址:/datasource.json + * + * 请求返回的json格式: + * {"ResultCode":1, + * "Content": + * [{"Identity":31375837,"Name":"DataSource-31375837","DbType":"mysql", + * "DriverClassName":"com.mysql.jdbc.Driver", + * "URL":"jdbc:mysql://localhost:3306/dragoon_v25_masterdb","UserName":"root", + * "FilterClassNames":["com.alibaba.druid.filter.stat.StatFilter"], + * "WaitThreadCount":0,"NotEmptyWaitCount":0,"NotEmptyWaitMillis":0,"PoolingCount":1, + * "PoolingPeak":0,"ActiveCount":0,"ActivePeak":1,"ActivePeakTime":"Tue Aug 21 21:22:33 CST 2012", + * "InitialSize":1,"MinIdle":1,"MaxActive":20,"QueryTimeout":0,"TransactionQueryTimeout":0, + * "LoginTimeout":0,"ValidConnectionCheckerClassName":"com.alibaba.druid.pool.vendor.MySqlValidConnectionChecker", + * "ExceptionSorterClassName":"com.alibaba.druid.pool.vendor.MySqlExceptionSorter", + * "TestOnBorrow":false,"TestOnReturn":false,"TestWhileIdle":true,"DefaultAutoCommit":true, + * "DefaultReadOnly":true,"LogicConnectCount":93,"LogicCloseCount":93,"LogicConnectErrorCount":0, + * "PhysicalConnectCount":1,"PhysicalCloseCount":0,"PhysicalConnectErrorCount":0, + * "ExecuteCount":93,"ErrorCount":0,"CommitCount":0,"RollbackCount":0,"PSCacheAccessCount":31, + * "PSCacheHitCount":30,"PSCacheMissCount":1,"StartTransactionCount":0, + * "TransactionHistogram":[0,0,0,0,0,0],"ConnectionHoldTimeHistogram":[0,0,48,45,0,0,0,0], + * "RemoveAbandoned":false + * }] + * } + * */ +public class DruidDataSourcePanel extends DruidPanel { + + private static final long serialVersionUID = 1L; + private static final String REQUEST_URL = "/datasource.json"; + private static final String KEY_WORD_IDENTITY = "Identity"; + + public DruidDataSourcePanel() { + super(); + this.url = REQUEST_URL; + } + @Override + protected void tableDataProcess( + ArrayList> data) { + ColumnData columnData = TableDataProcessor.row2col(data, KEY_WORD_IDENTITY); + tableModel = new DruidTableModel(columnData.getDatas()); + table.setModel(tableModel); + RowHeaderTable header = new RowHeaderTable( + columnData.getNames(),table,50,columnData.getCount()); + scrollPane.setRowHeaderView(header); + } +} diff --git a/src/main/java/com/alibaba/druid/support/jconsole/DruidDriverPanel.java b/src/main/java/com/alibaba/druid/support/jconsole/DruidDriverPanel.java index 1fb1443edd..21f3fb613e 100644 --- a/src/main/java/com/alibaba/druid/support/jconsole/DruidDriverPanel.java +++ b/src/main/java/com/alibaba/druid/support/jconsole/DruidDriverPanel.java @@ -1,22 +1,51 @@ -/* - * Copyright 1999-2011 Alibaba Group Holding Ltd. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.alibaba.druid.support.jconsole; - -public class DruidDriverPanel extends DruidPanel { - - private static final long serialVersionUID = 1L; - -} +/* + * Copyright 1999-2011 Alibaba Group Holding Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alibaba.druid.support.jconsole; + +import java.util.ArrayList; +import java.util.LinkedHashMap; + +import com.alibaba.druid.support.jconsole.model.DruidTableModel; + +/** + * 请求地址:/basic.json + * + * 请求返回的json格式: + * {"ResultCode":1,"Content": + * {"Version":"0.2.6","Drivers": + * ["sun.jdbc.odbc.JdbcOdbcDriver","com.alibaba.druid.mock.MockDriver", + * "com.mysql.jdbc.Driver","com.alibaba.druid.proxy.DruidDriver"] + * } + * } + * */ +public class DruidDriverPanel extends DruidPanel { + + private static final long serialVersionUID = 1L; + private static final String REQUEST_URL = "/basic.json"; + + public DruidDriverPanel() { + super(); + url = REQUEST_URL; + } + + @Override + protected void tableDataProcess( + ArrayList> data) { + tableModel = new DruidTableModel(data); + table.setModel(tableModel); + } +} + diff --git a/src/main/java/com/alibaba/druid/support/jconsole/DruidPanel.java b/src/main/java/com/alibaba/druid/support/jconsole/DruidPanel.java index f525873b5b..a7882a9ddf 100644 --- a/src/main/java/com/alibaba/druid/support/jconsole/DruidPanel.java +++ b/src/main/java/com/alibaba/druid/support/jconsole/DruidPanel.java @@ -1,36 +1,164 @@ -/* - * Copyright 1999-2011 Alibaba Group Holding Ltd. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.alibaba.druid.support.jconsole; - -import javax.management.MBeanServerConnection; -import javax.swing.JPanel; - -import com.sun.tools.jconsole.JConsoleContext; - -public class DruidPanel extends JPanel { - - private static final long serialVersionUID = 1L; - - protected Object doInBackground(JConsoleContext context) throws Exception { - doInBackground(context.getMBeanServerConnection()); - - return null; - } - - protected void doInBackground(MBeanServerConnection conn) throws Exception { - System.out.println("doInBackground"); - } -} +/* + * Copyright 1999-2011 Alibaba Group Holding Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alibaba.druid.support.jconsole; + +import java.awt.GridBagConstraints; +import java.awt.GridBagLayout; +import java.util.ArrayList; +import java.util.Date; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +import javax.management.MBeanServerConnection; +import javax.management.ObjectName; +import javax.swing.JPanel; +import javax.swing.JScrollPane; +import javax.swing.JTable; + +import com.alibaba.druid.stat.DruidStatService; +import com.alibaba.druid.support.jconsole.model.DruidTableModel; +import com.alibaba.druid.support.json.JSONUtils; +import com.alibaba.druid.support.logging.Log; +import com.alibaba.druid.support.logging.LogFactory; +import com.sun.tools.jconsole.JConsoleContext; + +public abstract class DruidPanel extends JPanel { + + private static final long serialVersionUID = 1L; + protected static final int RESP_SUCCESS_RESULT = 1; + protected static final String RESP_JSON_RESULT_KEY = "ResultCode"; + protected static final String RESP_JSON_CONTENT_KEY = "Content"; + protected static final long DEFAULT_ACTIVE_TIME = 5*60*1000; + + protected static final int DRUID_TABLE_WIDTH = 600; + protected static final int DRUID_TABLE_HEIGHT = 500; + + protected JScrollPane scrollPane; + protected DruidTableModel tableModel; + protected JTable table; + protected String url; + + /** 界面刷新的间隔时间,单位为毫秒. */ + protected long activeTime; + protected long lastRefreshTime; + private final static Log LOG = LogFactory.getLog(DruidPanel.class); + + protected DruidPanel(long activeTime) { + this.activeTime = activeTime; + } + + protected DruidPanel() { + activeTime = DEFAULT_ACTIVE_TIME; + } + + @SuppressWarnings("unchecked") + protected ArrayList> parseData(Object respData) { + ArrayList> data = null; + if (respData instanceof Map) { + LinkedHashMap map = (LinkedHashMap)respData; + int rv = (Integer)map.get(RESP_JSON_RESULT_KEY); + + if (rv == RESP_SUCCESS_RESULT) { + Object content = map.get(RESP_JSON_CONTENT_KEY); + if (content instanceof List) { + data = (ArrayList>)content; + } else if (content instanceof Map) { + LinkedHashMap contentEle + = (LinkedHashMap)content; + data = new ArrayList>(); + data.add(contentEle); + } + } + } + return data; + } + + protected Object getData(String url,MBeanServerConnection conn) throws Exception { + Object o = null; + ObjectName name = new ObjectName(DruidStatService.MBEAN_NAME); + + String result = (String) conn.invoke(name, "service", + new String[] { url }, new String[] { String.class.getName() }); + o = JSONUtils.parse(result); + if (LOG.isDebugEnabled()) { + LOG.debug(o.toString()); + } + return o; + } + + protected abstract void tableDataProcess(ArrayList> data); + + protected void addOrRefreshTable(String url,MBeanServerConnection conn) throws Exception { + if (url != null) { + boolean needRefresh = false; + long timeNow = new Date().getTime(); + if (scrollPane == null) { + table = new JTable(); + + scrollPane = new JScrollPane(table); + scrollPane.setAutoscrolls(true); + GridBagLayout gridbag = new GridBagLayout(); + GridBagConstraints c = new GridBagConstraints(); + setLayout(gridbag); + + c.fill = GridBagConstraints.BOTH; + c.gridx = 0; + c.gridy = 0; + c.weightx = 9; + c.weighty = 9; + + gridbag.setConstraints(scrollPane, c); + + this.add(scrollPane); + needRefresh = true; + lastRefreshTime = timeNow; + } else { + if (lastRefreshTime + activeTime < timeNow) { + needRefresh = true; + lastRefreshTime = timeNow; + } + } + if (needRefresh) { + LOG.debug("refresh" + timeNow); + ArrayList> data = parseData(getData( + url, conn)); + if (data != null) { + tableDataProcess(data); + } + } + + } else { + // url不存在 + LOG.warn("url不存在"); + } + } + + protected Object doInBackground(JConsoleContext context) throws Exception { + doInBackground(context.getMBeanServerConnection()); + + return null; + } + + protected void doInBackground(MBeanServerConnection conn) { + + try { + addOrRefreshTable(url,conn); + } catch (Exception e) { + LOG.warn("", e); + } + } +} \ No newline at end of file diff --git a/src/main/java/com/alibaba/druid/support/jconsole/DruidSQLPanel.java b/src/main/java/com/alibaba/druid/support/jconsole/DruidSQLPanel.java index 133ea50f05..60e3063e26 100644 --- a/src/main/java/com/alibaba/druid/support/jconsole/DruidSQLPanel.java +++ b/src/main/java/com/alibaba/druid/support/jconsole/DruidSQLPanel.java @@ -1,36 +1,110 @@ -/* - * Copyright 1999-2011 Alibaba Group Holding Ltd. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.alibaba.druid.support.jconsole; - -import javax.management.MBeanServerConnection; -import javax.management.ObjectName; - -import com.alibaba.druid.stat.DruidStatService; -import com.alibaba.druid.support.json.JSONUtils; - -public class DruidSQLPanel extends DruidPanel { - - private static final long serialVersionUID = 1L; - - protected void doInBackground(MBeanServerConnection conn) throws Exception { - ObjectName name = new ObjectName(DruidStatService.MBEAN_NAME); - String url = "/sql.json"; - String result = (String) conn.invoke(name, "service", new String[] { url }, new String[] { String.class.getName() }); - Object o = JSONUtils.parse(result); - - System.out.println(o); - } -} +/* + * Copyright 1999-2011 Alibaba Group Holding Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alibaba.druid.support.jconsole; + +import java.util.ArrayList; +import java.util.LinkedHashMap; + +import com.alibaba.druid.support.jconsole.model.DruidTableModel; +import com.alibaba.druid.support.jconsole.model.RowHeaderTable; +/** + * 请求地址 /sql.json + * + * 返回数据格式: + *
+ * {
+    "ResultCode": 1,
+    "Content": [
+        {
+            "BatchSizeMax": 0,
+            "BatchSizeTotal": 0,
+            "ConcurrentMax": 1,
+            "DbType": "h2",
+            "EffectedRowCount": 18,
+            "EffectedRowCountHistogram": [
+                0,6,0,0,0,0
+            ],
+            "EffectedRowCountMax": 4,
+            "ErrorCount": 0,
+            "ExecuteAndResultHoldTimeHistogram": [
+                5,0,1,0,0,0,0,0
+            ],
+            "ExecuteAndResultSetHoldTime": 0,
+            "ExecuteCount": 6,
+            "FetchRowCount": 0,
+            "FetchRowCountHistogram": [
+                6,0,0,0,0,0
+            ],
+            "FetchRowCountMax": 0,
+            "Histogram": [
+                5,0,1,0,0,0,0,0
+            ],
+            "ID": 9,
+            "InTransactionCount": 6,
+            "LastSlowParameters": "[4]",
+            "LastTime": "2012-08-22 02:57:56",
+            "MaxTimespan": 18,
+            "MaxTimespanOccurTime": "2012-08-22 12:38:56",
+            "ResultSetHoldTime": 0,
+            "RunningCount": 0,
+            "SQL": "delete from acct_group_permission where group_id=?",
+            "TotalTime": 21
+        },
+     ]
+  }
+  
+ * */ +public class DruidSQLPanel extends DruidPanel { + + private static final long serialVersionUID = 1L; + private static final String REQUEST_URL = "/sql.json"; + private static final ArrayList SHOW_LIST = new ArrayList() { + + private static final long serialVersionUID = 1L; + + { + add("SQL"); + add("ExecuteCount"); + add("TotalTime"); + add("InTransactionCount"); + add("ErrorCount"); + add("EffectedRowCount"); + add("FetchRowCount"); + add("RunningCount"); + add("ConcurrentMax"); + add("Histogram"); + add("EffectedRowCountHistogram"); + add("ExecuteAndResultHoldTimeHistogram"); + add("FetchRowCountHistogram"); + } + }; + private RowHeaderTable header; + + public DruidSQLPanel() { + super(); + this.url = REQUEST_URL; + } + + @Override + protected void tableDataProcess( + ArrayList> data) { + tableModel = new DruidTableModel(data,SHOW_LIST); + table.setModel(tableModel); + + header = new RowHeaderTable(table,20); + scrollPane.setRowHeaderView(header); + } +} diff --git a/src/main/java/com/alibaba/druid/support/jconsole/model/DruidTableModel.java b/src/main/java/com/alibaba/druid/support/jconsole/model/DruidTableModel.java new file mode 100644 index 0000000000..36f69fdfe3 --- /dev/null +++ b/src/main/java/com/alibaba/druid/support/jconsole/model/DruidTableModel.java @@ -0,0 +1,116 @@ +/* + * Copyright 1999-2011 Alibaba Group Holding Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alibaba.druid.support.jconsole.model; + +import java.util.ArrayList; +import java.util.LinkedHashMap; + +import javax.swing.event.TableModelListener; +import javax.swing.table.TableModel; + +public class DruidTableModel implements TableModel { + private ArrayList> list; + private ArrayList showKeys; + + public DruidTableModel(ArrayList> list) { + super(); + this.list = list; + showKeys = null; + } + + public DruidTableModel(ArrayList> list, + ArrayList showKeys) { + super(); + this.list = list; + this.showKeys = showKeys; + } + + + @Override + public Class getColumnClass(int columnIndex) { + return String.class; + } + + @Override + public int getColumnCount() { + int colCount = 0; + if (showKeys != null) { + colCount = showKeys.size(); + } else if (list != null) { + int listLen = list.size(); + if (listLen > 0) { + colCount = list.get(0).size(); + } + } + return colCount; + } + + @Override + public String getColumnName(int columnIndex) { + if (showKeys != null && showKeys.size() > 0) { + return showKeys.get(columnIndex); + } + if (list != null && list.size() > 0) { + LinkedHashMap firstElement = list.get(0); + Object[] keys = firstElement.keySet().toArray(); + return keys[columnIndex].toString(); + } + return null; + } + + @Override + public int getRowCount() { + return list.size(); + } + + @Override + public Object getValueAt(int rowIndex, int columnIndex) { + if (list != null && rowIndex < list.size()) { + LinkedHashMap dataNow = list.get(rowIndex); + if (showKeys != null) { + int titleLen = showKeys.size(); + if (titleLen > 0 && columnIndex < titleLen) { + return dataNow.get(showKeys.get(columnIndex)); + } + } else { + Object[] values = dataNow.values().toArray(); + return values[columnIndex]; + } + } + return null; + } + + @Override + public boolean isCellEditable(int rowIndex, int columnIndex) { + return false; + } + + @Override + public void addTableModelListener(TableModelListener l) { + + } + + @Override + public void removeTableModelListener(TableModelListener l) { + + } + + @Override + public void setValueAt(Object aValue, int rowIndex, int columnIndex) { + + } + +} diff --git a/src/main/java/com/alibaba/druid/support/jconsole/model/RowHeaderTable.java b/src/main/java/com/alibaba/druid/support/jconsole/model/RowHeaderTable.java new file mode 100644 index 0000000000..0689652ebd --- /dev/null +++ b/src/main/java/com/alibaba/druid/support/jconsole/model/RowHeaderTable.java @@ -0,0 +1,157 @@ +/* + * Copyright 1999-2011 Alibaba Group Holding Ltd. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.alibaba.druid.support.jconsole.model; + +import java.awt.Color; +import java.awt.Component; +import java.awt.Dimension; +import java.util.ArrayList; + +import javax.swing.JLabel; +import javax.swing.JTable; +import javax.swing.ListSelectionModel; +import javax.swing.UIManager; +import javax.swing.event.ListSelectionEvent; +import javax.swing.event.ListSelectionListener; +import javax.swing.table.DefaultTableModel; +import javax.swing.table.JTableHeader; +import javax.swing.table.TableCellRenderer; + +/** + * 用于显示RowHeader的JTable,只需要将其加入JScrollPane的RowHeaderView即可为JTable生成行标题 + */ +public class RowHeaderTable extends JTable +{ + private static final long serialVersionUID = 1L; + + /** + * 为JTable添加RowHeader, + * @param refTable 需要添加rowHeader的JTable + * @param columnWideth rowHeader的宽度 + */ + public RowHeaderTable(JTable refTable,int columnWidth){ + this(null,refTable,columnWidth,1); + } + + public RowHeaderTable(ArrayList title,JTable refTable,int columnWidth) { + this(title,refTable,columnWidth,1); + } + + public RowHeaderTable(ArrayList title,JTable refTable,int columnWidth,int rowSpan) { + super(new DefaultTableModel(refTable.getRowCount()/rowSpan,1)); + this.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);//不可以调整列宽 + this.getColumnModel().getColumn(0).setPreferredWidth(columnWidth); + this.setDefaultRenderer(Object.class,new RowHeaderRenderer(title,refTable,this,rowSpan));//设置渲染器 + this.setPreferredScrollableViewportSize (new Dimension(columnWidth,0)); + } +} +/** + * 用于显示RowHeader的JTable的渲染器,当选择某行时,该行颜色会发生变化 + */ +final class RowHeaderRenderer extends JLabel implements TableCellRenderer,ListSelectionListener +{ + private static final long serialVersionUID = 1L; + private JTable reftable;//需要添加rowHeader的JTable + private JTable tableShow;//用于显示rowHeader的JTable + private ArrayList headerList; + private int rowHeightNow; + private int rowSpan; + + public RowHeaderRenderer(JTable reftable,JTable tableShow) { + this(null,reftable,tableShow,0); + } + + public RowHeaderRenderer(ArrayList headerList, + JTable reftable,JTable tableShow,int rowSpan) + { + this.headerList = headerList; + this.reftable = reftable; + this.tableShow=tableShow; + //增加监听器,实现当在reftable中选择行时,RowHeader会发生颜色变化 + ListSelectionModel listModel=reftable.getSelectionModel(); + listModel.addListSelectionListener(this); + rowHeightNow = reftable.getRowCount()*reftable.getRowHeight(); + this.rowSpan = rowSpan; + if (rowSpan > 1) { + rowHeightNow = rowSpan*reftable.getRowHeight(); + } + } + public Component getTableCellRendererComponent(JTable table,Object obj, + boolean isSelected,boolean hasFocus,int row, int col) + { + int rowCountNow = reftable.getRowCount()/rowSpan; + ((DefaultTableModel)table.getModel()).setRowCount(rowCountNow); + JTableHeader header = reftable.getTableHeader(); + this.setOpaque(true); + setBorder(UIManager.getBorder("TableHeader.cellBorder"));//设置为TableHeader的边框类型 + setHorizontalAlignment(CENTER);//让text居中显示 + setBackground(header.getBackground());//设置背景色为TableHeader的背景色 + if ( isSelect(row) ) //当选取单元格时,在row header上设置成选取颜色 + { + setForeground(Color.white); + setBackground(Color.lightGray); + } + else + { + setForeground(header.getForeground()); + } + setFont(header.getFont()); + if (row <= rowCountNow){ + showCol(row); + } + return this; + } + + private void showCol(int row) { + + String text = null; + if (headerList != null && row < headerList.size()) { + text = headerList.get(row); + } else { + text = String.valueOf(row+1); + } + if (rowSpan > 1) { + setText(text); + this.tableShow.setRowHeight(row, rowHeightNow); + } else { + setText(text); + } + + } + + public void valueChanged(ListSelectionEvent e){ + this.tableShow.repaint(); + } + private boolean isSelect(int row) + { + int[] sel = reftable.getSelectedRows(); + if (rowSpan <= 1) { + for ( int i=0,len = sel.length; i> rowDatas, String keyword) { + ColumnData datas = new ColumnData(); + ArrayList> coldatas + = new ArrayList>(); + ArrayList colNames = new ArrayList(); + int rowCount = 0; + int colCount = 0; + for(LinkedHashMap row: rowDatas) { + String keyNow = row.remove(keyword).toString(); + colNames.add(keyNow); + rowCount ++; + + for(Map.Entry element : row.entrySet()) { + LinkedHashMap colData + = new LinkedHashMap(); + colData.put(COLUMN_KEY_NAME, element.getKey()); + colData.put(COLUMN_VALUE_NAME, element.getValue()); + coldatas.add(colData); + if (rowCount == 1) { + colCount++; + } + } + } + datas.setCount(colCount); + datas.setDatas(coldatas); + datas.setNames(colNames); + return datas; + } + + public static class ColumnData { + private ArrayList names; + private ArrayList> datas; + private int count; + + public ColumnData() { + super(); + } + + public ArrayList getNames() { + return names; + } + public void setNames(ArrayList names) { + this.names = names; + } + public ArrayList> getDatas() { + return datas; + } + public void setDatas(ArrayList> datas) { + this.datas = datas; + } + public int getCount() { + return count; + } + public void setCount(int count) { + this.count = count; + } + } +} diff --git a/src/test/java/com/alibaba/druid/bvt/pool/DruidDataSourceTest4.java b/src/test/java/com/alibaba/druid/bvt/pool/DruidDataSourceTest4.java new file mode 100644 index 0000000000..a6c6f5da8d --- /dev/null +++ b/src/test/java/com/alibaba/druid/bvt/pool/DruidDataSourceTest4.java @@ -0,0 +1,102 @@ +package com.alibaba.druid.bvt.pool; + +import java.sql.SQLException; + +import junit.framework.Assert; +import junit.framework.TestCase; + +import com.alibaba.druid.pool.DruidDataSource; +import com.alibaba.druid.pool.ExceptionSorter; +import com.alibaba.druid.pool.vendor.MySqlValidConnectionChecker; + +public class DruidDataSourceTest4 extends TestCase { + + private DruidDataSource dataSource; + + protected void setUp() throws Exception { + dataSource = new DruidDataSource(); + dataSource.setUrl("jdbc:mock:xxx"); + dataSource.setTestOnBorrow(false); + dataSource.setInitialSize(1); + + } + + protected void tearDown() throws Exception { + dataSource.close(); + } + + public void test_getTransactionThresholdMillis() { + Assert.assertEquals(0, dataSource.getTransactionThresholdMillis()); + + dataSource.setTransactionThresholdMillis(100); + + Assert.assertEquals(100, dataSource.getTransactionThresholdMillis()); + } + + public void test_getTransactionHistogramRanges() { + Assert.assertNotNull(dataSource.getTransactionHistogramRanges()); + } + + public void test_getTransactionHistogramRanges_1() { + Assert.assertEquals(5, dataSource.getTransactionHistogramRanges().length); + } + + public void test_setValidConnectionCheckerClassName() throws Exception { + Assert.assertNull(dataSource.getValidConnectionChecker()); + dataSource.setValidConnectionCheckerClassName(MySqlValidConnectionChecker.class.getName()); + Assert.assertNotNull(dataSource.getValidConnectionChecker()); + } + + public void test_setMinIdle() throws Exception { + Assert.assertEquals(0, dataSource.getMinIdle()); + dataSource.init(); + dataSource.setMinIdle(1); + Assert.assertEquals(1, dataSource.getMinIdle()); + } + + public void test_setMinIdle_error() throws Exception { + Assert.assertEquals(0, dataSource.getMinIdle()); + dataSource.init(); + Exception error = null; + try { + dataSource.setMinIdle(100); + } catch (Exception e) { + error = e; + } + Assert.assertNotNull(error); + Assert.assertEquals(0, dataSource.getMinIdle()); + } + + public void test_setExceptionSorter_error() throws Exception { + dataSource.setExceptionSorter("xx"); + } + + public void test_setExceptionSorter_error2() throws Exception { + Exception error = null; + try { + dataSource.setExceptionSorter(MyExceptionSorter.class.getName()); + } catch (Exception e) { + error = e; + } + Assert.assertNotNull(error); + } + + public void test_getParentLogger() throws Exception { + Exception error = null; + try { + dataSource.getParentLogger(); + } catch (Exception e) { + error = e; + } + Assert.assertNotNull(error); + } + + private class MyExceptionSorter implements ExceptionSorter { + + @Override + public boolean isExceptionFatal(SQLException e) { + return false; + } + + } +} diff --git a/src/test/java/com/alibaba/druid/bvt/pool/DruidDataSourceTest5.java b/src/test/java/com/alibaba/druid/bvt/pool/DruidDataSourceTest5.java new file mode 100644 index 0000000000..fdc56cc0ac --- /dev/null +++ b/src/test/java/com/alibaba/druid/bvt/pool/DruidDataSourceTest5.java @@ -0,0 +1,92 @@ +package com.alibaba.druid.bvt.pool; + +import java.sql.Connection; +import java.sql.SQLException; +import java.util.concurrent.atomic.AtomicBoolean; + +import org.junit.Assert; + +import junit.framework.TestCase; + +import com.alibaba.druid.pool.DruidDataSource; +import com.alibaba.druid.pool.ValidConnectionChecker; + +public class DruidDataSourceTest5 extends TestCase { + + private DruidDataSource dataSource; + + private final AtomicBoolean validate = new AtomicBoolean(true); + + protected void setUp() throws Exception { + validate.set(true); + + dataSource = new DruidDataSource(); + dataSource.setUrl("jdbc:mock:xxx"); + dataSource.setTestOnBorrow(false); + dataSource.setInitialSize(1); + + dataSource.setValidConnectionChecker(new ValidConnectionChecker() { + + @Override + public boolean isValidConnection(Connection c, String query, int validationQueryTimeout) { + return validate.get(); + } + }); + } + + protected void tearDown() throws Exception { + dataSource.close(); + } + + public void testValidate() throws Exception { + validate.set(false); + + Exception error = null; + try { + dataSource.getConnection(); + } catch (SQLException e) { + error = e; + } + Assert.assertNotNull(error); + + validate.set(true); + + Connection conn = dataSource.getConnection(); + conn.close(); + } + + public void testValidate_1() throws Exception { + validate.set(false); + + Exception error = null; + try { + dataSource.init(); + } catch (SQLException e) { + error = e; + } + Assert.assertNotNull(error); + + validate.set(true); + + Connection conn = dataSource.getConnection(); + conn.close(); + } + + public void testValidate_3() throws Exception { + validate.set(false); + + Exception error = null; + try { + dataSource.init(); + } catch (SQLException e) { + error = e; + } + Assert.assertNotNull(error); + + validate.set(true); + + Connection conn = dataSource.getConnection(); + conn.close(); + } + +} diff --git a/src/test/java/com/alibaba/druid/bvt/pool/DruidDataSourceTest6.java b/src/test/java/com/alibaba/druid/bvt/pool/DruidDataSourceTest6.java new file mode 100644 index 0000000000..dfc32456f0 --- /dev/null +++ b/src/test/java/com/alibaba/druid/bvt/pool/DruidDataSourceTest6.java @@ -0,0 +1,113 @@ +package com.alibaba.druid.bvt.pool; + +import java.sql.Connection; +import java.sql.SQLException; +import java.sql.Statement; +import java.util.concurrent.atomic.AtomicInteger; + +import javax.security.auth.callback.NameCallback; + +import junit.framework.TestCase; + +import org.junit.Assert; + +import com.alibaba.druid.filter.FilterAdapter; +import com.alibaba.druid.filter.FilterChain; +import com.alibaba.druid.mock.MockResultSet; +import com.alibaba.druid.pool.DruidDataSource; +import com.alibaba.druid.proxy.jdbc.ResultSetProxy; +import com.alibaba.druid.proxy.jdbc.ResultSetProxyImpl; +import com.alibaba.druid.proxy.jdbc.StatementProxy; +import com.alibaba.druid.util.DruidPasswordCallback; + +public class DruidDataSourceTest6 extends TestCase { + + private DruidDataSource dataSource; + + private final AtomicInteger errorCount = new AtomicInteger(); + private final AtomicInteger returnEmptyCount = new AtomicInteger(); + + protected void setUp() throws Exception { + returnEmptyCount.set(0); + + dataSource = new DruidDataSource(); + dataSource.setUrl("jdbc:mock:xxx"); + dataSource.setTestOnBorrow(true); + dataSource.setInitialSize(1); + dataSource.setValidationQuery("select 1"); + dataSource.setValidationQueryTimeout(10); + dataSource.setQueryTimeout(100); + + dataSource.setUserCallback(new NameCallback("xx") { + + }); + + dataSource.setPasswordCallback(new DruidPasswordCallback() { + @Override + public char[] getPassword() { + return "xx".toCharArray(); + } + }); + + dataSource.getProxyFilters().add(new FilterAdapter() { + + public ResultSetProxy statement_executeQuery(FilterChain chain, StatementProxy statement, String sql) + throws SQLException { + if (errorCount.get() > 0) { + errorCount.decrementAndGet(); + throw new RuntimeException(); + } + + if (returnEmptyCount.get() > 0) { + returnEmptyCount.decrementAndGet(); + return new ResultSetProxyImpl(statement, new MockResultSet(statement), 0, sql); + } + + return chain.statement_executeQuery(statement, sql); + } + }); + } + + protected void tearDown() throws Exception { + dataSource.close(); + } + + public void testValidate() throws Exception { + returnEmptyCount.set(1); + + Exception error = null; + try { + dataSource.init(); + } catch (SQLException e) { + error = e; + } + Assert.assertNotNull(error); + + { + returnEmptyCount.set(1); + Connection conn = dataSource.getConnection(); + conn.close(); + } + + { + returnEmptyCount.set(1); + Connection conn = dataSource.getConnection(); + conn.close(); + } + + { + errorCount.set(1); + Connection conn = dataSource.getConnection(); + conn.close(); + } + + Connection conn = dataSource.getConnection(); + + Statement stmt = conn.createStatement(); + Assert.assertEquals(100, stmt.getQueryTimeout()); + stmt.close(); + + conn.close(); + } + +} diff --git a/src/test/java/com/alibaba/druid/bvt/pool/DruidDataSourceTest7.java b/src/test/java/com/alibaba/druid/bvt/pool/DruidDataSourceTest7.java new file mode 100644 index 0000000000..ea3cbecc14 --- /dev/null +++ b/src/test/java/com/alibaba/druid/bvt/pool/DruidDataSourceTest7.java @@ -0,0 +1,50 @@ +package com.alibaba.druid.bvt.pool; + +import java.sql.SQLException; +import java.util.Properties; + +import org.junit.Assert; + +import junit.framework.TestCase; + +import com.alibaba.druid.filter.FilterAdapter; +import com.alibaba.druid.filter.FilterChain; +import com.alibaba.druid.pool.DruidDataSource; +import com.alibaba.druid.proxy.jdbc.ConnectionProxy; + +public class DruidDataSourceTest7 extends TestCase { + + private DruidDataSource dataSource; + + protected void setUp() throws Exception { + dataSource = new DruidDataSource(); + dataSource.setUrl("jdbc:mock:xxx"); + dataSource.setInitialSize(1); + dataSource.getProxyFilters().add(new FilterAdapter() { + + @Override + public ConnectionProxy connection_connect(FilterChain chain, Properties info) throws SQLException { + throw new RuntimeException(); + } + }); + } + + protected void tearDown() throws Exception { + dataSource.close(); + } + + public void testInitError() throws Exception { + Assert.assertEquals(0, dataSource.getCreateErrorCount()); + Throwable error = null; + try { + dataSource.init(); + } catch (RuntimeException e) { + error = e; + } + Assert.assertNotNull(error); + Assert.assertTrue(dataSource.getCreateErrorCount() > 0); + + dataSource.getCompositeData(); + } + +} diff --git a/src/test/java/com/alibaba/druid/bvt/pool/DruidDataSourceTest8.java b/src/test/java/com/alibaba/druid/bvt/pool/DruidDataSourceTest8.java new file mode 100644 index 0000000000..0ca88cbd78 --- /dev/null +++ b/src/test/java/com/alibaba/druid/bvt/pool/DruidDataSourceTest8.java @@ -0,0 +1,48 @@ +package com.alibaba.druid.bvt.pool; + +import java.sql.SQLException; +import java.util.Properties; + +import org.junit.Assert; + +import junit.framework.TestCase; + +import com.alibaba.druid.filter.FilterAdapter; +import com.alibaba.druid.filter.FilterChain; +import com.alibaba.druid.pool.DruidDataSource; +import com.alibaba.druid.proxy.jdbc.ConnectionProxy; + +public class DruidDataSourceTest8 extends TestCase { + + private DruidDataSource dataSource; + + protected void setUp() throws Exception { + dataSource = new DruidDataSource(); + dataSource.setUrl("jdbc:mock:xxx"); + dataSource.setInitialSize(1); + dataSource.getProxyFilters().add(new FilterAdapter() { + + @Override + public ConnectionProxy connection_connect(FilterChain chain, Properties info) throws SQLException { + throw new Error(); + } + }); + } + + protected void tearDown() throws Exception { + dataSource.close(); + } + + public void testInitError() throws Exception { + Assert.assertEquals(0, dataSource.getCreateErrorCount()); + Throwable error = null; + try { + dataSource.init(); + } catch (Throwable e) { + error = e; + } + Assert.assertNotNull(error); + Assert.assertTrue(dataSource.getCreateErrorCount() > 0); + } + +} diff --git a/src/test/java/com/alibaba/druid/bvt/pool/DruidDataSourceTest9.java b/src/test/java/com/alibaba/druid/bvt/pool/DruidDataSourceTest9.java new file mode 100644 index 0000000000..b7e76f9137 --- /dev/null +++ b/src/test/java/com/alibaba/druid/bvt/pool/DruidDataSourceTest9.java @@ -0,0 +1,38 @@ +package com.alibaba.druid.bvt.pool; + +import java.sql.Connection; + +import junit.framework.TestCase; + +import org.junit.Assert; + +import com.alibaba.druid.pool.DruidDataSource; + +public class DruidDataSourceTest9 extends TestCase { + + private DruidDataSource dataSource; + + protected void setUp() throws Exception { + dataSource = new DruidDataSource(); + dataSource.setUrl("jdbc:mock:xxx"); + dataSource.setInitialSize(1); + dataSource.setDefaultReadOnly(true); + dataSource.setDefaultTransactionIsolation(Connection.TRANSACTION_SERIALIZABLE); + dataSource.setDefaultCatalog("c123"); + } + + protected void tearDown() throws Exception { + dataSource.close(); + } + + public void testDefault() throws Exception { + Connection conn = dataSource.getConnection(); + + Assert.assertEquals(true, conn.isReadOnly()); + Assert.assertEquals(Connection.TRANSACTION_SERIALIZABLE, conn.getTransactionIsolation()); + Assert.assertEquals("c123", conn.getCatalog()); + + conn.close(); + } + +} diff --git a/src/test/java/com/alibaba/druid/bvt/pool/DruidDataSourceTest_notEmptyWait.java b/src/test/java/com/alibaba/druid/bvt/pool/DruidDataSourceTest_notEmptyWait.java index d8338afc54..bc6510bb66 100644 --- a/src/test/java/com/alibaba/druid/bvt/pool/DruidDataSourceTest_notEmptyWait.java +++ b/src/test/java/com/alibaba/druid/bvt/pool/DruidDataSourceTest_notEmptyWait.java @@ -68,8 +68,15 @@ public class DruidDataSourceTest_notEmptyWait extends TestCase { threads[i].start(); } - startLatch.await(100, TimeUnit.MILLISECONDS); + startLatch.await(10, TimeUnit.MILLISECONDS); + for (int i = 0; i < 100; ++i) { + if (dataSource.getNotEmptyWaitThreadCount() == 10) { + break; + } + Thread.sleep(10); + } + Assert.assertEquals(10, dataSource.getNotEmptyWaitThreadCount()); Assert.assertEquals(10, dataSource.getNotEmptyWaitThreadPeak()); diff --git a/src/test/java/com/alibaba/druid/bvt/pool/DruidPooledCallableStatementTest.java b/src/test/java/com/alibaba/druid/bvt/pool/DruidPooledCallableStatementTest.java index 639b3afbd1..bc829e9e3d 100644 --- a/src/test/java/com/alibaba/druid/bvt/pool/DruidPooledCallableStatementTest.java +++ b/src/test/java/com/alibaba/druid/bvt/pool/DruidPooledCallableStatementTest.java @@ -21,6 +21,8 @@ public class DruidPooledCallableStatementTest extends TestCase { private DruidDataSource dataSource; + private boolean throwError = true; + protected void setUp() throws Exception { dataSource = new DruidDataSource(); @@ -32,7 +34,11 @@ public class DruidPooledCallableStatementTest extends TestCase { public boolean callableStatement_wasNull(FilterChain chain, CallableStatementProxy statement) throws SQLException { + if (throwError) { throw new SQLException(); + } else { + return chain.callableStatement_wasNull(statement); + } } }); } @@ -41,11 +47,27 @@ public class DruidPooledCallableStatementTest extends TestCase { dataSource.close(); } - public void test_wasNull() throws Exception { + public void test_wasNull_noerror() throws Exception { Connection conn = dataSource.getConnection(); CallableStatement stmt = conn.prepareCall("select 1"); stmt.execute(); + throwError = false; + stmt.wasNull(); + + Assert.assertEquals(0, dataSource.getErrorCount()); + + stmt.close(); + conn.close(); + + Assert.assertEquals(1, dataSource.getPoolingCount()); + } + + public void test_wasNull_error() throws Exception { + Connection conn = dataSource.getConnection(); + CallableStatement stmt = conn.prepareCall("select 1"); + stmt.execute(); + Assert.assertEquals(0, dataSource.getErrorCount()); Exception error = null; @@ -63,14 +85,14 @@ public class DruidPooledCallableStatementTest extends TestCase { Assert.assertEquals(1, dataSource.getPoolingCount()); } - + public void test_getObject() throws Exception { Connection conn = dataSource.getConnection(); DruidPooledCallableStatement stmt = (DruidPooledCallableStatement) conn.prepareCall("select 1"); stmt.execute(); Assert.assertEquals(0, dataSource.getErrorCount()); - + Exception error = null; try { stmt.getObject(1, String.class); @@ -78,22 +100,22 @@ public class DruidPooledCallableStatementTest extends TestCase { error = e; } Assert.assertNotNull(error); - + Assert.assertEquals(0, dataSource.getErrorCount()); - + stmt.close(); conn.close(); - + Assert.assertEquals(1, dataSource.getPoolingCount()); } - + public void test_getObject_1() throws Exception { Connection conn = dataSource.getConnection(); DruidPooledCallableStatement stmt = (DruidPooledCallableStatement) conn.prepareCall("select 1"); stmt.execute(); - + Assert.assertEquals(0, dataSource.getErrorCount()); - + Exception error = null; try { stmt.getObject("1", String.class); @@ -101,48 +123,48 @@ public class DruidPooledCallableStatementTest extends TestCase { error = e; } Assert.assertNotNull(error); - + Assert.assertEquals(0, dataSource.getErrorCount()); - + stmt.close(); conn.close(); - + Assert.assertEquals(1, dataSource.getPoolingCount()); } - + public void test_wrap() throws Exception { - + Connection conn = dataSource.getConnection(); CallableStatement stmt = conn.prepareCall("select 1"); - + Assert.assertNotNull(stmt.unwrap(CallableStatement.class)); Assert.assertEquals(MockCallableStatement.class, stmt.unwrap(CallableStatement.class).getClass()); - + stmt.close(); conn.close(); } - + public void test_wrap_1() throws Exception { - + Connection conn = dataSource.getConnection(); CallableStatement stmt = conn.prepareCall("select 1"); - + Assert.assertNotNull(stmt.unwrap(PreparedStatement.class)); Assert.assertEquals(MockCallableStatement.class, stmt.unwrap(CallableStatement.class).getClass()); - + stmt.close(); conn.close(); } - + public void test_wrap_2() throws Exception { dataSource.getProxyFilters().clear(); - + Connection conn = dataSource.getConnection(); CallableStatement stmt = conn.prepareCall("select 1"); - + Assert.assertNotNull(stmt.unwrap(PreparedStatement.class)); Assert.assertEquals(MockCallableStatement.class, stmt.unwrap(CallableStatement.class).getClass()); - + stmt.close(); conn.close(); } diff --git a/src/test/java/com/alibaba/druid/bvt/pool/DruidPooledStatementTest.java b/src/test/java/com/alibaba/druid/bvt/pool/DruidPooledStatementTest.java new file mode 100644 index 0000000000..8ec964d685 --- /dev/null +++ b/src/test/java/com/alibaba/druid/bvt/pool/DruidPooledStatementTest.java @@ -0,0 +1,1187 @@ +package com.alibaba.druid.bvt.pool; + +import java.sql.Connection; +import java.sql.SQLException; +import java.sql.SQLFeatureNotSupportedException; +import java.sql.SQLWarning; +import java.sql.Statement; + +import junit.framework.TestCase; + +import org.junit.Assert; + +import com.alibaba.druid.filter.FilterAdapter; +import com.alibaba.druid.filter.FilterChain; +import com.alibaba.druid.pool.DruidDataSource; +import com.alibaba.druid.pool.DruidPooledStatement; +import com.alibaba.druid.proxy.jdbc.ResultSetProxy; +import com.alibaba.druid.proxy.jdbc.StatementProxy; + +public class DruidPooledStatementTest extends TestCase { + + private DruidDataSource dataSource; + + protected void setUp() throws Exception { + dataSource = new DruidDataSource(); + dataSource.setUrl("jdbc:mock:xxx"); + dataSource.setTestOnBorrow(false); + dataSource.getProxyFilters().add(new ErrorFilter()); + } + + protected void tearDown() throws Exception { + dataSource.close(); + } + + public void test_executeQuery_error() throws Exception { + Connection conn = dataSource.getConnection(); + + Statement stmt = conn.createStatement(); + + Assert.assertEquals(0, dataSource.getPoolingCount()); + Assert.assertEquals(1, dataSource.getActiveCount()); + Assert.assertEquals(0, dataSource.getErrorCount()); + + Exception error = null; + try { + stmt.executeQuery("select 1"); + } catch (Exception e) { + error = e; + } + Assert.assertNotNull(error); + + Assert.assertEquals(1, dataSource.getErrorCount()); + + stmt.close(); + conn.close(); + + Assert.assertEquals(1, dataSource.getPoolingCount()); + Assert.assertEquals(0, dataSource.getActiveCount()); + } + + public void test_executeUpdate_error() throws Exception { + Connection conn = dataSource.getConnection(); + + Statement stmt = conn.createStatement(); + + Assert.assertEquals(0, dataSource.getPoolingCount()); + Assert.assertEquals(1, dataSource.getActiveCount()); + Assert.assertEquals(0, dataSource.getErrorCount()); + + Exception error = null; + try { + stmt.executeUpdate("select 1"); + } catch (Exception e) { + error = e; + } + Assert.assertNotNull(error); + + Assert.assertEquals(1, dataSource.getErrorCount()); + + stmt.close(); + conn.close(); + + Assert.assertEquals(1, dataSource.getPoolingCount()); + Assert.assertEquals(0, dataSource.getActiveCount()); + } + + public void test_executeUpdate_error_1() throws Exception { + Connection conn = dataSource.getConnection(); + + Statement stmt = conn.createStatement(); + + Assert.assertEquals(0, dataSource.getPoolingCount()); + Assert.assertEquals(1, dataSource.getActiveCount()); + Assert.assertEquals(0, dataSource.getErrorCount()); + + Exception error = null; + try { + stmt.executeUpdate("select 1", Statement.RETURN_GENERATED_KEYS); + } catch (Exception e) { + error = e; + } + Assert.assertNotNull(error); + + Assert.assertEquals(1, dataSource.getErrorCount()); + + stmt.close(); + conn.close(); + + Assert.assertEquals(1, dataSource.getPoolingCount()); + Assert.assertEquals(0, dataSource.getActiveCount()); + } + + public void test_executeUpdate_error_2() throws Exception { + Connection conn = dataSource.getConnection(); + + Statement stmt = conn.createStatement(); + + Assert.assertEquals(0, dataSource.getPoolingCount()); + Assert.assertEquals(1, dataSource.getActiveCount()); + Assert.assertEquals(0, dataSource.getErrorCount()); + + Exception error = null; + try { + stmt.executeUpdate("select 1", new int[0]); + } catch (Exception e) { + error = e; + } + Assert.assertNotNull(error); + + Assert.assertEquals(1, dataSource.getErrorCount()); + + stmt.close(); + conn.close(); + + Assert.assertEquals(1, dataSource.getPoolingCount()); + Assert.assertEquals(0, dataSource.getActiveCount()); + } + + public void test_executeUpdate_error_3() throws Exception { + Connection conn = dataSource.getConnection(); + + Statement stmt = conn.createStatement(); + + Assert.assertEquals(0, dataSource.getPoolingCount()); + Assert.assertEquals(1, dataSource.getActiveCount()); + Assert.assertEquals(0, dataSource.getErrorCount()); + + Exception error = null; + try { + stmt.executeUpdate("select 1", new String[0]); + } catch (Exception e) { + error = e; + } + Assert.assertNotNull(error); + + Assert.assertEquals(1, dataSource.getErrorCount()); + + stmt.close(); + conn.close(); + + Assert.assertEquals(1, dataSource.getPoolingCount()); + Assert.assertEquals(0, dataSource.getActiveCount()); + } + + public void test_execute_error() throws Exception { + Connection conn = dataSource.getConnection(); + + Statement stmt = conn.createStatement(); + + Assert.assertEquals(0, dataSource.getPoolingCount()); + Assert.assertEquals(1, dataSource.getActiveCount()); + Assert.assertEquals(0, dataSource.getErrorCount()); + + Exception error = null; + try { + stmt.execute("select 1"); + } catch (Exception e) { + error = e; + } + Assert.assertNotNull(error); + + Assert.assertEquals(1, dataSource.getErrorCount()); + + stmt.close(); + conn.close(); + + Assert.assertEquals(1, dataSource.getPoolingCount()); + Assert.assertEquals(0, dataSource.getActiveCount()); + } + + public void test_execute_error_1() throws Exception { + Connection conn = dataSource.getConnection(); + + Statement stmt = conn.createStatement(); + + Assert.assertEquals(0, dataSource.getPoolingCount()); + Assert.assertEquals(1, dataSource.getActiveCount()); + Assert.assertEquals(0, dataSource.getErrorCount()); + + Exception error = null; + try { + stmt.execute("select 1", Statement.RETURN_GENERATED_KEYS); + } catch (Exception e) { + error = e; + } + Assert.assertNotNull(error); + + Assert.assertEquals(1, dataSource.getErrorCount()); + + stmt.close(); + conn.close(); + + Assert.assertEquals(1, dataSource.getPoolingCount()); + Assert.assertEquals(0, dataSource.getActiveCount()); + } + + public void test_execute_error_2() throws Exception { + Connection conn = dataSource.getConnection(); + + Statement stmt = conn.createStatement(); + + Assert.assertEquals(0, dataSource.getPoolingCount()); + Assert.assertEquals(1, dataSource.getActiveCount()); + Assert.assertEquals(0, dataSource.getErrorCount()); + + Exception error = null; + try { + stmt.execute("select 1", new int[0]); + } catch (Exception e) { + error = e; + } + Assert.assertNotNull(error); + + Assert.assertEquals(1, dataSource.getErrorCount()); + + stmt.close(); + conn.close(); + + Assert.assertEquals(1, dataSource.getPoolingCount()); + Assert.assertEquals(0, dataSource.getActiveCount()); + } + + public void test_execute_error_3() throws Exception { + Connection conn = dataSource.getConnection(); + + Statement stmt = conn.createStatement(); + + Assert.assertEquals(0, dataSource.getPoolingCount()); + Assert.assertEquals(1, dataSource.getActiveCount()); + Assert.assertEquals(0, dataSource.getErrorCount()); + + Exception error = null; + try { + stmt.execute("select 1", new String[0]); + } catch (Exception e) { + error = e; + } + Assert.assertNotNull(error); + + Assert.assertEquals(1, dataSource.getErrorCount()); + + stmt.close(); + conn.close(); + + Assert.assertEquals(1, dataSource.getPoolingCount()); + Assert.assertEquals(0, dataSource.getActiveCount()); + } + + public void test_getMaxFieldSize_error() throws Exception { + Connection conn = dataSource.getConnection(); + + Statement stmt = conn.createStatement(); + + Assert.assertEquals(0, dataSource.getPoolingCount()); + Assert.assertEquals(1, dataSource.getActiveCount()); + Assert.assertEquals(0, dataSource.getErrorCount()); + + Exception error = null; + try { + stmt.getMaxFieldSize(); + } catch (Exception e) { + error = e; + } + Assert.assertNotNull(error); + + Assert.assertEquals(1, dataSource.getErrorCount()); + + stmt.close(); + conn.close(); + + Assert.assertEquals(1, dataSource.getPoolingCount()); + Assert.assertEquals(0, dataSource.getActiveCount()); + } + + public void test_setMaxFieldSize_error() throws Exception { + Connection conn = dataSource.getConnection(); + + Statement stmt = conn.createStatement(); + + Assert.assertEquals(0, dataSource.getPoolingCount()); + Assert.assertEquals(1, dataSource.getActiveCount()); + Assert.assertEquals(0, dataSource.getErrorCount()); + + Exception error = null; + try { + stmt.setMaxFieldSize(0); + } catch (Exception e) { + error = e; + } + Assert.assertNotNull(error); + + Assert.assertEquals(1, dataSource.getErrorCount()); + + stmt.close(); + conn.close(); + + Assert.assertEquals(1, dataSource.getPoolingCount()); + Assert.assertEquals(0, dataSource.getActiveCount()); + } + + public void test_getMaxRows_error() throws Exception { + Connection conn = dataSource.getConnection(); + + Statement stmt = conn.createStatement(); + + Assert.assertEquals(0, dataSource.getPoolingCount()); + Assert.assertEquals(1, dataSource.getActiveCount()); + Assert.assertEquals(0, dataSource.getErrorCount()); + + Exception error = null; + try { + stmt.getMaxRows(); + } catch (Exception e) { + error = e; + } + Assert.assertNotNull(error); + + Assert.assertEquals(1, dataSource.getErrorCount()); + + stmt.close(); + conn.close(); + + Assert.assertEquals(1, dataSource.getPoolingCount()); + Assert.assertEquals(0, dataSource.getActiveCount()); + } + + public void test_setMaxRows_error() throws Exception { + Connection conn = dataSource.getConnection(); + + Statement stmt = conn.createStatement(); + + Assert.assertEquals(0, dataSource.getPoolingCount()); + Assert.assertEquals(1, dataSource.getActiveCount()); + Assert.assertEquals(0, dataSource.getErrorCount()); + + Exception error = null; + try { + stmt.setMaxRows(0); + } catch (Exception e) { + error = e; + } + Assert.assertNotNull(error); + + Assert.assertEquals(1, dataSource.getErrorCount()); + + stmt.close(); + conn.close(); + + Assert.assertEquals(1, dataSource.getPoolingCount()); + Assert.assertEquals(0, dataSource.getActiveCount()); + } + + public void test_setEscapeProcessing_error() throws Exception { + Connection conn = dataSource.getConnection(); + + Statement stmt = conn.createStatement(); + + Assert.assertEquals(0, dataSource.getPoolingCount()); + Assert.assertEquals(1, dataSource.getActiveCount()); + Assert.assertEquals(0, dataSource.getErrorCount()); + + Exception error = null; + try { + stmt.setEscapeProcessing(true); + } catch (Exception e) { + error = e; + } + Assert.assertNotNull(error); + + Assert.assertEquals(1, dataSource.getErrorCount()); + + stmt.close(); + conn.close(); + + Assert.assertEquals(1, dataSource.getPoolingCount()); + Assert.assertEquals(0, dataSource.getActiveCount()); + } + + public void test_getQueryTimeout_error() throws Exception { + Connection conn = dataSource.getConnection(); + + Statement stmt = conn.createStatement(); + + Assert.assertEquals(0, dataSource.getPoolingCount()); + Assert.assertEquals(1, dataSource.getActiveCount()); + Assert.assertEquals(0, dataSource.getErrorCount()); + + Exception error = null; + try { + stmt.getQueryTimeout(); + } catch (Exception e) { + error = e; + } + Assert.assertNotNull(error); + + Assert.assertEquals(1, dataSource.getErrorCount()); + + stmt.close(); + conn.close(); + + Assert.assertEquals(1, dataSource.getPoolingCount()); + Assert.assertEquals(0, dataSource.getActiveCount()); + } + + public void test_setQueryTimeout_error() throws Exception { + Connection conn = dataSource.getConnection(); + + Statement stmt = conn.createStatement(); + + Assert.assertEquals(0, dataSource.getPoolingCount()); + Assert.assertEquals(1, dataSource.getActiveCount()); + Assert.assertEquals(0, dataSource.getErrorCount()); + + Exception error = null; + try { + stmt.setQueryTimeout(-1); + } catch (Exception e) { + error = e; + } + Assert.assertNotNull(error); + + Assert.assertEquals(1, dataSource.getErrorCount()); + + stmt.close(); + conn.close(); + + Assert.assertEquals(1, dataSource.getPoolingCount()); + Assert.assertEquals(0, dataSource.getActiveCount()); + } + + public void test_cancel_error() throws Exception { + Connection conn = dataSource.getConnection(); + + Statement stmt = conn.createStatement(); + + Assert.assertEquals(0, dataSource.getPoolingCount()); + Assert.assertEquals(1, dataSource.getActiveCount()); + Assert.assertEquals(0, dataSource.getErrorCount()); + + Exception error = null; + try { + stmt.cancel(); + } catch (Exception e) { + error = e; + } + Assert.assertNotNull(error); + + Assert.assertEquals(1, dataSource.getErrorCount()); + + stmt.close(); + conn.close(); + + Assert.assertEquals(1, dataSource.getPoolingCount()); + Assert.assertEquals(0, dataSource.getActiveCount()); + } + + public void test_getWarnings_error() throws Exception { + Connection conn = dataSource.getConnection(); + + Statement stmt = conn.createStatement(); + + Assert.assertEquals(0, dataSource.getPoolingCount()); + Assert.assertEquals(1, dataSource.getActiveCount()); + Assert.assertEquals(0, dataSource.getErrorCount()); + + Exception error = null; + try { + stmt.getWarnings(); + } catch (Exception e) { + error = e; + } + Assert.assertNotNull(error); + + Assert.assertEquals(1, dataSource.getErrorCount()); + + stmt.close(); + conn.close(); + + Assert.assertEquals(1, dataSource.getPoolingCount()); + Assert.assertEquals(0, dataSource.getActiveCount()); + } + + public void test_clearWarnings_error() throws Exception { + Connection conn = dataSource.getConnection(); + + Statement stmt = conn.createStatement(); + + Assert.assertEquals(0, dataSource.getPoolingCount()); + Assert.assertEquals(1, dataSource.getActiveCount()); + Assert.assertEquals(0, dataSource.getErrorCount()); + + Exception error = null; + try { + stmt.clearWarnings(); + } catch (Exception e) { + error = e; + } + Assert.assertNotNull(error); + + Assert.assertEquals(1, dataSource.getErrorCount()); + + stmt.close(); + conn.close(); + + Assert.assertEquals(1, dataSource.getPoolingCount()); + Assert.assertEquals(0, dataSource.getActiveCount()); + } + + public void test_setCursorName_error() throws Exception { + Connection conn = dataSource.getConnection(); + + Statement stmt = conn.createStatement(); + + Assert.assertEquals(0, dataSource.getPoolingCount()); + Assert.assertEquals(1, dataSource.getActiveCount()); + Assert.assertEquals(0, dataSource.getErrorCount()); + + Exception error = null; + try { + stmt.setCursorName(null); + } catch (Exception e) { + error = e; + } + Assert.assertNotNull(error); + + Assert.assertEquals(1, dataSource.getErrorCount()); + + stmt.close(); + conn.close(); + + Assert.assertEquals(1, dataSource.getPoolingCount()); + Assert.assertEquals(0, dataSource.getActiveCount()); + } + + public void test_getResultSet_error() throws Exception { + Connection conn = dataSource.getConnection(); + + Statement stmt = conn.createStatement(); + + Assert.assertEquals(0, dataSource.getPoolingCount()); + Assert.assertEquals(1, dataSource.getActiveCount()); + Assert.assertEquals(0, dataSource.getErrorCount()); + + Exception error = null; + try { + stmt.getResultSet(); + } catch (Exception e) { + error = e; + } + Assert.assertNotNull(error); + + Assert.assertEquals(1, dataSource.getErrorCount()); + + stmt.close(); + conn.close(); + + Assert.assertEquals(1, dataSource.getPoolingCount()); + Assert.assertEquals(0, dataSource.getActiveCount()); + Assert.assertEquals(0, dataSource.getDataSourceStat().getResultSetStat().getOpenCount()); + } + + public void test_getUpdateCount_error() throws Exception { + Connection conn = dataSource.getConnection(); + + Statement stmt = conn.createStatement(); + + Assert.assertEquals(0, dataSource.getPoolingCount()); + Assert.assertEquals(1, dataSource.getActiveCount()); + Assert.assertEquals(0, dataSource.getErrorCount()); + + Exception error = null; + try { + stmt.getUpdateCount(); + } catch (Exception e) { + error = e; + } + Assert.assertNotNull(error); + + Assert.assertEquals(1, dataSource.getErrorCount()); + + stmt.close(); + conn.close(); + + Assert.assertEquals(1, dataSource.getPoolingCount()); + Assert.assertEquals(0, dataSource.getActiveCount()); + } + + public void test_getMoreResults_error() throws Exception { + Connection conn = dataSource.getConnection(); + + Statement stmt = conn.createStatement(); + + Assert.assertEquals(0, dataSource.getPoolingCount()); + Assert.assertEquals(1, dataSource.getActiveCount()); + Assert.assertEquals(0, dataSource.getErrorCount()); + + Exception error = null; + try { + stmt.getMoreResults(); + } catch (Exception e) { + error = e; + } + Assert.assertNotNull(error); + + Assert.assertEquals(1, dataSource.getErrorCount()); + + stmt.close(); + conn.close(); + + Assert.assertEquals(1, dataSource.getPoolingCount()); + Assert.assertEquals(0, dataSource.getActiveCount()); + } + + public void test_setFetchDirection_error() throws Exception { + Connection conn = dataSource.getConnection(); + + Statement stmt = conn.createStatement(); + + Assert.assertEquals(0, dataSource.getPoolingCount()); + Assert.assertEquals(1, dataSource.getActiveCount()); + Assert.assertEquals(0, dataSource.getErrorCount()); + + Exception error = null; + try { + stmt.setFetchDirection(0); + } catch (Exception e) { + error = e; + } + Assert.assertNotNull(error); + + Assert.assertEquals(1, dataSource.getErrorCount()); + + stmt.close(); + conn.close(); + + Assert.assertEquals(1, dataSource.getPoolingCount()); + Assert.assertEquals(0, dataSource.getActiveCount()); + } + + public void test_getFetchDirection_error() throws Exception { + Connection conn = dataSource.getConnection(); + + Statement stmt = conn.createStatement(); + + Assert.assertEquals(0, dataSource.getPoolingCount()); + Assert.assertEquals(1, dataSource.getActiveCount()); + Assert.assertEquals(0, dataSource.getErrorCount()); + + Exception error = null; + try { + stmt.getFetchDirection(); + } catch (Exception e) { + error = e; + } + Assert.assertNotNull(error); + + Assert.assertEquals(1, dataSource.getErrorCount()); + + stmt.close(); + conn.close(); + + Assert.assertEquals(1, dataSource.getPoolingCount()); + Assert.assertEquals(0, dataSource.getActiveCount()); + } + + public void test_setFetchSize_error() throws Exception { + Connection conn = dataSource.getConnection(); + + Statement stmt = conn.createStatement(); + + Assert.assertEquals(0, dataSource.getPoolingCount()); + Assert.assertEquals(1, dataSource.getActiveCount()); + Assert.assertEquals(0, dataSource.getErrorCount()); + + Exception error = null; + try { + stmt.setFetchSize(0); + } catch (Exception e) { + error = e; + } + Assert.assertNotNull(error); + + Assert.assertEquals(1, dataSource.getErrorCount()); + + stmt.close(); + conn.close(); + + Assert.assertEquals(1, dataSource.getPoolingCount()); + Assert.assertEquals(0, dataSource.getActiveCount()); + } + + public void test_getFetchSize_error() throws Exception { + Connection conn = dataSource.getConnection(); + + Statement stmt = conn.createStatement(); + + Assert.assertEquals(0, dataSource.getPoolingCount()); + Assert.assertEquals(1, dataSource.getActiveCount()); + Assert.assertEquals(0, dataSource.getErrorCount()); + + Exception error = null; + try { + stmt.getFetchSize(); + } catch (Exception e) { + error = e; + } + Assert.assertNotNull(error); + + Assert.assertEquals(1, dataSource.getErrorCount()); + + stmt.close(); + conn.close(); + + Assert.assertEquals(1, dataSource.getPoolingCount()); + Assert.assertEquals(0, dataSource.getActiveCount()); + } + + public void test_getResultSetConcurrency_error() throws Exception { + Connection conn = dataSource.getConnection(); + + Statement stmt = conn.createStatement(); + + Assert.assertEquals(0, dataSource.getPoolingCount()); + Assert.assertEquals(1, dataSource.getActiveCount()); + Assert.assertEquals(0, dataSource.getErrorCount()); + + Exception error = null; + try { + stmt.getResultSetConcurrency(); + } catch (Exception e) { + error = e; + } + Assert.assertNotNull(error); + + Assert.assertEquals(1, dataSource.getErrorCount()); + + stmt.close(); + conn.close(); + + Assert.assertEquals(1, dataSource.getPoolingCount()); + Assert.assertEquals(0, dataSource.getActiveCount()); + } + + public void test_getResultSetType_error() throws Exception { + Connection conn = dataSource.getConnection(); + + Statement stmt = conn.createStatement(); + + Assert.assertEquals(0, dataSource.getPoolingCount()); + Assert.assertEquals(1, dataSource.getActiveCount()); + Assert.assertEquals(0, dataSource.getErrorCount()); + + Exception error = null; + try { + stmt.getResultSetType(); + } catch (Exception e) { + error = e; + } + Assert.assertNotNull(error); + + Assert.assertEquals(1, dataSource.getErrorCount()); + + stmt.close(); + conn.close(); + + Assert.assertEquals(1, dataSource.getPoolingCount()); + Assert.assertEquals(0, dataSource.getActiveCount()); + } + + public void test_addBatch_error() throws Exception { + Connection conn = dataSource.getConnection(); + + Statement stmt = conn.createStatement(); + + Assert.assertEquals(0, dataSource.getPoolingCount()); + Assert.assertEquals(1, dataSource.getActiveCount()); + Assert.assertEquals(0, dataSource.getErrorCount()); + + Exception error = null; + try { + stmt.addBatch("select 1"); + } catch (Exception e) { + error = e; + } + Assert.assertNotNull(error); + + Assert.assertEquals(1, dataSource.getErrorCount()); + + stmt.close(); + conn.close(); + + Assert.assertEquals(1, dataSource.getPoolingCount()); + Assert.assertEquals(0, dataSource.getActiveCount()); + } + + public void test_clearBatch_error() throws Exception { + Connection conn = dataSource.getConnection(); + + Statement stmt = conn.createStatement(); + + Assert.assertEquals(0, dataSource.getPoolingCount()); + Assert.assertEquals(1, dataSource.getActiveCount()); + Assert.assertEquals(0, dataSource.getErrorCount()); + + Exception error = null; + try { + stmt.clearBatch(); + } catch (Exception e) { + error = e; + } + Assert.assertNotNull(error); + + Assert.assertEquals(1, dataSource.getErrorCount()); + + stmt.close(); + conn.close(); + + Assert.assertEquals(1, dataSource.getPoolingCount()); + Assert.assertEquals(0, dataSource.getActiveCount()); + } + + public void test_executeBatch_error() throws Exception { + Connection conn = dataSource.getConnection(); + + Statement stmt = conn.createStatement(); + + Assert.assertEquals(0, dataSource.getPoolingCount()); + Assert.assertEquals(1, dataSource.getActiveCount()); + Assert.assertEquals(0, dataSource.getErrorCount()); + + Exception error = null; + try { + stmt.executeBatch(); + } catch (Exception e) { + error = e; + } + Assert.assertNotNull(error); + + Assert.assertEquals(1, dataSource.getErrorCount()); + + stmt.close(); + conn.close(); + + Assert.assertEquals(1, dataSource.getPoolingCount()); + Assert.assertEquals(0, dataSource.getActiveCount()); + } + + public void test_getMoreResults_error_1() throws Exception { + Connection conn = dataSource.getConnection(); + + Statement stmt = conn.createStatement(); + + Assert.assertEquals(0, dataSource.getPoolingCount()); + Assert.assertEquals(1, dataSource.getActiveCount()); + Assert.assertEquals(0, dataSource.getErrorCount()); + + Exception error = null; + try { + stmt.getMoreResults(0); + } catch (Exception e) { + error = e; + } + Assert.assertNotNull(error); + + Assert.assertEquals(1, dataSource.getErrorCount()); + + stmt.close(); + conn.close(); + + Assert.assertEquals(1, dataSource.getPoolingCount()); + Assert.assertEquals(0, dataSource.getActiveCount()); + } + + public void test_getGeneratedKeys_error() throws Exception { + Connection conn = dataSource.getConnection(); + + Statement stmt = conn.createStatement(); + + Assert.assertEquals(0, dataSource.getPoolingCount()); + Assert.assertEquals(1, dataSource.getActiveCount()); + Assert.assertEquals(0, dataSource.getErrorCount()); + + Exception error = null; + try { + stmt.getGeneratedKeys(); + } catch (Exception e) { + error = e; + } + Assert.assertNotNull(error); + + Assert.assertEquals(1, dataSource.getErrorCount()); + + stmt.close(); + conn.close(); + + Assert.assertEquals(1, dataSource.getPoolingCount()); + Assert.assertEquals(0, dataSource.getActiveCount()); + } + + public void test_getResultSetHoldability_error() throws Exception { + Connection conn = dataSource.getConnection(); + + Statement stmt = conn.createStatement(); + + Assert.assertEquals(0, dataSource.getPoolingCount()); + Assert.assertEquals(1, dataSource.getActiveCount()); + Assert.assertEquals(0, dataSource.getErrorCount()); + + Exception error = null; + try { + stmt.getResultSetHoldability(); + } catch (Exception e) { + error = e; + } + Assert.assertNotNull(error); + + Assert.assertEquals(1, dataSource.getErrorCount()); + + stmt.close(); + conn.close(); + + Assert.assertEquals(1, dataSource.getPoolingCount()); + Assert.assertEquals(0, dataSource.getActiveCount()); + } + + public void test_closeOnCompletion_error() throws Exception { + Connection conn = dataSource.getConnection(); + + DruidPooledStatement stmt = (DruidPooledStatement) conn.createStatement(); + + Assert.assertEquals(0, dataSource.getPoolingCount()); + Assert.assertEquals(1, dataSource.getActiveCount()); + Assert.assertEquals(0, dataSource.getErrorCount()); + + Exception error = null; + try { + stmt.closeOnCompletion(); + } catch (SQLFeatureNotSupportedException e) { + error = e; + } + Assert.assertNotNull(error); + + Assert.assertEquals(0, dataSource.getErrorCount()); + + stmt.close(); + conn.close(); + + Assert.assertEquals(1, dataSource.getPoolingCount()); + Assert.assertEquals(0, dataSource.getActiveCount()); + } + + public void test_isCloseOnCompletion_error() throws Exception { + Connection conn = dataSource.getConnection(); + + DruidPooledStatement stmt = (DruidPooledStatement) conn.createStatement(); + + Assert.assertEquals(0, dataSource.getPoolingCount()); + Assert.assertEquals(1, dataSource.getActiveCount()); + Assert.assertEquals(0, dataSource.getErrorCount()); + + Exception error = null; + try { + stmt.isCloseOnCompletion(); + } catch (SQLFeatureNotSupportedException e) { + error = e; + } + Assert.assertNotNull(error); + + Assert.assertEquals(0, dataSource.getErrorCount()); + + stmt.close(); + conn.close(); + + Assert.assertEquals(1, dataSource.getPoolingCount()); + Assert.assertEquals(0, dataSource.getActiveCount()); + } + + private final class ErrorFilter extends FilterAdapter { + + @Override + public ResultSetProxy statement_executeQuery(FilterChain chain, StatementProxy statement, String sql) + throws SQLException { + throw new SQLException(); + } + + @Override + public int statement_executeUpdate(FilterChain chain, StatementProxy statement, String sql) throws SQLException { + throw new SQLException(); + } + + @Override + public int statement_executeUpdate(FilterChain chain, StatementProxy statement, String sql, + int autoGeneratedKeys) throws SQLException { + throw new SQLException(); + } + + @Override + public int statement_executeUpdate(FilterChain chain, StatementProxy statement, String sql, int columnIndexes[]) + throws SQLException { + throw new SQLException(); + } + + @Override + public int statement_executeUpdate(FilterChain chain, StatementProxy statement, String sql, + String columnNames[]) throws SQLException { + throw new SQLException(); + } + + @Override + public boolean statement_execute(FilterChain chain, StatementProxy statement, String sql) throws SQLException { + throw new SQLException(); + } + + @Override + public boolean statement_execute(FilterChain chain, StatementProxy statement, String sql, int autoGeneratedKeys) + throws SQLException { + throw new SQLException(); + } + + @Override + public boolean statement_execute(FilterChain chain, StatementProxy statement, String sql, int columnIndexes[]) + throws SQLException { + throw new SQLException(); + } + + @Override + public boolean statement_execute(FilterChain chain, StatementProxy statement, String sql, String columnNames[]) + throws SQLException { + throw new SQLException(); + } + + @Override + public int statement_getMaxFieldSize(FilterChain chain, StatementProxy statement) throws SQLException { + throw new SQLException(); + } + + @Override + public int statement_getMaxRows(FilterChain chain, StatementProxy statement) throws SQLException { + throw new SQLException(); + } + + @Override + public void statement_setMaxFieldSize(FilterChain chain, StatementProxy statement, int max) throws SQLException { + throw new SQLException(); + } + + @Override + public void statement_setMaxRows(FilterChain chain, StatementProxy statement, int max) throws SQLException { + throw new SQLException(); + } + + @Override + public void statement_setEscapeProcessing(FilterChain chain, StatementProxy statement, boolean enable) + throws SQLException { + throw new SQLException(); + } + + @Override + public int statement_getQueryTimeout(FilterChain chain, StatementProxy statement) throws SQLException { + throw new SQLException(); + } + + @Override + public void statement_setQueryTimeout(FilterChain chain, StatementProxy statement, int seconds) + throws SQLException { + throw new SQLException(); + } + + @Override + public void statement_cancel(FilterChain chain, StatementProxy statement) throws SQLException { + throw new SQLException(); + } + + @Override + public SQLWarning statement_getWarnings(FilterChain chain, StatementProxy statement) throws SQLException { + throw new SQLException(); + } + + @Override + public void statement_clearWarnings(FilterChain chain, StatementProxy statement) throws SQLException { + throw new SQLException(); + } + + @Override + public void statement_setCursorName(FilterChain chain, StatementProxy statement, String name) + throws SQLException { + throw new SQLException(); + } + + @Override + public ResultSetProxy statement_getResultSet(FilterChain chain, StatementProxy statement) throws SQLException { + throw new SQLException(); + } + + @Override + public int statement_getUpdateCount(FilterChain chain, StatementProxy statement) throws SQLException { + throw new SQLException(); + } + + @Override + public boolean statement_getMoreResults(FilterChain chain, StatementProxy statement) throws SQLException { + throw new SQLException(); + } + + @Override + public void statement_setFetchDirection(FilterChain chain, StatementProxy statement, int value) + throws SQLException { + throw new SQLException(); + } + + @Override + public int statement_getFetchDirection(FilterChain chain, StatementProxy statement) throws SQLException { + throw new SQLException(); + } + + @Override + public int statement_getFetchSize(FilterChain chain, StatementProxy statement) throws SQLException { + throw new SQLException(); + } + + @Override + public void statement_setFetchSize(FilterChain chain, StatementProxy statement, int value) throws SQLException { + throw new SQLException(); + } + + @Override + public int statement_getResultSetConcurrency(FilterChain chain, StatementProxy statement) throws SQLException { + throw new SQLException(); + } + + @Override + public int statement_getResultSetType(FilterChain chain, StatementProxy statement) throws SQLException { + throw new SQLException(); + } + + @Override + public void statement_addBatch(FilterChain chain, StatementProxy statement, String sql) throws SQLException { + throw new SQLException(); + } + + @Override + public void statement_clearBatch(FilterChain chain, StatementProxy statement) throws SQLException { + throw new SQLException(); + } + + @Override + public int[] statement_executeBatch(FilterChain chain, StatementProxy statement) throws SQLException { + throw new SQLException(); + } + + @Override + public boolean statement_getMoreResults(FilterChain chain, StatementProxy statement, int current) + throws SQLException { + throw new SQLException(); + } + + @Override + public ResultSetProxy statement_getGeneratedKeys(FilterChain chain, StatementProxy statement) throws SQLException { + throw new SQLException(); + } + + @Override + public int statement_getResultSetHoldability(FilterChain chain, StatementProxy statement) throws SQLException { + throw new SQLException(); + } + } +} diff --git a/src/test/java/com/alibaba/druid/bvt/pool/TestAbondon.java b/src/test/java/com/alibaba/druid/bvt/pool/TestAbondon.java index 7cfe291adc..74e6c0fb4c 100644 --- a/src/test/java/com/alibaba/druid/bvt/pool/TestAbondon.java +++ b/src/test/java/com/alibaba/druid/bvt/pool/TestAbondon.java @@ -47,7 +47,14 @@ public class TestAbondon extends TestCase { public void test_0() throws Exception { DruidPooledConnection conn = dataSource.getConnection(); Assert.assertEquals(false, conn.isClosed()); - Thread.sleep(200); + Thread.sleep(10); + + for (int i = 0; i < 100; ++i) { + if (conn.isAbandonded()) { + break; + } + Thread.sleep(10); + } Assert.assertEquals(true, conn.isAbandonded()); } }