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

The following examples show how to use com.mysql.cj.util.StringUtils#getBytes() . 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: JdbcPropertySetImpl.java    From FoxTelem with GNU General Public License v3.0 6 votes vote down vote up
@Override
public void postInitialization() {

    // Adjust max rows
    if (getIntegerProperty(PropertyKey.maxRows).getValue() == 0) {
        // adjust so that it will become MysqlDefs.MAX_ROWS in execSQL()
        super.<Integer> getProperty(PropertyKey.maxRows).setValue(Integer.valueOf(-1), null);
    }

    //
    // Check character encoding
    //
    String testEncoding = getStringProperty(PropertyKey.characterEncoding).getValue();

    if (testEncoding != null) {
        // Attempt to use the encoding, and bail out if it can't be used
        String testString = "abc";
        StringUtils.getBytes(testString, testEncoding);
    }

    if (getBooleanProperty(PropertyKey.useCursorFetch).getValue()) {
        // assume server-side prepared statements are wanted because they're required for this functionality
        super.<Boolean> getProperty(PropertyKey.useServerPrepStmts).setValue(true);
    }
}
 
Example 2
Source File: ClientPreparedQuery.java    From FoxTelem with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Get bytes representation for a parameter in a statement batch.
 * 
 * @param parameterIndex
 *            parameter index
 * @param commandIndex
 *            command index
 * @return bytes
 */
public byte[] getBytesRepresentationForBatch(int parameterIndex, int commandIndex) {
    Object batchedArg = this.batchedArgs.get(commandIndex);
    if (batchedArg instanceof String) {
        return StringUtils.getBytes((String) batchedArg, this.charEncoding);
    }

    BindValue bv = ((ClientPreparedQueryBindings) batchedArg).getBindValues()[parameterIndex];
    if (bv.isStream()) {
        return streamToBytes(bv.getStreamValue(), false, bv.getStreamLength(), this.useStreamLengthsInPrepStmts.getValue());
    }
    byte parameterVal[] = bv.getByteValue();
    if (parameterVal == null) {
        return null;
    }

    if ((parameterVal[0] == '\'') && (parameterVal[parameterVal.length - 1] == '\'')) {
        byte[] valNoQuotes = new byte[parameterVal.length - 2];
        System.arraycopy(parameterVal, 1, valNoQuotes, 0, parameterVal.length - 2);

        return valNoQuotes;
    }

    return parameterVal;
}
 
Example 3
Source File: ClientPreparedQuery.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Get bytes representation for a parameter in a statement batch.
 * 
 * @param parameterIndex
 * @param commandIndex
 */
public byte[] getBytesRepresentationForBatch(int parameterIndex, int commandIndex) {
    Object batchedArg = this.batchedArgs.get(commandIndex);
    if (batchedArg instanceof String) {
        return StringUtils.getBytes((String) batchedArg, this.charEncoding);
    }

    BindValue bv = ((ClientPreparedQueryBindings) batchedArg).getBindValues()[parameterIndex];
    if (bv.isStream()) {
        return streamToBytes(bv.getStreamValue(), false, bv.getStreamLength(), this.useStreamLengthsInPrepStmts.getValue());
    }
    byte parameterVal[] = bv.getByteValue();
    if (parameterVal == null) {
        return null;
    }

    if ((parameterVal[0] == '\'') && (parameterVal[parameterVal.length - 1] == '\'')) {
        byte[] valNoQuotes = new byte[parameterVal.length - 2];
        System.arraycopy(parameterVal, 1, valNoQuotes, 0, parameterVal.length - 2);

        return valNoQuotes;
    }

    return parameterVal;
}
 
