1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 package org.apache.commons.monitoring.jdbc;
18
19 import org.apache.commons.monitoring.Role;
20 import org.apache.commons.monitoring.counters.Counter;
21 import org.apache.commons.monitoring.repositories.Repository;
22
23 import java.sql.Connection;
24 import java.sql.Driver;
25 import java.sql.DriverManager;
26 import java.sql.DriverPropertyInfo;
27 import java.sql.SQLException;
28 import java.sql.SQLFeatureNotSupportedException;
29 import java.util.Properties;
30 import java.util.logging.Logger;
31
32 public class MonitoringDriver implements Driver {
33 static {
34 try {
35 DriverManager.registerDriver(new MonitoringDriver());
36 } catch (final SQLException e) {
37
38 }
39 }
40
41 private static final String PREFIX = "jdbc:monitoring:";
42 private static final String DRIVER_SUFFIX = "delegateDriver=";
43
44 public static void load() {
45 }
46
47 @Override
48 public Connection connect(final String url, final Properties info) throws SQLException {
49 if (!acceptsURL(url)) {
50 throw new SQLException("Driver " + MonitoringDriver.class.getName() + " doesn't accept " + url + ". Pattern is jdbc:monitoring:<xxx>:<yyy>?delegateDriver=<zzz>");
51 }
52
53 final int driverIndex = url.indexOf(DRIVER_SUFFIX);
54
55 String realUrl = "jdbc:" + url.substring(PREFIX.length(), driverIndex);
56 if (realUrl.endsWith("?") || realUrl.endsWith("&")) {
57 realUrl = realUrl.substring(0, realUrl.length() - 1);
58 }
59
60 final String realDriver = url.substring(driverIndex + DRIVER_SUFFIX.length());
61 try {
62 final Driver delegate = Driver.class.cast(Class.forName(realDriver).newInstance());
63 return MonitoredConnection.monitor(delegate.connect(realUrl, info), Repository.INSTANCE.getCounter(new Counter.Key(Role.JDBC, url)));
64 } catch (final Exception e) {
65 throw new SQLException(e);
66 }
67 }
68
69 @Override
70 public boolean acceptsURL(final String url) throws SQLException {
71 return url != null && url.startsWith(PREFIX) && url.contains(DRIVER_SUFFIX);
72 }
73
74 @Override
75 public DriverPropertyInfo[] getPropertyInfo(final String url, final Properties info) throws SQLException {
76 return new DriverPropertyInfo[0];
77 }
78
79 @Override
80 public int getMajorVersion() {
81 return 1;
82 }
83
84 @Override
85 public int getMinorVersion() {
86 return 0;
87 }
88
89 @Override
90 public boolean jdbcCompliant() {
91 return true;
92 }
93
94
95 public Logger getParentLogger() throws SQLFeatureNotSupportedException {
96 return Logger.getLogger("commons-monitoring.jdbc-driver");
97 }
98 }