Example usage for java.sql ResultSet getCharacterStream

List of usage examples for java.sql ResultSet getCharacterStream

Introduction

In this page you can find the example usage for java.sql ResultSet getCharacterStream.

Prototype

java.io.Reader getCharacterStream(String columnLabel) throws SQLException;

Source Link

Document

Retrieves the value of the designated column in the current row of this ResultSet object as a java.io.Reader object.

Usage

From source file:org.kawanfw.test.api.client.InsertAndUpdateClobTestNew.java

/**
 * Test that the blob was were correctly inserted
 * //from w  w w  .j  a  v  a2  s.c o  m
 * @param connection
 */
public void selectClobTest(Connection connection, String originalFileName, String shaHexa) throws Exception {

    int item_id;

    String sql = "select * from documentation where item_id >= ? ";

    PreparedStatement prepStatement = connection.prepareStatement(sql);

    int i = 1;
    prepStatement.setInt(i++, 1);

    ResultSet rs = prepStatement.executeQuery();

    MessageDisplayer.display("");

    Reader reader = null;
    Writer writer = null;

    while (rs.next()) {

        item_id = rs.getInt("item_id");

        File originalFile = SqlTestParms.getFileFromUserHome(originalFileName);
        // String extension = "."
        // + StringUtils.substringAfterLast(originalFile.toString(),
        // ".");

        File file = InsertAndUpdateBlobTest.createTempFile(originalFile.toString());
        try {
            reader = rs.getCharacterStream("item_doc");

            if (reader != null) {
                writer = new BufferedWriter(new FileWriter(file));
                IOUtils.copy(reader, writer);

            } else {
                MessageDisplayer.display("item_doc column is null!");
            }

        } finally {
            IOUtils.closeQuietly(reader);
            IOUtils.closeQuietly(writer);
        }

        i = 1;
        item_id = rs.getInt(i++);

        MessageDisplayer.display("");
        MessageDisplayer.display("item_id     : " + item_id);

        // Compute the hash of the file
        Sha1Util sha1 = new Sha1Util();
        String shaHexaNew = sha1.getHexFileHash(file);

        Assert.assertEquals("Comparing original " + SqlTestParms.TEXT_FILE_1 + " new " + file + " hash values ",
                shaHexa, shaHexaNew);

        file.delete();

        MessageDisplayer.display("");
        MessageDisplayer.display("Ok, SHA-1 value of read file " + file + " is same as inserted file "
                + SqlTestParms.getFileFromUserHome(originalFileName));

    }

    prepStatement.close();
    rs.close();

    MessageDisplayer.display("Select done!");

}

From source file:org.nuxeo.ecm.core.storage.sql.db.dialect.DialectOracle.java

@Override
@SuppressWarnings("boxing")
public Serializable getFromResultSet(ResultSet rs, int index, Column column) throws SQLException {
    switch (column.getJdbcType()) {
    case Types.VARCHAR:
        String string = rs.getString(index);
        if (column.getType() == ColumnType.BLOBID && string != null) {
            return column.getModel().getBinary(string);
        } else {/*from   ww w. j a va 2  s. c om*/
            return string;
        }
    case Types.CLOB:
        // Oracle cannot read CLOBs using rs.getString when the ResultSet is
        // a ScrollableResultSet (the standard OracleResultSetImpl works
        // fine).
        Reader r = rs.getCharacterStream(index);
        if (r == null) {
            return null;
        }
        StringBuilder sb = new StringBuilder();
        char[] buffer = new char[4096];
        try {
            int n;
            while ((n = r.read(buffer)) != -1) {
                sb.append(new String(buffer, 0, n));
            }
        } catch (IOException e) {
            log.error("Cannot read CLOB", e);
        }
        return sb.toString();
    case Types.BIT:
        return rs.getBoolean(index);
    case Types.TINYINT:
    case Types.SMALLINT:
    case Types.INTEGER:
    case Types.BIGINT:
        return rs.getLong(index);
    case Types.DOUBLE:
        return rs.getDouble(index);
    case Types.TIMESTAMP:
        Timestamp ts = rs.getTimestamp(index);
        if (ts == null) {
            return null;
        } else {
            Serializable cal = new GregorianCalendar(); // XXX timezone
            ((Calendar) cal).setTimeInMillis(ts.getTime());
            return cal;
        }
    }
    throw new SQLException("Unhandled JDBC type: " + column.getJdbcType());
}

From source file:org.openmrs.module.sync.api.db.hibernate.usertype.SyncItemListSerializingUserType.java

/**
 * @see org.hibernate.usertype.UserType#nullSafeGet(java.sql.ResultSet, java.lang.String[], java.lang.Object)
 *///from  www .  j a v  a2s. com
public Object nullSafeGet(ResultSet rs, String[] names, Object owner) throws HibernateException, SQLException {
    if (rs.wasNull()) {
        return null;
    } else {
        Clob clob = rs.getClob(names[0]);

        if (clob == null) {
            return null;
        } else {
            // 2 Sep 2007 - Christian Allen - callen@pih.org
            // We need a workaround because clob.getSubString() and clob.length() throw an exception when used within the creating session
            //String content = clob.getSubString(1, (int)clob.length());
            // Here's the workaround:
            StringBuilder content = new StringBuilder();
            String line;

            BufferedReader br = new BufferedReader(rs.getCharacterStream(names[0]));
            try {
                while ((line = br.readLine()) != null) {
                    content.append(line);
                }
            } catch (IOException e) {
                throw new SQLException(e.toString());
            }
            // End workaround

            Collection<SyncItem> items = SyncUtil.getSyncItemsFromPayload(content.toString());

            return items;
        }
    }
}

From source file:org.seasar.s2sqlmap.spring.lob.port.DefaultLobHandler.java

public Reader getClobAsCharacterStream(ResultSet rs, int columnIndex) throws SQLException {
    logger.debug("Returning CLOB as character stream");
    return rs.getCharacterStream(columnIndex);
}

From source file:org.sonar.core.source.db.FileSourceDao.java

public <T> void readLineHashesStream(DbSession dbSession, String fileUuid, Function<Reader, T> function) {
    Connection connection = dbSession.getConnection();
    PreparedStatement pstmt = null;
    ResultSet rs = null;
    Reader reader = null;/*from  www .ja v  a 2  s .c o m*/
    try {
        pstmt = connection.prepareStatement("SELECT line_hashes FROM file_sources WHERE file_uuid=?");
        pstmt.setString(1, fileUuid);
        rs = pstmt.executeQuery();
        if (rs.next()) {
            reader = rs.getCharacterStream(1);
            function.apply(reader);
        }
    } catch (SQLException e) {
        throw new IllegalStateException("Fail to read FILE_SOURCES.LINE_HASHES of file " + fileUuid, e);
    } finally {
        IOUtils.closeQuietly(reader);
        DbUtils.closeQuietly(connection, pstmt, rs);
    }
}

From source file:org.sonar.db.source.FileSourceDao.java

public <T> void readLineHashesStream(DbSession dbSession, String fileUuid, Function<Reader, T> function) {
    Connection connection = dbSession.getConnection();
    PreparedStatement pstmt = null;
    ResultSet rs = null;
    Reader reader = null;/*from   ww  w .  j  av a2 s .  c o  m*/
    try {
        pstmt = connection
                .prepareStatement("SELECT line_hashes FROM file_sources WHERE file_uuid=? AND data_type=?");
        pstmt.setString(1, fileUuid);
        pstmt.setString(2, Type.SOURCE);
        rs = pstmt.executeQuery();
        if (rs.next()) {
            reader = rs.getCharacterStream(1);
            if (reader != null) {
                function.apply(reader);
            }
        }
    } catch (SQLException e) {
        throw new IllegalStateException("Fail to read FILE_SOURCES.LINE_HASHES of file " + fileUuid, e);
    } finally {
        IOUtils.closeQuietly(reader);
        DbUtils.closeQuietly(connection, pstmt, rs);
    }
}

From source file:org.sonar.server.source.db.FileSourceDao.java

public <T> void readLineHashesStream(DbSession dbSession, String fileUuid, Function<Reader, T> function) {
    Connection connection = dbSession.getConnection();
    PreparedStatement pstmt = null;
    ResultSet rs = null;
    Reader reader = null;/*w w  w  .  j  av a 2 s  .  co m*/
    try {
        pstmt = connection
                .prepareStatement("SELECT line_hashes FROM file_sources WHERE file_uuid=? AND data_type=?");
        pstmt.setString(1, fileUuid);
        pstmt.setString(2, Type.SOURCE);
        rs = pstmt.executeQuery();
        if (rs.next()) {
            reader = rs.getCharacterStream(1);
            function.apply(reader);
        }
    } catch (SQLException e) {
        throw new IllegalStateException("Fail to read FILE_SOURCES.LINE_HASHES of file " + fileUuid, e);
    } finally {
        IOUtils.closeQuietly(reader);
        DbUtils.closeQuietly(connection, pstmt, rs);
    }
}

From source file:org.sonar.server.source.index.SourceLineResultSetIterator.java

@Override
protected SourceFile read(ResultSet rs) throws SQLException {
    String projectUuid = rs.getString(1);
    String fileUuid = rs.getString(2);
    Long updatedAt = SqlUtil.getLong(rs, 3);
    if (updatedAt == null) {
        updatedAt = System.currentTimeMillis();
    }//from  w w  w. j  a v a2 s  . c  om
    Date updatedDate = new Date(updatedAt);
    SourceFile result = new SourceFile(fileUuid, updatedAt);

    Reader csv = rs.getCharacterStream(4);
    if (csv == null) {
        return result;
    }

    int line = 1;
    CSVParser csvParser = null;
    try {
        csvParser = new CSVParser(csv, CSVFormat.DEFAULT);

        for (CSVRecord csvRecord : csvParser) {
            SourceLineDoc doc = new SourceLineDoc(Maps.<String, Object>newHashMap());

            doc.setProjectUuid(projectUuid);
            doc.setFileUuid(fileUuid);
            doc.setLine(line);
            doc.setUpdateDate(updatedDate);
            doc.setScmRevision(csvRecord.get(0));
            doc.setScmAuthor(csvRecord.get(1));
            doc.setScmDate(DateUtils.parseDateTimeQuietly(csvRecord.get(2)));
            // UT
            doc.setUtLineHits(parseIntegerFromRecord(csvRecord.get(3)));
            doc.setUtConditions(parseIntegerFromRecord(csvRecord.get(4)));
            doc.setUtCoveredConditions(parseIntegerFromRecord(csvRecord.get(5)));
            // IT
            doc.setItLineHits(parseIntegerFromRecord(csvRecord.get(6)));
            doc.setItConditions(parseIntegerFromRecord(csvRecord.get(7)));
            doc.setItCoveredConditions(parseIntegerFromRecord(csvRecord.get(8)));
            // OVERALL
            doc.setOverallLineHits(parseIntegerFromRecord(csvRecord.get(9)));
            doc.setOverallConditions(parseIntegerFromRecord(csvRecord.get(10)));
            doc.setOverallCoveredConditions(parseIntegerFromRecord(csvRecord.get(11)));
            doc.setHighlighting(csvRecord.get(12));
            doc.setSymbols(csvRecord.get(13));

            doc.setDuplications(parseDuplications(csvRecord.get(14)));
            doc.setSource(csvRecord.get(csvRecord.size() - 1));

            result.addLine(doc);

            line++;
        }
    } catch (IOException ioError) {
        throw new IllegalStateException(
                "Impossible to open stream for file_sources.data with file_uuid " + fileUuid, ioError);
    } catch (ArrayIndexOutOfBoundsException lineError) {
        throw new IllegalStateException(
                String.format("Impossible to parse source line data, stuck at line %d", line), lineError);
    } finally {
        IOUtils.closeQuietly(csv);
        IOUtils.closeQuietly(csvParser);
    }

    return result;
}

From source file:org.springframework.jdbc.support.lob.DefaultLobHandler.java

@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 {/*from   w  w w  . j a  v  a 2s .c  om*/
        return rs.getCharacterStream(columnIndex);
    }
}

From source file:pl.psnc.synat.wrdz.realm.db.WrdzUserDatabaseHandler.java

/**
 * Retrieves user's password from the users database.
 * /*  w w  w .java2s  .  c  o  m*/
 * @param username
 *            name of the user whose password is to be retrieved.
 * @return retrieved password.
 */
public Password getPassword(String username) {
    Connection connection = null;
    PreparedStatement statement = null;
    ResultSet resultSet = null;
    try {
        connection = getConnection();
        statement = connection.prepareStatement(passwordQuery);
        statement.setString(1, username);
        resultSet = statement.executeQuery();
        if (resultSet.next()) {
            Reader pwdReader = resultSet.getCharacterStream(1);
            final char[] password = extractFromReader(pwdReader);
            final byte[] passwordBytes = Utility.convertCharArrayToByteArray(password, null);
            return digestAuthHandler.extractPasswordInformation(password, passwordBytes);
        }
    } catch (Exception ex) {
        logger.log(Level.SEVERE, "Cannot validate user with username ", username);
        if (logger.isLoggable(Level.FINE)) {
            logger.log(Level.FINE, "Cannot validate user", ex);
        }
    } finally {
        close(connection, statement, resultSet);
    }
    return null;
}