Java Code Examples for java.sql.Clob#getCharacterStream()

The following examples show how to use java.sql.Clob#getCharacterStream() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: DBTest.java    From canal with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unused")
private String clob2Str(Clob clob) {
    String content = "";
    try (Reader is = clob.getCharacterStream(); BufferedReader buff = new BufferedReader(is)) {
        String line = buff.readLine();
        StringBuilder sb = new StringBuilder();
        while (line != null) {
            sb.append(line);
            line = buff.readLine();
        }
        content = sb.toString();
    } catch (Exception e) {
        e.printStackTrace();
    }
    return content;
}
 
Example 2
Source File: ServerPreparedQueryBindings.java    From FoxTelem with GNU General Public License v3.0 6 votes vote down vote up
@Override
public void setClob(int parameterIndex, Clob x) {
    if (x == null) {
        setNull(parameterIndex);
    } else {
        try {
            ServerPreparedQueryBindValue binding = getBinding(parameterIndex, true);
            this.sendTypesToServer.compareAndSet(false, binding.resetToType(MysqlType.FIELD_TYPE_BLOB, this.numberOfExecutions));
            binding.value = x.getCharacterStream();
            binding.isLongData = true;
            binding.bindLength = this.useStreamLengthsInPrepStmts.getValue() ? x.length() : -1;
        } catch (Throwable t) {
            throw ExceptionFactory.createException(t.getMessage(), t);
        }
    }
}
 
Example 3
Source File: JdbcUtil.java    From datacollector with Apache License 2.0 6 votes vote down vote up
private String getClobString(Clob data, int maxClobSize) throws IOException, SQLException {
  if (data == null) {
    return null;
  }

  StringBuilder sb = new StringBuilder();
  int bufLen = 1024;
  char[] cbuf = new char[bufLen];

  // Read up to max clob length
  long maxRemaining = maxClobSize;
  int count;
  try(Reader r = data.getCharacterStream()) {
    while ((count = r.read(cbuf)) > -1 && maxRemaining > 0) {
      // If c is more then the remaining chars we want to read, read only as many are available
      if (count > maxRemaining) {
        count = (int) maxRemaining;
      }
      sb.append(cbuf, 0, count);
      // decrement available according to the number of chars we've read
      maxRemaining -= count;
    }
  }
  return sb.toString();
}
 
Example 4
Source File: RichTextConverterUtilities.java    From pentaho-reporting with GNU Lesser General Public License v2.1 6 votes vote down vote up
public static Reader convertToReader( final Object o ) throws IOException {
  if ( o instanceof char[] ) {
    return new StringReader( new String( (char[]) o ) );
  }
  if ( o instanceof String ) {
    return new StringReader( (String) o );
  }
  if ( o instanceof Clob ) {
    final Clob b = (Clob) o;
    try {
      return b.getCharacterStream();
    } catch ( SQLException e ) {
      throw new IOException( "Failed to convert from BLOB" );
    }
  }
  if ( o instanceof Reader ) {
    return (Reader) o;
  }
  return null;
}
 
Example 5
Source File: HarmonySerialClob.java    From spliceengine with GNU Affero General Public License v3.0 6 votes vote down vote up
public HarmonySerialClob(Clob clob) throws SQLException {
    Reader characterStream;

    if (clob == null) { throw new IllegalArgumentException(); }
    if ((characterStream = clob.getCharacterStream()) == null
            && clob.getAsciiStream() == null) { throw new IllegalArgumentException(); }

    this.clob = clob;
    origLen = clob.length();
    len = origLen;
    buf = new char[(int) len];
    try {
        characterStream.read(buf);
    } catch (IOException e) {

        throw new SQLException("SerialClob: "
                + e.getMessage(), e);
    }
}
 
Example 6
Source File: ServerPreparedStatement.java    From r-course with MIT License 6 votes vote down vote up
/**
 * @see java.sql.PreparedStatement#setClob(int, java.sql.Clob)
 */
@Override
public void setClob(int parameterIndex, Clob x) throws SQLException {
    synchronized (checkClosed().getConnectionMutex()) {

        if (x == null) {
            setNull(parameterIndex, java.sql.Types.BINARY);
        } else {
            BindValue binding = getBinding(parameterIndex, true);
            resetToType(binding, MysqlDefs.FIELD_TYPE_BLOB);

            binding.value = x.getCharacterStream();
            binding.isLongData = true;

            if (this.connection.getUseStreamLengthsInPrepStmts()) {
                binding.bindLength = x.length();
            } else {
                binding.bindLength = -1;
            }
        }
    }
}
 
Example 7
Source File: ClobFormatter.java    From jsqsh with Apache License 2.0 6 votes vote down vote up
public String format (Object value) {
    
    Clob clob = (Clob) value;
    StringBuilder sb = new StringBuilder();
    char []chars = new char[512];
    
    try {
        
        Reader in = clob.getCharacterStream();
        while (in.read(chars) >= 0) {
            
            sb.append(chars);
        }
        
        in.close();
    }
    catch (Exception e) {
        
        /* IGNORED */
    }
    
    return sb.toString();
}
 
Example 8
Source File: JtdsResultSet.java    From jTDS with GNU Lesser General Public License v2.1 5 votes vote down vote up
public Reader getCharacterStream(int columnIndex) throws SQLException {
    Clob clob = getClob(columnIndex);

    if (clob == null) {
        return null;
    }

    return clob.getCharacterStream();
}
 
Example 9
Source File: AbstractDIHCacheTestCase.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
protected String clobToString(Clob cl) {
  StringBuilder sb = new StringBuilder();
  try {
    Reader in = cl.getCharacterStream();
    char[] cbuf = new char[1024];
    int numGot = -1;
    while ((numGot = in.read(cbuf)) != -1) {
      sb.append(String.valueOf(cbuf, 0, numGot));
    }
  } catch (Exception e) {
    Assert.fail(e.toString());
  }
  return sb.toString();
}
 
Example 10
Source File: OracleLobHandler.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@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;
}
 
Example 11
Source File: Util.java    From rxjava-jdbc with Apache License 2.0 5 votes vote down vote up
private static <T> Object getObject(final ResultSet rs, Class<T> cls, int i) {
    try {
        if (rs.getObject(i) == null) {
            return null;
        }
        final int type = rs.getMetaData().getColumnType(i);
        // TODO java.util.Calendar support
        // TODO XMLGregorian Calendar support
        if (type == Types.DATE)
            return rs.getDate(i, Calendar.getInstance());
        else if (type == Types.TIME)
            return rs.getTime(i, Calendar.getInstance());
        else if (type == Types.TIMESTAMP)
            return rs.getTimestamp(i, Calendar.getInstance());
        else if (type == Types.CLOB && cls.equals(String.class)) {
            return toString(rs.getClob(i));
        } else if (type == Types.CLOB && Reader.class.isAssignableFrom(cls)) {
            Clob c = rs.getClob(i);
            Reader r = c.getCharacterStream();
            return createFreeOnCloseReader(c, r);
        } else if (type == Types.BLOB && cls.equals(byte[].class)) {
            return toBytes(rs.getBlob(i));
        } else if (type == Types.BLOB && InputStream.class.isAssignableFrom(cls)) {
            final Blob b = rs.getBlob(i);
            final InputStream is = rs.getBlob(i).getBinaryStream();
            return createFreeOnCloseInputStream(b, is);
        } else
            return rs.getObject(i);
    } catch (SQLException e) {
        throw new SQLRuntimeException(e);
    }
}
 
Example 12
Source File: LobStreamsTest.java    From spliceengine with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * 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();
}
 
Example 13
Source File: DefaultLobHandler.java    From effectivejava with Apache License 2.0 5 votes vote down vote up
@Override
public Reader getClobAsCharacterStream(ResultSet rs, int columnIndex) throws SQLException {
	logger.debug("Returning CLOB as character stream");
	if (this.wrapAsLob) {
		Clob clob = rs.getClob(columnIndex);
		return clob.getCharacterStream();
	}
	else {
		return rs.getCharacterStream(columnIndex);
	}
}
 
Example 14
Source File: Convert.java    From javalite with Apache License 2.0 5 votes vote down vote up
private static String clobToString(Clob clob) {
    Reader r = null;
    StringWriter sw = null;
    try {
        r = clob.getCharacterStream();
        sw = new StringWriter();
        copyStream(r, sw);
        return sw.toString();
    } catch (Exception e) {
        throw new ConversionException(e);
    } finally {
        closeQuietly(sw);
        closeQuietly(r);
    }
}
 
Example 15
Source File: OracleLobHandler.java    From effectivejava with Apache License 2.0 5 votes vote down vote up
@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;
}
 
Example 16
Source File: ClobUpdatableReaderTest.java    From spliceengine with GNU Affero General Public License v3.0 4 votes vote down vote up
/**
 * 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));
}
 
Example 17
Source File: JdbcUtil.java    From iaf with Apache License 2.0 4 votes vote down vote up
public static Reader getClobReader(Clob clob) throws SQLException, JdbcException {
	return clob.getCharacterStream();
}
 
Example 18
Source File: ResultSetIT.java    From snowflake-jdbc with Apache License 2.0 4 votes vote down vote up
@Test
public void testGetClob() throws Throwable
{
  Connection connection = getConnection();
  Statement statement = connection.createStatement();
  statement.execute("create or replace table testClob(cola text)");
  statement.execute("insert into testClob values('hello world')");
  statement.execute("insert into testClob values('hello world1')");
  statement.execute("insert into testClob values('hello world2')");
  statement.execute("insert into testClob values('hello world3')");
  ResultSet resultSet = statement.executeQuery("select * from testClob");
  resultSet.next();
  // test reading Clob
  char[] chars = new char[100];
  Reader reader = resultSet.getClob(1).getCharacterStream();
  int charRead;
  charRead = reader.read(chars, 0, chars.length);
  assertEquals(charRead, 11);
  assertEquals("hello world", resultSet.getClob(1).toString());

  // test reading truncated clob
  resultSet.next();
  Clob clob = resultSet.getClob(1);
  assertEquals(clob.length(), 12);
  clob.truncate(5);
  reader = clob.getCharacterStream();

  charRead = reader.read(chars, 0, chars.length);
  assertEquals(charRead, 5);

  // read from input stream
  resultSet.next();
  final InputStream input = resultSet.getClob(1).getAsciiStream();

  Reader in = new InputStreamReader(input, StandardCharsets.UTF_8);
  charRead = in.read(chars, 0, chars.length);
  assertEquals(charRead, 12);

  statement.close();
  connection.close();
}
 
Example 19
Source File: JtdsResultSet.java    From jTDS with GNU Lesser General Public License v2.1 4 votes vote down vote up
public void updateObject(int columnIndex, Object x) throws SQLException {
    checkOpen();
    int length = 0;
    int jdbcType = Types.VARCHAR; // Use for NULL values

    if (x != null) {
        // Need to do some conversion and testing here
        jdbcType = Support.getJdbcType(x);
        if (x instanceof BigDecimal) {
            int prec = getConnection().getMaxPrecision();
            x = Support.normalizeBigDecimal((BigDecimal)x, prec);
        } else if (x instanceof Blob) {
            Blob blob = (Blob) x;
            x = blob.getBinaryStream();
            length = (int) blob.length();
        } else if (x instanceof Clob) {
            Clob clob = (Clob) x;
            x = clob.getCharacterStream();
            length = (int) clob.length();
        } else if (x instanceof String) {
            length = ((String)x).length();
        } else if (x instanceof byte[]) {
            length = ((byte[])x).length;
        }
        if (jdbcType == Types.JAVA_OBJECT) {
            // Unsupported class of object
            if (columnIndex < 1 || columnIndex > columnCount) {
                throw new SQLException(Messages.get("error.resultset.colindex",
                        Integer.toString(columnIndex)),
                        "07009");
            }
            ColInfo ci = columns[columnIndex-1];
            throw new SQLException(
                    Messages.get("error.convert.badtypes",
                            x.getClass().getName(),
                            Support.getJdbcTypeName(ci.jdbcType)), "22005");
        }
    }

    setColValue(columnIndex, jdbcType, x, length);
}
 
Example 20
Source File: ClobUpdatableReaderTest.java    From gemfirexd-oss with Apache License 2.0 4 votes vote down vote up
/**
 * 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);
    StringBuilder sb = new StringBuilder ();
    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));
}