java.sql.Clob

Here are the examples of the java api class java.sql.Clob taken from open source projects.

1. UtilTest#testAutoMapClobToByteArray()

Project: rxjava-jdbc
File: UtilTest.java
@Test
public void testAutoMapClobToByteArray() throws SQLException {
    Clob clob = EasyMock.createMock(Clob.class);
    String s = "hello there";
    expect(clob.getCharacterStream()).andReturn(new StringReader(s)).once();
    clob.free();
    EasyMock.expectLastCall().once();
    replay(clob);
    Object string = autoMap(clob, String.class);
    assertEquals(s, string);
    verify(clob);
}

2. BlobTest#testFreeClob()

Project: pgjdbc-ng
File: BlobTest.java
@Test
public void testFreeClob() throws SQLException {
    Statement stmt = conn.createStatement();
    stmt.execute("INSERT INTO blobtest VALUES (1, lo_creat(-1))");
    ResultSet rs = stmt.executeQuery("SELECT data FROM blobtest");
    assertTrue(rs.next());
    Clob clob = rs.getClob(1);
    clob.free();
    try {
        clob.length();
        fail("Should have thrown an Exception because it was freed.");
    } catch (SQLException sqle) {
    }
    rs.close();
    stmt.close();
}

3. TemporaryLobCreator#setClobAsString()

Project: effectivejava
File: TemporaryLobCreator.java
@Override
public void setClobAsString(PreparedStatement ps, int paramIndex, String content) throws SQLException {
    Clob clob = ps.getConnection().createClob();
    clob.setString(1, content);
    this.temporaryClobs.add(clob);
    ps.setClob(paramIndex, clob);
    if (logger.isDebugEnabled()) {
        logger.debug(content != null ? "Copied string into temporary CLOB with length " + content.length() : "Set CLOB to null");
    }
}

4. BlobClob4BlobTest#testClobAfterCommitWithSecondClob()

Project: derby
File: BlobClob4BlobTest.java
/**
     * Make sure we get an error attempting to access the 
     * lob after commit.
     */
public void testClobAfterCommitWithSecondClob() throws SQLException {
    getConnection().setAutoCommit(false);
    Statement s1 = createStatement();
    ResultSet rs1 = s1.executeQuery("values cast('first' as clob)");
    rs1.next();
    Clob first = rs1.getClob(1);
    rs1.close();
    commit();
    Statement s2 = createStatement();
    ResultSet rs2 = s2.executeQuery("values cast('second' as clob)");
    rs2.next();
    Clob second = rs2.getClob(1);
    try {
        first.getSubString(1, 100);
        fail("first.getSubString should have failed because after the commit");
    } catch (SQLException se) {
        assertSQLState(INVALID_LOB, se);
    }
    assertEquals("second", second.getSubString(1, 100));
    rs2.close();
}

5. Util#setClob()

Project: rxjava-jdbc
File: Util.java
/**
     * Sets the clob parameter for the prepared statement.
     * 
     * @param ps
     * @param i
     * @param o
     * @param cls
     * @throws SQLException
     */
private static void setClob(PreparedStatement ps, int i, Object o, Class<?> cls) throws SQLException {
    final Reader r;
    if (o instanceof String)
        r = new StringReader((String) o);
    else if (o instanceof Reader)
        r = (Reader) o;
    else
        throw new RuntimeException("cannot insert parameter of type " + cls + " into clob column " + i);
    Clob c = ps.getConnection().createClob();
    Writer w = c.setCharacterStream(1);
    copy(r, w);
    ps.setClob(i, c);
}

6. BlobTest#testEOFClob()

Project: pgjdbc-ng
File: BlobTest.java
@Test
public void testEOFClob() throws SQLException, IOException {
    Statement stmt = conn.createStatement();
    stmt.execute("INSERT INTO blobtest VALUES (1, lo_creat(-1))");
    ResultSet rs = stmt.executeQuery("SELECT data FROM blobtest");
    assertTrue(rs.next());
    Clob clob = rs.getClob(1);
    Reader in = clob.getCharacterStream();
    assertEquals(-1, in.read());
    assertEquals(-1, in.read(new char[4], 0, 4));
    rs.close();
    stmt.close();
}

7. BlobTest#testGetBytesOffsetClob()

Project: pgjdbc-ng
File: BlobTest.java
@Test
public void testGetBytesOffsetClob() throws Exception {
    assertTrue(uploadFileClob("pom.xml") > 0);
    String eol = String.format("%n");
    Statement stmt = conn.createStatement();
    ResultSet rs = stmt.executeQuery("SELECT lo FROM testblob");
    assertTrue(rs.next());
    Clob lob = rs.getClob(1);
    int blobLength = 3 + eol.length();
    String data = lob.getSubString(2, blobLength);
    assertEquals(data.length(), blobLength);
    assertEquals(data.charAt(0), '!');
    assertEquals(data.charAt(1), '-');
    assertEquals(data.charAt(2), '-');
    for (int i = 0; i < eol.length(); i++) {
        assertEquals(data.charAt(3 + i), eol.charAt(i));
    }
    stmt.close();
    rs.close();
}

8. PGResultSet#updateClob()

Project: pgjdbc-ng
File: PGResultSet.java
@Override
public void updateClob(int columnIndex, Reader x) throws SQLException {
    checkClosed();
    checkUpdate();
    Clob clob = statement.connection.createClob();
    try {
        CharStreams.copy(x, clob.setCharacterStream(1));
    } catch (IOException e) {
        throw new SQLException(e);
    }
    set(columnIndex, clob);
}

9. PGPreparedStatement#setClob()

Project: pgjdbc-ng
File: PGPreparedStatement.java
@Override
public void setClob(int parameterIndex, Reader reader) throws SQLException {
    checkClosed();
    Clob clob = connection.createClob();
    try {
        CharStreams.copy(reader, clob.setCharacterStream(1));
    } catch (IOException e) {
        throw new SQLException(e);
    }
    set(parameterIndex, clob, Types.CLOB);
}

10. ClobToStringConverter#convertToEntityAttribute()

Project: olingo-odata2
File: ClobToStringConverter.java
@Override
public Clob convertToEntityAttribute(String string) {
    if (string == null) {
        return null;
    }
    Clob clob = null;
    try {
        clob = new JDBCClob(string);
    } catch (SQLException e) {
        e.printStackTrace();
    }
    return clob;
}

11. SQLService#toClob()

Project: odo
File: SQLService.java
/**
     * Converts the given string to a clob object
     *
     * @param stringName string name to clob
     * @param sqlConnection Connection object
     * @return Clob object or NULL
     */
public Clob toClob(String stringName, Connection sqlConnection) {
    Clob clobName = null;
    try {
        clobName = sqlConnection.createClob();
        clobName.setString(1, stringName);
    } catch (SQLException e) {
        logger.info("Unable to create clob object");
        e.printStackTrace();
    }
    return clobName;
}

12. TemporaryLobCreator#setClobAsCharacterStream()

Project: effectivejava
File: TemporaryLobCreator.java
@Override
public void setClobAsCharacterStream(PreparedStatement ps, int paramIndex, Reader characterStream, int contentLength) throws SQLException {
    Clob clob = ps.getConnection().createClob();
    try {
        FileCopyUtils.copy(characterStream, clob.setCharacterStream(1));
    } catch (IOException ex) {
        throw new DataAccessResourceFailureException("Could not copy into LOB stream", ex);
    }
    this.temporaryClobs.add(clob);
    ps.setClob(paramIndex, clob);
    if (logger.isDebugEnabled()) {
        logger.debug(characterStream != null ? "Copied character stream into temporary CLOB with length " + contentLength : "Set CLOB to null");
    }
}

13. TemporaryLobCreator#setClobAsAsciiStream()

Project: effectivejava
File: TemporaryLobCreator.java
@Override
public void setClobAsAsciiStream(PreparedStatement ps, int paramIndex, InputStream asciiStream, int contentLength) throws SQLException {
    Clob clob = ps.getConnection().createClob();
    try {
        FileCopyUtils.copy(asciiStream, clob.setAsciiStream(1));
    } catch (IOException ex) {
        throw new DataAccessResourceFailureException("Could not copy into LOB stream", ex);
    }
    this.temporaryClobs.add(clob);
    ps.setClob(paramIndex, clob);
    if (logger.isDebugEnabled()) {
        logger.debug(asciiStream != null ? "Copied ASCII stream into temporary CLOB with length " + contentLength : "Set CLOB to null");
    }
}

14. VarargsRoutines#add()

Project: derby
File: VarargsRoutines.java
public static String add(String seed, Clob... values) throws SQLException {
    if (values == null) {
        return null;
    }
    if (values.length == 0) {
        return null;
    }
    String result = "";
    for (Clob value : values) {
        result += value.getSubString(1L, (int) value.length());
    }
    return "clob " + seed + " " + result;
}

15. AnsiSignaturesTest#test_clob_Clob_String()

Project: derby
File: AnsiSignaturesTest.java
public void test_clob_Clob_String() throws Exception {
    Connection conn = getConnection();
    declareAndRunFunction("clob_Clob_String", "clob", new String[] { "varchar( 10 )" }, "'3'", "3");
    // now test clob arguments
    declareFunction(conn, "varchar_Clob_Clob", "varchar( 10 )", new String[] { "clob" });
    runFunction(conn, "varchar_Clob_Clob", " \"clob_Clob_String\"( 'abc' )", "abc", null);
    // make sure that you can set lob-typed ? parameters
    PreparedStatement ps = chattyPrepare(conn, "values ( \"varchar_Clob_Clob\"( ? ) )");
    String expectedValue = "abcdef";
    Clob clob = AnsiSignatures.clob_Clob_String(expectedValue);
    ps.setClob(1, clob);
    String actualValue = (String) getScalarString(ps);
    assertTrue(expectedValue.equals(actualValue));
}

16. BlobClob4BlobTest#testClobFinalizer()

Project: derby
File: BlobClob4BlobTest.java
/**
     * test clob finalizer closes the container (should only release table and
     * row locks that are read_committed)
     * NOTE: this test does not produce output since it needs to call the
     * garbage collector whose behaviour is unreliable. It is in the test run to
     * exercise the code (most of the time).
     */
public void testClobFinalizer() throws Exception {
    insertDefaultData();
    Statement stmt = createStatement();
    ResultSet rs = stmt.executeQuery("select a, b from testClob");
    Clob[] clobArray = new Clob[10];
    int[] clobLengthArray = new int[10];
    int j = 0;
    while (rs.next()) {
        clobArray[j] = rs.getClob(1);
        clobLengthArray[j++] = rs.getInt(2);
    }
    rs.close();
    stmt.close();
    for (int i = 0; i < 10; i++) {
        clobArray[i] = null;
    }
    System.gc();
    System.gc();
}

17. PreparedStatementTest#testSetCharacterStreamLengthless()

Project: derby
File: PreparedStatementTest.java
public void testSetCharacterStreamLengthless() throws IOException, SQLException {
    // Insert test data.
    String testString = "Test string for setCharacterStream?";
    Reader reader = new StringReader(testString);
    psInsertClob.setInt(1, key);
    psInsertClob.setCharacterStream(2, reader);
    psInsertClob.execute();
    reader.close();
    // Read back test data from database.
    psFetchClob.setInt(1, key);
    ResultSet rs = psFetchClob.executeQuery();
    assertTrue("No results retrieved", rs.next());
    Clob clobRetrieved = rs.getClob(1);
    // Verify test data.
    assertEquals("Mismatch test data in/out", testString, clobRetrieved.getSubString(1, testString.length()));
}

18. SqlNullCheckedResultSetTest#testSetNullClob()

Project: commons-dbutils
File: SqlNullCheckedResultSetTest.java
/**
     * Tests the setNullClob implementation.
     */
public void testSetNullClob() throws SQLException {
    assertNull(rs2.getNullClob());
    // Set what gets returned to something other than the default
    Clob clob = new SqlNullCheckedResultSetMockClob();
    rs2.setNullClob(clob);
    assertNotNull(rs.getClob(1));
    assertEquals(clob, rs.getClob(1));
    assertNotNull(rs.getClob("column"));
    assertEquals(clob, rs.getClob("column"));
}

19. SqlNullCheckedResultSetTest#testGetClob()

Project: commons-dbutils
File: SqlNullCheckedResultSetTest.java
/**
     * Tests the getClob implementation.
     */
public void testGetClob() throws SQLException {
    assertNull(rs.getClob(1));
    assertTrue(rs.wasNull());
    assertNull(rs.getClob("column"));
    assertTrue(rs.wasNull());
    // Set what gets returned to something other than the default
    Clob clob = new SqlNullCheckedResultSetMockClob();
    rs2.setNullClob(clob);
    assertNotNull(rs.getClob(1));
    assertEquals(clob, rs.getClob(1));
    assertNotNull(rs.getClob("column"));
    assertEquals(clob, rs.getClob("column"));
}

20. TestDatabaseConfiguration#testExtractPropertyValueCLOBEmpty()

Project: commons-configuration
File: TestDatabaseConfiguration.java
/**
     * Tests whether an empty CLOB is correctly handled by
     * extractPropertyValue().
     */
@Test
public void testExtractPropertyValueCLOBEmpty() throws ConfigurationException, SQLException {
    ResultSet rs = EasyMock.createMock(ResultSet.class);
    Clob clob = EasyMock.createMock(Clob.class);
    EasyMock.expect(rs.getObject(DatabaseConfigurationTestHelper.COL_VALUE)).andReturn(clob);
    EasyMock.expect(clob.length()).andReturn(0L);
    EasyMock.replay(rs, clob);
    DatabaseConfiguration config = helper.setUpConfig();
    assertEquals("Wrong extracted value", "", config.extractPropertyValue(rs));
    EasyMock.verify(rs, clob);
}

21. TestDatabaseConfiguration#testExtractPropertyValueCLOB()

Project: commons-configuration
File: TestDatabaseConfiguration.java
/**
     * Tests whether a CLOB as a property value is handled correctly.
     */
@Test
public void testExtractPropertyValueCLOB() throws ConfigurationException, SQLException {
    ResultSet rs = EasyMock.createMock(ResultSet.class);
    Clob clob = EasyMock.createMock(Clob.class);
    final String content = "This is the content of the test CLOB!";
    EasyMock.expect(rs.getObject(DatabaseConfigurationTestHelper.COL_VALUE)).andReturn(clob);
    EasyMock.expect(clob.length()).andReturn(Long.valueOf(content.length()));
    EasyMock.expect(clob.getSubString(1, content.length())).andReturn(content);
    EasyMock.replay(rs, clob);
    DatabaseConfiguration config = helper.setUpConfig();
    assertEquals("Wrong extracted value", content, config.extractPropertyValue(rs));
    EasyMock.verify(rs, clob);
}

22. ConnectionHandle#createClob()

Project: bonecp
File: ConnectionHandle.java
public Clob createClob() throws SQLException {
    Clob result = null;
    checkClosed();
    try {
        result = this.connection.createClob();
    } catch (SQLException e) {
        throw markPossiblyBroken(e);
    }
    return result;
}

23. LOBLocatorReleaseTest#testScrollableUpdateWithLocators()

Project: derby
File: LOBLocatorReleaseTest.java
/**
     * Tests a sequence of operations on a scrollable, updatable resultset.
     *
     * @throws SQLException if the test fails
     */
public void testScrollableUpdateWithLocators() throws SQLException {
    getConnection().setAutoCommit(false);
    Statement stmt = createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE);
    ResultSet rs = stmt.executeQuery("select dBlob, dClob from LOBLOC_NO_NULLS");
    rs.absolute(3);
    Clob c1 = rs.getClob(2);
    final int origLength = (int) c1.length();
    final String origContent = c1.getSubString(1, origLength);
    // Do a change
    c1.setString(origLength, "FIRSTPASS");
    rs.absolute(7);
    rs.next();
    // Move back to row 3
    rs.absolute(3);
    Clob c2 = rs.getClob(2);
    assertEquals(origContent, c2.getSubString(1, (int) c2.length()));
    // Should be a no-op
    rs.updateRow();
    rs.absolute(3);
    // Expect this to fail if the restriction that LOB columns cannot be
    // accessed more than once is enforced.
    Clob c3 = rs.getClob(2);
    assertEquals(origContent, c3.getSubString(1, (int) c3.length()));
    rs.previous();
    rs.next();
    Clob c4 = rs.getClob(2);
    final String newContent = "THIS IS THE NEW VALUE!";
    c4.setString(1, newContent);
    rs.updateClob(2, c4);
    rs.updateRow();
    c4.setString(1, "THIS IS NOT NOT NOT THE NEW VALUE!");
    rs.updateRow();
    rs.next();
    rs.absolute(3);
    Clob c5 = rs.getClob(2);
    assertEquals(newContent, c5.getSubString(1, (int) c5.length()));
    rollback();
    assertInvalid(c1);
    assertInvalid(c2);
    assertInvalid(c3);
    assertInvalid(c4);
    assertInvalid(c5);
}

24. ClobUpdatableReaderTest#testUpdateableReader()

Project: derby
File: ClobUpdatableReaderTest.java
/**
     * Tests updates on reader.
     */
public void testUpdateableReader() throws Exception {
    getConnection().setAutoCommit(false);
    PreparedStatement ps = prepareStatement("insert into updateClob " + "(id , data) values (? ,?)");
    ps.setInt(1, 1);
    StringBuffer sb = new StringBuffer();
    String base = "SampleSampleSample";
    for (int i = 0; i < 100; i++) {
        sb.append(base);
    }
    ps.setCharacterStream(2, new StringReader(sb.toString()), sb.length());
    ps.execute();
    ps.close();
    Statement stmt = createStatement();
    ResultSet rs = stmt.executeQuery("select data from " + "updateClob where id = 1");
    rs.next();
    Clob clob = rs.getClob(1);
    rs.close();
    stmt.close();
    assertEquals(sb.length(), clob.length());
    Reader r = clob.getCharacterStream();
    char[] clobData = new char[sb.length()];
    r.read(clobData);
    assertEquals("mismatch from inserted string", String.valueOf(clobData), sb.toString());
    r.close();
    //update before gettting the reader
    clob.setString(50, dummy);
    r = clob.getCharacterStream();
    r.skip(49);
    char[] newChars = new char[dummy.length()];
    r.read(newChars);
    assertEquals("update not reflected", dummy, String.valueOf(newChars));
    //update again and see if stream is refreshed
    clob.setString(75, dummy);
    r.skip(75 - 50 - dummy.length());
    char[] testChars = new char[dummy.length()];
    r.read(testChars);
    assertEquals("update not reflected", dummy, String.valueOf(newChars));
    r.close();
    //try inserting some unicode string
    String unicodeStr = getUnicodeString();
    clob.setString(50, unicodeStr);
    char[] utf16Chars = new char[unicodeStr.length()];
    r = clob.getCharacterStream();
    r.skip(49);
    r.read(utf16Chars);
    assertEquals("update not reflected", unicodeStr, String.valueOf(utf16Chars));
    r.close();
    Writer w = clob.setCharacterStream(1);
    //write enough data to switch the data to file
    r = clob.getCharacterStream();
    for (int i = 0; i < 10000; i++) {
        w.write(dummy);
    }
    w.close();
    clob.setString(500, unicodeStr);
    r.skip(499);
    char[] unicodeChars = new char[unicodeStr.length()];
    r.read(unicodeChars);
    assertEquals("update not reflected", unicodeStr, String.valueOf(unicodeChars));
}

25. TestLobApi#testClob()

Project: ThriftyPaxos
File: TestLobApi.java
private void testClob(int length) throws Exception {
    Random r = new Random(length);
    char[] data = new char[length];
    // (String.getBytes("UTF-8") only returns 1 byte for 0xd800-0xdfff)
    for (int i = 0; i < length; i++) {
        char c;
        do {
            c = (char) r.nextInt();
        } while (c >= 0xd800 && c <= 0xdfff);
        data[i] = c;
    }
    Clob c = conn.createClob();
    Writer out = c.setCharacterStream(1);
    out.write(data, 0, data.length);
    out.close();
    stat.execute("delete from test");
    PreparedStatement prep = conn.prepareStatement("insert into test values(?, ?)");
    prep.setInt(1, 1);
    prep.setClob(2, c);
    prep.execute();
    c = conn.createClob();
    c.setString(1, new String(data));
    prep.setInt(1, 2);
    prep.setClob(2, c);
    prep.execute();
    prep.setInt(1, 3);
    prep.setCharacterStream(2, new StringReader(new String(data)));
    prep.execute();
    prep.setInt(1, 4);
    prep.setCharacterStream(2, new StringReader(new String(data)), -1);
    prep.execute();
    NClob nc;
    nc = conn.createNClob();
    nc.setString(1, new String(data));
    prep.setInt(1, 5);
    prep.setNClob(2, nc);
    prep.execute();
    prep.setInt(1, 5);
    prep.setNClob(2, new StringReader(new String(data)));
    prep.execute();
    prep.setInt(1, 6);
    prep.setNClob(2, new StringReader(new String(data)), -1);
    prep.execute();
    prep.setInt(1, 7);
    prep.setNString(2, new String(data));
    prep.execute();
    ResultSet rs;
    rs = stat.executeQuery("select * from test");
    rs.next();
    Clob c2 = rs.getClob(2);
    assertEquals(length, c2.length());
    String s = c.getSubString(1, length);
    String s2 = c2.getSubString(1, length);
    while (rs.next()) {
        c2 = rs.getClob(2);
        assertEquals(length, c2.length());
        s2 = c2.getSubString(1, length);
        assertEquals(s, s2);
    }
}

26. BlobTest#testTruncateClob()

Project: pgjdbc-ng
File: BlobTest.java
@Test
public void testTruncateClob() throws SQLException {
    char[] chars = new char[100];
    for (char i = 0; i < chars.length; i++) {
        chars[i] = i;
    }
    String data = new String(chars);
    readWriteClob(data);
    PreparedStatement ps = conn.prepareStatement("SELECT ID, DATA FROM blobtest WHERE ID = 1");
    ResultSet rs = ps.executeQuery();
    assertTrue(rs.next());
    Clob clob = rs.getClob("DATA");
    assertEquals(100, clob.length());
    clob.truncate(50);
    assertEquals(50, clob.length());
    clob.truncate(150);
    assertEquals(150, clob.length());
    data = clob.getSubString(1, 200);
    assertEquals(150, data.length());
    for (char i = 0; i < 50; i++) {
        assertEquals(i, data.charAt(i));
    }
    for (int i = 50; i < 150; i++) {
        assertEquals(0, data.charAt(i));
    }
    rs.close();
    ps.close();
}

27. ParameterMappingTest#testClobMapping()

Project: derby
File: ParameterMappingTest.java
/**
     * Verify correct mapping of clobs.
     */
public void testClobMapping() throws Exception {
    Connection conn = getConnection();
    PreparedStatement ps;
    CallableStatement cs;
    Clob outVal;
    //
    // Clob input parameter
    //
    ps = chattyPrepare(conn, "create procedure clobIn\n" + "( in c clob, out result varchar( 100 ) )\n" + "language java\n" + "parameter style java\n" + "no sql\n" + "external name '" + getClass().getName() + ".clobIn'\n");
    ps.execute();
    ps.close();
    cs = chattyPrepareCall(conn, "call clobIn( cast( 'def' as clob ), ? )");
    cs.registerOutParameter(1, Types.VARCHAR);
    cs.execute();
    assertEquals("def", cs.getString(1));
    cs.close();
    cs = chattyPrepareCall(conn, "call clobIn( ?, ? )");
    cs.setClob(1, new HarmonySerialClob("ghi"));
    cs.registerOutParameter(2, Types.VARCHAR);
    cs.execute();
    assertEquals("ghi", cs.getString(2));
    cs.close();
    //
    // Clob output parameter
    //
    ps = chattyPrepare(conn, "create procedure clobOut\n" + "( out c clob )\n" + "language java\n" + "parameter style java\n" + "no sql\n" + "external name '" + getClass().getName() + ".clobOut'\n");
    ps.execute();
    ps.close();
    cs = chattyPrepareCall(conn, "call clobOut( ? )");
    cs.registerOutParameter(1, Types.CLOB);
    cs.execute();
    outVal = cs.getClob(1);
    assertEquals("abc", outVal.getSubString(1L, (int) outVal.length()));
    cs.close();
    //
    // Clob inout parameter
    //
    ps = chattyPrepare(conn, "create procedure clobInOut\n" + "( inout c clob )\n" + "language java\n" + "parameter style java\n" + "no sql\n" + "external name '" + getClass().getName() + ".clobInOut'\n");
    ps.execute();
    ps.close();
    cs = chattyPrepareCall(conn, "call clobInOut( ? )");
    cs.setClob(1, new HarmonySerialClob("ghi"));
    cs.registerOutParameter(1, Types.CLOB);
    cs.execute();
    outVal = cs.getClob(1);
    assertEquals("ihg", outVal.getSubString(1L, (int) outVal.length()));
    Clob inValue = makeBigClob();
    cs.setClob(1, inValue);
    cs.execute();
    Clob outValue = cs.getClob(1);
    compareClobs(inValue, outValue);
    cs.close();
}

28. ClobTest#testInsertCharacter_ReadOnlyToTemporary()

Project: derby
File: ClobTest.java
/**
     * Tests that Derby specific end-of-stream markers aren't passed over to
     * the temporary Clob, which doesn't use such markers.
     * <p>
     * Passing the marker over will normally result in a UTF encoding exception.
     * <p>
     * ID USAGE: reads id 2, writes id 10002
     */
public void testInsertCharacter_ReadOnlyToTemporary() throws IOException, SQLException {
    setAutoCommit(false);
    // Insert data, a medium sized Clob to store it as a stream.
    PreparedStatement ps = prepareStatement("insert into ClobTestData values (?,?)");
    int initalSize = 128 * 1024;
    ps.setInt(1, 2);
    ps.setCharacterStream(2, new LoopingAlphabetReader(initalSize), initalSize);
    ps.executeUpdate();
    // Select the Clob, and change one character.
    PreparedStatement psSelect = prepareStatement("select dClob from ClobTestData where id = ?");
    psSelect.setInt(1, 2);
    ResultSet lRs = psSelect.executeQuery();
    lRs.next();
    Clob lClob = lRs.getClob(1);
    lClob.setString(1, "K");
    Reader r = lClob.getCharacterStream();
    assertEquals('K', r.read());
    long length = 1;
    while (true) {
        // Since we're skipping characters, the bytes have to be decoded
        // and we will detect any encoding errors.
        long skipped = r.skip(4096);
        if (skipped > 0) {
            length += skipped;
        } else {
            break;
        }
    }
    lRs.close();
    assertEquals("Wrong length!", initalSize, length);
    // Reports the correct length, now try to insert it.
    ps.setInt(1, 10003);
    ps.setClob(2, lClob);
    ps.executeUpdate();
    // Fetch it back.
    psSelect.setInt(1, 10003);
    lRs = psSelect.executeQuery();
    lRs.next();
    Clob lClob2 = lRs.getClob(1);
    assertEquals(lClob.getCharacterStream(), lClob2.getCharacterStream());
    assertEquals(initalSize, lClob2.length());
}

29. TestLobApi#testLobStaysOpenUntilCommitted()

Project: ThriftyPaxos
File: TestLobApi.java
/**
     * According to the JDBC spec, BLOB and CLOB objects must stay open even if
     * the result set is closed (see ResultSet.close).
     */
private void testLobStaysOpenUntilCommitted() throws Exception {
    Connection conn = getConnection("lob");
    stat = conn.createStatement();
    stat.execute("create table test(id identity, c clob, b blob)");
    PreparedStatement prep = conn.prepareStatement("insert into test values(null, ?, ?)");
    prep.setString(1, "");
    prep.setBytes(2, new byte[0]);
    prep.execute();
    Random r = new Random(1);
    char[] chars = new char[100000];
    for (int i = 0; i < chars.length; i++) {
        chars[i] = (char) r.nextInt(10000);
    }
    String d = new String(chars);
    prep.setCharacterStream(1, new StringReader(d), -1);
    byte[] bytes = new byte[100000];
    r.nextBytes(bytes);
    prep.setBinaryStream(2, new ByteArrayInputStream(bytes), -1);
    prep.execute();
    conn.setAutoCommit(false);
    ResultSet rs = stat.executeQuery("select * from test order by id");
    rs.next();
    Clob c1 = rs.getClob(2);
    Blob b1 = rs.getBlob(3);
    rs.next();
    Clob c2 = rs.getClob(2);
    Blob b2 = rs.getBlob(3);
    assertFalse(rs.next());
    // now close
    rs.close();
    // but the LOBs must stay open
    assertEquals(0, c1.length());
    assertEquals(0, b1.length());
    assertEquals(chars.length, c2.length());
    assertEquals(bytes.length, b2.length());
    assertEquals("", c1.getSubString(1, 0));
    assertEquals(new byte[0], b1.getBytes(1, 0));
    assertEquals(d, c2.getSubString(1, (int) c2.length()));
    assertEquals(bytes, b2.getBytes(1, (int) b2.length()));
    stat.execute("drop table test");
    conn.close();
}

30. TestLobApi#testUnsupportedOperations()

Project: ThriftyPaxos
File: TestLobApi.java
private void testUnsupportedOperations() throws Exception {
    Connection conn = getConnection("lob");
    stat = conn.createStatement();
    stat.execute("create table test(id int, c clob, b blob)");
    stat.execute("insert into test values(1, 'x', x'00')");
    ResultSet rs = stat.executeQuery("select * from test order by id");
    rs.next();
    Clob clob = rs.getClob(2);
    byte[] data = IOUtils.readBytesAndClose(clob.getAsciiStream(), -1);
    assertEquals("x", new String(data, "UTF-8"));
    assertTrue(clob.toString().endsWith("'x'"));
    clob.free();
    assertTrue(clob.toString().endsWith("null"));
    assertThrows(ErrorCode.FEATURE_NOT_SUPPORTED_1, clob).truncate(0);
    assertThrows(ErrorCode.FEATURE_NOT_SUPPORTED_1, clob).setAsciiStream(1);
    assertThrows(ErrorCode.FEATURE_NOT_SUPPORTED_1, clob).setString(1, "", 0, 1);
    assertThrows(ErrorCode.FEATURE_NOT_SUPPORTED_1, clob).position("", 0);
    assertThrows(ErrorCode.FEATURE_NOT_SUPPORTED_1, clob).position((Clob) null, 0);
    assertThrows(ErrorCode.FEATURE_NOT_SUPPORTED_1, clob).getCharacterStream(1, 1);
    Blob blob = rs.getBlob(3);
    assertThrows(ErrorCode.FEATURE_NOT_SUPPORTED_1, blob).truncate(0);
    assertThrows(ErrorCode.FEATURE_NOT_SUPPORTED_1, blob).setBytes(1, new byte[0], 0, 0);
    assertThrows(ErrorCode.FEATURE_NOT_SUPPORTED_1, blob).position(new byte[1], 0);
    assertThrows(ErrorCode.FEATURE_NOT_SUPPORTED_1, blob).position((Blob) null, 0);
    assertThrows(ErrorCode.FEATURE_NOT_SUPPORTED_1, blob).getBinaryStream(1, 1);
    assertTrue(blob.toString().endsWith("X'00'"));
    blob.free();
    assertTrue(blob.toString().endsWith("null"));
    stat.execute("drop table test");
    conn.close();
}

