-
Notifications
You must be signed in to change notification settings - Fork 0
/
ProxyConnectionHandler.java
50 lines (42 loc) · 1.71 KB
/
ProxyConnectionHandler.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
package com.binghe.querycounter.query_counter;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.sql.Connection;
import java.sql.PreparedStatement;
public class ProxyConnectionHandler implements InvocationHandler {
private final Connection connection;
private final QueryCounter queryCounter;
public ProxyConnectionHandler(Connection connection, QueryCounter queryCounter) {
this.connection = connection;
this.queryCounter = queryCounter;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
if (queryCounter.isCountable()) {
if (method.getName().equals("prepareStatement") || method.getName().equals("createStatement")) {
return getConnectionWithCountQuery(method, args);
}
}
return method.invoke(connection, args);
}
private Object getConnectionWithCountQuery(Method method, Object[] args)
throws InvocationTargetException, IllegalAccessException {
PreparedStatement preparedStatement = (PreparedStatement) method.invoke(connection, args);
for (Object statement : args) {
if (isQueryStatement(statement)) {
System.out.println("## Query : " + (String) statement);
queryCounter.countOne();
break;
}
}
return preparedStatement;
}
private boolean isQueryStatement(Object statement) {
if (statement.getClass().isAssignableFrom(String.class)) {
String sql = (String) statement;
return sql.startsWith("select");
}
return false;
}
}