Example usage for java.sql Clob getSubString

List of usage examples for java.sql Clob getSubString

Introduction

In this page you can find the example usage for java.sql Clob getSubString.

Prototype

String getSubString(long pos, int length) throws SQLException;

Source Link

Document

Retrieves a copy of the specified substring in the CLOB value designated by this Clob object.

Usage

From source file:org.apache.sqoop.lib.LargeObjectLoader.java

/**
 * Actually read a ClobRef instance from the ResultSet and materialize
 * the data either inline or to a file./*from   w  w  w .ja  v  a 2  s.  c om*/
 *
 * @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()));
    }
}

From source file:org.apache.tika.parser.jdbc.JDBCTableReader.java

protected void handleClob(String tableName, String columnName, int rowNum, ResultSet resultSet, int columnIndex,
        ContentHandler handler, ParseContext context) throws SQLException, IOException, SAXException {
    Clob clob = resultSet.getClob(columnIndex);
    if (resultSet.wasNull()) {
        return;// w  ww  .  java 2s  .c o m
    }
    boolean truncated = clob.length() > Integer.MAX_VALUE || clob.length() > maxClobLength;

    int readSize = (clob.length() < maxClobLength ? (int) clob.length() : maxClobLength);
    Metadata m = new Metadata();
    m.set(Database.TABLE_NAME, tableName);
    m.set(Database.COLUMN_NAME, columnName);
    m.set(Database.PREFIX + "ROW_NUM", Integer.toString(rowNum));
    m.set(Database.PREFIX + "IS_CLOB", "true");
    m.set(Database.PREFIX + "CLOB_LENGTH", Long.toString(clob.length()));
    m.set(Database.PREFIX + "IS_CLOB_TRUNCATED", Boolean.toString(truncated));
    m.set(Metadata.CONTENT_TYPE, "text/plain; charset=UTF-8");
    m.set(Metadata.CONTENT_LENGTH, Integer.toString(readSize));
    m.set(TikaMetadataKeys.RESOURCE_NAME_KEY,
            //just in case something screwy is going on with the column name
            FilenameUtils.normalize(FilenameUtils.getName(columnName + "_" + rowNum + ".txt")));

    //is there a more efficient way to go from a Reader to an InputStream?
    String s = clob.getSubString(0, readSize);
    if (embeddedDocumentUtil.shouldParseEmbedded(m)) {
        embeddedDocumentUtil.parseEmbedded(new ByteArrayInputStream(s.getBytes(UTF_8)), handler, m, true);
    }
}

From source file:org.finra.dm.dao.Log4jOverridableConfigurer.java

/**
 * Converts a CLOB to a string. This method was mostly obtained from DatabaseConfiguration.
 *
 * @param clob the CLOB to be converted.
 *
 * @return the extracted string value./*from   www  .j av  a2 s .  c o m*/
 * @throws SQLException if an error occurs.
 */
protected String convertClob(Clob clob) throws SQLException {
    int len = (int) clob.length();
    return (len > 0) ? clob.getSubString(1, len) : ""; // Note getSubString has the first character at position 1 (not 0).
}

From source file:org.jboss.dashboard.database.hibernate.StringBlobType.java

public Object nullSafeGet(ResultSet rs, String[] names, SessionImplementor session, Object owner)
        throws HibernateException, SQLException {
    if (log.isDebugEnabled())
        log.debug("Getting value with names " + Arrays.asList(names));
    Object o = rs.getObject(names[0]);
    if (o == null) {
        return null;
    } else if (o instanceof Blob) {
        final Blob blob = (Blob) o;
        try {/* w w  w .  j  ava2s .co  m*/
            byte bytes[] = blob.getBytes(1, (int) blob.length());
            if (bytes == null)
                return null;
            return new String(bytes, STRING_ENCODING);
        } catch (UnsupportedEncodingException e) {
            log.error("Error:", e);
            return new String(blob.getBytes(1, (int) blob.length()));
        }
    } else if (o instanceof String) {
        return o;
    } else if (o instanceof byte[]) {
        try {
            return new String((byte[]) o, STRING_ENCODING);
        } catch (UnsupportedEncodingException e) {
            log.error("Error: ", e);
            return null;
        }
    } else if (o instanceof Clob) {
        //added for H2 support
        final Clob clob = (Clob) o;
        return clob.getSubString(1, (int) clob.length());
    } else {
        throw new IllegalArgumentException(
                "Unexpected value read. Must be Blob or String, but it is " + o.getClass());
    }
}

From source file:org.jumpmind.symmetric.db.derby.DerbyFunctions.java

public static String clobToString(String columnName, String tableName, String whereClause) throws SQLException {
    String str = null;//  w ww  . j a  va2  s  .  c o  m
    if (StringUtils.isNotBlank(whereClause)) {
        Connection conn = DriverManager.getConnection(CURRENT_CONNECTION_URL);
        String sql = "select " + columnName + " from " + tableName + " where " + whereClause;
        PreparedStatement ps = conn.prepareStatement(sql);
        ResultSet rs = ps.executeQuery();
        if (rs.next()) {
            Clob clob = rs.getClob(1);
            if (clob != null) {
                str = clob.getSubString(1, MAX_STRING_LENGTH);
            }
        }
        ps.close();
        conn.close();
    }
    return str == null ? "" : escape(str);
}

From source file:org.orbisgis.corejdbc.internal.ReadRowSetImpl.java

/**
 * Fetch a batch that start with firstPk
 *
 * @param firstPk     First row PK/*  ww  w.  j av a2  s .  c o  m*/
 * @param cacheData   False to only feed rowFetchFirstPk
 * @param queryOffset Offset pk fetching by this number of rows
 * @return Pk of next batch
 * @throws SQLException
 */
private Long fetchBatch(Long firstPk, boolean cacheData, int queryOffset) throws SQLException {
    if (cacheData) {
        currentBatch.clear();
    }
    final int columnCount = getColumnCount();
    if (cachedColumnNames == null) {
        cacheColumnNames();
    }
    boolean ignoreFirstColumn = !cachedColumnNames.containsKey(pk_name);
    try (Connection connection = dataSource.getConnection();
            PreparedStatement st = createBatchQuery(connection, firstPk, cacheData, queryOffset,
                    cacheData ? fetchSize + 1 : 1, ignoreFirstColumn || !cacheData);
            ResultSet rsBatch = st.executeQuery()) {

        int curRow = 1;
        while (rsBatch.next()) {
            long currentRowPk = rsBatch.getLong(pk_name);
            if (cacheData) {
                int offset = ignoreFirstColumn ? 1 : 0;
                Object[] row = new Object[columnCount];
                for (int idColumn = 1 + offset; idColumn <= columnCount + offset; idColumn++) {
                    Object obj = rsBatch.getObject(idColumn);
                    if (obj instanceof Clob) {
                        Clob clob = (Clob) obj;
                        obj = clob.getSubString(1, NUMBER_CHARACTERS) + " ...";
                    }
                    row[idColumn - 1 - offset] = obj;
                }
                currentBatch.add(new Row(row, currentRowPk));
                if (curRow++ == fetchSize + 1) {
                    return rsBatch.getLong(pk_name);
                }
            } else {
                return currentRowPk;
            }
        }
        return null;

    }
}

From source file:org.orbisgis.corejdbc.internal.ReadRowSetImpl.java

/**
 * Read the content of the DB near the current row id
 *//*  w  w  w .  java2s. co m*/
protected void refreshRowCache() throws SQLException {
    if (!cache.containsKey(rowId) && rowId > 0 && rowId <= getRowCount()) {
        try (Resource res = resultSetHolder.getResource()) {
            ResultSet rs = res.getResultSet();
            final int columnCount = getColumnCount();
            if (cachedColumnNames == null) {
                cacheColumnNames();
            }
            // Do not use pk if not available or if using indeterminate fetch without filtering
            if (pk_name.isEmpty()) {
                boolean validRow = false;
                if (rs.getType() == ResultSet.TYPE_FORWARD_ONLY) {
                    if (rowId < rs.getRow()) {
                        // If the result set is Forward only, we have to re-execute the request in order to read the row
                        resultSetHolder.close();
                        res.close();
                        try (Resource res2 = resultSetHolder.getResource()) {
                            rs = res2.getResultSet();
                        }
                    }
                    while (rs.getRow() < rowId) {
                        validRow = rs.next();
                    }
                } else {
                    validRow = rs.absolute((int) rowId);
                }
                if (validRow) {
                    Object[] row = new Object[columnCount];
                    for (int idColumn = 1; idColumn <= columnCount; idColumn++) {
                        Object obj = rs.getObject(idColumn);
                        if (obj instanceof Clob) {
                            Clob clob = (Clob) obj;
                            obj = clob.getSubString(1, (int) clob.length());
                        }
                        row[idColumn - 1] = obj;
                    }
                    cache.put(rowId, new Row(row, null));
                }
            } else {
                // Fetch block pk of current row
                final int targetBatch = (int) (rowId - 1) / fetchSize;
                if (currentBatchId != targetBatch) {
                    if (targetBatch >= rowFetchFirstPk.size()
                            || (targetBatch != 0 && rowFetchFirstPk.get(targetBatch) == null)) {
                        // For optimisation sake
                        // Like binary search if the gap of target batch is too wide, require average PK values
                        int topBatchCount = getBatchCount();
                        int lowerBatchCount = 0;
                        int intermediateBatchFetching = 0;
                        while (lowerBatchCount + ((topBatchCount - lowerBatchCount) / 2) != targetBatch
                                && intermediateBatchFetching < MAX_INTERMEDIATE_BATCH) {
                            int midleBatchTarget = lowerBatchCount + ((topBatchCount - lowerBatchCount) / 2);
                            if (targetBatch < midleBatchTarget) {
                                topBatchCount = midleBatchTarget;
                            } else {
                                if (midleBatchTarget >= rowFetchFirstPk.size()
                                        || rowFetchFirstPk.get(midleBatchTarget) == null) {
                                    fetchBatchPk(midleBatchTarget);
                                }
                                intermediateBatchFetching++;
                                lowerBatchCount = midleBatchTarget;
                            }
                        }
                        fetchBatchPk(targetBatch);
                    }
                    // Fetch all data of current batch
                    Long firstPk = fetchBatch(rowFetchFirstPk.get(targetBatch), true, 0);
                    if (firstPk != null) {
                        if (targetBatch + 1 < rowFetchFirstPk.size()) {
                            rowFetchFirstPk.set(targetBatch + 1, firstPk);
                        } else {
                            rowFetchFirstPk.add(firstPk);
                        }
                    }
                    currentBatchId = targetBatch;
                }
                // Ok, still in current batch
                int targetRowInBatch = (int) (rowId - 1) % fetchSize;
                if (targetRowInBatch < currentBatch.size()) {
                    cache.put(rowId, currentBatch.get(targetRowInBatch));
                }
            }
        }
    }
    currentRow = cache.get(rowId);
}

From source file:org.pentaho.di.jdbc.Support.java

/**
 * Convert an existing data object to the specified JDBC type.
 *
 * @param callerReference an object reference to the caller of this method;
 *                        must be a <code>Connection</code>,
 *                        <code>Statement</code> or <code>ResultSet</code>
 * @param x               the data object to convert
 * @param jdbcType        the required type constant from
 *                        <code>java.sql.Types</code>
 * @return the converted data object//from  w  ww. j  a v  a2s  .  c  o  m
 * @throws SQLException if the conversion is not supported or fails
 */
static Object convert(Object callerReference, Object x, int jdbcType, String charSet) throws SQLException {
    try {
        switch (jdbcType) {
        case java.sql.Types.TINYINT:
        case java.sql.Types.SMALLINT:
        case java.sql.Types.INTEGER:
            if (x == null) {
                return INTEGER_ZERO;
            } else if (x instanceof Integer) {
                return x;
            } else if (x instanceof Byte) {
                return new Integer(((Byte) x).byteValue() & 0xFF);
            } else if (x instanceof Number) {
                return new Integer(((Number) x).intValue());
            } else if (x instanceof String) {
                return new Integer(((String) x).trim());
            } else if (x instanceof Boolean) {
                return ((Boolean) x).booleanValue() ? INTEGER_ONE : INTEGER_ZERO;
            }
            break;

        case java.sql.Types.BIGINT:
            if (x == null) {
                return LONG_ZERO;
            } else if (x instanceof Long) {
                return x;
            } else if (x instanceof Byte) {
                return new Long(((Byte) x).byteValue() & 0xFF);
            } else if (x instanceof Number) {
                return new Long(((Number) x).longValue());
            } else if (x instanceof String) {
                return new Long(((String) x).trim());
            } else if (x instanceof Boolean) {
                return ((Boolean) x).booleanValue() ? LONG_ONE : LONG_ZERO;
            }

            break;

        case java.sql.Types.REAL:
            if (x == null) {
                return FLOAT_ZERO;
            } else if (x instanceof Float) {
                return x;
            } else if (x instanceof Byte) {
                return new Float(((Byte) x).byteValue() & 0xFF);
            } else if (x instanceof Number) {
                return new Float(((Number) x).floatValue());
            } else if (x instanceof String) {
                return new Float(((String) x).trim());
            } else if (x instanceof Boolean) {
                return ((Boolean) x).booleanValue() ? FLOAT_ONE : FLOAT_ZERO;
            }

            break;

        case java.sql.Types.FLOAT:
        case java.sql.Types.DOUBLE:
            if (x == null) {
                return DOUBLE_ZERO;
            } else if (x instanceof Double) {
                return x;
            } else if (x instanceof Byte) {
                return new Double(((Byte) x).byteValue() & 0xFF);
            } else if (x instanceof Number) {
                return new Double(((Number) x).doubleValue());
            } else if (x instanceof String) {
                return new Double(((String) x).trim());
            } else if (x instanceof Boolean) {
                return ((Boolean) x).booleanValue() ? DOUBLE_ONE : DOUBLE_ZERO;
            }

            break;

        case java.sql.Types.NUMERIC:
        case java.sql.Types.DECIMAL:
            if (x == null) {
                return null;
            } else if (x instanceof BigDecimal) {
                return x;
            } else if (x instanceof Number) {
                return new BigDecimal(x.toString());
            } else if (x instanceof String) {
                return new BigDecimal((String) x);
            } else if (x instanceof Boolean) {
                return ((Boolean) x).booleanValue() ? BIG_DECIMAL_ONE : BIG_DECIMAL_ZERO;
            }

            break;

        case java.sql.Types.VARCHAR:
        case java.sql.Types.CHAR:
            if (x == null) {
                return null;
            } else if (x instanceof String) {
                return x;
            } else if (x instanceof Number) {
                return x.toString();
            } else if (x instanceof Boolean) {
                return ((Boolean) x).booleanValue() ? "1" : "0";
            } else if (x instanceof Clob) {
                Clob clob = (Clob) x;
                long length = clob.length();

                if (length > Integer.MAX_VALUE) {
                    throw new SQLException(BaseMessages.getString(PKG, "error.normalize.lobtoobig"), "22000");
                }

                return clob.getSubString(1, (int) length);
            } else if (x instanceof Blob) {
                Blob blob = (Blob) x;
                long length = blob.length();

                if (length > Integer.MAX_VALUE) {
                    throw new SQLException(BaseMessages.getString(PKG, "error.normalize.lobtoobig"), "22000");
                }

                x = blob.getBytes(1, (int) length);
            }

            if (x instanceof byte[]) {
                return toHex((byte[]) x);
            }

            return x.toString(); // Last hope!

        case java.sql.Types.BIT:
        case java.sql.Types.BOOLEAN:
            if (x == null) {
                return Boolean.FALSE;
            } else if (x instanceof Boolean) {
                return x;
            } else if (x instanceof Number) {
                return (((Number) x).intValue() == 0) ? Boolean.FALSE : Boolean.TRUE;
            } else if (x instanceof String) {
                String tmp = ((String) x).trim();

                return ("1".equals(tmp) || "true".equalsIgnoreCase(tmp)) ? Boolean.TRUE : Boolean.FALSE;
            }

            break;

        case java.sql.Types.VARBINARY:
        case java.sql.Types.BINARY:
            if (x == null) {
                return null;
            } else if (x instanceof byte[]) {
                return x;
            } else if (x instanceof Blob) {
                Blob blob = (Blob) x;

                return blob.getBytes(1, (int) blob.length());
            } else if (x instanceof Clob) {
                Clob clob = (Clob) x;
                long length = clob.length();

                if (length > Integer.MAX_VALUE) {
                    throw new SQLException(BaseMessages.getString(PKG, "error.normalize.lobtoobig"), "22000");
                }

                x = clob.getSubString(1, (int) length);
            }

            if (x instanceof String) {
                //
                // Strictly speaking this conversion is not required by
                // the JDBC standard but jTDS has always supported it.
                //
                if (charSet == null) {
                    charSet = "ISO-8859-1";
                }

                try {
                    return ((String) x).getBytes(charSet);
                } catch (UnsupportedEncodingException e) {
                    return ((String) x).getBytes();
                }
            } else if (x instanceof UniqueIdentifier) {
                return ((UniqueIdentifier) x).getBytes();
            }

            break;

        case java.sql.Types.TIMESTAMP:
            if (x == null) {
                return null;
            } else if (x instanceof DateTime) {
                return ((DateTime) x).toTimestamp();
            } else if (x instanceof java.sql.Timestamp) {
                return x;
            } else if (x instanceof java.sql.Date) {
                return new java.sql.Timestamp(((java.sql.Date) x).getTime());
            } else if (x instanceof java.sql.Time) {
                return new java.sql.Timestamp(((java.sql.Time) x).getTime());
            } else if (x instanceof java.lang.String) {
                return java.sql.Timestamp.valueOf(((String) x).trim());
            }

            break;

        case java.sql.Types.DATE:
            if (x == null) {
                return null;
            } else if (x instanceof DateTime) {
                return ((DateTime) x).toDate();
            } else if (x instanceof java.sql.Date) {
                return x;
            } else if (x instanceof java.sql.Time) {
                return DATE_ZERO;
            } else if (x instanceof java.sql.Timestamp) {
                synchronized (cal) {
                    cal.setTime((java.util.Date) x);
                    cal.set(Calendar.HOUR_OF_DAY, 0);
                    cal.set(Calendar.MINUTE, 0);
                    cal.set(Calendar.SECOND, 0);
                    cal.set(Calendar.MILLISECOND, 0);
                    // VM1.4+ only              return new java.sql.Date(cal.getTimeInMillis());
                    return new java.sql.Date(cal.getTime().getTime());
                }
            } else if (x instanceof java.lang.String) {
                return java.sql.Date.valueOf(((String) x).trim());
            }

            break;

        case java.sql.Types.TIME:
            if (x == null) {
                return null;
            } else if (x instanceof DateTime) {
                return ((DateTime) x).toTime();
            } else if (x instanceof java.sql.Time) {
                return x;
            } else if (x instanceof java.sql.Date) {
                return TIME_ZERO;
            } else if (x instanceof java.sql.Timestamp) {
                synchronized (cal) {
                    // VM 1.4+ only             cal.setTimeInMillis(((java.sql.Timestamp)x).getTime());
                    cal.setTime((java.util.Date) x);
                    cal.set(Calendar.YEAR, 1970);
                    cal.set(Calendar.MONTH, 0);
                    cal.set(Calendar.DAY_OF_MONTH, 1);
                    // VM 1.4+ only             return new java.sql.Time(cal.getTimeInMillis());*/
                    return new java.sql.Time(cal.getTime().getTime());
                }
            } else if (x instanceof java.lang.String) {
                return java.sql.Time.valueOf(((String) x).trim());
            }

            break;

        case java.sql.Types.OTHER:
            return x;

        case java.sql.Types.JAVA_OBJECT:
            throw new SQLException(BaseMessages.getString(PKG, "error.convert.badtypes", x.getClass().getName(),
                    getJdbcTypeName(jdbcType)), "22005");

        case java.sql.Types.LONGVARBINARY:
        case java.sql.Types.BLOB:
            if (x == null) {
                return null;
            } else if (x instanceof Blob) {
                return x;
            } else if (x instanceof byte[]) {
                return new BlobImpl(getConnection(callerReference), (byte[]) x);
            } else if (x instanceof Clob) {
                //
                // Convert CLOB to BLOB. Not required by the standard but we will
                // do it anyway.
                //
                Clob clob = (Clob) x;
                try {
                    if (charSet == null) {
                        charSet = "ISO-8859-1";
                    }
                    Reader rdr = clob.getCharacterStream();
                    BlobImpl blob = new BlobImpl(getConnection(callerReference));
                    BufferedWriter out = new BufferedWriter(
                            new OutputStreamWriter(blob.setBinaryStream(1), charSet));
                    // TODO Use a buffer to improve performance
                    int c;
                    while ((c = rdr.read()) >= 0) {
                        out.write(c);
                    }
                    out.close();
                    rdr.close();
                    return blob;
                } catch (UnsupportedEncodingException e) {
                    // Unlikely to happen but fall back on in memory copy
                    x = clob.getSubString(1, (int) clob.length());
                } catch (IOException e) {
                    throw new SQLException(BaseMessages.getString(PKG, "error.generic.ioerror", e.getMessage()),
                            "HY000");
                }
            }

            if (x instanceof String) {
                //
                // Strictly speaking this conversion is also not required by
                // the JDBC standard but jTDS has always supported it.
                //
                BlobImpl blob = new BlobImpl(getConnection(callerReference));
                String data = (String) x;

                if (charSet == null) {
                    charSet = "ISO-8859-1";
                }

                try {
                    blob.setBytes(1, data.getBytes(charSet));
                } catch (UnsupportedEncodingException e) {
                    blob.setBytes(1, data.getBytes());
                }

                return blob;
            }

            break;

        case java.sql.Types.LONGVARCHAR:
        case java.sql.Types.CLOB:
            if (x == null) {
                return null;
            } else if (x instanceof Clob) {
                return x;
            } else if (x instanceof Blob) {
                //
                // Convert BLOB to CLOB
                //
                Blob blob = (Blob) x;
                try {
                    InputStream is = blob.getBinaryStream();
                    ClobImpl clob = new ClobImpl(getConnection(callerReference));
                    Writer out = clob.setCharacterStream(1);
                    // TODO Use a buffer to improve performance
                    int b;
                    // These reads/writes are buffered by the undelying blob buffers
                    while ((b = is.read()) >= 0) {
                        out.write(hex[b >> 4]);
                        out.write(hex[b & 0x0F]);
                    }
                    out.close();
                    is.close();
                    return clob;
                } catch (IOException e) {
                    throw new SQLException(BaseMessages.getString(PKG, "error.generic.ioerror", e.getMessage()),
                            "HY000");
                }
            } else if (x instanceof Boolean) {
                x = ((Boolean) x).booleanValue() ? "1" : "0";
            } else if (!(x instanceof byte[])) {
                x = x.toString();
            }

            if (x instanceof byte[]) {
                ClobImpl clob = new ClobImpl(getConnection(callerReference));
                clob.setString(1, toHex((byte[]) x));

                return clob;
            } else if (x instanceof String) {
                return new ClobImpl(getConnection(callerReference), (String) x);
            }

            break;

        default:
            throw new SQLException(
                    BaseMessages.getString(PKG, "error.convert.badtypeconst", getJdbcTypeName(jdbcType)),
                    "HY004");
        }

        throw new SQLException(BaseMessages.getString(PKG, "error.convert.badtypes", x.getClass().getName(),
                getJdbcTypeName(jdbcType)), "22005");
    } catch (NumberFormatException nfe) {
        throw new SQLException(
                BaseMessages.getString(PKG, "error.convert.badnumber", getJdbcTypeName(jdbcType)), "22000");
    }
}

From source file:org.pentaho.di.jdbc.Support.java

/**
 * Embed the data object as a string literal in the buffer supplied.
 *
 * @param buf The buffer in which the data will be embeded.
 * @param value The data object./*from   w  w w  .j  a  v  a 2  s  .  c o m*/
 * @param isUnicode Set to <code>true</code> if Unicode strings should be used, else <code>false</code>.
 * @param connection The {@link ConnectionJDBC3} object.
 */
static void embedData(StringBuffer buf, Object value, boolean isUnicode, ConnectionJDBC3 connection)
        throws SQLException {
    buf.append(' ');
    if (value == null) {
        buf.append("NULL ");
        return;
    }

    if (value instanceof Blob) {
        Blob blob = (Blob) value;

        value = blob.getBytes(1, (int) blob.length());
    } else if (value instanceof Clob) {
        Clob clob = (Clob) value;

        value = clob.getSubString(1, (int) clob.length());
    }

    if (value instanceof DateTime) {
        buf.append('\'');
        buf.append(value);
        buf.append('\'');
    } else if (value instanceof byte[]) {
        byte[] bytes = (byte[]) value;

        int len = bytes.length;

        if (len >= 0) {
            buf.append('0').append('x');
            if (len == 0) {
                // Zero length binary values are not allowed
                buf.append('0').append('0');
            } else {
                for (int i = 0; i < len; i++) {
                    int b1 = bytes[i] & 0xFF;

                    buf.append(hex[b1 >> 4]);
                    buf.append(hex[b1 & 0x0F]);
                }
            }
        }
    } else if (value instanceof String) {
        String tmp = (String) value;
        int len = tmp.length();

        if (isUnicode) {
            buf.append('N');
        }
        buf.append('\'');

        for (int i = 0; i < len; i++) {
            char c = tmp.charAt(i);

            if (c == '\'') {
                buf.append('\'');
            }

            buf.append(c);
        }

        buf.append('\'');
    } else if (value instanceof java.sql.Date) {
        DateTime dt = new DateTime((java.sql.Date) value);
        buf.append('\'');
        buf.append(dt);
        buf.append('\'');
    } else if (value instanceof java.sql.Time) {
        DateTime dt = new DateTime((java.sql.Time) value);
        buf.append('\'');
        buf.append(dt);
        buf.append('\'');
    } else if (value instanceof java.sql.Timestamp) {
        DateTime dt = new DateTime((java.sql.Timestamp) value);
        buf.append('\'');
        buf.append(dt);
        buf.append('\'');
    } else if (value instanceof Boolean) {
        buf.append(((Boolean) value).booleanValue() ? '1' : '0');
    } else if (value instanceof BigDecimal) {
        //
        // Ensure large decimal number does not overflow the
        // maximum precision of the server.
        // Main problem is with small numbers e.g. BigDecimal(1.0).toString() =
        // 0.1000000000000000055511151231....
        //
        String tmp = value.toString();
        int maxlen = connection.getMaxPrecision();
        if (tmp.charAt(0) == '-') {
            maxlen++;
        }
        if (tmp.indexOf('.') >= 0) {
            maxlen++;
        }
        if (tmp.length() > maxlen) {
            buf.append(tmp.substring(0, maxlen));
        } else {
            buf.append(tmp);
        }
    } else {
        buf.append(value.toString());
    }
    buf.append(' ');
}

From source file:org.pentaho.di.jdbc.Support.java

/**
 * Converts a LOB to the equivalent Java type, i.e. <code>Clob</code> to
 * <code>String</code> and <code>Blob</code> to <code>byte[]</code>. If the
 * value passed is not a LOB object, it is left unchanged and no exception
 * is thrown; the idea is to transparently convert only LOBs.
 *
 * @param value an object that may be a LOB
 * @return if the value was a LOB, the equivalent Java object, otherwise
 *         the original value/*  w  ww .j  a  v  a2  s.  c  o  m*/
 * @throws SQLException if an error occurs while reading the LOB contents
 */
public static Object convertLOB(Object value) throws SQLException {
    if (value instanceof Clob) {
        Clob c = (Clob) value;
        return c.getSubString(1, (int) c.length());
    }

    if (value instanceof Blob) {
        Blob b = (Blob) value;
        return b.getBytes(1, (int) b.length());
    }

    return value;
}