31. TestLob#testRemovedAfterTimeout()

Project: ThriftyPaxos
File: TestLob.java
private void testRemovedAfterTimeout() throws Exception {
    deleteDb("lob");
    final String url = getURL("lob;lob_timeout=50", true);
    Connection conn = getConnection(url);
    Statement stat = conn.createStatement();
    stat.execute("create table test(id int primary key, data clob)");
    PreparedStatement prep = conn.prepareStatement("insert into test values(?, ?)");
    prep.setInt(1, 1);
    prep.setString(2, "aaa" + new String(new char[1024 * 16]).replace((char) 0, 'x'));
    prep.execute();
    prep.setInt(1, 2);
    prep.setString(2, "bbb" + new String(new char[1024 * 16]).replace((char) 0, 'x'));
    prep.execute();
    ResultSet rs = stat.executeQuery("select * from test order by id");
    rs.next();
    Clob c1 = rs.getClob(2);
    assertEquals("aaa", c1.getSubString(1, 3));
    rs.next();
    assertEquals("aaa", c1.getSubString(1, 3));
    rs.close();
    assertEquals("aaa", c1.getSubString(1, 3));
    stat.execute("delete from test");
    c1.getSubString(1, 3);
    // wait until it times out
    Thread.sleep(100);
    // start a new transaction, to be sure
    stat.execute("delete from test");
    try {
        c1.getSubString(1, 3);
        fail();
    } catch (SQLException e) {
    }
    conn.close();
}

32. BlobTest#testWrapperClob()

Project: pgjdbc-ng
File: BlobTest.java
@Test
public void testWrapperClob() throws SQLException {
    conn.setAutoCommit(false);
    PreparedStatement stmt = conn.prepareStatement("INSERT INTO blobtest VALUES (1, ?)");
    final Clob clob = conn.createClob();
    Clob wrapper = new Clob() {

        @Override
        public long length() throws SQLException {
            return clob.length();
        }

        @Override
        public String getSubString(long pos, int length) throws SQLException {
            return clob.getSubString(pos, length);
        }

        @Override
        public Reader getCharacterStream() throws SQLException {
            return clob.getCharacterStream();
        }

        @Override
        public InputStream getAsciiStream() throws SQLException {
            return clob.getAsciiStream();
        }

        @Override
        public long position(String searchstr, long start) throws SQLException {
            return clob.position(searchstr, start);
        }

        @Override
        public long position(Clob searchstr, long start) throws SQLException {
            return clob.position(searchstr, start);
        }

        @Override
        public int setString(long pos, String str) throws SQLException {
            return clob.setString(pos, str);
        }

        @Override
        public int setString(long pos, String str, int offset, int len) throws SQLException {
            return clob.setString(pos, str, offset, len);
        }

        @Override
        public OutputStream setAsciiStream(long pos) throws SQLException {
            return clob.setAsciiStream(pos);
        }

        @Override
        public Writer setCharacterStream(long pos) throws SQLException {
            return clob.setCharacterStream(pos);
        }

        @Override
        public void truncate(long len) throws SQLException {
            clob.truncate(len);
        }

        @Override
        public void free() throws SQLException {
            clob.free();
        }

        @Override
        public Reader getCharacterStream(long pos, long length) throws SQLException {
            return clob.getCharacterStream(pos, length);
        }
    };
    stmt.setClob(1, wrapper);
    stmt.execute();
    stmt.close();
    conn.commit();
}

33. BlobTest#testPatternClob()

Project: pgjdbc-ng
File: BlobTest.java
@Test
public void testPatternClob() throws SQLException {
    String data = "abcdefghijklmnopqrstuvwxyx0123456789";
    String pattern = "def";
    PreparedStatement ps = conn.prepareStatement("INSERT INTO blobtest VALUES (1, lo_creat(-1))");
    ps.executeUpdate();
    ps.close();
    ps = conn.prepareStatement("SELECT ID, DATA FROM blobtest WHERE ID = 1");
    ResultSet rs = ps.executeQuery();
    assertTrue(rs.next());
    Clob c = rs.getClob("DATA");
    c.setString(1, data);
    rs.close();
    ps.close();
    ps = conn.prepareStatement("SELECT ID, DATA FROM blobtest WHERE ID = 1");
    rs = ps.executeQuery();
    assertTrue(rs.next());
    c = rs.getClob("DATA");
    long position = c.position(pattern, 1);
    String rspData = c.getSubString(position, pattern.length());
    assertEquals("Request should be the same as the response", pattern, rspData);
    rs.close();
    ps.close();
}

34. BlobTest#readWriteClob()

Project: pgjdbc-ng
File: BlobTest.java
/**
   *
   * @param offset
   * @param data
   * @throws SQLException
   */
private void readWriteClob(int offset, String data) throws SQLException {
    PreparedStatement ps = conn.prepareStatement("INSERT INTO blobtest VALUES (1, lo_creat(-1))");
    ps.executeUpdate();
    ps.close();
    ps = conn.prepareStatement("SELECT ID, DATA FROM blobtest WHERE ID = 1");
    ResultSet rs = ps.executeQuery();
    assertTrue(rs.next());
    Clob b = rs.getClob("DATA");
    b.setString(offset, data);
    rs.close();
    ps.close();
    ps = conn.prepareStatement("SELECT ID, DATA FROM blobtest WHERE ID = 1");
    rs = ps.executeQuery();
    assertTrue(rs.next());
    b = rs.getClob("DATA");
    String rspData = b.getSubString(offset, data.length());
    assertEquals("Request should be the same as the response", data, rspData);
    rs.close();
    ps.close();
}

35. SQLInputImplTests#test08()

Project: openjdk
File: SQLInputImplTests.java
/*
     * Validate a Clob can be read
     */
@Test(enabled = true)
public void test08() throws Exception {
    Clob c = new StubClob();
    Object[] values = { c };
    SQLInputImpl sqli = new SQLInputImpl(values, map);
    Clob c2 = sqli.readClob();
    assertTrue(c.getSubString(1, (int) c.length()).equals(c2.getSubString(1, (int) c2.length())));
}

36. LobLimitsTest#updateClob2()

Project: derby
File: LobLimitsTest.java
/*
     * Basically this test will do an update using updateClob api and verifies
     * the updated data. select row from clobtbl2 and then update a row in
     * clobtbl and verify updated data in clobtbl against the data in the
     * original file
     * 
     * @param updateRowId id of the row that needs to be updated
     */
private void updateClob2(String testId, PreparedStatement sel, int cloblen, int id, int updateRowId, int updateIdVal, String file) throws Exception {
    println("========================================");
    println("START " + testId + " - select and then update clob of size= " + cloblen + " - Uses updateClob api");
    PreparedStatement ps1 = prepareStatement("SELECT * FROM CLOBTBL FOR UPDATE", ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_UPDATABLE);
    PreparedStatement ps = prepareStatement("SELECT CONTENT,DLEN FROM CLOBTBL2 " + "where ID =?");
    ps.setInt(1, id);
    // retrieve row from clobtbl2
    ResultSet rs = ps.executeQuery();
    rs.next();
    Clob value = rs.getClob(1);
    long l = value.length();
    long dlen = rs.getLong(2);
    if (dlen != l) {
        println("FAIL - MISMATCH LENGTHS GOT " + l + " expected " + dlen + " for row in CLOBTBL2 with ID=" + id);
    }
    ResultSet rs1 = ps1.executeQuery();
    while (rs1.next()) {
        if (rs1.getInt(1) == updateRowId) {
            rs1.updateClob(4, value);
            rs1.updateInt(1, updateIdVal);
            rs1.updateInt(2, 0);
            rs1.updateLong(3, dlen);
            rs1.updateRow();
            break;
        }
    }
    commit();
    // close resultsets
    rs.close();
    rs1.close();
    // verify
    // now select and verify that update went through ok.
    sel.setInt(1, updateIdVal);
    ResultSet rs2 = sel.executeQuery();
    rs2.next();
    Clob updatedValue = rs2.getClob(1);
    assertEquals("FAIL - MISMATCH length of updated clob value ," + "found=" + updatedValue.length() + ",expected = " + l, l, updatedValue.length());
    compareClobToFile(updatedValue.getCharacterStream(), file, (int) l);
    if (updatedValue.length() != l) {
        println("FAIL - MISMATCH length of updated clob value ," + "found=" + updatedValue.length() + ",expected = " + l);
    } else
        compareClobToFile(updatedValue.getCharacterStream(), file, (int) l);
    println("========================================");
}

37. LobLimitsTest#selectUpdateClob2()

Project: derby
File: LobLimitsTest.java
/*
     * Basically this test will do an update using setBlob api and verifies the
     * updated data. select row from clobtbl2 and then update a row in clobtbl
     * and verify updated data in clobtbl against the data in the original file
     */
private void selectUpdateClob2(String testId, PreparedStatement ps, PreparedStatement sel, int cloblen, int id, int updateId, String file) throws Exception {
    println("========================================");
    println("START " + testId + " - select and then update clob of size= " + cloblen + " - Uses setClob api");
    // retrieve row from clobtbl2
    ps.setInt(1, id);
    ResultSet rs = ps.executeQuery();
    rs.next();
    Clob value = rs.getClob(1);
    long l = value.length();
    long dlen = rs.getLong(2);
    assertEquals("FAIL - MISMATCH LENGTHS GOT " + l + " expected " + dlen + " for row in CLOBTBL2 with ID=" + id, dlen, l);
    PreparedStatement psUpd = prepareStatement("update CLOBTBL set content=?,dlen =? " + "where id = ?");
    psUpd.setClob(1, value);
    psUpd.setLong(2, l);
    psUpd.setInt(3, updateId);
    assertUpdateCount(psUpd, 1);
    commit();
    // now select and verify that update went through ok.
    sel.setInt(1, updateId);
    ResultSet rs2 = sel.executeQuery();
    rs2.next();
    Clob updatedValue = rs2.getClob(1);
    assertEquals("FAIL - MISMATCH length of updated clob value , found=" + updatedValue.length() + ",expected = " + l, l, updatedValue.length());
    compareClobToFile(updatedValue.getCharacterStream(), file, (int) l);
    commit();
    // close resultsets
    rs.close();
    rs2.close();
    println("========================================");
}

38. LobLimitsTest#selectUpdateClob()

Project: derby
File: LobLimitsTest.java
/*
     * Basically this test will do an update using setClob api - select row from
     * clobtbl and then update a row in clobtbl and verify updated data in
     * clobtbl
     */
private void selectUpdateClob(String testId, PreparedStatement ps, int cloblen, int id, int updateId) throws Exception {
    println("========================================");
    println("START " + testId + " - select and then update clob of size= " + cloblen + " - Uses setClob api");
    ps.setInt(1, id);
    ResultSet rs = ps.executeQuery();
    rs.next();
    Clob value = rs.getClob(1);
    long l = value.length();
    long dlen = rs.getLong(2);
    assertEquals("FAIL - MISMATCH LENGTHS GOT " + l + " expected " + dlen + " for row in CLOBTBL with ID=" + id, dlen, l);
    PreparedStatement psUpd = prepareStatement("update CLOBTBL set content=?, " + "dlen =? where id = ?");
    psUpd.setCharacterStream(1, value.getCharacterStream(), (int) l);
    psUpd.setLong(2, l);
    psUpd.setInt(3, updateId);
    if (usingDerbyNetClient()) {
        // DERBY-5317 cannot use setCharacterStream with value from
        // Clob.getCharacterStream because server will try to stream
        // lob to and from server at the same time. setClob can be
        // used as a work around.
        // Verify that new error is thrown 
        assertPreparedStatementError("XN023", psUpd);
        return;
    } else {
        assertUpdateCount(psUpd, 1);
    }
    commit();
    // now select and verify that update went through ok.
    ps.setInt(1, updateId);
    ResultSet rs2 = ps.executeQuery();
    rs2.next();
    Clob updatedValue = rs2.getClob(1);
    assertEquals("FAIL - Retrieving the updated clob length does not match " + "expected length = " + l + " found = " + updatedValue.length(), l, updatedValue.length());
    commit();
    // close resultsets
    rs.close();
    rs2.close();
    println("========================================");
}

39. ClobUpdatableReaderTest#testUpdateableStoreReader()

Project: derby
File: ClobUpdatableReaderTest.java
/**
     * Test updating a large clob
     */
public void testUpdateableStoreReader() throws Exception {
    getConnection().setAutoCommit(false);
    PreparedStatement ps = prepareStatement("insert into updateClob " + "(id , data) values (? ,?)");
    ps.setInt(1, 2);
    StringBuffer sb = new StringBuffer();
    String base = "SampleSampleSample";
    for (int i = 0; i < 100000; i++) {
        sb.append(base);
    }
    //insert a large enough data to ensure stream is created in dvd
    ps.setCharacterStream(2, new StringReader(sb.toString()), sb.length());
    ps.execute();
    ps.close();
    Statement stmt = createStatement();
    ResultSet rs = stmt.executeQuery("select data from " + "updateClob where id = 2");
    rs.next();
    Clob clob = rs.getClob(1);
    rs.close();
    stmt.close();
    assertEquals(sb.length(), clob.length());
    Reader r = clob.getCharacterStream();
    String newString = "this is a new string";
    //access reader before modifying the clob
    long l = r.skip(100);
    clob.setString(1001, newString);
    //l chars are already skipped
    long toSkip = 1000 - l;
    while (toSkip > 0) {
        long skipped = r.skip(toSkip);
        toSkip -= skipped;
    }
    char[] newdata = new char[newString.length()];
    int len = r.read(newdata);
    assertEquals("updated not reflected", newString, new String(newdata, 0, len));
    r.close();
}

40. BlobClob4BlobTest#testNegativeTestDerby265Clob()

Project: derby
File: BlobClob4BlobTest.java
/**
     * Test fix for derby-265.
     * Test that if getClob is called after the transaction
     * in which it was created is committed, a proper user error
     * is thrown instead of an NPE.
     * Basically per the spec, getClob is valid only for the duration of
     * the transaction in it was created in
     * Updated for DERBY-1511: The test case wasn't supposed to fail in the
     * first place (neither with NPE nor with "proper user error") since none
     * of the CLOBs are accessed after the transaction that created them was
     * completed.
     * @throws Exception
     */
public void testNegativeTestDerby265Clob() throws Exception {
    getConnection().setAutoCommit(false);
    PreparedStatement ps = prepareStatement("insert into testClob(b, a) values(?,?)");
    for (int i = 0; i < 3; i++) {
        Reader fis = new LoopingAlphabetReader(300000);
        ps.setInt(1, i);
        ps.setCharacterStream(2, fis, 300000);
        ps.executeUpdate();
        fis.close();
    }
    commit();
    getConnection().setAutoCommit(true);
    Statement s = createStatement(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY);
    s.execute("SELECT b, a FROM testClob");
    ResultSet rs1 = s.getResultSet();
    Statement s2 = createStatement(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY);
    s2.executeQuery("SELECT b, a FROM testClob");
    ResultSet rs2 = s2.getResultSet();
    rs2.next();
    Clob b2 = rs2.getClob(2);
    rs1.next();
    Clob b1 = rs1.getClob(2);
    rs1.close();
    // DERBY-1511: Fetching the next CLOB here used to fail because it
    // had been pre-fetched before the commit and was closed in the commit.
    // Now, we don't pre-fetch CLOBs anymore, so expect to get a working
    // object here.
    assertTrue(rs2.next());
    assertNotNull(rs2.getClob(2));
    rs2.close();
}

41. BlobClob4BlobTest#checkContentsBeforeAndAfterUpdatingClob()

Project: derby
File: BlobClob4BlobTest.java
private void checkContentsBeforeAndAfterUpdatingClob(ResultSet rs) throws SQLException {
    Clob c;
    String value, expectedValue;
    String clobData = "initial clob ";
    String updatedClobData = "updated clob ";
    c = rs.getClob(2);
    // check contents
    value = c.getSubString(1, (int) c.length());
    expectedValue = clobData + rs.getInt(1);
    assertEquals("FAIL - wrong clob value", expectedValue, value);
    // update contents
    value = updatedClobData + rs.getInt(1);
    c.setString(1, value);
    rs.updateClob(2, c);
    rs.updateRow();
    // check update values
    // leave the row
    rs.next();
    // go back to updated row
    rs.previous();
    c = rs.getClob(2);
    // check contents
    value = c.getSubString(1, (int) c.length());
    expectedValue = updatedClobData + rs.getInt(1);
    assertEquals("FAIL - wrong clob value", expectedValue, value);
}

42. BlobClob4BlobTest#testSetClob()

Project: derby
File: BlobClob4BlobTest.java
/**
     * test setClob
     */
public void testSetClob() throws Exception {
    insertDefaultData();
    ResultSet rs, rs2;
    Statement stmt = createStatement();
    stmt.execute("create table testSetClob (a CLOB(300k), b integer)");
    PreparedStatement ps = prepareStatement("insert into testSetClob values(?,?)");
    rs = stmt.executeQuery("select a, b from testClob");
    Clob clob;
    int clobLength;
    while (rs.next()) {
        // get the first column as a clob
        clob = rs.getClob(1);
        clobLength = rs.getInt(2);
        if (clob != null && clobLength != 0) {
            ps.setClob(1, clob);
            ps.setInt(2, clobLength);
            ps.executeUpdate();
        }
    }
    rs.close();
    rs = stmt.executeQuery("select a, b from testSetClob");
    Clob clob2;
    int clobLength2, nullClobs = 0;
    while (rs.next()) {
        clob2 = rs.getClob(1);
        clobLength2 = rs.getInt(2);
        assertFalse("FAIL - Clob is NULL", clob2 == null);
        assertEquals("FAIL - clob.length() != clobLength", clobLength2, clob2.length());
    }
    rs.close();
    stmt.executeUpdate("DROP TABLE testSetClob");
    stmt.close();
}

43. PreparedStatementTest#testSetClobLengthless()

Project: derby
File: PreparedStatementTest.java
/**
     * Insert <code>Clob</code> without specifying length and read it back
     * for verification.
     *
     * @throws IOException If an IOException during the close operation on the
     *                     reader.
     * @throws SQLException If an SQLException occurs.
     */
public void testSetClobLengthless() throws IOException, SQLException {
    // Life span of Clob objects are the transaction.  Need autocommit off
    // to have Clob objects survive execution of next statement.
    getConnection().setAutoCommit(false);
    //Create the Clob and insert data into it.
    Clob insertClob = getConnection().createClob();
    OutputStream os = insertClob.setAsciiStream(1);
    os.write(BYTES);
    //Insert the Clob created above into the
    //database.
    psInsertClob.setInt(1, key);
    psInsertClob.setClob(2, insertClob);
    psInsertClob.execute();
    // Read back test data from database.
    psFetchClob.setInt(1, key);
    ResultSet rs = psFetchClob.executeQuery();
    assertTrue("No results retrieved", rs.next());
    Clob clobRetrieved = rs.getClob(1);
    // Verify test data.
    assertEquals(insertClob, clobRetrieved);
}

44. PreparedStatementTest#testSetClob()

Project: derby
File: PreparedStatementTest.java
//-----------------------------------------------------------------------
// Begin test for setClob and setBlob
/*
       we need a table in which a Clob or a Blob can be stored. We basically
       need to write tests for the setClob and the setBlob methods. 
       Proper process would be
       a) Do a createClob or createBlob
       b) Populate data in the LOB
       c) Store in Database

       But the createClob and createBlob implementations are not 
       available on the EmbeddedServer. So instead the workaround adopted
       is 

       a) store a Clob or Blob in Database. 
       b) Retrieve it from the database.
       c) store it back using setClob or setBlob

     */
/**
     *
     * Test the setClob() method
     *
     * @throws SQLException if a failure occurs during the call to setClob
     *
     */
public void testSetClob() throws IOException, SQLException {
    // Life span of Clob objects are limited by the transaction.  Need
    // autocommit off so Clob objects survive execution of next statement.
    getConnection().setAutoCommit(false);
    //insert default values into the table
    String str = "Test data for the Clob object";
    StringReader is = new StringReader("Test data for the Clob object");
    is.reset();
    //initially insert the data
    psInsertClob.setInt(1, key);
    psInsertClob.setClob(2, is, str.length());
    psInsertClob.executeUpdate();
    //Now query to retrieve the Clob
    psFetchClob.setInt(1, key);
    ResultSet rs = psFetchClob.executeQuery();
    rs.next();
    Clob clobToBeInserted = rs.getClob(1);
    rs.close();
    //Now use the setClob method
    int secondKey = requestKey();
    psInsertClob.setInt(1, secondKey);
    psInsertClob.setClob(2, clobToBeInserted);
    psInsertClob.execute();
    psInsertClob.close();
    //Now test to see that the Clob has been stored correctly
    psFetchClob.setInt(1, secondKey);
    rs = psFetchClob.executeQuery();
    rs.next();
    Clob clobRetrieved = rs.getClob(1);
    assertEquals(clobToBeInserted, clobRetrieved);
}

45. TestClobTransformer#simple()

Project: lucene-solr
File: TestClobTransformer.java
@Test
public void simple() throws Exception {
    List<Map<String, String>> flds = new ArrayList<>();
    Map<String, String> f = new HashMap<>();
    // <field column="dsc" clob="true" name="description" />
    f.put(DataImporter.COLUMN, "dsc");
    f.put(ClobTransformer.CLOB, "true");
    f.put(DataImporter.NAME, "description");
    flds.add(f);
    Context ctx = getContext(null, new VariableResolver(), null, Context.FULL_DUMP, flds, Collections.EMPTY_MAP);
    Transformer t = new ClobTransformer();
    Map<String, Object> row = new HashMap<>();
    Clob clob = (Clob) Proxy.newProxyInstance(this.getClass().getClassLoader(), new Class[] { Clob.class }, new InvocationHandler() {

        @Override
        public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
            if (method.getName().equals("getCharacterStream")) {
                return new StringReader("hello!");
            }
            return null;
        }
    });
    row.put("dsc", clob);
    t.transformRow(row, ctx);
    assertEquals("hello!", row.get("dsc"));
}

46. TestResultSet#testInsertRowWithUpdatableResultSetDefault()

Project: ThriftyPaxos
File: TestResultSet.java
private void testInsertRowWithUpdatableResultSetDefault() throws Exception {
    stat.execute("create table test(id int primary key, " + "data varchar(255) default 'Hello')");
    PreparedStatement prep = conn.prepareStatement("select * from test", ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE);
    ResultSet rs = prep.executeQuery();
    rs.moveToInsertRow();
    rs.updateInt(1, 1);
    rs.insertRow();
    rs.close();
    rs = stat.executeQuery("select * from test");
    assertTrue(rs.next());
    assertEquals("Hello", rs.getString(2));
    assertEquals("Hello", rs.getString("data"));
    assertEquals("Hello", rs.getNString(2));
    assertEquals("Hello", rs.getNString("data"));
    assertEquals("Hello", IOUtils.readStringAndClose(rs.getNCharacterStream(2), -1));
    assertEquals("Hello", IOUtils.readStringAndClose(rs.getNCharacterStream("data"), -1));
    assertEquals("Hello", IOUtils.readStringAndClose(rs.getNClob(2).getCharacterStream(), -1));
    assertEquals("Hello", IOUtils.readStringAndClose(rs.getNClob("data").getCharacterStream(), -1));
    rs = prep.executeQuery();
    rs.moveToInsertRow();
    rs.updateInt(1, 2);
    rs.updateNString(2, "Hello");
    rs.insertRow();
    rs.moveToInsertRow();
    rs.updateInt(1, 3);
    rs.updateNString("data", "Hello");
    rs.insertRow();
    Clob c;
    Writer w;
    rs.moveToInsertRow();
    rs.updateInt(1, 4);
    c = conn.createClob();
    w = c.setCharacterStream(1);
    w.write("Hello");
    w.close();
    rs.updateClob(2, c);
    rs.insertRow();
    rs.moveToInsertRow();
    rs.updateInt(1, 5);
    c = conn.createClob();
    w = c.setCharacterStream(1);
    w.write("Hello");
    w.close();
    rs.updateClob("data", c);
    rs.insertRow();
    InputStream in;
    rs.moveToInsertRow();
    rs.updateInt(1, 6);
    in = new ByteArrayInputStream("Hello".getBytes("UTF-8"));
    rs.updateAsciiStream(2, in);
    rs.insertRow();
    rs.moveToInsertRow();
    rs.updateInt(1, 7);
    in = new ByteArrayInputStream("Hello".getBytes("UTF-8"));
    rs.updateAsciiStream("data", in);
    rs.insertRow();
    rs.moveToInsertRow();
    rs.updateInt(1, 8);
    in = new ByteArrayInputStream("Hello-".getBytes("UTF-8"));
    rs.updateAsciiStream(2, in, 5);
    rs.insertRow();
    rs.moveToInsertRow();
    rs.updateInt(1, 9);
    in = new ByteArrayInputStream("Hello-".getBytes("UTF-8"));
    rs.updateAsciiStream("data", in, 5);
    rs.insertRow();
    rs.moveToInsertRow();
    rs.updateInt(1, 10);
    in = new ByteArrayInputStream("Hello-".getBytes("UTF-8"));
    rs.updateAsciiStream(2, in, 5L);
    rs.insertRow();
    rs.moveToInsertRow();
    rs.updateInt(1, 11);
    in = new ByteArrayInputStream("Hello-".getBytes("UTF-8"));
    rs.updateAsciiStream("data", in, 5L);
    rs.insertRow();
    rs = stat.executeQuery("select * from test");
    while (rs.next()) {
        assertEquals("Hello", rs.getString(2));
    }
    stat.execute("drop table test");
}

47. TestLob#testClob()

Project: ThriftyPaxos
File: TestLob.java
private void testClob() throws Exception {
    deleteDb("lob");
    Connection conn;
    conn = reconnect(null);
    conn.createStatement().execute("CREATE TABLE TEST(ID IDENTITY, C CLOB)");
    PreparedStatement prep = conn.prepareStatement("INSERT INTO TEST(C) VALUES(?)");
    prep.setCharacterStream(1, new CharArrayReader("Bohlen".toCharArray()), "Bohlen".length());
    prep.execute();
    prep.setCharacterStream(1, new CharArrayReader("Böhlen".toCharArray()), "Böhlen".length());
    prep.execute();
    prep.setCharacterStream(1, getRandomReader(501, 1), -1);
    prep.execute();
    prep.setCharacterStream(1, getRandomReader(1501, 2), 401);
    prep.execute();
    conn = reconnect(conn);
    ResultSet rs = conn.createStatement().executeQuery("SELECT * FROM TEST ORDER BY ID");
    rs.next();
    assertEquals("Bohlen", rs.getString("C"));
    assertEqualReaders(new CharArrayReader("Bohlen".toCharArray()), rs.getCharacterStream("C"), -1);
    rs.next();
    assertEqualReaders(new CharArrayReader("Böhlen".toCharArray()), rs.getCharacterStream("C"), -1);
    rs.next();
    assertEqualReaders(getRandomReader(501, 1), rs.getCharacterStream("C"), -1);
    Clob clob = rs.getClob("C");
    assertEqualReaders(getRandomReader(501, 1), clob.getCharacterStream(), -1);
    assertEquals(501, clob.length());
    rs.next();
    assertEqualReaders(getRandomReader(401, 2), rs.getCharacterStream("C"), -1);
    assertEqualReaders(getRandomReader(1500, 2), rs.getCharacterStream("C"), 401);
    clob = rs.getClob("C");
    assertEqualReaders(getRandomReader(1501, 2), clob.getCharacterStream(), 401);
    assertEqualReaders(getRandomReader(401, 2), clob.getCharacterStream(), 401);
    assertEquals(401, clob.length());
    assertFalse(rs.next());
    conn.close();
}

48. TestLob#testLobHibernate()

Project: ThriftyPaxos
File: TestLob.java
private void testLobHibernate() throws Exception {
    deleteDb("lob");
    Connection conn0 = reconnect(null);
    conn0.getAutoCommit();
    conn0.setAutoCommit(false);
    DatabaseMetaData dbMeta0 = conn0.getMetaData();
    dbMeta0.getDatabaseProductName();
    dbMeta0.getDatabaseMajorVersion();
    dbMeta0.getDatabaseProductVersion();
    dbMeta0.getDriverName();
    dbMeta0.getDriverVersion();
    dbMeta0.supportsResultSetType(1004);
    dbMeta0.supportsBatchUpdates();
    dbMeta0.dataDefinitionCausesTransactionCommit();
    dbMeta0.dataDefinitionIgnoredInTransactions();
    dbMeta0.supportsGetGeneratedKeys();
    conn0.getAutoCommit();
    conn0.getAutoCommit();
    conn0.commit();
    conn0.setAutoCommit(true);
    Statement stat0 = conn0.createStatement();
    stat0.executeUpdate("drop table CLOB_ENTITY if exists");
    stat0.getWarnings();
    stat0.executeUpdate("create table CLOB_ENTITY (ID bigint not null, " + "DATA clob, CLOB_DATA clob, primary key (ID))");
    stat0.getWarnings();
    stat0.close();
    conn0.getWarnings();
    conn0.clearWarnings();
    conn0.setAutoCommit(false);
    conn0.getAutoCommit();
    conn0.getAutoCommit();
    PreparedStatement prep0 = conn0.prepareStatement("select max(ID) from CLOB_ENTITY");
    ResultSet rs0 = prep0.executeQuery();
    rs0.next();
    rs0.getLong(1);
    rs0.wasNull();
    rs0.close();
    prep0.close();
    conn0.getAutoCommit();
    PreparedStatement prep1 = conn0.prepareStatement("insert into CLOB_ENTITY" + "(DATA, CLOB_DATA, ID) values (?, ?, ?)");
    prep1.setNull(1, 2005);
    StringBuilder buff = new StringBuilder(10000);
    for (int i = 0; i < 10000; i++) {
        buff.append((char) ('0' + (i % 10)));
    }
    Reader x = new StringReader(buff.toString());
    prep1.setCharacterStream(2, x, 10000);
    prep1.setLong(3, 1);
    prep1.addBatch();
    prep1.executeBatch();
    prep1.close();
    conn0.getAutoCommit();
    conn0.getAutoCommit();
    conn0.commit();
    conn0.isClosed();
    conn0.getWarnings();
    conn0.clearWarnings();
    conn0.getAutoCommit();
    conn0.getAutoCommit();
    PreparedStatement prep2 = conn0.prepareStatement("select c_.ID as ID0_0_, c_.DATA as S_, " + "c_.CLOB_DATA as CLOB3_0_0_ from CLOB_ENTITY c_ where c_.ID=?");
    prep2.setLong(1, 1);
    ResultSet rs1 = prep2.executeQuery();
    rs1.next();
    rs1.getCharacterStream("S_");
    Clob clob0 = rs1.getClob("CLOB3_0_0_");
    rs1.wasNull();
    rs1.next();
    rs1.close();
    prep2.getMaxRows();
    prep2.getQueryTimeout();
    prep2.close();
    conn0.getAutoCommit();
    Reader r = clob0.getCharacterStream();
    for (int i = 0; i < 10000; i++) {
        int ch = r.read();
        if (ch != ('0' + (i % 10))) {
            fail("expected " + (char) ('0' + (i % 10)) + " got: " + ch + " (" + (char) ch + ")");
        }
    }
    int ch = r.read();
    if (ch != -1) {
        fail("expected -1 got: " + ch);
    }
    conn0.close();
}

49. SimpleResultSet#getClob()

Project: ThriftyPaxos
File: SimpleResultSet.java
/**
     * Returns the value as a java.sql.Clob.
     * This is only supported if the
     * result set was created using a Clob object.
     *
     * @param columnIndex (1,2,...)
     * @return the value
     */
@Override
public Clob getClob(int columnIndex) throws SQLException {
    Clob c = (Clob) get(columnIndex);
    return c == null ? null : c;
}

50. LargeObjectLoader#readClobRef()

Project: sqoop
File: LargeObjectLoader.java
/**
   * Actually read a ClobRef instance from the ResultSet and materialize
   * the data either inline or to a file.
   *
   * @param colNum the column of the ResultSet's current row to read.
   * @param r the ResultSet to read from.
   * @return a ClobRef encapsulating the data in this field.
   * @throws IOException if an error occurs writing to the FileSystem.
   * @throws SQLException if an error occurs reading from the database.
   */
public com.cloudera.sqoop.lib.ClobRef readClobRef(int colNum, ResultSet r) throws IOException, InterruptedException, SQLException {
    long maxInlineLobLen = conf.getLong(MAX_INLINE_LOB_LEN_KEY, DEFAULT_MAX_LOB_LENGTH);
    Clob c = r.getClob(colNum);
    if (null == c) {
        return null;
    } else if (c.length() > maxInlineLobLen) {
        // Deserialize large CLOB into separate file.
        long len = c.length();
        LobFile.Writer lobWriter = getClobWriter();
        long recordOffset = lobWriter.tell();
        Reader reader = null;
        Writer w = lobWriter.writeClobRecord(len);
        try {
            reader = c.getCharacterStream();
            copyAll(reader, w);
        } finally {
            if (null != w) {
                w.close();
            }
            if (null != reader) {
                reader.close();
            }
            // Mark the record as finished.
            lobWriter.finishRecord();
        }
        return new com.cloudera.sqoop.lib.ClobRef(getRelativePath(lobWriter), recordOffset, len);
    } else {
        // This is a 1-based array.
        return new com.cloudera.sqoop.lib.ClobRef(c.getSubString(1, (int) c.length()));
    }
}

51. UtilTest#testMapObjectExistingClob()

Project: rxjava-jdbc
File: UtilTest.java
@Test
public void testMapObjectExistingClob() throws SQLException, IOException {
    final Clob mock = Mockito.mock(Clob.class);
    Mockito.when(mock.getCharacterStream()).thenAnswer(new Answer<Reader>() {

        @Override
        public Reader answer(InvocationOnMock invocationOnMock) throws Throwable {
            return new StringReader("test");
        }
    });
    final ResultSetMetaData metaData = Mockito.mock(ResultSetMetaData.class);
    Mockito.when(metaData.getColumnType(1)).thenAnswer(new Answer<Integer>() {

        @Override
        public Integer answer(InvocationOnMock invocationOnMock) throws Throwable {
            return Types.CLOB;
        }
    });
    ResultSet resultSet = Mockito.mock(ResultSet.class);
    Mockito.when(resultSet.getObject(1)).thenAnswer(new Answer<Clob>() {

        @Override
        public Clob answer(InvocationOnMock invocationOnMock) throws Throwable {
            return mock;
        }
    });
    Mockito.when(resultSet.getClob(1)).thenAnswer(new Answer<Clob>() {

        @Override
        public Clob answer(InvocationOnMock invocationOnMock) throws Throwable {
            return mock;
        }
    });
    Mockito.when(resultSet.getMetaData()).thenAnswer(new Answer<ResultSetMetaData>() {

        @Override
        public ResultSetMetaData answer(InvocationOnMock invocationOnMock) throws Throwable {
            return metaData;
        }
    });
    assertEquals(Util.mapObject(resultSet, String.class, 1), "test");
}

52. UtilTest#testAutoMapClobToSimple()

Project: rxjava-jdbc
File: UtilTest.java
@Test
public void testAutoMapClobToSimple() throws SQLException {
    Clob clob = EasyMock.createMock(Clob.class);
    replay(clob);
    Object result = autoMap(clob, Simple.class);
    assertEquals(clob, result);
    verify(clob);
}

53. BlobTest#readWriteClobStream()

Project: pgjdbc-ng
File: BlobTest.java
/**
   * Reads then writes data to the clob via a stream.
   *
   * @param offset
   * @param data
   * @throws SQLException
   * @throws IOException
   */
private void readWriteClobStream(int offset, String data) throws SQLException, IOException {
    PreparedStatement ps = conn.prepareStatement("INSERT INTO blobtest VALUES (1, lo_creat(-1))");
    ps.executeUpdate();
    ps.close();
    ps = conn.prepareStatement("SELECT ID, DATA FROM blobtest WHERE ID = 1");
    ResultSet rs = ps.executeQuery();
    assertTrue(rs.next());
    Clob c = rs.getClob("DATA");
    Writer out = c.setCharacterStream(offset);
    out.write(data);
    out.flush();
    out.close();
    rs.close();
    ps.close();
    ps = conn.prepareStatement("SELECT ID, DATA FROM blobtest WHERE ID = 1");
    rs = ps.executeQuery();
    assertTrue(rs.next());
    c = rs.getClob("DATA");
    Reader in = c.getCharacterStream();
    char[] rspData = new char[data.length()];
    in.skip(offset - 1);
    in.read(rspData);
    in.close();
    assertEquals("Request should be the same as the response", data, new String(rspData));
    rs.close();
    ps.close();
}

54. BlobTest#testParallelStreamsClob()

Project: pgjdbc-ng
File: BlobTest.java
@Test
public void testParallelStreamsClob() throws Exception {
    assertTrue(uploadFileClob("pom.xml") > 0);
    Statement stmt = conn.createStatement();
    ResultSet rs = stmt.executeQuery("SELECT lo FROM testblob");
    assertTrue(rs.next());
    Clob lob = rs.getClob(1);
    Reader is1 = lob.getCharacterStream();
    Reader is2 = lob.getCharacterStream();
    while (true) {
        int i1 = is1.read();
        int i2 = is2.read();
        assertEquals(i1, i2);
        if (i1 == -1)
            break;
    }
    is1.close();
    is2.close();
    rs.close();
    stmt.close();
}

55. BlobTest#testMultipleStreamsClob()

Project: pgjdbc-ng
File: BlobTest.java
@Test
public void testMultipleStreamsClob() throws Exception {
    assertTrue(uploadFileClob("pom.xml") > 0);
    Statement stmt = conn.createStatement();
    ResultSet rs = stmt.executeQuery("SELECT lo FROM testblob");
    assertTrue(rs.next());
    Clob lob = rs.getClob(1);
    char[] data = new char[2];
    Reader r = lob.getCharacterStream();
    assertEquals(data.length, r.read(data));
    assertEquals(data[0], '<');
    assertEquals(data[1], '!');
    r.close();
    r = lob.getCharacterStream();
    assertEquals(data.length, r.read(data));
    assertEquals(data[0], '<');
    assertEquals(data[1], '!');
    r.close();
    rs.close();
    stmt.close();
}

56. BlobTest#testSet()

Project: pgjdbc-ng
File: BlobTest.java
@Test
public void testSet() throws SQLException {
    Statement stmt = conn.createStatement();
    stmt.execute("INSERT INTO testblob(id,lo) VALUES ('1', lo_creat(-1))");
    ResultSet rs = stmt.executeQuery("SELECT lo FROM testblob");
    assertTrue(rs.next());
    PreparedStatement pstmt = conn.prepareStatement("INSERT INTO testblob(id, lo) VALUES(?,?)");
    Blob blob = rs.getBlob(1);
    pstmt.setString(1, "setObjectTypeBlob");
    pstmt.setObject(2, blob, Types.BLOB);
    assertEquals(1, pstmt.executeUpdate());
    blob = rs.getBlob(1);
    pstmt.setString(1, "setObjectBlob");
    pstmt.setObject(2, blob);
    assertEquals(1, pstmt.executeUpdate());
    blob = rs.getBlob(1);
    pstmt.setString(1, "setBlob");
    pstmt.setBlob(2, blob);
    assertEquals(1, pstmt.executeUpdate());
    Clob clob = rs.getClob(1);
    pstmt.setString(1, "setObjectTypeClob");
    pstmt.setObject(2, clob, Types.CLOB);
    assertEquals(1, pstmt.executeUpdate());
    clob = rs.getClob(1);
    pstmt.setString(1, "setObjectClob");
    pstmt.setObject(2, clob);
    assertEquals(1, pstmt.executeUpdate());
    clob = rs.getClob(1);
    pstmt.setString(1, "setClob");
    pstmt.setClob(2, clob);
    assertEquals(1, pstmt.executeUpdate());
    rs.close();
    stmt.close();
    pstmt.close();
}

57. BlobTest#testSet()

Project: pgjdbc
File: BlobTest.java
public void testSet() throws SQLException {
    Statement stmt = con.createStatement();
    stmt.execute("INSERT INTO testblob(id,lo) VALUES ('1', lo_creat(-1))");
    ResultSet rs = stmt.executeQuery("SELECT lo FROM testblob");
    assertTrue(rs.next());
    PreparedStatement pstmt = con.prepareStatement("INSERT INTO testblob(id, lo) VALUES(?,?)");
    Blob blob = rs.getBlob(1);
    pstmt.setString(1, "setObjectTypeBlob");
    pstmt.setObject(2, blob, Types.BLOB);
    assertEquals(1, pstmt.executeUpdate());
    blob = rs.getBlob(1);
    pstmt.setString(1, "setObjectBlob");
    pstmt.setObject(2, blob);
    assertEquals(1, pstmt.executeUpdate());
    blob = rs.getBlob(1);
    pstmt.setString(1, "setBlob");
    pstmt.setBlob(2, blob);
    assertEquals(1, pstmt.executeUpdate());
    Clob clob = rs.getClob(1);
    pstmt.setString(1, "setObjectTypeClob");
    pstmt.setObject(2, clob, Types.CLOB);
    assertEquals(1, pstmt.executeUpdate());
    clob = rs.getClob(1);
    pstmt.setString(1, "setObjectClob");
    pstmt.setObject(2, clob);
    assertEquals(1, pstmt.executeUpdate());
    clob = rs.getClob(1);
    pstmt.setString(1, "setClob");
    pstmt.setClob(2, clob);
    assertEquals(1, pstmt.executeUpdate());
}

58. SQLOutputImplTests#test06()

Project: openjdk
File: SQLOutputImplTests.java
/*
     * Validate a Clob can be written and returned
     */
@Test(enabled = true)
public void test06() throws Exception {
    Clob c = new StubClob();
    outImpl.writeClob(c);
    SerialClob sc = (SerialClob) results.get(0);
    assertTrue(c.getSubString(1, (int) c.length()).equals(sc.getSubString(1, (int) sc.length())));
}

59. BaseRowSetTests#testAdvancedParameters()

Project: openjdk
File: BaseRowSetTests.java
/*
     * DataProvider used to set advanced parameters for types that are supported
     */
@DataProvider(name = "testAdvancedParameters")
private Object[][] testAdvancedParameters() throws SQLException {
    byte[] bytes = new byte[10];
    Ref aRef = new SerialRef(new StubRef("INTEGER", query));
    Array aArray = new SerialArray(new StubArray("INTEGER", new Object[1]));
    Blob aBlob = new SerialBlob(new StubBlob());
    Clob aClob = new SerialClob(new StubClob());
    Reader rdr = new StringReader(query);
    InputStream is = new StringBufferInputStream(query);
    ;
    brs = new StubBaseRowSet();
    brs.setBytes(1, bytes);
    brs.setAsciiStream(2, is, query.length());
    brs.setRef(3, aRef);
    brs.setArray(4, aArray);
    brs.setBlob(5, aBlob);
    brs.setClob(6, aClob);
    brs.setBinaryStream(7, is, query.length());
    brs.setUnicodeStream(8, is, query.length());
    brs.setCharacterStream(9, rdr, query.length());
    return new Object[][] { { 1, bytes }, { 2, is }, { 3, aRef }, { 4, aArray }, { 5, aBlob }, { 6, aClob }, { 7, is }, { 8, is }, { 9, rdr } };
}

60. ProfileService#getProfileFromResultSet()

Project: odo
File: ProfileService.java
/**
     * Creates a Profile object from a SQL resultset
     *
     * @param result resultset containing the profile
     * @return Profile
     * @throws Exception exception
     */
private Profile getProfileFromResultSet(ResultSet result) throws Exception {
    Profile profile = new Profile();
    profile.setId(result.getInt(Constants.GENERIC_ID));
    Clob clobProfileName = result.getClob(Constants.PROFILE_PROFILE_NAME);
    String profileName = clobProfileName.getSubString(1, (int) clobProfileName.length());
    profile.setName(profileName);
    return profile;
}

61. ClobValueAdaptor#get()

Project: nutz
File: ClobValueAdaptor.java
public Object get(ResultSet rs, String colName) throws SQLException {
    Clob clob = rs.getClob(colName);
    if (clob == null)
        return null;
    File f = this.createTempFile();
    Streams.writeAndClose(Streams.fileOutw(f), clob.getCharacterStream());
    return new SimpleClob(f);
}

62. NClobTypeHandler#getNullableResult()

Project: mybatis-3
File: NClobTypeHandler.java
@Override
public String getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
    String value = "";
    Clob clob = cs.getClob(columnIndex);
    if (clob != null) {
        int size = (int) clob.length();
        value = clob.getSubString(1, size);
    }
    return value;
}

63. NClobTypeHandler#getNullableResult()

Project: mybatis-3
File: NClobTypeHandler.java
@Override
public String getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
    String value = "";
    Clob clob = rs.getClob(columnIndex);
    if (clob != null) {
        int size = (int) clob.length();
        value = clob.getSubString(1, size);
    }
    return value;
}

64. NClobTypeHandler#getNullableResult()

Project: mybatis-3
File: NClobTypeHandler.java
@Override
public String getNullableResult(ResultSet rs, String columnName) throws SQLException {
    String value = "";
    Clob clob = rs.getClob(columnName);
    if (clob != null) {
        int size = (int) clob.length();
        value = clob.getSubString(1, size);
    }
    return value;
}

65. ClobTypeHandler#getNullableResult()

Project: mybatis-3
File: ClobTypeHandler.java
@Override
public String getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
    String value = "";
    Clob clob = cs.getClob(columnIndex);
    if (clob != null) {
        int size = (int) clob.length();
        value = clob.getSubString(1, size);
    }
    return value;
}

66. ClobTypeHandler#getNullableResult()

Project: mybatis-3
File: ClobTypeHandler.java
@Override
public String getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
    String value = "";
    Clob clob = rs.getClob(columnIndex);
    if (clob != null) {
        int size = (int) clob.length();
        value = clob.getSubString(1, size);
    }
    return value;
}

67. ClobTypeHandler#getNullableResult()

Project: mybatis-3
File: ClobTypeHandler.java
@Override
public String getNullableResult(ResultSet rs, String columnName) throws SQLException {
    String value = "";
    Clob clob = rs.getClob(columnName);
    if (clob != null) {
        int size = (int) clob.length();
        value = clob.getSubString(1, size);
    }
    return value;
}

68. NClobTypeHandler#getNullableResult()

Project: mybatis
File: NClobTypeHandler.java
@Override
public String getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
    String value = "";
    Clob clob = cs.getClob(columnIndex);
    if (clob != null) {
        int size = (int) clob.length();
        value = clob.getSubString(1, size);
    }
    return value;
}

