📄 connectiontest.java
字号:
return; } Enumeration allInterfaces = NetworkInterface.getNetworkInterfaces(); SpawnedWorkerCounter counter = new SpawnedWorkerCounter(); List allChecks = new ArrayList(); while (allInterfaces.hasMoreElements()) { NetworkInterface intf = (NetworkInterface)allInterfaces.nextElement(); Enumeration allAddresses = intf.getInetAddresses(); allChecks.add(new LocalSocketAddressCheckThread(allAddresses, counter)); } counter.setWorkerCount(allChecks.size()); for (Iterator it = allChecks.iterator(); it.hasNext();) { LocalSocketAddressCheckThread t = (LocalSocketAddressCheckThread)it.next(); t.start(); } // Wait for tests to complete.... synchronized (counter) { while (counter.workerCount > 0 /* safety valve */) { counter.wait(); if (counter.workerCount == 0) { System.out.println("Done!"); break; } } } boolean didOneWork = false; boolean didOneFail = false; for (Iterator it = allChecks.iterator(); it.hasNext();) { LocalSocketAddressCheckThread t = (LocalSocketAddressCheckThread)it.next(); if (t.atLeastOneWorked) { didOneWork = true; break; } else { if (!didOneFail) { didOneFail = true; } } } assertTrue("At least one connection was made with the localSocketAddress set", didOneWork); NonRegisteringDriver d = new NonRegisteringDriver(); String hostname = d.host(d.parseURL(dbUrl, null)); if (!hostname.startsWith(":") && !hostname.startsWith("localhost")) { int indexOfColon = hostname.indexOf(":"); if (indexOfColon != -1) { hostname = hostname.substring(0, indexOfColon); } boolean isLocalIf = false; isLocalIf = (null != NetworkInterface.getByName(hostname)); if (!isLocalIf) { try { isLocalIf = (null != NetworkInterface.getByInetAddress(InetAddress.getByName(hostname))); } catch (Throwable t) { isLocalIf = false; } } if (!isLocalIf) { assertTrue("At least one connection didn't fail with localSocketAddress set", didOneFail); } } } class SpawnedWorkerCounter { private int workerCount = 0; synchronized void setWorkerCount(int i) { workerCount = i; } synchronized void decrementWorkerCount() { workerCount--; notify(); } } class LocalSocketAddressCheckThread extends Thread { boolean atLeastOneWorked = false; Enumeration allAddresses = null; SpawnedWorkerCounter counter = null; LocalSocketAddressCheckThread(Enumeration e, SpawnedWorkerCounter c) { allAddresses = e; counter = c; } public void run() { while (allAddresses.hasMoreElements()) { InetAddress addr = (InetAddress)allAddresses.nextElement(); try { Properties props = new Properties(); props.setProperty("localSocketAddress", addr.getHostAddress()); props.setProperty("connectTimeout", "2000"); getConnectionWithProps(props).close(); atLeastOneWorked = true; break; } catch (SQLException sqlEx) { // ignore, we're only seeing if one of these tests succeeds } } counter.decrementWorkerCount(); } } public void testUsageAdvisorTooLargeResultSet() throws Exception { Connection uaConn = null; PrintStream stderr = System.err; StringBuffer logBuf = new StringBuffer(); StandardLogger.bufferedLog = logBuf; try { Properties props = new Properties(); props.setProperty("useUsageAdvisor", "true"); props.setProperty("resultSetSizeThreshold", "4"); props.setProperty("logger", "StandardLogger"); uaConn = getConnectionWithProps(props); assertTrue("Result set threshold message not present", logBuf.toString().indexOf("larger than \"resultSetSizeThreshold\" of 4 rows") != -1); } finally { System.setErr(stderr); closeMemberJDBCResources(); if (uaConn != null) { uaConn.close(); } } } public void testUseLocalSessionStateRollback() throws Exception { if (!versionMeetsMinimum(5, 0, 0)) { return; } Properties props = new Properties(); props.setProperty("useLocalSessionState", "true"); props.setProperty("profileSQL", "true"); StringBuffer buf = new StringBuffer(); StandardLogger.bufferedLog = buf; createTable("testUseLocalSessionState", "(field1 varchar(32)) ENGINE=InnoDB"); Connection localStateConn = null; Statement localStateStmt = null; try { localStateConn = getConnectionWithProps(props); localStateStmt = localStateConn.createStatement(); localStateConn.setAutoCommit(false); localStateStmt.executeUpdate("INSERT INTO testUseLocalSessionState VALUES ('abc')"); localStateConn.rollback(); localStateConn.rollback(); localStateStmt.executeUpdate("INSERT INTO testUseLocalSessionState VALUES ('abc')"); localStateConn.commit(); localStateConn.commit(); localStateStmt.close(); } finally { StandardLogger.bufferedLog = null; if (localStateStmt != null) { localStateStmt.close(); } if (localStateConn != null) { localStateConn.close(); } } int rollbackCount = 0; int rollbackPos = 0; String searchIn = buf.toString(); while (rollbackPos != -1) { rollbackPos = searchIn.indexOf("rollback", rollbackPos); if (rollbackPos != -1) { rollbackPos += "rollback".length(); rollbackCount++; } } assertEquals(1, rollbackCount); int commitCount = 0; int commitPos = 0; // space is important here, we don't want to count "autocommit" while (commitPos != -1) { commitPos = searchIn.indexOf(" commit", commitPos); if (commitPos != -1) { commitPos += " commit".length(); commitCount++; } } assertEquals(1, commitCount); } /** * Checks if setting useCursorFetch to "true" automatically * enables server-side prepared statements. */ public void testCouplingOfCursorFetch() throws Exception { if (!versionMeetsMinimum(5, 0)) { return; } Connection fetchConn = null; try { Properties props = new Properties(); props.setProperty("useServerPrepStmts", "false"); // force the issue props.setProperty("useCursorFetch", "true"); fetchConn = getConnectionWithProps(props); String classname = "com.mysql.jdbc.ServerPreparedStatement"; if (Util.isJdbc4()) { classname = "com.mysql.jdbc.JDBC4ServerPreparedStatement"; } assertEquals(classname, fetchConn.prepareStatement("SELECT 1").getClass().getName()); } finally { if (fetchConn != null) { fetchConn.close(); } } } public void testInterfaceImplementation() throws Exception { testInterfaceImplementation(getConnectionWithProps((Properties)null)); MysqlConnectionPoolDataSource cpds = new MysqlConnectionPoolDataSource(); cpds.setUrl(dbUrl); testInterfaceImplementation(cpds.getPooledConnection().getConnection()); } private void testInterfaceImplementation(Connection connToCheck) throws Exception { Method[] dbmdMethods = java.sql.DatabaseMetaData.class.getMethods(); // can't do this statically, as we return different // implementations depending on JDBC version DatabaseMetaData dbmd = connToCheck.getMetaData(); checkInterfaceImplemented(dbmdMethods, dbmd.getClass(), dbmd); Statement stmtToCheck = connToCheck.createStatement(); checkInterfaceImplemented(java.sql.Statement.class.getMethods(), stmtToCheck.getClass(), stmtToCheck); PreparedStatement pStmtToCheck = connToCheck.prepareStatement("SELECT 1"); ParameterMetaData paramMd = pStmtToCheck.getParameterMetaData(); checkInterfaceImplemented(java.sql.PreparedStatement.class.getMethods(), pStmtToCheck.getClass(), pStmtToCheck); checkInterfaceImplemented(java.sql.ParameterMetaData.class.getMethods(), paramMd.getClass(), paramMd); pStmtToCheck = ((com.mysql.jdbc.Connection) connToCheck).serverPrepareStatement("SELECT 1"); checkInterfaceImplemented(java.sql.PreparedStatement.class.getMethods(), pStmtToCheck.getClass(), pStmtToCheck); ResultSet toCheckRs = connToCheck.createStatement().executeQuery("SELECT 1"); checkInterfaceImplemented(java.sql.ResultSet.class.getMethods(), toCheckRs.getClass(), toCheckRs); toCheckRs = connToCheck.createStatement().executeQuery("SELECT 1"); checkInterfaceImplemented(java.sql.ResultSetMetaData.class.getMethods(), toCheckRs.getMetaData().getClass(), toCheckRs.getMetaData()); if (versionMeetsMinimum(5, 0, 0)) { createProcedure("interfaceImpl", "(IN p1 INT)\nBEGIN\nSELECT 1;\nEND"); CallableStatement cstmt = connToCheck.prepareCall("{CALL interfaceImpl(?)}"); checkInterfaceImplemented(java.sql.CallableStatement.class.getMethods(), cstmt.getClass(), cstmt); } checkInterfaceImplemented(java.sql.Connection.class.getMethods(), connToCheck.getClass(), connToCheck); } private void checkInterfaceImplemented(Method[] interfaceMethods, Class implementingClass, Object invokeOn) throws NoSuchMethodException { for (int i = 0; i < interfaceMethods.length; i++) { Method toFind = interfaceMethods[i]; Method toMatch = implementingClass.getMethod(toFind.getName(), toFind.getParameterTypes()); assertNotNull(toFind.toString(), toMatch); Object[] args = new Object[toFind.getParameterTypes().length]; try { toMatch.invoke(invokeOn, args); } catch (IllegalArgumentException e) { } catch (IllegalAccessException e) { } catch (InvocationTargetException e) { } catch (java.lang.AbstractMethodError e) { throw e; } } } public void testNonVerifyServerCert() throws Exception { getConnectionWithProps("useSSL=true,verifyServerCertificate=false,requireSSL=true"); } public void testSelfDestruct() throws Exception { Connection selfDestructingConn = getConnectionWithProps("selfDestructOnPingMaxOperations=2"); boolean failed = false; for (int i = 0; i < 20; i++) { selfDestructingConn.createStatement().executeQuery("SELECT 1"); try { selfDestructingConn.createStatement().executeQuery("/* ping */ SELECT 1"); } catch (SQLException sqlEx) { String sqlState = sqlEx.getSQLState(); assertEquals("08S01", sqlState); failed = true; break; } } if (!failed) { fail("Connection should've self-destructed"); } failed = false; selfDestructingConn = getConnectionWithProps("selfDestructOnPingSecondsLifetime=1"); long begin = System.currentTimeMillis(); for (int i = 0; i < 20; i++) { selfDestructingConn.createStatement().executeQuery("SELECT SLEEP(1)"); try { selfDestructingConn.createStatement().executeQuery("/* ping */ SELECT 1"); } catch (SQLException sqlEx) { String sqlState = sqlEx.getSQLState(); assertEquals("08S01", sqlState); failed = true; break; } } if (!failed) { fail("Connection should've self-destructed"); } } public void testLifecyleInterceptor() throws Exception { createTable("testLifecycleInterceptor", "(field1 int) ENGINE=InnoDB"); Connection liConn = null; try { liConn = getConnectionWithProps("connectionLifecycleInterceptors=testsuite.simple.TestLifecycleInterceptor"); liConn.setAutoCommit(false); liConn.createStatement().executeUpdate("INSERT INTO testLifecycleInterceptor VALUES (1)"); liConn.commit(); assertEquals(TestLifecycleInterceptor.transactionsBegun, 1); assertEquals(TestLifecycleInterceptor.transactionsCompleted, 1); liConn.createStatement().executeQuery("SELECT * FROM testLifecycleInterceptor"); assertEquals(TestLifecycleInterceptor.transactionsBegun, 2); // implicit commit liConn.createStatement().executeUpdate("CREATE TABLE testLifecycleFoo (field1 int)"); assertEquals(TestLifecycleInterceptor.transactionsCompleted, 2); } finally { if (liConn != null) { liConn.createStatement().executeUpdate("DROP TABLE IF EXISTS testLifecycleFoo"); liConn.close(); } } }}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -