PageRenderTime 46ms CodeModel.GetById 10ms RepoModel.GetById 0ms app.codeStats 0ms

/EQEmuJSM/mysql-connector-java-5.1.13/src/testsuite/BaseTestCase.java

http://cubbers-eqemu-utils.googlecode.com/
Java | 975 lines | 648 code | 167 blank | 160 comment | 133 complexity | fac961e9defe8796b7efd932af4c5c64 MD5 | raw file
Possible License(s): GPL-2.0, LGPL-2.1, Apache-2.0
  1. /*
  2. Copyright 2002-2007 MySQL AB, 2008-2010 Sun Microsystems
  3. All rights reserved. Use is subject to license terms.
  4. The MySQL Connector/J is licensed under the terms of the GPL,
  5. like most MySQL Connectors. There are special exceptions to the
  6. terms and conditions of the GPL as it is applied to this software,
  7. see the FLOSS License Exception available on mysql.com.
  8. This program is free software; you can redistribute it and/or
  9. modify it under the terms of the GNU General Public License as
  10. published by the Free Software Foundation; version 2 of the
  11. License.
  12. This program is distributed in the hope that it will be useful,
  13. but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  15. GNU General Public License for more details.
  16. You should have received a copy of the GNU General Public License
  17. along with this program; if not, write to the Free Software
  18. Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
  19. 02110-1301 USA
  20. */
  21. package testsuite;
  22. import java.lang.reflect.Method;
  23. import java.io.BufferedOutputStream;
  24. import java.io.File;
  25. import java.io.FileOutputStream;
  26. import java.io.FilenameFilter;
  27. import java.io.IOException;
  28. import java.sql.Blob;
  29. import java.sql.Connection;
  30. import java.sql.DriverManager;
  31. import java.sql.PreparedStatement;
  32. import java.sql.ResultSet;
  33. import java.sql.SQLException;
  34. import java.sql.Statement;
  35. import java.util.ArrayList;
  36. import java.util.HashMap;
  37. import java.util.HashSet;
  38. import java.util.Iterator;
  39. import java.util.List;
  40. import java.util.Locale;
  41. import java.util.Map;
  42. import java.util.Properties;
  43. import java.util.Set;
  44. import junit.framework.TestCase;
  45. import com.mysql.jdbc.NonRegisteringDriver;
  46. import com.mysql.jdbc.ReplicationDriver;
  47. import com.mysql.jdbc.StringUtils;
  48. /**
  49. * Base class for all test cases. Creates connections, statements, etc. and
  50. * closes them.
  51. *
  52. * @author Mark Matthews
  53. * @version $Id: BaseTestCase.java 5440 2006-06-27 17:00:53 +0000 (Tue, 27 Jun
  54. * 2006) mmatthews $
  55. */
  56. public abstract class BaseTestCase extends TestCase {
  57. private final static String ADMIN_CONNECTION_PROPERTY_NAME = "com.mysql.jdbc.testsuite.admin-url";
  58. private final static String NO_MULTI_HOST_PROPERTY_NAME = "com.mysql.jdbc.testsuite.no-multi-hosts-tests";
  59. /**
  60. * JDBC URL, initialized from com.mysql.jdbc.testsuite.url system property,
  61. * or defaults to jdbc:mysql:///test
  62. */
  63. protected static String dbUrl = "jdbc:mysql:///test";
  64. /** Instance counter */
  65. private static int instanceCount = 1;
  66. /** Connection to server, initialized in setUp() Cleaned up in tearDown(). */
  67. protected Connection conn = null;
  68. /** list of schema objects to be dropped in tearDown */
  69. private List createdObjects;
  70. /** The driver to use */
  71. protected String dbClass = "com.mysql.jdbc.Driver";
  72. /** My instance number */
  73. private int myInstanceNumber = 0;
  74. /**
  75. * PreparedStatement to be used in tests, not initialized. Cleaned up in
  76. * tearDown().
  77. */
  78. protected PreparedStatement pstmt = null;
  79. /**
  80. * ResultSet to be used in tests, not initialized. Cleaned up in tearDown().
  81. */
  82. protected ResultSet rs = null;
  83. /**
  84. * Statement to be used in tests, initialized in setUp(). Cleaned up in
  85. * tearDown().
  86. */
  87. protected Statement stmt = null;
  88. private boolean runningOnJdk131 = false;
  89. /**
  90. * Creates a new BaseTestCase object.
  91. *
  92. * @param name
  93. * The name of the JUnit test case
  94. */
  95. public BaseTestCase(String name) {
  96. super(name);
  97. this.myInstanceNumber = instanceCount++;
  98. String newDbUrl = System.getProperty("com.mysql.jdbc.testsuite.url");
  99. if ((newDbUrl != null) && (newDbUrl.trim().length() != 0)) {
  100. dbUrl = newDbUrl;
  101. } else {
  102. String defaultDbUrl = System
  103. .getProperty("com.mysql.jdbc.testsuite.url.default");
  104. if ((defaultDbUrl != null) && (defaultDbUrl.trim().length() != 0)) {
  105. dbUrl = defaultDbUrl;
  106. }
  107. }
  108. String newDriver = System
  109. .getProperty("com.mysql.jdbc.testsuite.driver");
  110. if ((newDriver != null) && (newDriver.trim().length() != 0)) {
  111. this.dbClass = newDriver;
  112. }
  113. try {
  114. Blob.class.getMethod("truncate", new Class[] { Long.TYPE });
  115. this.runningOnJdk131 = false;
  116. } catch (NoSuchMethodException nsme) {
  117. this.runningOnJdk131 = true;
  118. }
  119. }
  120. protected void createSchemaObject(String objectType, String objectName,
  121. String columnsAndOtherStuff) throws SQLException {
  122. this.createdObjects.add(new String[] {objectType, objectName});
  123. dropSchemaObject(objectType, objectName);
  124. StringBuffer createSql = new StringBuffer(objectName.length()
  125. + objectType.length() + columnsAndOtherStuff.length() + 10);
  126. createSql.append("CREATE ");
  127. createSql.append(objectType);
  128. createSql.append(" ");
  129. createSql.append(objectName);
  130. createSql.append(" ");
  131. createSql.append(columnsAndOtherStuff);
  132. try {
  133. this.stmt.executeUpdate(createSql.toString());
  134. } catch (SQLException sqlEx) {
  135. if ("42S01".equals(sqlEx.getSQLState())) {
  136. System.err.println("WARN: Stale mysqld table cache preventing table creation - flushing tables and trying again");
  137. this.stmt.executeUpdate("FLUSH TABLES"); // some bug in 5.1 on the mac causes tables to not disappear from the cache
  138. this.stmt.executeUpdate(createSql.toString());
  139. } else {
  140. throw sqlEx;
  141. }
  142. }
  143. }
  144. protected void createFunction(String functionName, String functionDefn)
  145. throws SQLException {
  146. createSchemaObject("FUNCTION", functionName, functionDefn);
  147. }
  148. protected void dropFunction(String functionName) throws SQLException {
  149. dropSchemaObject("FUNCTION", functionName);
  150. }
  151. protected void createProcedure(String procedureName, String procedureDefn)
  152. throws SQLException {
  153. createSchemaObject("PROCEDURE", procedureName, procedureDefn);
  154. }
  155. protected void dropProcedure(String procedureName) throws SQLException {
  156. dropSchemaObject("PROCEDURE", procedureName);
  157. }
  158. protected void createTable(String tableName, String columnsAndOtherStuff)
  159. throws SQLException {
  160. createSchemaObject("TABLE", tableName, columnsAndOtherStuff);
  161. }
  162. protected void createTable(String tableName, String columnsAndOtherStuff,
  163. String engine) throws SQLException {
  164. createSchemaObject("TABLE", tableName,
  165. columnsAndOtherStuff + " " + getTableTypeDecl() + " = " + engine);
  166. }
  167. protected void dropTable(String tableName) throws SQLException {
  168. dropSchemaObject("TABLE", tableName);
  169. }
  170. protected void dropSchemaObject(String objectType, String objectName)
  171. throws SQLException {
  172. this.stmt.executeUpdate("DROP " + objectType + " IF EXISTS "
  173. + objectName);
  174. }
  175. protected Connection getAdminConnection() throws SQLException {
  176. return getAdminConnectionWithProps(new Properties());
  177. }
  178. protected Connection getAdminConnectionWithProps(Properties props)
  179. throws SQLException {
  180. String adminUrl = System.getProperty(ADMIN_CONNECTION_PROPERTY_NAME);
  181. if (adminUrl != null) {
  182. return DriverManager.getConnection(adminUrl, props);
  183. } else {
  184. return null;
  185. }
  186. }
  187. protected Connection getConnectionWithProps(String propsList) throws SQLException {
  188. return getConnectionWithProps(dbUrl, propsList);
  189. }
  190. protected Connection getConnectionWithProps(String url, String propsList) throws SQLException {
  191. Properties props = new Properties();
  192. if (propsList != null) {
  193. List keyValuePairs = StringUtils.split(propsList, ",", false);
  194. Iterator iter = keyValuePairs.iterator();
  195. while (iter.hasNext()) {
  196. String kvp = (String)iter.next();
  197. List splitUp = StringUtils.split(kvp, "=", false);
  198. StringBuffer value = new StringBuffer();
  199. for (int i = 1; i < splitUp.size(); i++) {
  200. if (i != 1) {
  201. value.append("=");
  202. }
  203. value.append(splitUp.get(i));
  204. }
  205. props.setProperty(splitUp.get(0).toString().trim(), value.toString());
  206. }
  207. }
  208. return getConnectionWithProps(url, props);
  209. }
  210. /**
  211. * Returns a new connection with the given properties
  212. *
  213. * @param props
  214. * the properties to use (the URL will come from the standard for
  215. * this testcase).
  216. *
  217. * @return a new connection using the given properties.
  218. *
  219. * @throws SQLException
  220. * DOCUMENT ME!
  221. */
  222. protected Connection getConnectionWithProps(Properties props)
  223. throws SQLException {
  224. return DriverManager.getConnection(dbUrl, props);
  225. }
  226. protected Connection getConnectionWithProps(String url, Properties props)
  227. throws SQLException {
  228. return DriverManager.getConnection(url, props);
  229. }
  230. /**
  231. * Returns the per-instance counter (for messages when multi-threading
  232. * stress tests)
  233. *
  234. * @return int the instance number
  235. */
  236. protected int getInstanceNumber() {
  237. return this.myInstanceNumber;
  238. }
  239. protected String getMysqlVariable(Connection c, String variableName)
  240. throws SQLException {
  241. Object value = getSingleIndexedValueWithQuery(c, 2,
  242. "SHOW VARIABLES LIKE '" + variableName + "'");
  243. if (value != null) {
  244. if (value instanceof byte[]) {
  245. // workaround for bad 4.1.x bugfix
  246. return new String((byte[]) value);
  247. }
  248. return value.toString();
  249. }
  250. return null;
  251. }
  252. /**
  253. * Returns the named MySQL variable from the currently connected server.
  254. *
  255. * @param variableName
  256. * the name of the variable to return
  257. *
  258. * @return the value of the given variable, or NULL if it doesn't exist
  259. *
  260. * @throws SQLException
  261. * if an error occurs
  262. */
  263. protected String getMysqlVariable(String variableName) throws SQLException {
  264. return getMysqlVariable(this.conn, variableName);
  265. }
  266. /**
  267. * Returns the properties that represent the default URL used for
  268. * connections for all testcases.
  269. *
  270. * @return properties parsed from com.mysql.jdbc.testsuite.url
  271. *
  272. * @throws SQLException
  273. * if parsing fails
  274. */
  275. protected Properties getPropertiesFromTestsuiteUrl() throws SQLException {
  276. Properties props = new NonRegisteringDriver().parseURL(dbUrl, null);
  277. String hostname = props
  278. .getProperty(NonRegisteringDriver.HOST_PROPERTY_KEY);
  279. if (hostname == null) {
  280. props.setProperty(NonRegisteringDriver.HOST_PROPERTY_KEY,
  281. "localhost");
  282. } else if (hostname.startsWith(":")) {
  283. props.setProperty(NonRegisteringDriver.HOST_PROPERTY_KEY,
  284. "localhost");
  285. props.setProperty(NonRegisteringDriver.PORT_PROPERTY_KEY, hostname
  286. .substring(1));
  287. }
  288. String portNumber = props
  289. .getProperty(NonRegisteringDriver.PORT_PROPERTY_KEY);
  290. if (portNumber == null) {
  291. props.setProperty(NonRegisteringDriver.PORT_PROPERTY_KEY, "3306");
  292. }
  293. return props;
  294. }
  295. protected int getRowCount(String tableName) throws SQLException {
  296. ResultSet countRs = null;
  297. try {
  298. countRs = this.stmt.executeQuery("SELECT COUNT(*) FROM "
  299. + tableName);
  300. countRs.next();
  301. return countRs.getInt(1);
  302. } finally {
  303. if (countRs != null) {
  304. countRs.close();
  305. }
  306. }
  307. }
  308. protected Object getSingleIndexedValueWithQuery(Connection c,
  309. int columnIndex, String query) throws SQLException {
  310. ResultSet valueRs = null;
  311. Statement svStmt = null;
  312. try {
  313. svStmt = c.createStatement();
  314. valueRs = svStmt.executeQuery(query);
  315. if (!valueRs.next()) {
  316. return null;
  317. }
  318. return valueRs.getObject(columnIndex);
  319. } finally {
  320. if (valueRs != null) {
  321. valueRs.close();
  322. }
  323. if (svStmt != null) {
  324. svStmt.close();
  325. }
  326. }
  327. }
  328. protected Object getSingleIndexedValueWithQuery(int columnIndex,
  329. String query) throws SQLException {
  330. return getSingleIndexedValueWithQuery(this.conn, columnIndex, query);
  331. }
  332. protected Object getSingleValue(String tableName, String columnName,
  333. String whereClause) throws SQLException {
  334. return getSingleValueWithQuery("SELECT " + columnName + " FROM "
  335. + tableName + ((whereClause == null) ? "" : " " + whereClause));
  336. }
  337. protected Object getSingleValueWithQuery(String query) throws SQLException {
  338. return getSingleIndexedValueWithQuery(1, query);
  339. }
  340. protected String getTableTypeDecl() throws SQLException {
  341. if (versionMeetsMinimum(5, 0)) {
  342. return "ENGINE";
  343. }
  344. return "TYPE";
  345. }
  346. protected boolean isAdminConnectionConfigured() {
  347. return System.getProperty(ADMIN_CONNECTION_PROPERTY_NAME) != null;
  348. }
  349. protected boolean isServerRunningOnWindows() throws SQLException {
  350. return (getMysqlVariable("datadir").indexOf('\\') != -1);
  351. }
  352. public void logDebug(String message) {
  353. if (System.getProperty("com.mysql.jdbc.testsuite.noDebugOutput") == null) {
  354. System.err.println(message);
  355. }
  356. }
  357. protected File newTempBinaryFile(String name, long size) throws IOException {
  358. File tempFile = File.createTempFile(name, "tmp");
  359. tempFile.deleteOnExit();
  360. cleanupTempFiles(tempFile, name);
  361. FileOutputStream fos = new FileOutputStream(tempFile);
  362. BufferedOutputStream bos = new BufferedOutputStream(fos);
  363. for (long i = 0; i < size; i++) {
  364. bos.write((byte) i);
  365. }
  366. bos.close();
  367. assertTrue(tempFile.exists());
  368. assertEquals(size, tempFile.length());
  369. return tempFile;
  370. }
  371. protected final boolean runLongTests() {
  372. return runTestIfSysPropDefined("com.mysql.jdbc.testsuite.runLongTests");
  373. }
  374. /**
  375. * Checks whether a certain system property is defined, in order to
  376. * run/not-run certain tests
  377. *
  378. * @param propName
  379. * the property name to check for
  380. *
  381. * @return true if the property is defined.
  382. */
  383. protected boolean runTestIfSysPropDefined(String propName) {
  384. String prop = System.getProperty(propName);
  385. return (prop != null) && (prop.length() > 0);
  386. }
  387. protected boolean runMultiHostTests() {
  388. return !runTestIfSysPropDefined(NO_MULTI_HOST_PROPERTY_NAME);
  389. }
  390. /**
  391. * Creates resources used by all tests.
  392. *
  393. * @throws Exception
  394. * if an error occurs.
  395. */
  396. public void setUp() throws Exception {
  397. System.out.println("Loading JDBC driver '" + this.dbClass + "'");
  398. Class.forName(this.dbClass).newInstance();
  399. System.out.println("Done.\n");
  400. this.createdObjects = new ArrayList();
  401. if (this.dbClass.equals("gwe.sql.gweMysqlDriver")) {
  402. try {
  403. this.conn = DriverManager.getConnection(dbUrl, "", "");
  404. } catch (Exception ex) {
  405. ex.printStackTrace();
  406. fail();
  407. }
  408. } else {
  409. try {
  410. this.conn = DriverManager.getConnection(dbUrl);
  411. } catch (Exception ex) {
  412. ex.printStackTrace();
  413. fail();
  414. }
  415. }
  416. System.out.println("Done.\n");
  417. this.stmt = this.conn.createStatement();
  418. try {
  419. if (dbUrl.indexOf("mysql") != -1) {
  420. this.rs = this.stmt.executeQuery("SELECT VERSION()");
  421. this.rs.next();
  422. logDebug("Connected to " + this.rs.getString(1));
  423. this.rs.close();
  424. this.rs = null;
  425. } else {
  426. logDebug("Connected to "
  427. + this.conn.getMetaData().getDatabaseProductName()
  428. + " / "
  429. + this.conn.getMetaData().getDatabaseProductVersion());
  430. }
  431. } finally {
  432. if (this.rs != null) {
  433. this.rs.close();
  434. }
  435. }
  436. }
  437. /**
  438. * Destroys resources created during the test case.
  439. *
  440. * @throws Exception
  441. * DOCUMENT ME!
  442. */
  443. public void tearDown() throws Exception {
  444. if (this.rs != null) {
  445. try {
  446. this.rs.close();
  447. } catch (SQLException SQLE) {
  448. ;
  449. }
  450. }
  451. if (System.getProperty("com.mysql.jdbc.testsuite.retainArtifacts") == null) {
  452. for (int i = 0; i < this.createdObjects.size(); i++) {
  453. try {
  454. String[] objectInfo = (String[])this.createdObjects.get(i);
  455. dropSchemaObject(objectInfo[0], objectInfo[1]);
  456. } catch (SQLException SQLE) {
  457. ;
  458. }
  459. }
  460. }
  461. if (this.stmt != null) {
  462. try {
  463. this.stmt.close();
  464. } catch (SQLException SQLE) {
  465. ;
  466. }
  467. }
  468. if (this.pstmt != null) {
  469. try {
  470. this.pstmt.close();
  471. } catch (SQLException SQLE) {
  472. ;
  473. }
  474. }
  475. if (this.conn != null) {
  476. try {
  477. this.conn.close();
  478. } catch (SQLException SQLE) {
  479. ;
  480. }
  481. }
  482. }
  483. /**
  484. * Checks whether the database we're connected to meets the given version
  485. * minimum
  486. *
  487. * @param major
  488. * the major version to meet
  489. * @param minor
  490. * the minor version to meet
  491. *
  492. * @return boolean if the major/minor is met
  493. *
  494. * @throws SQLException
  495. * if an error occurs.
  496. */
  497. protected boolean versionMeetsMinimum(int major, int minor)
  498. throws SQLException {
  499. return versionMeetsMinimum(major, minor, 0);
  500. }
  501. /**
  502. * Checks whether the database we're connected to meets the given version
  503. * minimum
  504. *
  505. * @param major
  506. * the major version to meet
  507. * @param minor
  508. * the minor version to meet
  509. *
  510. * @return boolean if the major/minor is met
  511. *
  512. * @throws SQLException
  513. * if an error occurs.
  514. */
  515. protected boolean versionMeetsMinimum(int major, int minor, int subminor)
  516. throws SQLException {
  517. return (((com.mysql.jdbc.Connection) this.conn).versionMeetsMinimum(
  518. major, minor, subminor));
  519. }
  520. protected boolean isRunningOnJdk131() {
  521. return this.runningOnJdk131;
  522. }
  523. protected boolean isClassAvailable(String classname) {
  524. try {
  525. Class.forName(classname);
  526. return true;
  527. } catch (ClassNotFoundException e) {
  528. return false;
  529. }
  530. }
  531. protected void closeMemberJDBCResources() {
  532. if (this.rs != null) {
  533. ResultSet toClose = this.rs;
  534. this.rs = null;
  535. try {
  536. toClose.close();
  537. } catch (SQLException sqlEx) {
  538. // ignore
  539. }
  540. }
  541. if (this.pstmt != null) {
  542. PreparedStatement toClose = this.pstmt;
  543. this.pstmt = null;
  544. try {
  545. toClose.close();
  546. } catch (SQLException sqlEx) {
  547. // ignore
  548. }
  549. }
  550. }
  551. protected boolean isRunningOnJRockit() {
  552. String vmVendor = System.getProperty("java.vm.vendor");
  553. return (vmVendor != null && vmVendor.toUpperCase(Locale.US).startsWith(
  554. "BEA"));
  555. }
  556. protected String randomString() {
  557. int length = (int)(Math.random() * 32);
  558. StringBuffer buf = new StringBuffer(length);
  559. for (int i = 0; i < length; i++) {
  560. buf.append((char)((Math.random() * 26) + 'a'));
  561. }
  562. return buf.toString();
  563. }
  564. protected void cleanupTempFiles(final File exampleTempFile, final String tempfilePrefix) {
  565. File tempfilePath = exampleTempFile.getParentFile();
  566. File[] possibleFiles = tempfilePath.listFiles(new FilenameFilter() {
  567. public boolean accept(File dir, String name) {
  568. return (name.indexOf(tempfilePrefix) != -1
  569. && !exampleTempFile.getName().equals(name));
  570. }});
  571. for (int i = 0; i < possibleFiles.length; i++) {
  572. try {
  573. possibleFiles[i].delete();
  574. } catch (Throwable t) {
  575. // ignore, we're only making a best effort cleanup attempt here
  576. }
  577. }
  578. }
  579. protected void assertResultSetLength(ResultSet rs, int len) throws Exception {
  580. assertTrue("Result set is scrollable", rs.getType() != ResultSet.TYPE_FORWARD_ONLY);
  581. int oldRowPos = rs.getRow();
  582. rs.last();
  583. assertEquals("Result set length", len, rs.getRow());
  584. if (oldRowPos > 0)
  585. rs.absolute(oldRowPos);
  586. else
  587. rs.beforeFirst();
  588. }
  589. protected void assertResultSetsEqual(ResultSet control, ResultSet test)
  590. throws Exception {
  591. int controlNumCols = control.getMetaData().getColumnCount();
  592. int testNumCols = test.getMetaData().getColumnCount();
  593. assertEquals(controlNumCols, testNumCols);
  594. StringBuffer rsAsString = new StringBuffer();
  595. while (control.next()) {
  596. test.next();
  597. rsAsString.append("\n");
  598. for (int i = 0; i < controlNumCols; i++) {
  599. Object controlObj = control.getObject(i + 1);
  600. Object testObj = test.getObject(i + 1);
  601. rsAsString.append("" + controlObj);
  602. rsAsString.append("\t = \t");
  603. rsAsString.append("" + testObj);
  604. rsAsString.append(", ");
  605. if (controlObj == null) {
  606. assertNull("Expected null, see last row: \n" + rsAsString.toString(), testObj);
  607. } else {
  608. assertNotNull("Expected non-null, see last row: \n" + rsAsString.toString(), testObj);
  609. }
  610. if (controlObj instanceof Float) {
  611. assertEquals("Float comparison failed, see last row: \n" + rsAsString.toString(), ((Float)controlObj).floatValue(),
  612. ((Float)testObj).floatValue(), 0.1);
  613. } else if (controlObj instanceof Double) {
  614. assertEquals("Double comparison failed, see last row: \n" + rsAsString.toString(), ((Double)controlObj).doubleValue(),
  615. ((Double)testObj).doubleValue(), 0.1);
  616. } else {
  617. assertEquals("Value comparison failed, see last row: \n" + rsAsString.toString(), controlObj, testObj);
  618. }
  619. }
  620. }
  621. int howMuchMore = 0;
  622. while (test.next()) {
  623. rsAsString.append("\n");
  624. howMuchMore++;
  625. for (int i = 0; i < controlNumCols; i++) {
  626. rsAsString.append("\t = \t");
  627. rsAsString.append("" + test.getObject(i + 1));
  628. rsAsString.append(", ");
  629. }
  630. }
  631. assertTrue("Found " + howMuchMore + " extra rows in result set to be compared: ", howMuchMore == 0);
  632. }
  633. /*
  634. * Set default values for primitives.
  635. * (prevents NPE in Java 1.4 when calling via reflection)
  636. */
  637. protected void fillPrimitiveDefaults(Class types[], Object vals[], int count) {
  638. for (int i = 0; i < count; ++i) {
  639. if (vals[i] != null)
  640. continue;
  641. String type = types[i].toString();
  642. if (type.equals("short")) {
  643. vals[i] = new Short((short)0);
  644. } else if (type.equals("int")) {
  645. vals[i] = new Integer(0);
  646. } else if (type.equals("long")) {
  647. vals[i] = new Long(0);
  648. } else if (type.equals("boolean")) {
  649. vals[i] = new Boolean(false);
  650. } else if (type.equals("byte")) {
  651. vals[i] = new Byte((byte)0);
  652. } else if (type.equals("double")) {
  653. vals[i] = new Double(0.0);
  654. } else if (type.equals("float")) {
  655. vals[i] = new Float(0.0);
  656. }
  657. }
  658. }
  659. /**
  660. * Retrieve the current system time in milliseconds, using the nanosecond
  661. * time if possible.
  662. */
  663. protected long currentTimeMillis() {
  664. try {
  665. Method mNanoTime = System.class.getDeclaredMethod("nanoTime", (Class[])null);
  666. return ((Long)mNanoTime.invoke(null, (Object[])null)).longValue() / 1000000;
  667. } catch(Exception ex) {
  668. return System.currentTimeMillis();
  669. }
  670. }
  671. protected Connection getMasterSlaveReplicationConnection() throws SQLException {
  672. Connection replConn = new ReplicationDriver().connect(
  673. getMasterSlaveUrl(), getMasterSlaveProps());
  674. return replConn;
  675. }
  676. protected String getMasterSlaveUrl() throws SQLException {
  677. StringBuffer urlBuf = new StringBuffer("jdbc:mysql://");
  678. Properties defaultProps = getPropertiesFromTestsuiteUrl();
  679. String hostname = defaultProps
  680. .getProperty(NonRegisteringDriver.HOST_PROPERTY_KEY);
  681. String portNumber = defaultProps.getProperty(NonRegisteringDriver.PORT_PROPERTY_KEY, "3306");
  682. hostname = (hostname == null ? "localhost" : hostname);
  683. for (int i = 0; i < 2; i++) {
  684. urlBuf.append(hostname);
  685. urlBuf.append(":");
  686. urlBuf.append(portNumber);
  687. if (i == 0) {
  688. urlBuf.append(",");
  689. }
  690. }
  691. urlBuf.append("/");
  692. return urlBuf.toString();
  693. }
  694. protected Properties getMasterSlaveProps() throws SQLException {
  695. Properties props = getPropertiesFromTestsuiteUrl();
  696. props.remove(NonRegisteringDriver.HOST_PROPERTY_KEY);
  697. props.remove(NonRegisteringDriver.PORT_PROPERTY_KEY);
  698. return props;
  699. }
  700. protected Connection getLoadBalancedConnection(int badHostLocation, String badHost,
  701. Properties props) throws SQLException {
  702. int indexOfHostStart = dbUrl.indexOf("://") + 3;
  703. int indexOfHostEnd = dbUrl.indexOf("/", indexOfHostStart);
  704. String firstHost = dbUrl.substring(indexOfHostStart, indexOfHostEnd);
  705. if (firstHost.length() == 0) {
  706. firstHost = "localhost:3306";
  707. }
  708. String dbAndConfigs = dbUrl.substring(indexOfHostEnd);
  709. if (badHost != null) {
  710. badHost = badHost + ",";
  711. }
  712. String hostsString = null;
  713. switch (badHostLocation) {
  714. case 1:
  715. hostsString = badHost + firstHost;
  716. break;
  717. case 2:
  718. hostsString = firstHost + "," + badHost + firstHost;
  719. break;
  720. case 3:
  721. hostsString = firstHost + "," + badHost;
  722. break;
  723. default:
  724. throw new IllegalArgumentException();
  725. }
  726. Connection lbConn = DriverManager.getConnection("jdbc:mysql:loadbalance://" + hostsString + dbAndConfigs, props);
  727. return lbConn;
  728. }
  729. protected Connection getLoadBalancedConnection() throws SQLException {
  730. return getLoadBalancedConnection(1, "", null);
  731. }
  732. protected Connection getLoadBalancedConnection(Properties props)
  733. throws SQLException {
  734. return getLoadBalancedConnection(1, "", props);
  735. }
  736. protected void copyBasePropertiesIntoProps(Properties props, NonRegisteringDriver d)
  737. throws SQLException {
  738. Properties testCaseProps = d.parseURL(BaseTestCase.dbUrl, null);
  739. String user = testCaseProps.getProperty(NonRegisteringDriver.USER_PROPERTY_KEY);
  740. if (user != null) {
  741. props.setProperty(NonRegisteringDriver.USER_PROPERTY_KEY, user);
  742. }
  743. String password = testCaseProps.getProperty(NonRegisteringDriver.PASSWORD_PROPERTY_KEY);
  744. if (password != null) {
  745. props.setProperty(NonRegisteringDriver.PASSWORD_PROPERTY_KEY, password);
  746. }
  747. String port = testCaseProps.getProperty(NonRegisteringDriver.PORT_PROPERTY_KEY);
  748. if (port != null) {
  749. props.setProperty(NonRegisteringDriver.PORT_PROPERTY_KEY, port);
  750. } else {
  751. String host = testCaseProps.getProperty(NonRegisteringDriver.HOST_PROPERTY_KEY);
  752. if (host != null) {
  753. String[] hostPort = host.split(":");
  754. if (hostPort.length > 1) {
  755. props.setProperty(NonRegisteringDriver.PORT_PROPERTY_KEY, hostPort[1]);
  756. }
  757. }
  758. }
  759. }
  760. protected String getPortFreeHostname(Properties props, NonRegisteringDriver d)
  761. throws SQLException {
  762. String host = d.parseURL(BaseTestCase.dbUrl, props).getProperty(NonRegisteringDriver.HOST_PROPERTY_KEY);
  763. if(host == null){
  764. host = "localhost";
  765. }
  766. host = host.split(":")[0];
  767. return host;
  768. }
  769. protected Connection getUnreliableLoadBalancedConnection(String[] hostNames,
  770. Properties props) throws Exception {
  771. return getUnreliableLoadBalancedConnection(hostNames,
  772. props, new HashSet());
  773. }
  774. protected Connection getUnreliableLoadBalancedConnection(String[] hostNames,
  775. Properties props, Set downedHosts) throws Exception {
  776. if(props == null){
  777. props = new Properties();
  778. }
  779. NonRegisteringDriver d = new NonRegisteringDriver();
  780. this.copyBasePropertiesIntoProps(props, d);
  781. props.setProperty("socketFactory", "testsuite.UnreliableSocketFactory");
  782. Properties parsed = d.parseURL(BaseTestCase.dbUrl, props);
  783. String db = parsed.getProperty(NonRegisteringDriver.DBNAME_PROPERTY_KEY);
  784. String port = parsed.getProperty(NonRegisteringDriver.PORT_PROPERTY_KEY);
  785. String host = getPortFreeHostname(props, d);
  786. UnreliableSocketFactory.flushAllHostLists();
  787. StringBuffer hostString = new StringBuffer();
  788. String glue = "";
  789. for(int i = 0; i < hostNames.length; i++){
  790. UnreliableSocketFactory.mapHost(hostNames[i], host);
  791. hostString.append(glue);
  792. glue = ",";
  793. hostString.append(hostNames[i] + ":" + (port == null ? "3306" : port));
  794. if (downedHosts.contains(hostNames[i])) {
  795. UnreliableSocketFactory.downHost(hostNames[i]);
  796. }
  797. }
  798. props.remove(NonRegisteringDriver.HOST_PROPERTY_KEY);
  799. return getConnectionWithProps("jdbc:mysql:loadbalance://" + hostString.toString() +"/" + db, props);
  800. }
  801. }