69. NClobTypeHandler#getNullableResult()

Project: mybatis
File: NClobTypeHandler.java
@Override
public String getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
    String value = "";
    Clob clob = rs.getClob(columnIndex);
    if (clob != null) {
        int size = (int) clob.length();
        value = clob.getSubString(1, size);
    }
    return value;
}

70. NClobTypeHandler#getNullableResult()

Project: mybatis
File: NClobTypeHandler.java
@Override
public String getNullableResult(ResultSet rs, String columnName) throws SQLException {
    String value = "";
    Clob clob = rs.getClob(columnName);
    if (clob != null) {
        int size = (int) clob.length();
        value = clob.getSubString(1, size);
    }
    return value;
}

71. ClobTypeHandler#getNullableResult()

Project: mybatis
File: ClobTypeHandler.java
@Override
public String getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
    String value = "";
    Clob clob = cs.getClob(columnIndex);
    if (clob != null) {
        int size = (int) clob.length();
        value = clob.getSubString(1, size);
    }
    return value;
}

72. ClobTypeHandler#getNullableResult()

Project: mybatis
File: ClobTypeHandler.java
@Override
public String getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
    String value = "";
    Clob clob = rs.getClob(columnIndex);
    if (clob != null) {
        int size = (int) clob.length();
        value = clob.getSubString(1, size);
    }
    return value;
}

73. ClobTypeHandler#getNullableResult()

Project: mybatis
File: ClobTypeHandler.java
@Override
public String getNullableResult(ResultSet rs, String columnName) throws SQLException {
    String value = "";
    Clob clob = rs.getClob(columnName);
    if (clob != null) {
        int size = (int) clob.length();
        value = clob.getSubString(1, size);
    }
    return value;
}

74. OracleLobHandler#getClobAsCharacterStream()

Project: effectivejava
File: OracleLobHandler.java
@Override
public Reader getClobAsCharacterStream(ResultSet rs, int columnIndex) throws SQLException {
    logger.debug("Returning Oracle CLOB as character stream");
    Clob clob = rs.getClob(columnIndex);
    initializeResourcesBeforeRead(rs.getStatement().getConnection(), clob);
    Reader retVal = (clob != null ? clob.getCharacterStream() : null);
    releaseResourcesAfterRead(rs.getStatement().getConnection(), clob);
    return retVal;
}

75. OracleLobHandler#getClobAsAsciiStream()

Project: effectivejava
File: OracleLobHandler.java
@Override
public InputStream getClobAsAsciiStream(ResultSet rs, int columnIndex) throws SQLException {
    logger.debug("Returning Oracle CLOB as ASCII stream");
    Clob clob = rs.getClob(columnIndex);
    initializeResourcesBeforeRead(rs.getStatement().getConnection(), clob);
    InputStream retVal = (clob != null ? clob.getAsciiStream() : null);
    releaseResourcesAfterRead(rs.getStatement().getConnection(), clob);
    return retVal;
}

76. OracleLobHandler#getClobAsString()

Project: effectivejava
File: OracleLobHandler.java
@Override
public String getClobAsString(ResultSet rs, int columnIndex) throws SQLException {
    logger.debug("Returning Oracle CLOB as string");
    Clob clob = rs.getClob(columnIndex);
    initializeResourcesBeforeRead(rs.getStatement().getConnection(), clob);
    String retVal = (clob != null ? clob.getSubString(1, (int) clob.length()) : null);
    releaseResourcesAfterRead(rs.getStatement().getConnection(), clob);
    return retVal;
}

77. UpdatableResultSetTest#testUpdateClobStringParameterName()

Project: derby
File: UpdatableResultSetTest.java
/**
     * This methods tests the ResultSet interface method
     * updateClob
     *
     * @throws Exception
     */
public void testUpdateClobStringParameterName() throws Exception {
    //Byte array in which the returned bytes from
    //the Database after the update are stored. This
    //array is then checked to determine if it
    //has the same elements of the Byte array used for
    //the update operation
    byte[] bytes_ret = new byte[10];
    //1 Input Stream for insertion
    InputStream is1 = new java.io.ByteArrayInputStream(BYTES1);
    //2 Input Stream for insertion
    InputStream is2 = new java.io.ByteArrayInputStream(BYTES2);
    //Prepared Statement used to insert the data
    PreparedStatement ps_sb = prep("dClob");
    //first insert
    ps_sb.setInt(1, key);
    ps_sb.setAsciiStream(2, is1, BYTES1.length);
    ps_sb.executeUpdate();
    //second insert
    int key2 = requestKey();
    ps_sb.setInt(1, key2);
    ps_sb.setAsciiStream(2, is2, BYTES2.length);
    ps_sb.executeUpdate();
    ps_sb.close();
    //Update operation
    //use a different ResultSet variable so that the
    //other tests can go on unimpacted
    //we do not have set methods on Clob and Blob implemented
    //So query the first Clob from the database
    //update the second result set with this
    //Clob value
    ResultSet rs1 = fetch("dClob", key);
    rs1.next();
    Clob clob = rs1.getClob(1);
    rs1.close();
    rs1 = fetchUpd("dClob", key2);
    rs1.next();
    rs1.updateClob("dClob", clob);
    rs1.updateRow();
    rs1.close();
    //Query to see whether the data that has been updated
    //using the updateClob method is the same
    //data that we expected
    rs1 = fetch("dClob", key2);
    rs1.next();
    assertEquals(clob, rs1.getClob(1));
    rs1.close();
}

78. UpdatableResultSetTest#testUpdateClob()

Project: derby
File: UpdatableResultSetTest.java
/**
     * This methods tests the ResultSet interface method
     * updateClob
     *
     * @throws Exception
     */
public void testUpdateClob() throws Exception {
    //Byte array in which the returned bytes from
    //the Database after the update are stored. This
    //array is then checked to determine if it
    //has the same elements of the Byte array used for
    //the update operation
    byte[] bytes_ret = new byte[10];
    //1 Input Stream for insertion
    InputStream is1 = new java.io.ByteArrayInputStream(BYTES1);
    //2 Input Stream for insertion
    InputStream is2 = new java.io.ByteArrayInputStream(BYTES2);
    //Prepared Statement used to insert the data
    PreparedStatement ps_sb = prep("dClob");
    //first insert
    ps_sb.setInt(1, key);
    ps_sb.setAsciiStream(2, is1, BYTES1.length);
    ps_sb.executeUpdate();
    //second insert
    int key2 = requestKey();
    ps_sb.setInt(1, key2);
    ps_sb.setAsciiStream(2, is2, BYTES2.length);
    ps_sb.executeUpdate();
    ps_sb.close();
    //Update operation
    //use a different ResultSet variable so that the
    //other tests can go on unimpacted
    //we do not have set methods on Clob and Blob implemented
    //So query the first Clob from the database
    //update the second result set with this
    //Clob value
    ResultSet rs1 = fetchUpd("dClob", key);
    rs1.next();
    Clob clob = rs1.getClob(1);
    rs1.close();
    rs1 = fetchUpd("dClob", key2);
    rs1.next();
    rs1.updateClob(1, clob);
    rs1.updateRow();
    rs1.close();
    //Query to see whether the data that has been updated
    //using the updateClob method is the same
    //data that we expected
    rs1 = fetch("dClob", key2);
    rs1.next();
    assertEquals(clob, rs1.getClob(1));
    rs1.close();
}

79. LobStreamsTest#testClobCharacterWrite1Char()

Project: derby
File: LobStreamsTest.java
/**
     * Tests the ClobWriter.write(int c) method
     **/
public void testClobCharacterWrite1Char() throws Exception {
    char testchar = 'a';
    PreparedStatement stmt3 = prepareStatement("SELECT c FROM testBlobX1 WHERE a = 1");
    ResultSet rs3 = stmt3.executeQuery();
    rs3.next();
    Clob clob = rs3.getClob(1);
    assertTrue("FAIL -- clob is NULL", clob != null);
    Writer clobWriter = clob.setCharacterStream(1L);
    clobWriter.write(testchar);
    clobWriter.close();
    PreparedStatement stmt4 = prepareStatement("UPDATE testBlobX1 SET c = ? WHERE a = 1");
    stmt4.setClob(1, clob);
    stmt4.executeUpdate();
    stmt4.close();
    rs3.close();
    rs3 = stmt3.executeQuery();
    assertTrue("FAIL -- clob not found", rs3.next());
    clob = rs3.getClob(1);
    long new_length = clob.length();
    assertEquals("FAIL -- wrong clob length", 1, new_length);
    // Check contents ...
    Reader lStream = clob.getCharacterStream();
    char clobchar = (char) lStream.read();
    assertEquals("FAIL - fetched Clob and original contents do " + "not match", testchar, clobchar);
    lStream.close();
    rs3.close();
    stmt3.close();
}

80. LobStreamsTest#testClobCharacterWrite1ParamString()

Project: derby
File: LobStreamsTest.java
/**
     * Tests the ClobWriter.write(String str) method
     **/
public void testClobCharacterWrite1ParamString() throws Exception {
    PreparedStatement stmt3 = prepareStatement("SELECT c FROM testBlobX1 WHERE a = 1");
    ResultSet rs3 = stmt3.executeQuery();
    rs3.next();
    Clob clob = rs3.getClob(1);
    assertTrue("FAIL -- clob is NULL", clob != null);
    Writer clobWriter = clob.setCharacterStream(1L);
    clobWriter.write(unicodeTestString);
    clobWriter.close();
    PreparedStatement stmt4 = prepareStatement("UPDATE testBlobX1 SET c = ? WHERE a = 1");
    stmt4.setClob(1, clob);
    stmt4.executeUpdate();
    stmt4.close();
    rs3.close();
    rs3 = stmt3.executeQuery();
    assertTrue("FAIL -- clob not found", rs3.next());
    clob = rs3.getClob(1);
    long new_length = clob.length();
    assertEquals("FAIL -- wrong clob length", unicodeTestString.length(), new_length);
    // Check contents ...
    Reader lStream = clob.getCharacterStream();
    assertTrue("FAIL - Clob and buffer contents do not match", compareClobReader2CharArray(unicodeTestString.toCharArray(), lStream));
    lStream.close();
    rs3.close();
    stmt3.close();
}

81. LobStreamsTest#testClobCharacterWrite3ParamString()

Project: derby
File: LobStreamsTest.java
/**
     * Tests the ClobWriter.write(String str, int off, int len) method
     **/
public void testClobCharacterWrite3ParamString() throws Exception {
    PreparedStatement stmt3 = prepareStatement("SELECT c FROM testBlobX1 WHERE a = 1");
    ResultSet rs3 = stmt3.executeQuery();
    rs3.next();
    Clob clob = rs3.getClob(1);
    assertTrue("FAIL -- clob is NULL", clob != null);
    Writer clobWriter = clob.setCharacterStream(1L);
    clobWriter.write(unicodeTestString, 0, unicodeTestString.length());
    clobWriter.close();
    PreparedStatement stmt4 = prepareStatement("UPDATE testBlobX1 SET c = ? WHERE a = 1");
    stmt4.setClob(1, clob);
    stmt4.executeUpdate();
    stmt4.close();
    rs3.close();
    rs3 = stmt3.executeQuery();
    assertTrue("FAIL -- clob not found", rs3.next());
    clob = rs3.getClob(1);
    long new_length = clob.length();
    assertEquals("FAIL -- wrong clob length", unicodeTestString.length(), new_length);
    // Check contents ...
    Reader lStream = clob.getCharacterStream();
    assertTrue("FAIL - Clob and buffer contents do not match", compareClobReader2CharArray(unicodeTestString.toCharArray(), lStream));
    lStream.close();
    rs3.close();
    stmt3.close();
}

82. LobStreamsTest#testClobCharacterWrite3ParamChar()

Project: derby
File: LobStreamsTest.java
/**
     * Tests the ClobWriter.write(char cbuf[], int off, int len) method
     **/
public void testClobCharacterWrite3ParamChar() throws Exception {
    char[] testdata = unicodeTestString.toCharArray();
    PreparedStatement stmt3 = prepareStatement("SELECT c FROM testBlobX1 WHERE a = 1");
    ResultSet rs3 = stmt3.executeQuery();
    rs3.next();
    Clob clob = rs3.getClob(1);
    assertTrue("FAIL -- clob is NULL", clob != null);
    Writer clobWriter = clob.setCharacterStream(1L);
    clobWriter.write(testdata, 0, testdata.length);
    clobWriter.close();
    PreparedStatement stmt4 = prepareStatement("UPDATE testBlobX1 SET c = ? WHERE a = 1");
    stmt4.setClob(1, clob);
    stmt4.executeUpdate();
    stmt4.close();
    rs3.close();
    rs3 = stmt3.executeQuery();
    assertTrue("FAIL -- clob not found", rs3.next());
    clob = rs3.getClob(1);
    long new_length = clob.length();
    assertEquals("FAIL -- wrong clob length", testdata.length, new_length);
    // Check contents ...
    Reader lStream = clob.getCharacterStream();
    assertTrue("FAIL - Clob and buffer contents do not match", compareClobReader2CharArray(testdata, lStream));
    lStream.close();
    rs3.close();
    stmt3.close();
}

83. LobStreamsTest#testClobAsciiWrite3Param()

Project: derby
File: LobStreamsTest.java
/**
     * Tests the ClobOutputStream.write(byte  b[], int off, int len) method
     **/
public void testClobAsciiWrite3Param() throws Exception {
    InputStream streamIn = new LoopingAlphabetStream(streamSize[0]);
    assertTrue("FAIL -- file not found", streamIn != null);
    PreparedStatement stmt3 = prepareStatement("SELECT c FROM testBlobX1 WHERE a = 1");
    ResultSet rs3 = stmt3.executeQuery();
    rs3.next();
    Clob clob = rs3.getClob(1);
    assertTrue("FAIL -- clob is NULL", clob != null);
    int count = 0;
    byte[] buffer = new byte[1024];
    OutputStream outstream = clob.setAsciiStream(1L);
    while ((count = streamIn.read(buffer)) != -1) {
        outstream.write(buffer, 0, count);
    }
    outstream.close();
    streamIn.close();
    PreparedStatement stmt4 = prepareStatement("UPDATE testBlobX1 SET c = ? WHERE a = 1");
    stmt4.setClob(1, clob);
    stmt4.executeUpdate();
    stmt4.close();
    rs3.close();
    rs3 = stmt3.executeQuery();
    assertTrue("FAIL -- clob not found", rs3.next());
    clob = rs3.getClob(1);
    long new_length = clob.length();
    assertEquals("FAIL -- wrong clob length", streamSize[0], new_length);
    // Check contents ...
    InputStream fStream = new LoopingAlphabetStream(streamSize[0]);
    InputStream lStream = clob.getAsciiStream();
    assertTrue("FAIL - Clob and file contents do not match", compareLob2File(fStream, lStream));
    fStream.close();
    lStream.close();
    rs3.close();
    stmt3.close();
}

84. LobStreamsTest#testClobAsciiWrite1Param()

Project: derby
File: LobStreamsTest.java
/**
     * Tests the ClobOutputStream.write(int b) method
     **/
