📄 xmlbinding.java
字号:
// This next one is important because it verifies // that implicit/default values which are defined // in a DTD _are_ actually processed, even though // we don't perform validation. Thus this next // query _should_ return a match. int rowCount = existsQuery(conn, "xTable.t1", "//person/@noteTwo"); if (rowCount == 0) { System.out.println("FAILED: Query on DTD default didn't " + "return any matches."); } } catch (Exception e) { System.out.println("Unexpected exception: "); e.printStackTrace(System.out); } // Test binding nulls to the XMLEXISTS operands. Binding // of the second (XML) operand is not allowed and was // checked in "doBindTests()" above. Here we just // check binding of the first operand, which should be // a string. try { PreparedStatement pSt = conn.prepareStatement( "select i from xTable.t1 where " + "XMLEXISTS (? PASSING BY VALUE x)"); System.out.print("Binding string in XMLEXISTS: "); bindAndExecute(pSt, 1, Types.CHAR, "//d48", null, false); // Null should work, too. System.out.print("Binding Java null string in XMLEXISTS: "); bindAndExecute(pSt, 1, Types.CHAR, null, null, false); System.out.print("Binding SQL NULL string in XMLEXISTS: "); bindAndExecute(pSt, 1, Types.VARCHAR, null, null, true); } catch (Exception e) { System.out.println("Unexpected exception: "); e.printStackTrace(System.out); } System.out.println("\n[ End XMLEXISTS tests. ]\n"); } /** * Helper method. Inserts the contents of a file into * the received table using "setCharacterStream". * @param conn A connection to the test database. * @param tableName Name of the target table * @param fName Name of the file whose content we * want to insert. * @param numRows Number of times we should insert * the received file's content. */ private void insertFiles(Connection conn, String tableName, String fName, int numRows) throws Exception { // First we have to figure out many chars long the // file is. InputStream iS = this.getClass().getResourceAsStream(fName); InputStreamReader reader = new InputStreamReader(iS); char [] cA = new char[1024]; int charCount = 0; for (int len = reader.read(cA, 0, cA.length); len != -1; charCount += len, len = reader.read(cA, 0, cA.length)); reader.close(); // Now that we know the number of characters, we can // insert using a stream. PreparedStatement pSt = conn.prepareStatement( "insert into xTable.t1(x) values (" + "xmlparse(document ? preserve whitespace))"); for (int i = 0; i < numRows; i++) { iS = this.getClass().getResourceAsStream(fName); reader = new InputStreamReader(iS); pSt.setCharacterStream(1, reader, charCount); pSt.execute(); reader.close(); System.out.println("Inserted roughly " + (charCount / 1000) + "k of data."); } } /** * Helper method. Inserts an XML document into the * received table using setString. This method * parallels "insertFiles" above, except that it * should be used for documents that require a DTD * in order to be complete. In that case, the * location of the DTD has to modified _in_ the * document so that it can be found regardless of * whether we're running in embedded mode or in * server/client mode. * @param conn A connection to the test database. * @param tableName Name of the target table * @param fName Name of the file whose content we * want to insert. * @param dtdName Name of the DTD file that the * received file uses. * @param numRows Number of times we should insert * the received file's content. */ private void insertDocWithDTD(Connection conn, String tableName, String fName, String dtdName, int numRows) throws Exception { boolean needsUpdate = true; String currPath = System.getProperty("user.dir"); String fileSep = System.getProperty("file.separator"); String dtdPath = currPath; boolean foundDTD = false; while (!foundDTD) { try { FileReader fR = new FileReader(dtdPath + fileSep + dtdName); // If we get here, then we found the DTD in // the current path, so we're done. foundDTD = true; dtdPath = "file:///" + dtdPath + fileSep + dtdName; break; } catch (java.io.IOException ie) { // Couldn't find the DTD in the current path. // The harness uses a lot of subdirectories when // running tests (for client, or server, or // suites, or nested suites...etc.), so we // back up one directory and try again. int pos = dtdPath.lastIndexOf(fileSep); if (pos == -1) { // we're at the top of the path and haven't // found the DTD yet. This shouldn't happen. throw new Exception("Couldn't find DTD '" + dtdName + "' for insertion of file '" + fName + "'."); } dtdPath = dtdPath.substring(0, pos); } } // Read the file into memory so we can update it. InputStream iS = this.getClass().getResourceAsStream(fName); InputStreamReader reader = new InputStreamReader(iS); char [] cA = new char[1024]; StringBuffer sBuf = new StringBuffer(); int charCount = 0; for (int len = reader.read(cA, 0, cA.length); len != -1; charCount += len, len = reader.read(cA, 0, cA.length)) { sBuf.append(cA, 0, len); } reader.close(); // Now replace the DTD location, if needed. String docAsString = sBuf.toString(); int pos = docAsString.indexOf(dtdName); if (pos != -1) sBuf.replace(pos, pos + dtdName.length(), dtdPath); // Now (finally) do the insert using the in-memory // document with the correct DTD location. docAsString = sBuf.toString(); PreparedStatement pSt = conn.prepareStatement( "insert into xTable.t1(x) values (" + "xmlparse(document ? preserve whitespace))"); charCount = docAsString.length(); for (int i = 0; i < numRows; i++) { pSt.setString(1, docAsString); pSt.execute(); System.out.println("Inserted roughly " + (charCount / 1000) + "k of data."); } } /** * Helper method. Selects all rows from the received * table name that have at least one node matching * the received XPath expression. Does this query * using the XMLEXISTS operator. * @param conn A connection to the test database. * @param tableName Table to query. * @param xPath The XPath expression to evaluate. * @return The number of rows that match the * XPath expression. */ private int existsQuery(Connection conn, String tableName, String xPath) throws Exception { PreparedStatement pSt = conn.prepareStatement( "select i from " + tableName + " where " + "xmlexists('" + xPath + "' passing by value x)"); System.out.println("Running XMLEXISTS with: " + xPath); ResultSet rs = pSt.executeQuery(); String xResult = null; int rowCount = 0; while (rs.next()) { rowCount++; } System.out.println("--> Matching rows: " + rowCount); return rowCount; } /** * Helper method. Attempts to bind a parameter to a * given value using the given type, and then prints * the result of that attempt (PASS/FAIL). * @param pSt The prepared statement holding the parameter * that we want to bind. * @param paramNum Which parameter in pSt we want to bind. * @param paramType The type of the value to be bound. * @param bindValue The value to be used for binding. * @param sqlState The expected SQLState for the binding * error, if one is expected. Null if the bind is expected * to succeed. * @param bindSqlNull True if we should bind using a SQL * NULL (i.e. "setNull()"). */ private void bindAndExecute(PreparedStatement pSt, int paramNum, int paramType, Object bindValue, String sqlState, boolean bindSqlNull) { SQLException actualException = null; try { // First try to bind. if (bindSqlNull) { pSt.setNull(paramNum, paramType); } else { switch (paramType) { case Types.CHAR: case Types.VARCHAR: pSt.setString(paramNum, (String)bindValue); break; case Types.INTEGER: pSt.setInt(paramNum, ((Integer)bindValue).intValue()); break; default: System.out.println("ERROR: Unexpected bind type (" + paramType + ") in call to doBind."); break; } } // Now try to execute. pSt.execute(); } catch (SQLException e) { actualException = e; } checkException(actualException, sqlState); } /** * Helper method. Checks to see if the received SQLException * has a SQLState that matches the target/expected SQLState. * Prints out a message saying the result of this check, and * in the case where the actual error is NOT the expected * error, prints a full stack trace to System.out. * @param se The SQLException to be checked. * @param targetState The expected SQLState; null if no * error was expected. */ private void checkException(SQLException se, String targetState) { if (targetState == null) { if (se == null) { System.out.println("PASS -- Completed without exception, " + "as expected."); } else { System.out.println("FAIL -- Was expected to succeed, but " + "failed with error " + se.getSQLState() + "."); se.printStackTrace(System.out); } return; } if (se == null) { System.out.println("FAIL -- Completed without exception when " + "error " + targetState + " was expected."); return; } if (!targetState.equals(se.getSQLState())) { System.out.println("FAIL: Caught error " + se.getSQLState() + " when was expecting error " + targetState + "."); se.printStackTrace(System.out); return; } System.out.println("PASS -- caught expected error " + targetState + "."); }}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -