Java Code Examples for com.mysql.cj.util.StringUtils#toString()

The following examples show how to use com.mysql.cj.util.StringUtils#toString() . 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: NativePacketPayload.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Read len bytes from internal buffer starting from current position decoding them into String using the specified character encoding.
 * 
 * @param type
 * @param encoding
 *            if null then platform default encoding is used
 * @param len
 * @return
 */
public String readString(StringLengthDataType type, String encoding, int len) {
    String res = null;
    switch (type) {
        case STRING_FIXED:
        case STRING_VAR:
            if ((this.position + len) > this.payloadLength) {
                throw ExceptionFactory.createException(WrongArgumentException.class, Messages.getString("Buffer.1"));
            }

            res = StringUtils.toString(this.byteBuffer, this.position, len, encoding);
            this.position += len;
            break;

    }
    return res;
}
 
Example 2
Source File: ResultSetImpl.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
private String getStringForClob(int columnIndex) throws SQLException {
    String asString = null;

    String forcedEncoding = this.connection.getPropertySet().getStringReadableProperty(PropertyDefinitions.PNAME_clobCharacterEncoding).getStringValue();

    if (forcedEncoding == null) {
        asString = getString(columnIndex);
    } else {
        byte[] asBytes = null;

        asBytes = getBytes(columnIndex);

        if (asBytes != null) {
            asString = StringUtils.toString(asBytes, forcedEncoding);
        }
    }

    return asString;
}
 
Example 3
Source File: ResultSetImpl.java    From FoxTelem with GNU General Public License v3.0 6 votes vote down vote up
private String getStringForClob(int columnIndex) throws SQLException {
    String asString = null;

    String forcedEncoding = this.connection.getPropertySet().getStringProperty(PropertyKey.clobCharacterEncoding).getStringValue();

    if (forcedEncoding == null) {
        asString = getString(columnIndex);
    } else {
        byte[] asBytes = null;

        asBytes = getBytes(columnIndex);

        if (asBytes != null) {
            asString = StringUtils.toString(asBytes, forcedEncoding);
        }
    }

    return asString;
}
 
Example 4
Source File: NativePacketPayload.java    From FoxTelem with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Read len bytes from internal buffer starting from current position decoding them into String using the specified character encoding.
 * 
 * @param type
 *            {@link StringLengthDataType}
 * @param encoding
 *            if null then platform default encoding is used
 * @param len
 *            length
 * @return string
 */
public String readString(StringLengthDataType type, String encoding, int len) {
    String res = null;
    switch (type) {
        case STRING_FIXED:
        case STRING_VAR:
            if ((this.position + len) > this.payloadLength) {
                throw ExceptionFactory.createException(WrongArgumentException.class, Messages.getString("Buffer.1"));
            }

            res = StringUtils.toString(this.byteBuffer, this.position, len, encoding);
            this.position += len;
            break;

    }
    return res;
}
 
Example 5
Source File: NativePacketPayload.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
public static String extractSqlFromPacket(String possibleSqlQuery, NativePacketPayload packet, int endOfQueryPacketPosition, int maxQuerySizeToLog) {
    String extractedSql = null;

    if (possibleSqlQuery != null) {
        if (possibleSqlQuery.length() > maxQuerySizeToLog) {
            StringBuilder truncatedQueryBuf = new StringBuilder(possibleSqlQuery.substring(0, maxQuerySizeToLog));
            truncatedQueryBuf.append(Messages.getString("MysqlIO.25"));
            extractedSql = truncatedQueryBuf.toString();
        } else {
            extractedSql = possibleSqlQuery;
        }
    }

    if (extractedSql == null) {
        // This is probably from a client-side prepared statement

        int extractPosition = endOfQueryPacketPosition;

        boolean truncated = false;

        if (endOfQueryPacketPosition > maxQuerySizeToLog) {
            extractPosition = maxQuerySizeToLog;
            truncated = true;
        }

        extractedSql = StringUtils.toString(packet.getByteBuffer(), 1, (extractPosition - 1));

        if (truncated) {
            extractedSql += Messages.getString("MysqlIO.25");
        }
    }

    return extractedSql;
}
 
Example 6
Source File: NativePacketPayload.java    From FoxTelem with GNU General Public License v3.0 5 votes vote down vote up
public static String extractSqlFromPacket(String possibleSqlQuery, NativePacketPayload packet, int endOfQueryPacketPosition, int maxQuerySizeToLog) {
    String extractedSql = null;

    if (possibleSqlQuery != null) {
        if (possibleSqlQuery.length() > maxQuerySizeToLog) {
            StringBuilder truncatedQueryBuf = new StringBuilder(possibleSqlQuery.substring(0, maxQuerySizeToLog));
            truncatedQueryBuf.append(Messages.getString("MysqlIO.25"));
            extractedSql = truncatedQueryBuf.toString();
        } else {
            extractedSql = possibleSqlQuery;
        }
    }

    if (extractedSql == null) {
        // This is probably from a client-side prepared statement

        int extractPosition = endOfQueryPacketPosition;

        boolean truncated = false;

        if (endOfQueryPacketPosition > maxQuerySizeToLog) {
            extractPosition = maxQuerySizeToLog;
            truncated = true;
        }

        extractedSql = StringUtils.toString(packet.getByteBuffer(), 1, (extractPosition - 1));

        if (truncated) {
            extractedSql += Messages.getString("MysqlIO.25");
        }
    }

    return extractedSql;
}
 
Example 7
Source File: CallableStatement.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Check whether the stored procedure alters any data or is safe for read-only usage.
 * 
 * @return true if procedure does not alter data
 * @throws SQLException
 */
private boolean checkReadOnlyProcedure() throws SQLException {
    synchronized (checkClosed().getConnectionMutex()) {
        if (this.noAccessToProcedureBodies) {
            return false;
        }

        if (this.paramInfo.isReadOnlySafeChecked) {
            return this.paramInfo.isReadOnlySafeProcedure;
        }

        ResultSet rs = null;
        java.sql.PreparedStatement ps = null;

        try {
            String procName = extractProcedureName();

            String catalog = this.getCurrentCatalog();

            if (procName.indexOf(".") != -1) {
                catalog = procName.substring(0, procName.indexOf("."));

                if (StringUtils.startsWithIgnoreCaseAndWs(catalog, "`") && catalog.trim().endsWith("`")) {
                    catalog = catalog.substring(1, catalog.length() - 1);
                }

                procName = procName.substring(procName.indexOf(".") + 1);
                procName = StringUtils.toString(StringUtils.stripEnclosure(StringUtils.getBytes(procName), "`", "`"));
            }
            ps = this.connection.prepareStatement("SELECT SQL_DATA_ACCESS FROM information_schema.routines WHERE routine_schema = ? AND routine_name = ?");
            ps.setMaxRows(0);
            ps.setFetchSize(0);

            ps.setString(1, catalog);
            ps.setString(2, procName);
            rs = ps.executeQuery();
            if (rs.next()) {
                String sqlDataAccess = rs.getString(1);
                if ("READS SQL DATA".equalsIgnoreCase(sqlDataAccess) || "NO SQL".equalsIgnoreCase(sqlDataAccess)) {
                    synchronized (this.paramInfo) {
                        this.paramInfo.isReadOnlySafeChecked = true;
                        this.paramInfo.isReadOnlySafeProcedure = true;
                    }
                    return true;
                }
            }
        } catch (SQLException e) {
            // swallow the Exception
        } finally {
            if (rs != null) {
                rs.close();
            }
            if (ps != null) {
                ps.close();
            }

        }
        this.paramInfo.isReadOnlySafeChecked = false;
        this.paramInfo.isReadOnlySafeProcedure = false;
    }
    return false;

}
 
Example 8
Source File: ProfilerEventImpl.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Unpacks a binary representation of this event.
 * 
 * @param buf
 *            the binary representation of this event
 * @return the unpacked Event
 */
public static ProfilerEvent unpack(byte[] buf) {
    int pos = 0;

    byte eventType = buf[pos++];
    long connectionId = readInt(buf, pos);
    pos += 8;
    int statementId = readInt(buf, pos);
    pos += 4;
    int resultSetId = readInt(buf, pos);
    pos += 4;
    long eventCreationTime = readLong(buf, pos);
    pos += 8;
    long eventDuration = readLong(buf, pos);
    pos += 4;

    byte[] eventDurationUnits = readBytes(buf, pos);
    pos += 4;

    if (eventDurationUnits != null) {
        pos += eventDurationUnits.length;
    }

    readInt(buf, pos);
    pos += 4;
    byte[] eventCreationAsBytes = readBytes(buf, pos);
    pos += 4;

    if (eventCreationAsBytes != null) {
        pos += eventCreationAsBytes.length;
    }

    byte[] message = readBytes(buf, pos);
    pos += 4;

    if (message != null) {
        pos += message.length;
    }

    return new ProfilerEventImpl(eventType, "", "", connectionId, statementId, resultSetId, eventCreationTime, eventDuration,
            StringUtils.toString(eventDurationUnits, "ISO8859_1"), StringUtils.toString(eventCreationAsBytes, "ISO8859_1"), null,
            StringUtils.toString(message, "ISO8859_1"));
}
 
Example 9
Source File: StringConverter.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Implement the logic for indirect conversions.
 */
@Override
public T createFromBytes(byte[] origBytes, int offset, int length) {
    MysqlTextValueDecoder stringInterpreter = new MysqlTextValueDecoder();

    // TODO: Too expensive to convert from other charset to ASCII here? UTF-8 (e.g.) doesn't need any conversion before being sent to the decoder
    String s = StringUtils.toString(origBytes, offset, length, this.encoding);
    byte[] bytes = s.getBytes();

    ValueFactory<T> vf = this.targetVf;

    issueConversionViaParsingWarning();

    if (s.length() == 0) {
        if (this.emptyStringsConvertToZero) {
            // use long=0 as this is mainly numerical oriented
            return this.targetVf.createFromLong(0);
        }
        // Else throw exception down below
    } else if (s.equalsIgnoreCase("true")) {
        return vf.createFromLong(1);
    } else if (s.equalsIgnoreCase("false")) {
        return vf.createFromLong(0);
    } else if (s.contains("e") || s.contains("E") || s.matches("-?(\\d+)?\\.\\d+")) {
        // floating point
        return stringInterpreter.decodeDouble(bytes, 0, bytes.length, vf);
    } else if (s.matches("-?\\d+")) {
        // integer
        if (s.charAt(0) == '-') {
            return stringInterpreter.decodeInt8(bytes, 0, bytes.length, vf);
        }
        return stringInterpreter.decodeUInt8(bytes, 0, bytes.length, vf);
    } else if (s.length() == MysqlTextValueDecoder.DATE_BUF_LEN && s.charAt(4) == '-' && s.charAt(7) == '-') {
        return stringInterpreter.decodeDate(bytes, 0, bytes.length, vf);
    } else if (s.length() >= MysqlTextValueDecoder.TIME_STR_LEN_MIN && s.length() <= MysqlTextValueDecoder.TIME_STR_LEN_MAX && s.charAt(2) == ':'
            && s.charAt(5) == ':') {
        return stringInterpreter.decodeTime(bytes, 0, bytes.length, vf);
    } else if (s.length() >= MysqlTextValueDecoder.TIMESTAMP_NOFRAC_STR_LEN
            && (s.length() <= MysqlTextValueDecoder.TIMESTAMP_STR_LEN_MAX || s.length() == MysqlTextValueDecoder.TIMESTAMP_STR_LEN_WITH_NANOS)
            && s.charAt(4) == '-' && s.charAt(7) == '-' && s.charAt(10) == ' ' && s.charAt(13) == ':' && s.charAt(16) == ':') {
        return stringInterpreter.decodeTimestamp(bytes, 0, bytes.length, vf);
    }
    throw new DataConversionException(Messages.getString("ResultSet.UnableToInterpretString", new Object[] { s }));
}
 
Example 10
Source File: CallableStatement.java    From FoxTelem with GNU General Public License v3.0 4 votes vote down vote up
/**
 * Check whether the stored procedure alters any data or is safe for read-only usage.
 * 
 * @return true if procedure does not alter data
 * @throws SQLException
 *             if a database access error occurs or this method is called on a closed PreparedStatement
 */
private boolean checkReadOnlyProcedure() throws SQLException {
    synchronized (checkClosed().getConnectionMutex()) {
        if (this.noAccessToProcedureBodies) {
            return false;
        }

        if (this.paramInfo.isReadOnlySafeChecked) {
            return this.paramInfo.isReadOnlySafeProcedure;
        }

        ResultSet rs = null;
        java.sql.PreparedStatement ps = null;

        try {
            String procName = extractProcedureName();

            String catalog = this.getCurrentCatalog();

            if (procName.indexOf(".") != -1) {
                catalog = procName.substring(0, procName.indexOf("."));

                if (StringUtils.startsWithIgnoreCaseAndWs(catalog, "`") && catalog.trim().endsWith("`")) {
                    catalog = catalog.substring(1, catalog.length() - 1);
                }

                procName = procName.substring(procName.indexOf(".") + 1);
                procName = StringUtils.toString(StringUtils.stripEnclosure(StringUtils.getBytes(procName), "`", "`"));
            }
            ps = this.connection.prepareStatement("SELECT SQL_DATA_ACCESS FROM information_schema.routines WHERE routine_schema = ? AND routine_name = ?");
            ps.setMaxRows(0);
            ps.setFetchSize(0);

            ps.setString(1, catalog);
            ps.setString(2, procName);
            rs = ps.executeQuery();
            if (rs.next()) {
                String sqlDataAccess = rs.getString(1);
                if ("READS SQL DATA".equalsIgnoreCase(sqlDataAccess) || "NO SQL".equalsIgnoreCase(sqlDataAccess)) {
                    synchronized (this.paramInfo) {
                        this.paramInfo.isReadOnlySafeChecked = true;
                        this.paramInfo.isReadOnlySafeProcedure = true;
                    }
                    return true;
                }
            }
        } catch (SQLException e) {
            // swallow the Exception
        } finally {
            if (rs != null) {
                rs.close();
            }
            if (ps != null) {
                ps.close();
            }

        }
        this.paramInfo.isReadOnlySafeChecked = false;
        this.paramInfo.isReadOnlySafeProcedure = false;
    }
    return false;

}
 
Example 11
Source File: ProfilerEventImpl.java    From FoxTelem with GNU General Public License v3.0 4 votes vote down vote up
/**
 * Unpacks a binary representation of this event.
 * 
 * @param buf
 *            the binary representation of this event
 * @return the unpacked Event
 */
public static ProfilerEvent unpack(byte[] buf) {
    int pos = 0;

    byte eventType = buf[pos++];
    long connectionId = readInt(buf, pos);
    pos += 8;
    int statementId = readInt(buf, pos);
    pos += 4;
    int resultSetId = readInt(buf, pos);
    pos += 4;
    long eventCreationTime = readLong(buf, pos);
    pos += 8;
    long eventDuration = readLong(buf, pos);
    pos += 4;

    byte[] eventDurationUnits = readBytes(buf, pos);
    pos += 4;

    if (eventDurationUnits != null) {
        pos += eventDurationUnits.length;
    }

    readInt(buf, pos);
    pos += 4;
    byte[] eventCreationAsBytes = readBytes(buf, pos);
    pos += 4;

    if (eventCreationAsBytes != null) {
        pos += eventCreationAsBytes.length;
    }

    byte[] message = readBytes(buf, pos);
    pos += 4;

    if (message != null) {
        pos += message.length;
    }

    return new ProfilerEventImpl(eventType, "", "", connectionId, statementId, resultSetId, eventCreationTime, eventDuration,
            StringUtils.toString(eventDurationUnits, "ISO8859_1"), StringUtils.toString(eventCreationAsBytes, "ISO8859_1"), null,
            StringUtils.toString(message, "ISO8859_1"));
}
 
Example 12
Source File: StringConverter.java    From FoxTelem with GNU General Public License v3.0 4 votes vote down vote up
/**
 * Implement the logic for indirect conversions.
 */
@Override
public T createFromBytes(byte[] origBytes, int offset, int length) {
    MysqlTextValueDecoder stringInterpreter = new MysqlTextValueDecoder();

    // TODO: Too expensive to convert from other charset to ASCII here? UTF-8 (e.g.) doesn't need any conversion before being sent to the decoder
    String s = StringUtils.toString(origBytes, offset, length, this.encoding);
    byte[] bytes = s.getBytes();

    ValueFactory<T> vf = this.targetVf;

    issueConversionViaParsingWarning();

    if (s.length() == 0) {
        if (this.emptyStringsConvertToZero) {
            // use long=0 as this is mainly numerical oriented
            return this.targetVf.createFromLong(0);
        }
        // Else throw exception down below
    } else if (s.equalsIgnoreCase("true")) {
        return vf.createFromLong(1);
    } else if (s.equalsIgnoreCase("false")) {
        return vf.createFromLong(0);
    } else if (s.contains("e") || s.contains("E") || s.matches("-?(\\d+)?\\.\\d+")) {
        // floating point
        return stringInterpreter.decodeDouble(bytes, 0, bytes.length, vf);
    } else if (s.matches("-?\\d+")) {
        // integer
        if (s.charAt(0) == '-') {
            return stringInterpreter.decodeInt8(bytes, 0, bytes.length, vf);
        }
        return stringInterpreter.decodeUInt8(bytes, 0, bytes.length, vf);
    } else if (s.length() == MysqlTextValueDecoder.DATE_BUF_LEN && s.charAt(4) == '-' && s.charAt(7) == '-') {
        return stringInterpreter.decodeDate(bytes, 0, bytes.length, vf);
    } else if (s.length() >= MysqlTextValueDecoder.TIME_STR_LEN_MIN && s.length() <= MysqlTextValueDecoder.TIME_STR_LEN_MAX && s.charAt(2) == ':'
            && s.charAt(5) == ':') {
        return stringInterpreter.decodeTime(bytes, 0, bytes.length, vf);
    } else if (s.length() >= MysqlTextValueDecoder.TIMESTAMP_NOFRAC_STR_LEN
            && (s.length() <= MysqlTextValueDecoder.TIMESTAMP_STR_LEN_MAX || s.length() == MysqlTextValueDecoder.TIMESTAMP_STR_LEN_WITH_NANOS)
            && s.charAt(4) == '-' && s.charAt(7) == '-' && s.charAt(10) == ' ' && s.charAt(13) == ':' && s.charAt(16) == ':') {
        return stringInterpreter.decodeTimestamp(bytes, 0, bytes.length, vf);
    }
    throw new DataConversionException(Messages.getString("ResultSet.UnableToInterpretString", new Object[] { s }));
}
 
Example 13
Source File: StringValueFactory.java    From lams with GNU General Public License v2.0 2 votes vote down vote up
/**
 * Interpret the given byte array as a string. This value factory needs to know the encoding to interpret the string. The default (null) will interpet the
 * byte array using the platform encoding.
 */
public String createFromBytes(byte[] bytes, int offset, int length) {
    return StringUtils.toString(bytes, offset, length, this.encoding);
}
 
Example 14
Source File: StringValueFactory.java    From FoxTelem with GNU General Public License v3.0 2 votes vote down vote up
/**
 * Interpret the given byte array as a string. This value factory needs to know the encoding to interpret the string. The default (null) will interpet the
 * byte array using the platform encoding.
 * 
 * @param bytes
 *            byte array
 * @param offset
 *            offset
 * @param length
 *            data length in bytes
 * @return string
 */
public String createFromBytes(byte[] bytes, int offset, int length) {
    return StringUtils.toString(bytes, offset, length, this.encoding);
}