public void testClobAsciiWrite1Param() throws Exception {
    InputStream streamIn = new LoopingAlphabetStream(streamSize[1]);
    PreparedStatement stmt3 = prepareStatement("SELECT c FROM testBlobX1 WHERE a = 1");
    ResultSet rs3 = stmt3.executeQuery();
    rs3.next();
    Clob clob = rs3.getClob(1);
    assertTrue("FAIL -- clob is NULL", clob != null);
    int buffer;
    OutputStream outstream = clob.setAsciiStream(1L);
    while ((buffer = streamIn.read()) != -1) {
        outstream.write(buffer);
    }
    outstream.close();
    streamIn.close();
    PreparedStatement stmt4 = prepareStatement("UPDATE testBlobX1 SET c = ? WHERE a = 1");
    stmt4.setClob(1, clob);
    stmt4.executeUpdate();
    stmt4.close();
    rs3.close();
    rs3 = stmt3.executeQuery();
    assertTrue("FAIL -- clob not found", rs3.next());
    clob = rs3.getClob(1);
    long new_length = clob.length();
    assertEquals("FAIL -- wrong clob length", streamSize[1], new_length);
    // Check contents ...
    InputStream fStream = new LoopingAlphabetStream(streamSize[1]);
    InputStream lStream = clob.getAsciiStream();
    assertTrue("FAIL - Clob and file contents do not match", compareLob2File(fStream, lStream));
    fStream.close();
    lStream.close();
    rs3.close();
    stmt3.close();
}

85. ClobUpdatableReaderTest#testMultiplexedOperationProblem()

Project: derby
File: ClobUpdatableReaderTest.java
/**
     * Tests that the Clob can handle multiple streams and the length call
     * multiplexed.
     * <p>
     * This test was written after bug DERBY-2806 was reported, where getting
     * the length of the Clob after fetching a stream from it would exhaust
     * the stream and cause the next read to return -1.
     * <p>
     * The test is written to work on a Clob that operates on streams from
     * the store, which currently means that it must be over a certain size
     * and that no modifying methods can be called on it.
     */
public void testMultiplexedOperationProblem() throws IOException, SQLException {
    getConnection().setAutoCommit(false);
    int length = 266000;
    PreparedStatement ps = prepareStatement("insert into updateClob (id, data) values (?,?)");
    ps.setInt(1, length);
    ps.setCharacterStream(2, new LoopingAlphabetReader(length), length);
    assertEquals(1, ps.executeUpdate());
    ps.close();
    PreparedStatement psFetchClob = prepareStatement("select data from updateClob where id = ?");
    psFetchClob.setInt(1, length);
    ResultSet rs = psFetchClob.executeQuery();
    assertTrue("No Clob of length " + length + " in database", rs.next());
    Clob clob = rs.getClob(1);
    assertEquals(length, clob.length());
    Reader r = clob.getCharacterStream();
    int lastReadChar = r.read();
    lastReadChar = assertCorrectChar(lastReadChar, r.read());
    lastReadChar = assertCorrectChar(lastReadChar, r.read());
    assertEquals(length, clob.length());
    // Must be bigger than internal buffers might be.
    int nextChar;
    for (int i = 2; i < 160000; i++) {
        nextChar = r.read();
        // Check manually to report position where it fails.
        if (nextChar == -1) {
            fail("Failed at position " + i + ", stream should not be" + " exhausted now");
        }
        lastReadChar = assertCorrectChar(lastReadChar, nextChar);
    }
    lastReadChar = assertCorrectChar(lastReadChar, r.read());
    lastReadChar = assertCorrectChar(lastReadChar, r.read());
    InputStream ra = clob.getAsciiStream();
    assertEquals(length, clob.length());
    int lastReadAscii = ra.read();
    lastReadAscii = assertCorrectChar(lastReadAscii, ra.read());
    lastReadAscii = assertCorrectChar(lastReadAscii, ra.read());
    assertEquals(length, clob.length());
    lastReadAscii = assertCorrectChar(lastReadAscii, ra.read());
    lastReadChar = assertCorrectChar(lastReadChar, r.read());
    // Close resources.
    r.close();
    ra.close();
    rs.close();
    psFetchClob.close();
}

86. BlobClob4BlobTest#testSelfDestructiveClob2()

Project: derby
File: BlobClob4BlobTest.java
/**
     * test behaviour of system with self destructive user
     * drop table and see what happens to the clob
     * expect an IOException when moving to a new page of the long column
     */
public void testSelfDestructiveClob2() throws Exception {
    insertDefaultData();
    Statement stmt = createStatement();
    ResultSet rs = stmt.executeQuery("select a,b from testClob where b = 10000");
    byte[] buff = new byte[128];
    // fetch row back, get the column as a clob.
    Clob clob = null;
    InputStream fin;
    int clobLength = 0, i = 0;
    assertTrue("FAIL - row not found", rs.next());
    i++;
    clobLength = rs.getInt(2);
    // get the first column as a clob
    clob = rs.getClob(1);
    assertEquals("FAIL - wrong clob length", 10000, clobLength);
    fin = clob.getAsciiStream();
    int columnSize = 0;
    stmt.executeUpdate("drop table testClob");
    try {
        while (columnSize < 11000) {
            int size = fin.read(buff);
            if (size == -1)
                break;
            columnSize += size;
        }
        fail("FAIL - should have got an IOException");
    } catch (java.io.IOException ioe) {
        if (usingEmbedded()) {
            assertEquals("FAIL - wrong exception", "ERROR 40XD0: Container has been closed.", ioe.getMessage());
        }
    }
    rollback();
}

87. BlobClob4BlobTest#testSelfDestructiveClob()

Project: derby
File: BlobClob4BlobTest.java
/**
     * test behaviour of system with self destructive user
     * update a long column underneath a clob
     */
public void testSelfDestructiveClob() throws Exception {
    insertDefaultData();
    Statement stmt = createStatement();
    ResultSet rs = stmt.executeQuery("select a, b from testClob where b = 10000");
    byte[] buff = new byte[128];
    // fetch row back, get the column as a clob.
    Clob clob = null;
    InputStream fin;
    int clobLength = 0, i = 0;
    assertTrue("FAIL - row not found", rs.next());
    i++;
    clobLength = rs.getInt(2);
    // get the first column as a clob
    clob = rs.getClob(1);
    assertEquals("FAIL - wrong clob length", 10000, clobLength);
    fin = clob.getAsciiStream();
    int columnSize = 0;
    PreparedStatement ps = prepareStatement("update testClob set a = ? where b = 10000");
    StringBuffer foo = new StringBuffer();
    for (int k = 0; k < 1000; k++) foo.append('j');
    ps.setString(1, foo.toString());
    ps.executeUpdate();
    rs = stmt.executeQuery("select a from testClob where b = 10000");
    while (rs.next()) {
        int j = 1;
        String val = rs.getString(1);
        assertEquals("FAIL - invalid blob value", foo.substring(0, 50), val.substring(0, 50));
        j++;
    }
    while (columnSize < 11000) {
        int size = fin.read(buff);
        if (size == -1)
            break;
        columnSize += size;
    }
    assertEquals("FAIL - invalid column size", 10000, columnSize);
    assertEquals("FAIL - invalid column size", clobLength, columnSize);
    assertEquals("FAIL - invalid column size", columnSize, clob.length());
    rs.close();
    stmt.close();
}

88. BlobClob4BlobTest#updateClobWithUpdateCharacterStream()

Project: derby
File: BlobClob4BlobTest.java
private void updateClobWithUpdateCharacterStream(ResultSet rs) throws SQLException {
    Clob c;
    String value, expectedValue;
    String clobData = "initial clob ";
    String updatedClobData = "updated clob ";
    c = rs.getClob(2);
    // check contents
    value = c.getSubString(1, (int) c.length());
    expectedValue = clobData + rs.getInt(1);
    assertEquals("FAIL - wrong clob value", expectedValue, value);
    // update contents
    value = (updatedClobData + rs.getInt(1));
    Reader updateValue = new StringReader(value);
    rs.updateCharacterStream(2, updateValue, value.length());
    rs.updateRow();
    // check update values
    // leave the row
    rs.next();
    // go back to updated row
    rs.previous();
    c = rs.getClob(2);
    // check contents
    value = c.getSubString(1, (int) c.length());
    expectedValue = updatedClobData + rs.getInt(1);
    assertEquals("FAIL - wrong clob value", expectedValue, value);
}

89. BlobClob4BlobTest#testGetClobBeforeAndAfterUpdate()

Project: derby
File: BlobClob4BlobTest.java
/**
     * Test fix for derby-1382.
     *
     * Test that the getClob() returns the correct value for the clob before and
     * after updating the clob when using result sets of type
     * TYPE_SCROLL_INSENSITIVE.
     *
     * @throws SQLException
     */
public void testGetClobBeforeAndAfterUpdate() throws SQLException {
    String clobData = "initial clob ";
    PreparedStatement ps = prepareStatement("insert into " + "testClob (b, a) values (?, ?)");
    for (int i = 0; i < 10; i++) {
        ps.setInt(1, i);
        ps.setString(2, clobData + i);
        ps.execute();
    }
    ps.close();
    Statement scrollStmt = createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE);
    ResultSet rs = scrollStmt.executeQuery("SELECT b, a FROM testClob");
    String value;
    Clob c;
    rs.first();
    checkContentsBeforeAndAfterUpdatingClob(rs);
    rs.next();
    checkContentsBeforeAndAfterUpdatingClob(rs);
    rs.relative(3);
    checkContentsBeforeAndAfterUpdatingClob(rs);
    rs.absolute(7);
    checkContentsBeforeAndAfterUpdatingClob(rs);
    rs.previous();
    checkContentsBeforeAndAfterUpdatingClob(rs);
    rs.last();
    checkContentsBeforeAndAfterUpdatingClob(rs);
    rs.previous();
    checkContentsBeforeAndAfterUpdatingClob(rs);
    rs.close();
    scrollStmt.close();
}

90. BlobClob4BlobTest#testClobAfterClosingConnection()

Project: derby
File: BlobClob4BlobTest.java
/**
     * test accessing clob after closing the connection
     */
public void testClobAfterClosingConnection() throws Exception {
    insertDefaultData();
    Statement stmt = createStatement();
    ResultSet rs = stmt.executeQuery("select a,b from testClob");
    // fetch row back, get the column as a clob.
    Clob clob = null, shortClob = null;
    int clobLength;
    while (rs.next()) {
        clobLength = rs.getInt(2);
        if (clobLength == 10000)
            clob = rs.getClob(1);
        if (clobLength == 26)
            shortClob = rs.getClob(1);
    }
    /*
         * We call it before the commit(); to cache the result
         * DERBY-3574
         */
    clob.length();
    shortClob.length();
    rs.close();
    stmt.close();
    commit();
    getConnection().close();
    try {
        long len = shortClob.length();
        //Clobs on the Embedded side and the NetworkClient
        //side are not accessible after closing the
        //connection. Should have thrown an SQLException here.
        fail("FAIL - should not be able to access Clob after " + "Connection Close");
    } catch (SQLException e) {
        checkException(NO_CURRENT_CONNECTION, e);
    }
    // these should all give blob/clob data unavailable exceptions
    try {
        clob.length();
        //Large Clobs on the Embedded side and the NetworkClient
        //side are not accessible after Connection Close. Should
        //have thrown an SQLException here.
        fail("FAIL - should not be able to access large " + "Clob after Connection Close");
    } catch (SQLException e) {
        checkException(NO_CURRENT_CONNECTION, e);
    }
    try {
        clob.getSubString(2, 3);
        //Large Clobs on the Embedded side and the NetworkClient
        //side are not accessible after Connection Close. Should
        //have thrown an SQLException here.
        fail("FAIL - should not be able to access large " + "Clob after Connection Close");
    } catch (SQLException e) {
        checkException(NO_CURRENT_CONNECTION, e);
    }
    try {
        clob.getAsciiStream();
        //Large Clobs on the Embedded side and the NetworkClient
        //side are not accessible after Connection Close. Should
        //have thrown an SQLException here.
        fail("FAIL - should not be able to access large " + "Clob after Connection Close");
    } catch (SQLException e) {
        checkException(NO_CURRENT_CONNECTION, e);
    }
    try {
        clob.position("foo", 2);
        //Large Clobs on the Embedded side and the NetworkClient
        //side are not accessible after Connection Close. Should
        //have thrown an SQLException here.
        fail("FAIL - should not be able to access large " + "Clob after Connection Close");
    } catch (SQLException e) {
        checkException(NO_CURRENT_CONNECTION, e);
    }
    try {
        clob.position(clob, 2);
        //Large Clobs on the Embedded side and the NetworkClient
        //side are not accessible after Connection Close. Should
        //have thrown an SQLException here.
        fail("FAIL - should not be able to access large " + "Clob after Connection Close");
    } catch (SQLException e) {
        checkException(NO_CURRENT_CONNECTION, e);
    }
}

91. BlobClob4BlobTest#testClobAfterCommit()

Project: derby
File: BlobClob4BlobTest.java
/**
     * test accessing clob after commit
     */
public void testClobAfterCommit() throws Exception {
    insertDefaultData();
    Statement stmt = createStatement();
    ResultSet rs = stmt.executeQuery("select a,b from testClob");
    // fetch row back, get the column as a clob.
    Clob clob = null, shortClob = null;
    int clobLength;
    int i = 0;
    while (rs.next()) {
        clobLength = rs.getInt(2);
        if (clobLength == 10000)
            clob = rs.getClob(1);
        if (clobLength == 26)
            shortClob = rs.getClob(1);
    }
    /*
        * We call it before the commit(); to cache the result
        * DERBY-3574
        */
    clob.length();
    shortClob.length();
    rs.close();
    stmt.close();
    commit();
    assertTrue("FAIL - shortClob is NULL", shortClob != null);
    // this should give blob/clob unavailable exceptions on client
    try {
        shortClob.length();
        //Should have thrown an SQLException in the
        fail("FAIL - should not be able to access Clob after commit");
    } catch (SQLException e) {
        checkException(INVALID_LOB, e);
    }
    // these should all give blob/clob data unavailable exceptions
    try {
        clob.length();
        //Large Clobs not accessible after commit. 
        //Should have thrown an SQLException here.
        fail("FAIL - should not be able to access large Clob after commit");
    } catch (SQLException e) {
        checkException(INVALID_LOB, e);
    }
    try {
        clob.getSubString(2, 3);
        //Large Clobs are not accessible after commit. 
        //Should have thrown an SQLException here.
        fail("FAIL - should not be able to access large Clob after commit");
    } catch (SQLException e) {
        checkException(INVALID_LOB, e);
    }
    try {
        clob.getAsciiStream();
        //Large Clobs are not accessible after commit. 
        //Should have thrown an SQLException here.
        fail("FAIL - should not be able to access large Clob after commit");
    } catch (SQLException e) {
        checkException(INVALID_LOB, e);
    }
    try {
        clob.position("foo", 2);
        //Large Clobs are not accessible after commit. 
        //Should have thrown an SQLException here.
        fail("FAIL - should not be able to access large Clob after commit");
    } catch (SQLException e) {
        checkException(INVALID_LOB, e);
    }
    try {
        clob.position(clob, 2);
        //Large Clobs are not accessible after commit. 
        //Should have thrown an SQLException here.
        fail("FAIL - should not be able to access large Clob after commit");
    } catch (SQLException e) {
        checkException(INVALID_LOB, e);
    }
}

92. BlobClob4BlobTest#testLockingWithLongRowClob()

Project: derby
File: BlobClob4BlobTest.java
/**
     * test locking with a long row + long column
     */