Example 4
Source File: XMessageBuilder.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
public XMessage buildMysql41AuthContinue(String user, String password, byte[] salt, String database) {
    // TODO: encoding for all this?
    String encoding = "UTF8";
    byte[] userBytes = user == null ? new byte[] {} : StringUtils.getBytes(user, encoding);
    byte[] passwordBytes = password == null || password.length() == 0 ? new byte[] {} : StringUtils.getBytes(password, encoding);
    byte[] databaseBytes = database == null ? new byte[] {} : StringUtils.getBytes(database, encoding);

    byte[] hashedPassword = passwordBytes;
    if (password != null && password.length() > 0) {
        hashedPassword = Security.scramble411(passwordBytes, salt);
        // protocol dictates *-prefixed hex string as hashed password
        hashedPassword = String.format("*%040x", new java.math.BigInteger(1, hashedPassword)).getBytes();
    }

    // this is what would happen in the SASL provider but we don't need the overhead of all the plumbing.
    byte[] reply = new byte[databaseBytes.length + userBytes.length + hashedPassword.length + 2];

    // reply is length-prefixed when sent so we just separate fields by \0
    System.arraycopy(databaseBytes, 0, reply, 0, databaseBytes.length);
    int pos = databaseBytes.length;
    reply[pos++] = 0;
    System.arraycopy(userBytes, 0, reply, pos, userBytes.length);
    pos += userBytes.length;
    reply[pos++] = 0;
    System.arraycopy(hashedPassword, 0, reply, pos, hashedPassword.length);

    AuthenticateContinue.Builder builder = AuthenticateContinue.newBuilder();
    builder.setAuthData(ByteString.copyFrom(reply));
    return new XMessage(builder.build());
}
 
Example 5
Source File: MysqlClearPasswordPlugin.java    From FoxTelem with GNU General Public License v3.0 5 votes vote down vote up
public boolean nextAuthenticationStep(NativePacketPayload fromServer, List<NativePacketPayload> toServer) {
    toServer.clear();

    String encoding = this.protocol.versionMeetsMinimum(5, 7, 6) ? this.protocol.getPasswordCharacterEncoding() : "UTF-8";
    NativePacketPayload bresp = new NativePacketPayload(StringUtils.getBytes(this.password != null ? this.password : "", encoding));

    bresp.setPosition(bresp.getPayloadLength());
    bresp.writeInteger(IntegerDataType.INT1, 0);
    bresp.setPosition(0);

    toServer.add(bresp);
    return true;
}
 
Example 6
Source File: UpdatableResultSet.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
public void insertRow() throws SQLException {
    synchronized (checkClosed().getConnectionMutex()) {
        if (!this.onInsertRow) {
            throw SQLError.createSQLException(Messages.getString("UpdatableResultSet.7"), getExceptionInterceptor());
        }

        this.inserter.executeUpdate();

        long autoIncrementId = this.inserter.getLastInsertID();
        Field[] fields = this.getMetadata().getFields();
        int numFields = fields.length;
        byte[][] newRow = new byte[numFields][];

        for (int i = 0; i < numFields; i++) {
            if (this.inserter.isNull(i)) {
                newRow[i] = null;
            } else {
                newRow[i] = this.inserter.getBytesRepresentation(i);
            }

            // WARN: This non-variant only holds if MySQL never allows more than one auto-increment key (which is the way it is _today_)
            if (fields[i].isAutoIncrement() && autoIncrementId > 0) {
                newRow[i] = StringUtils.getBytes(String.valueOf(autoIncrementId));
                this.inserter.setBytesNoEscapeNoQuotes(i + 1, newRow[i]);
            }
        }

        Row resultSetRow = new ByteArrayRow(newRow, getExceptionInterceptor());

        // inserter is always a client-side prepared statement, so it's safe to use it
        // with ByteArrayRow for server-side prepared statement too
        refreshRow(this.inserter, resultSetRow);

        this.rowData.addRow(resultSetRow);
        resetInserter();
    }
}
 
Example 7
Source File: Clob.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * @see java.sql.Clob#getAsciiStream()
 */
public InputStream getAsciiStream() throws SQLException {
    if (this.charData != null) {
        return new ByteArrayInputStream(StringUtils.getBytes(this.charData));
    }

    return null;
}
 
Example 8
Source File: MysqlClearPasswordPlugin.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
public boolean nextAuthenticationStep(NativePacketPayload fromServer, List<NativePacketPayload> toServer) {
    toServer.clear();

    String encoding = this.protocol.versionMeetsMinimum(5, 7, 6) ? this.protocol.getPasswordCharacterEncoding() : "UTF-8";
    NativePacketPayload bresp = new NativePacketPayload(StringUtils.getBytes(this.password != null ? this.password : "", encoding));

    bresp.setPosition(bresp.getPayloadLength());
    bresp.writeInteger(IntegerDataType.INT1, 0);
    bresp.setPosition(0);

    toServer.add(bresp);
    return true;
}
 
Example 9
Source File: Clob.java    From FoxTelem with GNU General Public License v3.0 5 votes vote down vote up
@Override
public InputStream getAsciiStream() throws SQLException {
    if (this.charData != null) {
        return new ByteArrayInputStream(StringUtils.getBytes(this.charData));
    }

    return null;
}
 
Example 10
Source File: XMessageBuilder.java    From FoxTelem with GNU General Public License v3.0 5 votes vote down vote up
public XMessage buildMysql41AuthContinue(String user, String password, byte[] salt, String database) {
    // TODO: encoding for all this?
    String encoding = "UTF8";
    byte[] userBytes = user == null ? new byte[] {} : StringUtils.getBytes(user, encoding);
    byte[] passwordBytes = password == null || password.length() == 0 ? new byte[] {} : StringUtils.getBytes(password, encoding);
    byte[] databaseBytes = database == null ? new byte[] {} : StringUtils.getBytes(database, encoding);

    byte[] hashedPassword = passwordBytes;
    if (password != null && password.length() > 0) {
        hashedPassword = Security.scramble411(passwordBytes, salt);
        // protocol dictates *-prefixed hex string as hashed password
        hashedPassword = String.format("*%040x", new java.math.BigInteger(1, hashedPassword)).getBytes();
    }

    // this is what would happen in the SASL provider but we don't need the overhead of all the plumbing.
    byte[] reply = new byte[databaseBytes.length + userBytes.length + hashedPassword.length + 2];

    // reply is length-prefixed when sent so we just separate fields by \0
    System.arraycopy(databaseBytes, 0, reply, 0, databaseBytes.length);
    int pos = databaseBytes.length;
    reply[pos++] = 0;
    System.arraycopy(userBytes, 0, reply, pos, userBytes.length);
    pos += userBytes.length;
    reply[pos++] = 0;
    System.arraycopy(hashedPassword, 0, reply, pos, hashedPassword.length);

    AuthenticateContinue.Builder builder = AuthenticateContinue.newBuilder();
    builder.setAuthData(ByteString.copyFrom(reply));
    return new XMessage(builder.build());
}
 
Example 11
Source File: ClientPreparedQueryBindings.java    From FoxTelem with GNU General Public License v3.0 4 votes vote down vote up
@Override
public void setNString(int parameterIndex, String x) {
    if (x == null) {
        setNull(parameterIndex);
    } else {
        if (this.charEncoding.equalsIgnoreCase("UTF-8") || this.charEncoding.equalsIgnoreCase("utf8")) {
            setString(parameterIndex, x);
            return;
        }

        int stringLength = x.length();
        // Ignore sql_mode=NO_BACKSLASH_ESCAPES in current implementation.

        // Add introducer _utf8 for NATIONAL CHARACTER
        StringBuilder buf = new StringBuilder((int) (x.length() * 1.1 + 4));
        buf.append("_utf8");
        buf.append('\'');

        //
        // Note: buf.append(char) is _faster_ than appending in blocks, because the block append requires a System.arraycopy().... go figure...
        //

        for (int i = 0; i < stringLength; ++i) {
            char c = x.charAt(i);

            switch (c) {
                case 0: /* Must be escaped for 'mysql' */
                    buf.append('\\');
                    buf.append('0');
                    break;
                case '\n': /* Must be escaped for logs */
                    buf.append('\\');
                    buf.append('n');
                    break;
                case '\r':
                    buf.append('\\');
                    buf.append('r');
                    break;
                case '\\':
                    buf.append('\\');
                    buf.append('\\');
                    break;
                case '\'':
                    buf.append('\\');
                    buf.append('\'');
                    break;
                case '"': /* Better safe than sorry */
                    if (this.session.getServerSession().useAnsiQuotedIdentifiers()) {
                        buf.append('\\');
                    }
                    buf.append('"');
                    break;
                case '\032': /* This gives problems on Win32 */
                    buf.append('\\');
                    buf.append('Z');
                    break;
                default:
                    buf.append(c);
            }
        }

        buf.append('\'');

        byte[] parameterAsBytes = this.isLoadDataQuery ? StringUtils.getBytes(buf.toString()) : StringUtils.getBytes(buf.toString(), "UTF-8");

        setValue(parameterIndex, parameterAsBytes, MysqlType.VARCHAR); // TODO was Types.NVARCHAR
    }
}
 
Example 12
Source File: CallableStatement.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Used to fake up some metadata when we don't have access to
 * SHOW CREATE PROCEDURE or mysql.proc.
 * 
 * @throws SQLException
 *             if we can't build the metadata.
 */
private void fakeParameterTypes(boolean isReallyProcedure) throws SQLException {
    synchronized (checkClosed().getConnectionMutex()) {
        String encoding = this.connection.getSession().getServerSession().getCharacterSetMetadata();
        int collationIndex = this.connection.getSession().getServerSession().getMetadataCollationIndex();
        Field[] fields = new Field[13];

        fields[0] = new Field("", "PROCEDURE_CAT", collationIndex, encoding, MysqlType.CHAR, 0);
        fields[1] = new Field("", "PROCEDURE_SCHEM", collationIndex, encoding, MysqlType.CHAR, 0);
        fields[2] = new Field("", "PROCEDURE_NAME", collationIndex, encoding, MysqlType.CHAR, 0);
        fields[3] = new Field("", "COLUMN_NAME", collationIndex, encoding, MysqlType.CHAR, 0);
        fields[4] = new Field("", "COLUMN_TYPE", collationIndex, encoding, MysqlType.CHAR, 0);
        fields[5] = new Field("", "DATA_TYPE", collationIndex, encoding, MysqlType.SMALLINT, 0);
        fields[6] = new Field("", "TYPE_NAME", collationIndex, encoding, MysqlType.CHAR, 0);
        fields[7] = new Field("", "PRECISION", collationIndex, encoding, MysqlType.INT, 0);
        fields[8] = new Field("", "LENGTH", collationIndex, encoding, MysqlType.INT, 0);
        fields[9] = new Field("", "SCALE", collationIndex, encoding, MysqlType.SMALLINT, 0);
        fields[10] = new Field("", "RADIX", collationIndex, encoding, MysqlType.SMALLINT, 0);
        fields[11] = new Field("", "NULLABLE", collationIndex, encoding, MysqlType.SMALLINT, 0);
        fields[12] = new Field("", "REMARKS", collationIndex, encoding, MysqlType.CHAR, 0);

        String procName = isReallyProcedure ? extractProcedureName() : null;

        byte[] procNameAsBytes = null;

        procNameAsBytes = procName == null ? null : StringUtils.getBytes(procName, "UTF-8");

        ArrayList<Row> resultRows = new ArrayList<>();

        for (int i = 0; i < ((PreparedQuery<?>) this.query).getParameterCount(); i++) {
            byte[][] row = new byte[13][];
            row[0] = null; // PROCEDURE_CAT
            row[1] = null; // PROCEDURE_SCHEM
            row[2] = procNameAsBytes; // PROCEDURE/NAME
            row[3] = s2b(String.valueOf(i)); // COLUMN_NAME

            row[4] = s2b(String.valueOf(java.sql.DatabaseMetaData.procedureColumnIn));

            row[5] = s2b(String.valueOf(MysqlType.VARCHAR.getJdbcType())); // DATA_TYPE
            row[6] = s2b(MysqlType.VARCHAR.getName()); // TYPE_NAME
            row[7] = s2b(Integer.toString(65535)); // PRECISION
            row[8] = s2b(Integer.toString(65535)); // LENGTH
            row[9] = s2b(Integer.toString(0)); // SCALE
            row[10] = s2b(Integer.toString(10)); // RADIX

            row[11] = s2b(Integer.toString(java.sql.DatabaseMetaData.procedureNullableUnknown)); // nullable

            row[12] = null;

            resultRows.add(new ByteArrayRow(row, getExceptionInterceptor()));
        }

        java.sql.ResultSet paramTypesRs = this.resultSetFactory.createFromResultsetRows(ResultSet.CONCUR_READ_ONLY, ResultSet.TYPE_SCROLL_INSENSITIVE,
                new ResultsetRowsStatic(resultRows, new DefaultColumnDefinition(fields)));

        convertGetProcedureColumnsToInternalDescriptors(paramTypesRs);
    }
}
 
Example 13
Source File: Security.java    From FoxTelem with GNU General Public License v3.0 4 votes vote down vote up
public static byte[] scramble411(String password, byte[] seed, String passwordEncoding) {
    byte[] passwordBytes = (passwordEncoding == null || passwordEncoding.length() == 0) ? StringUtils.getBytes(password)
            : StringUtils.getBytes(password, passwordEncoding);
    return scramble411(passwordBytes, seed);
}
 
Example 14
Source File: AbstractQueryBindings.java    From FoxTelem with GNU General Public License v3.0 4 votes vote down vote up
public synchronized final void setValue(int paramIndex, String val, MysqlType type) {
    byte[] parameterAsBytes = StringUtils.getBytes(val, this.charEncoding);
    setValue(paramIndex, parameterAsBytes, type);
}
 
Example 15
Source File: NativeProtocol.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Build a query packet from the given string and send it to the server.
 * 
 * @param callingQuery
 * @param query
 * @param characterEncoding
 * @param maxRows
 * @param streamResults
 * @param catalog
 * @param cachedMetadata
 * @param getProfilerEventHandlerInstanceFunction
 * @param resultSetFactory
 * @return
 * @throws IOException
 */
public final <T extends Resultset> T sendQueryString(Query callingQuery, String query, String characterEncoding, int maxRows, boolean streamResults,
        String catalog, ColumnDefinition cachedMetadata, GetProfilerEventHandlerInstanceFunction getProfilerEventHandlerInstanceFunction,
        ProtocolEntityFactory<T, NativePacketPayload> resultSetFactory) throws IOException {
    String statementComment = this.queryComment;

    if (this.propertySet.getBooleanReadableProperty(PropertyDefinitions.PNAME_includeThreadNamesAsStatementComment).getValue()) {
        statementComment = (statementComment != null ? statementComment + ", " : "") + "java thread: " + Thread.currentThread().getName();
    }

    // We don't know exactly how many bytes we're going to get from the query. Since we're dealing with UTF-8, the max is 4, so pad it
    // (4 * query) + space for headers
    int packLength = 1 + (query.length() * 4) + 2;

    byte[] commentAsBytes = null;

    if (statementComment != null) {
        commentAsBytes = StringUtils.getBytes(statementComment, characterEncoding);

        packLength += commentAsBytes.length;
        packLength += 6; // for /*[space] [space]*/
    }

    // TODO decide how to safely use the shared this.sendPacket
    //if (this.sendPacket == null) {
    NativePacketPayload sendPacket = new NativePacketPayload(packLength);
    //}

    sendPacket.setPosition(0);

    sendPacket.writeInteger(IntegerDataType.INT1, NativeConstants.COM_QUERY);

    if (commentAsBytes != null) {
        sendPacket.writeBytes(StringLengthDataType.STRING_FIXED, Constants.SLASH_STAR_SPACE_AS_BYTES);
        sendPacket.writeBytes(StringLengthDataType.STRING_FIXED, commentAsBytes);
        sendPacket.writeBytes(StringLengthDataType.STRING_FIXED, Constants.SPACE_STAR_SLASH_SPACE_AS_BYTES);
    }

    if (!this.platformDbCharsetMatches && StringUtils.startsWithIgnoreCaseAndWs(query, "LOAD DATA")) {
        sendPacket.writeBytes(StringLengthDataType.STRING_FIXED, StringUtils.getBytes(query));
    } else {
        sendPacket.writeBytes(StringLengthDataType.STRING_FIXED, StringUtils.getBytes(query, characterEncoding));
    }

    return sendQueryPacket(callingQuery, sendPacket, maxRows, streamResults, catalog, cachedMetadata, getProfilerEventHandlerInstanceFunction,
            resultSetFactory);
}
 
Example 16
Source File: ProfilerEventImpl.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
public byte[] pack() {

        int len = 1 + 4 + 4 + 4 + 8 + 4 + 4;

        byte[] eventCreationAsBytes = null;

        getEventCreationPointAsString();

        if (this.eventCreationPointDesc != null) {
            eventCreationAsBytes = StringUtils.getBytes(this.eventCreationPointDesc, "ISO8859_1");
            len += (4 + eventCreationAsBytes.length);
        } else {
            len += 4;
        }

        byte[] messageAsBytes = null;

        if (this.message != null) {
            messageAsBytes = StringUtils.getBytes(this.message, "ISO8859_1");
            len += (4 + messageAsBytes.length);
        } else {
            len += 4;
        }

        byte[] durationUnitsAsBytes = null;

        if (this.durationUnits != null) {
            durationUnitsAsBytes = StringUtils.getBytes(this.durationUnits, "ISO8859_1");
            len += (4 + durationUnitsAsBytes.length);
        } else {
            len += 4;
            durationUnitsAsBytes = StringUtils.getBytes("", "ISO8859_1");
        }

        byte[] buf = new byte[len];

        int pos = 0;

        buf[pos++] = this.getEventType();
        pos = writeLong(this.connectionId, buf, pos);
        pos = writeInt(this.statementId, buf, pos);
        pos = writeInt(this.resultSetId, buf, pos);
        pos = writeLong(this.eventCreationTime, buf, pos);
        pos = writeLong(this.eventDuration, buf, pos);
        pos = writeBytes(durationUnitsAsBytes, buf, pos);
        pos = writeInt(this.eventCreationPointIndex, buf, pos);

        if (eventCreationAsBytes != null) {
            pos = writeBytes(eventCreationAsBytes, buf, pos);
        } else {
            pos = writeInt(0, buf, pos);
        }

        if (messageAsBytes != null) {
            pos = writeBytes(messageAsBytes, buf, pos);
        } else {
            pos = writeInt(0, buf, pos);
        }

        return buf;
    }
 
Example 17
Source File: AbstractPreparedQuery.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Creates the packet that contains the query to be sent to the server.
 * 
 * @param bindValues
 *            values
 * 
 * @return a Buffer filled with the query that represents this statement
 */
@SuppressWarnings("unchecked")
@Override
public <M extends Message> M fillSendPacket(QueryBindings<?> bindings) {
    synchronized (this) {
        BindValue[] bindValues = bindings.getBindValues();

        NativePacketPayload sendPacket = this.session.getSharedSendPacket();

        sendPacket.writeInteger(IntegerDataType.INT1, NativeConstants.COM_QUERY);

        boolean useStreamLengths = this.useStreamLengthsInPrepStmts.getValue();

        //
        // Try and get this allocation as close as possible for BLOBs
        //
        int ensurePacketSize = 0;

        String statementComment = this.session.getProtocol().getQueryComment();

        byte[] commentAsBytes = null;

        if (statementComment != null) {
            commentAsBytes = StringUtils.getBytes(statementComment, this.charEncoding);

            ensurePacketSize += commentAsBytes.length;
            ensurePacketSize += 6; // for /*[space] [space]*/
        }

        for (int i = 0; i < bindValues.length; i++) {
            if (bindValues[i].isStream() && useStreamLengths) {
                ensurePacketSize += bindValues[i].getStreamLength();
            }
        }

        if (ensurePacketSize != 0) {
            sendPacket.ensureCapacity(ensurePacketSize);
        }

        if (commentAsBytes != null) {
            sendPacket.writeBytes(StringLengthDataType.STRING_FIXED, Constants.SLASH_STAR_SPACE_AS_BYTES);
            sendPacket.writeBytes(StringLengthDataType.STRING_FIXED, commentAsBytes);
            sendPacket.writeBytes(StringLengthDataType.STRING_FIXED, Constants.SPACE_STAR_SLASH_SPACE_AS_BYTES);
        }

        byte[][] staticSqlStrings = this.parseInfo.getStaticSql();
        for (int i = 0; i < bindValues.length; i++) {
            bindings.checkParameterSet(i);

            sendPacket.writeBytes(StringLengthDataType.STRING_FIXED, staticSqlStrings[i]);

            if (bindValues[i].isStream()) {
                streamToBytes(sendPacket, bindValues[i].getStreamValue(), true, bindValues[i].getStreamLength(), useStreamLengths);
            } else {
                sendPacket.writeBytes(StringLengthDataType.STRING_FIXED, bindValues[i].getByteValue());
            }
        }

        sendPacket.writeBytes(StringLengthDataType.STRING_FIXED, staticSqlStrings[bindValues.length]);

        return (M) sendPacket;
    }
}
 
Example 18
Source File: AbstractPreparedQuery.java    From FoxTelem with GNU General Public License v3.0 4 votes vote down vote up
/**
 * Creates the packet that contains the query to be sent to the server.
 * 
 * @param bindings
 *            values
 * 
 * @return a Buffer filled with the query that represents this statement
 */
@SuppressWarnings("unchecked")
@Override
public <M extends Message> M fillSendPacket(QueryBindings<?> bindings) {
    synchronized (this) {
        BindValue[] bindValues = bindings.getBindValues();

        NativePacketPayload sendPacket = this.session.getSharedSendPacket();

        sendPacket.writeInteger(IntegerDataType.INT1, NativeConstants.COM_QUERY);

        boolean useStreamLengths = this.useStreamLengthsInPrepStmts.getValue();

        //
        // Try and get this allocation as close as possible for BLOBs
        //
        int ensurePacketSize = 0;

        String statementComment = this.session.getProtocol().getQueryComment();

        byte[] commentAsBytes = null;

        if (statementComment != null) {
            commentAsBytes = StringUtils.getBytes(statementComment, this.charEncoding);

            ensurePacketSize += commentAsBytes.length;
            ensurePacketSize += 6; // for /*[space] [space]*/
        }

        for (int i = 0; i < bindValues.length; i++) {
            if (bindValues[i].isStream() && useStreamLengths) {
                ensurePacketSize += bindValues[i].getStreamLength();
            }
        }

        if (ensurePacketSize != 0) {
            sendPacket.ensureCapacity(ensurePacketSize);
        }

        if (commentAsBytes != null) {
            sendPacket.writeBytes(StringLengthDataType.STRING_FIXED, Constants.SLASH_STAR_SPACE_AS_BYTES);
            sendPacket.writeBytes(StringLengthDataType.STRING_FIXED, commentAsBytes);
            sendPacket.writeBytes(StringLengthDataType.STRING_FIXED, Constants.SPACE_STAR_SLASH_SPACE_AS_BYTES);
        }

        byte[][] staticSqlStrings = this.parseInfo.getStaticSql();
        for (int i = 0; i < bindValues.length; i++) {
            bindings.checkParameterSet(i);

            sendPacket.writeBytes(StringLengthDataType.STRING_FIXED, staticSqlStrings[i]);

            if (bindValues[i].isStream()) {
                streamToBytes(sendPacket, bindValues[i].getStreamValue(), true, bindValues[i].getStreamLength(), useStreamLengths);
            } else {
                sendPacket.writeBytes(StringLengthDataType.STRING_FIXED, bindValues[i].getByteValue());
            }
        }

        sendPacket.writeBytes(StringLengthDataType.STRING_FIXED, staticSqlStrings[bindValues.length]);

        return (M) sendPacket;
    }
}
 
Example 19
Source File: StatementImpl.java    From FoxTelem with GNU General Public License v3.0 4 votes vote down vote up
protected ResultSetInternalMethods getGeneratedKeysInternal(long numKeys) throws SQLException {
    synchronized (checkClosed().getConnectionMutex()) {
        String encoding = this.session.getServerSession().getCharacterSetMetadata();
        int collationIndex = this.session.getServerSession().getMetadataCollationIndex();
        Field[] fields = new Field[1];
        fields[0] = new Field("", "GENERATED_KEY", collationIndex, encoding, MysqlType.BIGINT_UNSIGNED, 20);

        ArrayList<Row> rowSet = new ArrayList<>();

        long beginAt = getLastInsertID();

        if (this.results != null) {
            String serverInfo = this.results.getServerInfo();

            //
            // Only parse server info messages for 'REPLACE' queries
            //
            if ((numKeys > 0) && (this.results.getFirstCharOfQuery() == 'R') && (serverInfo != null) && (serverInfo.length() > 0)) {
                numKeys = getRecordCountFromInfo(serverInfo);
            }

            if ((beginAt != 0 /* BIGINT UNSIGNED can wrap the protocol representation */) && (numKeys > 0)) {
                for (int i = 0; i < numKeys; i++) {
                    byte[][] row = new byte[1][];
                    if (beginAt > 0) {
                        row[0] = StringUtils.getBytes(Long.toString(beginAt));
                    } else {
                        byte[] asBytes = new byte[8];
                        asBytes[7] = (byte) (beginAt & 0xff);
                        asBytes[6] = (byte) (beginAt >>> 8);
                        asBytes[5] = (byte) (beginAt >>> 16);
                        asBytes[4] = (byte) (beginAt >>> 24);
                        asBytes[3] = (byte) (beginAt >>> 32);
                        asBytes[2] = (byte) (beginAt >>> 40);
                        asBytes[1] = (byte) (beginAt >>> 48);
                        asBytes[0] = (byte) (beginAt >>> 56);

                        BigInteger val = new BigInteger(1, asBytes);

                        row[0] = val.toString().getBytes();
                    }
                    rowSet.add(new ByteArrayRow(row, getExceptionInterceptor()));
                    beginAt += this.connection.getAutoIncrementIncrement();
                }
            }
        }

        ResultSetImpl gkRs = this.resultSetFactory.createFromResultsetRows(ResultSet.CONCUR_READ_ONLY, ResultSet.TYPE_SCROLL_INSENSITIVE,
                new ResultsetRowsStatic(rowSet, new DefaultColumnDefinition(fields)));

        return gkRs;
    }
}
 
Example 20
Source File: CallableStatement.java    From FoxTelem with GNU General Public License v3.0 2 votes vote down vote up
/**
 * Converts the given string to bytes, using the connection's character
 * encoding.
 *
 * @param s
 *            string
 * @return bytes
 */
protected byte[] s2b(String s) {
    return s == null ? null : StringUtils.getBytes(s, this.charEncoding);
}