public void testLockingWithLongRowClob() throws Exception {
    ResultSet rs;
    Statement stmt, stmt2;
    stmt = createStatement();
    stmt.execute("alter table testClob add column al varchar(2000)");
    stmt.execute("alter table testClob add column bl varchar(3000)");
    stmt.execute("alter table testClob add column cl varchar(2000)");
    stmt.execute("alter table testClob add column dl varchar(3000)");
    stmt.execute("alter table testClob add column el CLOB(400k)");
    PreparedStatement ps = prepareStatement("insert into testClob (al, bl, cl, dl, el, b) values(?,?,?,?,?,?)");
    ps.setString(1, Formatters.padString("blaaa", 2000));
    ps.setString(2, Formatters.padString("tralaaaa", 3000));
    ps.setString(3, Formatters.padString("foodar", 2000));
    ps.setString(4, Formatters.padString("moped", 3000));
    InputStream streamIn = new LoopingAlphabetStream(10000);
    ps.setAsciiStream(5, streamIn, 10000);
    ps.setInt(6, 1);
    // DERBY-4312 make sure commit() doesn't interfere here.
    commit();
    ps.executeUpdate();
    streamIn.close();
    ps.close();
    commit();
    stmt = createStatement();
    rs = stmt.executeQuery("select el from testClob");
    // fetch row back, get the column as a clob.
    Clob clob = null;
    assertTrue("FAIL - row not found", rs.next());
    clob = rs.getClob(1);
    assertTrue("FAIL - clob is null", clob != null);
    rs.close();
    stmt.close();
    Connection conn2 = openDefaultConnection();
    // turn off autocommit, otherwise blobs/clobs cannot hang around
    // until end of transaction
    conn2.setAutoCommit(false);
    // the following should timeout
    stmt2 = conn2.createStatement();
    try {
        stmt2.executeUpdate("update testClob set el = 'smurfball' where b = 1");
        // Cleanup on fail
        stmt2.close();
        conn2.rollback();
        conn2.close();
        fail("FAIL - statement should timeout");
    } catch (SQLException se) {
        checkException(LOCK_TIMEOUT, se);
    }
    // Test that update goes through after the transaction is committed
    commit();
    stmt2.executeUpdate("update testClob set el = 'smurfball' where b = 1");
    stmt2.close();
    conn2.commit();
    conn2.close();
}

93. BlobClob4BlobTest#testLockingClob()

Project: derby
File: BlobClob4BlobTest.java
/**
     * test locking
     */
public void testLockingClob() throws Exception {
    insertDefaultData();
    Statement stmt = createStatement();
    ResultSet rs = stmt.executeQuery("select a, b from testClob");
    // fetch row back, get the column as a clob.
    Clob clob = null, shortClob = null;
    int clobLength;
    while (rs.next()) {
        clobLength = rs.getInt(2);
        if (clobLength == 10000)
            clob = rs.getClob(1);
        if (clobLength == 26)
            shortClob = rs.getClob(1);
    }
    rs.close();
    stmt.close();
    assertTrue("shortClob is null", shortClob != null);
    assertTrue("clob is null", clob != null);
    Connection conn2 = openDefaultConnection();
    // turn off autocommit, otherwise blobs/clobs cannot hang around
    // until end of transaction
    conn2.setAutoCommit(false);
    // update should go through since we don't get any locks on clobs
    // that are not long columns
    Statement stmt2 = conn2.createStatement();
    stmt2.executeUpdate("update testClob set a = 'foo' where b = 26");
    assertEquals("FAIL: clob length changed", 26, shortClob.length());
    // should timeout waiting for the lock to do this
    try {
        stmt2.executeUpdate("update testClob set b = b + 1 where b = 10000");
        // Cleanup on fail
        stmt2.close();
        conn2.rollback();
        conn2.close();
        fail("FAIL: row should be locked");
    } catch (SQLException se) {
        checkException(LOCK_TIMEOUT, se);
    }
    // DERBY-3740, the reference below to clob must remain after the above
    // expected lock timeout, otherwise GC might run on the clob and
    // cause intermittent problems if the GC causes lock to be released
    // early.
    assertEquals("FAIL: clob length changed", 10000, clob.length());
    // Test that update goes through after the transaction is committed
    commit();
    stmt2.executeUpdate("update testClob set b = b + 1 where b = 10000");
    stmt2.close();
    conn2.rollback();
    conn2.close();
}

94. BlobClob4BlobTest#testClobAfterClose()

Project: derby
File: BlobClob4BlobTest.java
/**
     * make sure clob is still around after we go to the next row,
     * after we close the result set, and after we close the statement
     */
public void testClobAfterClose() throws Exception {
    insertDefaultData();
    Statement stmt = createStatement();
    ResultSet rs = stmt.executeQuery("select a, b from testClob");
    byte[] buff = new byte[128];
    Clob[] clobArray = new Clob[10];
    int[] clobLengthArray = new int[10];
    int j = 0;
    while (rs.next()) {
        clobArray[j] = rs.getClob(1);
        clobLengthArray[j++] = rs.getInt(2);
    }
    rs.close();
    stmt.close();
    for (int i = 0; i < 10; i++) {
        if (clobArray[i] != null) {
            InputStream fin = clobArray[i].getAsciiStream();
            int columnSize = 0;
            for (; ; ) {
                int size = fin.read(buff);
                if (size == -1)
                    break;
                columnSize += size;
            }
            assertEquals("FAIL - wrong column size", columnSize, clobLengthArray[i]);
            assertEquals("FAIL - wrong column size", columnSize, clobArray[i].length());
        }
    }
}

95. BlobClob4BlobTest#testRaisingOfExceptionsClob()

Project: derby
File: BlobClob4BlobTest.java
/**
     * test raising of exceptions
     */
public void testRaisingOfExceptionsClob() throws Exception {
    insertDefaultData();
    Statement stmt = createStatement();
    ResultSet rs = stmt.executeQuery("select a, b from testClob WHERE a is not NULL");
    int i = 0, clobLength = 0;
    Clob clob;
    rs.next();
    clob = rs.getClob(1);
    clobLength = rs.getInt(2);
    rs.close();
    assertFalse("FAIL - clob can not be null", clob == null);
    // 0 or negative position value
    try {
        clob.getSubString(0, 5);
        fail("FAIL - getSubString with 0 as position should have " + "caused an exception");
    } catch (SQLException e) {
        checkException(BLOB_BAD_POSITION, e);
    }
    // negative length value
    try {
        clob.getSubString(1, -76);
        fail("FAIL - getSubString with negative length should have " + "caused an exception");
    } catch (SQLException e) {
        checkException(BLOB_NONPOSITIVE_LENGTH, e);
    }
    // boundary negative 1 length
    try {
        clob.getSubString(1, -1);
        fail("FAIL - getSubString with negative length should have " + "caused an exception");
    } catch (SQLException e) {
        checkException(BLOB_NONPOSITIVE_LENGTH, e);
    }
    // before start with length zero
    try {
        clob.getSubString(0, 0);
        fail("FAIL - getSubString with 0 as position should have " + "caused an exception");
    } catch (SQLException e) {
        checkException(BLOB_BAD_POSITION, e);
    }
    // 2 past end with length 0
    try {
        clob.getSubString(clobLength + 2, 0);
        fail("FAIL - getSubString with position bigger than clob " + "should have caused an exception");
    } catch (SQLException e) {
        checkException(BLOB_POSITION_TOO_LARGE, e);
    }
    // 0 or negative position value
    try {
        clob.position("xx", -4000);
        fail("FAIL - position with negative as position should " + "have caused an exception");
    } catch (SQLException e) {
        checkException(BLOB_BAD_POSITION, e);
    }
    // null pattern
    try {
        clob.position((String) null, 5);
        fail("FAIL = position((String) null,5)");
    } catch (SQLException e) {
        checkException(BLOB_NULL_PATTERN_OR_SEARCH_STR, e);
    }
    // 0 or negative position value
    try {
        clob.position(clob, -42);
        fail("FAIL = position(clob,-42)");
    } catch (SQLException e) {
        checkException(BLOB_BAD_POSITION, e);
    }
    // null pattern
    try {
        clob.position((Clob) null, 5);
        fail("FAIL = pposition((Clob) null,5)");
    } catch (SQLException e) {
        checkException(BLOB_NULL_PATTERN_OR_SEARCH_STR, e);
    }
}

96. BlobClob4BlobTest#testSetClobToIntColumn()

Project: derby
File: BlobClob4BlobTest.java
/**
     * make sure setClob doesn't work on an int column
     */
public void testSetClobToIntColumn() throws Exception {
    insertDefaultData();
    PreparedStatement ps = prepareStatement("insert into testClob (b, c) values (?, ?)");
    Statement stmt = createStatement();
    ResultSet rs = stmt.executeQuery("select a, b from testClob");
    Clob clob;
    int clobLength;
    while (rs.next()) {
        // get the first ncolumn as a clob
        clob = rs.getClob(1);
        clobLength = rs.getInt(2);
        if (clob != null) {
            try {
                ps.setClob(1, clob);
                ps.setInt(2, clobLength);
                ps.executeUpdate();
                // Cleanup on fail
                rs.close();
                stmt.close();
                fail("FAIL - can not use setClob on int column");
            } catch (SQLException se) {
                checkException(LANG_DATA_TYPE_GET_MISMATCH, se);
            }
        }
    }
    rs.close();
    stmt.close();
}

97. BlobClob4BlobTest#runPositionClobTest()

Project: derby
File: BlobClob4BlobTest.java
private void runPositionClobTest() throws Exception {
    Statement stmt = createStatement();
    ResultSet rs = stmt.executeQuery("select a, b from testClob");
    int clobLength = 0;
    Clob clob;
    Statement stmt2 = createStatement();
    Random random = new Random();
    String searchString;
    int start, length, startSearchPos;
    int distance, maxStartPointDistance;
    long foundAt;
    // clobs are generated with looping alphabet streams
    maxStartPointDistance = CharAlphabet.MODERNLATINLOWER.length;
    while (rs.next()) {
        clob = rs.getClob(1);
        clobLength = rs.getInt(2);
        if (clob != null && clobLength > 0) {
            println("\n\nclobLength: " + clobLength);
            // Create a table with clobs to search
            stmt2.executeUpdate("CREATE TABLE searchClob " + "(a clob(300K), start int, position int)");
            // insert clobs into the table
            PreparedStatement ps = prepareStatement("INSERT INTO searchClob values (?, ?, ?) ");
            for (int i = 0; i < 10; i++) {
                // find a random string to search for
                start = Math.max(random.nextInt(clobLength - 1), 1);
                length = random.nextInt(clobLength - start) + 1;
                println("start:" + start + " length:" + length);
                searchString = clob.getSubString(start, length);
                // get random position to start the search from
                distance = random.nextInt(maxStartPointDistance);
                startSearchPos = Math.max((start - distance), 1);
                // make sure that the searched string does not happen
                // before the expected position
                String tmp = clob.getSubString(startSearchPos, start);
                if (tmp.indexOf(searchString) != -1) {
                    startSearchPos = start;
                }
                ps.setString(1, searchString);
                ps.setInt(2, startSearchPos);
                ps.setInt(3, start);
                ps.executeUpdate();
            }
            ps.close();
            ResultSet rs2 = stmt2.executeQuery("SELECT a, start, position FROM searchClob");
            while (rs2.next()) {
                Clob searchClob = rs2.getClob(1);
                startSearchPos = rs2.getInt(2);
                start = rs2.getInt(3);
                searchString = searchClob.getSubString(1L, (int) searchClob.length());
                println("startSearchPos: " + startSearchPos + "searchString: " + searchString);
                foundAt = clob.position(searchClob, startSearchPos);
                assertEquals("FAIL - wrong match found for " + searchString + " starting at " + startSearchPos + " with length " + searchString.length(), start, foundAt);
            }
            rs2.close();
            stmt2.executeUpdate("DROP TABLE searchClob");
        }
    }
    rs.close();
    stmt.close();
    stmt2.close();
}

98. BlobClob4BlobTest#runPositionStringTest()

Project: derby
File: BlobClob4BlobTest.java
private void runPositionStringTest() throws Exception {
    Statement stmt = createStatement();
    ResultSet rs = stmt.executeQuery("select a, b from testClob");
    int clobLength = 0;
    Clob clob;
    Random random = new Random();
    String searchString;
    int start, length, startSearchPos;
    int distance, maxStartPointDistance;
    long foundAt;
    // clobs are generated with looping alphabet streams
    maxStartPointDistance = CharAlphabet.MODERNLATINLOWER.length;
    while (rs.next()) {
        clob = rs.getClob(1);
        clobLength = rs.getInt(2);
        if (clob != null && clobLength > 0) {
            println("\n\nclobLength: " + clobLength);
            for (int i = 0; i < 10; i++) {
                // find a random string to search for
                start = Math.max(random.nextInt(clobLength - 1), 1);
                length = random.nextInt(clobLength - start) + 1;
                println("start:" + start + " length:" + length);
                searchString = clob.getSubString(start, length);
                // get random position to start the search from
                distance = random.nextInt(maxStartPointDistance);
                startSearchPos = Math.max((start - distance), 1);
                // make sure that the searched string does not happen
                // before the expected position
                String tmp = clob.getSubString(startSearchPos, start);
                if (tmp.indexOf(searchString) != -1) {
                    startSearchPos = start;
                }
                println("startSearchPos: " + startSearchPos + "searchString: " + searchString);
                foundAt = clob.position(searchString, startSearchPos);
                assertEquals("FAIL - wrong match found for " + searchString + " start at " + startSearchPos + " with length " + searchString.length(), start, foundAt);
            }
        }
    }
    rs.close();
    stmt.close();
}

99. BlobClob4BlobTest#testGetSubStringWithUnicode()

Project: derby
File: BlobClob4BlobTest.java
/**
     * test getSubString with unicode
     */
public void testGetSubStringWithUnicode() throws Exception {
    String[] unicodeStrings = { "abc", "???", "???" };
    insertUnicodeData(unicodeStrings);
    Statement stmt = createStatement();
    ResultSet rs = stmt.executeQuery("select a, b, c from testClob");
    int clobLength = 0, arrayIndex = 0;
    Clob clob;
    while (rs.next()) {
        clob = rs.getClob(1);
        clobLength = rs.getInt(2);
        arrayIndex = rs.getInt(3);
        if (clob != null) {
            if (arrayIndex >= 0) {
                assertEquals("FAIL - wrong substring returned", unicodeStrings[arrayIndex], clob.getSubString(1, 3));
            } else {
                if (clob.length() > 0) {
                    long charsToRead = Math.min((clob.length() / 3), 2048);
                    char[] charValue = new char[(int) charsToRead];
                    Reader clobReader = clob.getCharacterStream();
                    clobReader.read(charValue);
                    clobReader.read(charValue);
                    String subString = clob.getSubString(charsToRead + 1, (int) charsToRead);
                    assertEquals("FAIL - wrong substring length", charValue.length, subString.length());
                    for (int i = 0; i < charValue.length; i++) {
                        assertEquals("FAIL - wrong substring returned at " + i, charValue[i], subString.charAt(i));
                    }
                }
            }
        }
    }
    rs.close();
    stmt.close();
}

100. BlobClob4BlobTest#testGetSubString()

Project: derby
File: BlobClob4BlobTest.java
/**
     * test Clob.getSubString() method
     */
public void testGetSubString() throws Exception {
    insertDefaultData();
    Statement stmt = createStatement();
    ResultSet rs = stmt.executeQuery("select a, b from testClob");
    int clobLength = 0;
    Clob clob;
    while (rs.next()) {
        clob = rs.getClob(1);
        if (clob == null)
            continue;
        clobLength = rs.getInt(2);
        verifyInterval(clob, 9905, 50, 0, clobLength);
        verifyInterval(clob, 5910, 150, 1, clobLength);
        verifyInterval(clob, 5910, 50, 2, clobLength);
        verifyInterval(clob, 204, 50, 3, clobLength);
        verifyInterval(clob, 68, 50, 4, clobLength);
        verifyInterval(clob, 1, 50, 5, clobLength);
        verifyInterval(clob, 1, 1, 6, clobLength);
        // length 0 at start
        verifyInterval(clob, 1, 0, 7, clobLength);
        // and end
        verifyInterval(clob, clobLength + 1, 0, 8, clobLength);
        if (clobLength > 100) {
            String res = clob.getSubString(clobLength - 99, 200);
            assertEquals("FAIL - wrong length of substring", 100, res.length());
        }
    }
    rs.close();
    stmt.close();
}