Java Code Examples for com.mysql.cj.util.StringUtils

The following examples show how to use com.mysql.cj.util.StringUtils. These examples are extracted from open source projects. 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 Project: FoxTelem   Source File: StatementImpl.java    License: GNU General Public License v3.0 6 votes vote down vote up
protected static int findStartOfStatement(String sql) {
    int statementStartPos = 0;

    if (StringUtils.startsWithIgnoreCaseAndWs(sql, "/*")) {
        statementStartPos = sql.indexOf("*/");

        if (statementStartPos == -1) {
            statementStartPos = 0;
        } else {
            statementStartPos += 2;
        }
    } else if (StringUtils.startsWithIgnoreCaseAndWs(sql, "--") || StringUtils.startsWithIgnoreCaseAndWs(sql, "#")) {
        statementStartPos = sql.indexOf('\n');

        if (statementStartPos == -1) {
            statementStartPos = sql.indexOf('\r');

            if (statementStartPos == -1) {
                statementStartPos = 0;
            }
        }
    }

    return statementStartPos;
}
 
Example 2
@Override
public Integer parseObject(String value, ExceptionInterceptor exceptionInterceptor) {
    this.multiplier = 1;

    if (value.endsWith("k") || value.endsWith("K") || value.endsWith("kb") || value.endsWith("Kb") || value.endsWith("kB") || value.endsWith("KB")) {
        this.multiplier = 1024;
        int indexOfK = StringUtils.indexOfIgnoreCase(value, "k");
        value = value.substring(0, indexOfK);
    } else if (value.endsWith("m") || value.endsWith("M") || value.endsWith("mb") || value.endsWith("Mb") || value.endsWith("mB") || value.endsWith("MB")) {
        this.multiplier = 1024 * 1024;
        int indexOfM = StringUtils.indexOfIgnoreCase(value, "m");
        value = value.substring(0, indexOfM);
    } else if (value.endsWith("g") || value.endsWith("G") || value.endsWith("gb") || value.endsWith("Gb") || value.endsWith("gB") || value.endsWith("GB")) {
        this.multiplier = 1024 * 1024 * 1024;
        int indexOfG = StringUtils.indexOfIgnoreCase(value, "g");
        value = value.substring(0, indexOfG);
    }

    return super.parseObject(value, exceptionInterceptor);
}
 
Example 3
private void configureSQLStateList(String sqlStates) {
    if (sqlStates == null || "".equals(sqlStates)) {
        return;
    }
    List<String> states = StringUtils.split(sqlStates, ",", true);
    List<String> newStates = new ArrayList<>();

    for (String state : states) {
        if (state.length() > 0) {
            newStates.add(state);
        }
    }
    if (newStates.size() > 0) {
        this.sqlStateList = newStates;
    }
}
 
Example 4
/**
 * Add a packet to the debug buffer.
 */
private void pushPacketToDebugBuffer(byte[] packet, int packetLen) {
    int bytesToDump = Math.min(this.maxPacketDumpLength, packetLen);

    String packetPayload = StringUtils.dumpAsHex(packet, bytesToDump);

    StringBuilder packetDump = new StringBuilder(DEBUG_MSG_LEN + NativeConstants.HEADER_LENGTH + packetPayload.length());

    packetDump.append("Client ");
    packetDump.append(packet.toString());
    packetDump.append("--------------------> Server\n");
    packetDump.append("\nPacket payload:\n\n");
    packetDump.append(packetPayload);

    if (packetLen > this.maxPacketDumpLength) {
        packetDump.append("\nNote: Packet of " + packetLen + " bytes truncated to " + this.maxPacketDumpLength + " bytes.\n");
    }

    if ((this.packetDebugBuffer.size() + 1) > this.packetDebugBufferSize.getValue()) {
        this.packetDebugBuffer.removeFirst();
    }

    this.packetDebugBuffer.addLast(packetDump);
}
 
Example 5
Source Project: FoxTelem   Source File: UpdatableResultSet.java    License: GNU General Public License v3.0 6 votes vote down vote up
@Override
public void updateBigDecimal(int columnIndex, BigDecimal x) throws SQLException {
    synchronized (checkClosed().getConnectionMutex()) {
        if (!this.onInsertRow) {
            if (!this.doingUpdates) {
                this.doingUpdates = true;
                syncUpdate();
            }

            this.updater.setBigDecimal(columnIndex, x);
        } else {
            this.inserter.setBigDecimal(columnIndex, x);

            if (x == null) {
                this.thisRow.setBytes(columnIndex - 1, null);
            } else {
                this.thisRow.setBytes(columnIndex - 1, StringUtils.getBytes(x.toString()));
            }
        }
    }
}
 
Example 6
Source Project: lams   Source File: ResultSetImpl.java    License: GNU General Public License v2.0 6 votes vote down vote up
public String getString(int columnIndex) throws SQLException {
    checkRowPos();
    checkColumnBounds(columnIndex);

    Field f = this.columnDefinition.getFields()[columnIndex - 1];
    ValueFactory<String> vf = new StringValueFactory(f.getEncoding());
    // return YEAR values as Dates if necessary
    if (f.getMysqlTypeId() == MysqlType.FIELD_TYPE_YEAR && this.yearIsDateType) {
        vf = new YearToDateValueFactory<>(vf);
    }
    String stringVal = this.thisRow.getValue(columnIndex - 1, vf);

    if (this.padCharsWithSpace && stringVal != null && f.getMysqlTypeId() == MysqlType.FIELD_TYPE_STRING) {
        int maxBytesPerChar = this.session.getServerSession().getMaxBytesPerChar(f.getCollationIndex(), f.getEncoding());
        int fieldLength = (int) f.getLength() /* safe, bytes in a CHAR <= 1024 */ / maxBytesPerChar; /* safe, this will never be 0 */
        return StringUtils.padString(stringVal, fieldLength);
    }

    return stringVal;
}
 
Example 7
Source Project: FoxTelem   Source File: ClientPreparedQuery.java    License: 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 8
Source Project: lams   Source File: NativePacketPayload.java    License: 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 9
Source Project: FoxTelem   Source File: TracingPacketSender.java    License: GNU General Public License v3.0 6 votes vote down vote up
/**
 * Log the packet details to the provided logger.
 * 
 * @param packet
 *            packet as bytes
 * @param packetLen
 *            packet length
 * @param packetSequence
 *            sequence index
 */
private void logPacket(byte[] packet, int packetLen, byte packetSequence) {
    StringBuilder traceMessageBuf = new StringBuilder();

    traceMessageBuf.append("send packet payload:\n");
    traceMessageBuf.append("host: '");
    traceMessageBuf.append(this.host);
    traceMessageBuf.append("' serverThreadId: '");
    traceMessageBuf.append(this.serverThreadId);
    traceMessageBuf.append("' packetLen: '");
    traceMessageBuf.append(packetLen);
    traceMessageBuf.append("' packetSequence: '");
    traceMessageBuf.append(packetSequence);
    traceMessageBuf.append("'\n");
    traceMessageBuf.append(StringUtils.dumpAsHex(packet, packetLen));

    this.log.logTrace(traceMessageBuf.toString());
}
 
Example 10
Source Project: lams   Source File: TracingPacketSender.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * Log the packet details to the provided logger.
 */
private void logPacket(byte[] packet, int packetLen, byte packetSequence) {
    StringBuilder traceMessageBuf = new StringBuilder();

    traceMessageBuf.append("send packet payload:\n");
    traceMessageBuf.append("host: '");
    traceMessageBuf.append(this.host);
    traceMessageBuf.append("' serverThreadId: '");
    traceMessageBuf.append(this.serverThreadId);
    traceMessageBuf.append("' packetLen: '");
    traceMessageBuf.append(packetLen);
    traceMessageBuf.append("' packetSequence: '");
    traceMessageBuf.append(packetSequence);
    traceMessageBuf.append("'\n");
    traceMessageBuf.append(StringUtils.dumpAsHex(packet, packetLen));

    this.log.logTrace(traceMessageBuf.toString());
}
 
Example 11
Source Project: lams   Source File: UpdatableResultSet.java    License: GNU General Public License v2.0 6 votes vote down vote up
@Override
public void updateString(int columnIndex, String x) throws SQLException {
    synchronized (checkClosed().getConnectionMutex()) {
        if (!this.onInsertRow) {
            if (!this.doingUpdates) {
                this.doingUpdates = true;
                syncUpdate();
            }

            this.updater.setString(columnIndex, x);
        } else {
            this.inserter.setString(columnIndex, x);

            if (x == null) {
                this.thisRow.setBytes(columnIndex - 1, null);
            } else {
                this.thisRow.setBytes(columnIndex - 1, StringUtils.getBytes(x, this.charEncoding));
            }
        }
    }
}
 
Example 12
Source Project: lams   Source File: StatementImpl.java    License: GNU General Public License v2.0 6 votes vote down vote up
protected static int findStartOfStatement(String sql) {
    int statementStartPos = 0;

    if (StringUtils.startsWithIgnoreCaseAndWs(sql, "/*")) {
        statementStartPos = sql.indexOf("*/");

        if (statementStartPos == -1) {
            statementStartPos = 0;
        } else {
            statementStartPos += 2;
        }
    } else if (StringUtils.startsWithIgnoreCaseAndWs(sql, "--") || StringUtils.startsWithIgnoreCaseAndWs(sql, "#")) {
        statementStartPos = sql.indexOf('\n');

        if (statementStartPos == -1) {
            statementStartPos = sql.indexOf('\r');

            if (statementStartPos == -1) {
                statementStartPos = 0;
            }
        }
    }

    return statementStartPos;
}
 
Example 13
Source Project: FoxTelem   Source File: ExportControlled.java    License: GNU General Public License v3.0 6 votes vote down vote up
private static KeyStoreConf getKeyStoreConf(PropertySet propertySet, PropertyKey keyStoreUrlPropertyKey, PropertyKey keyStorePasswordPropertyKey,
        PropertyKey keyStoreTypePropertyKey) {

    String keyStoreUrl = propertySet.getStringProperty(keyStoreUrlPropertyKey).getValue();
    String keyStorePassword = propertySet.getStringProperty(keyStorePasswordPropertyKey).getValue();
    String keyStoreType = propertySet.getStringProperty(keyStoreTypePropertyKey).getValue();

    if (StringUtils.isNullOrEmpty(keyStoreUrl)) {
        keyStoreUrl = System.getProperty("javax.net.ssl.keyStore");
        keyStorePassword = System.getProperty("javax.net.ssl.keyStorePassword");
        keyStoreType = System.getProperty("javax.net.ssl.keyStoreType");
        if (StringUtils.isNullOrEmpty(keyStoreType)) {
            keyStoreType = propertySet.getStringProperty(keyStoreTypePropertyKey).getInitialValue();
        }
        // check URL
        if (!StringUtils.isNullOrEmpty(keyStoreUrl)) {
            try {
                new URL(keyStoreUrl);
            } catch (MalformedURLException e) {
                keyStoreUrl = "file:" + keyStoreUrl;
            }
        }
    }

    return new KeyStoreConf(keyStoreUrl, keyStorePassword, keyStoreType);
}
 
Example 14
private void configureSQLExceptionSubclassList(String sqlExClasses) {
    if (sqlExClasses == null || "".equals(sqlExClasses)) {
        return;
    }
    List<String> classes = StringUtils.split(sqlExClasses, ",", true);
    List<Class<?>> newClasses = new ArrayList<>();

    for (String exClass : classes) {
        try {
            Class<?> c = Class.forName(exClass);
            newClasses.add(c);
        } catch (Exception e) {
            // ignore and don't check, class doesn't exist
        }
    }
    if (newClasses.size() > 0) {
        this.sqlExClassList = newClasses;
    }
}
 
Example 15
Source Project: lams   Source File: ClientPreparedQuery.java    License: 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 16
Source Project: FoxTelem   Source File: XProtocol.java    License: GNU General Public License v3.0 6 votes vote down vote up
public XProtocol(HostInfo hostInfo, PropertySet propertySet) {
    String host = hostInfo.getHost();
    if (host == null || StringUtils.isEmptyOrWhitespaceOnly(host)) {
        host = "localhost";
    }
    int port = hostInfo.getPort();
    if (port < 0) {
        port = 33060;
    }
    this.defaultSchemaName = hostInfo.getDatabase();

    // Override common connectTimeout with xdevapi.connect-timeout to provide unified logic in StandardSocketFactory
    RuntimeProperty<Integer> connectTimeout = propertySet.getIntegerProperty(PropertyKey.connectTimeout);
    RuntimeProperty<Integer> xdevapiConnectTimeout = propertySet.getIntegerProperty(PropertyKey.xdevapiConnectTimeout);
    if (xdevapiConnectTimeout.isExplicitlySet() || !connectTimeout.isExplicitlySet()) {
        connectTimeout.setValue(xdevapiConnectTimeout.getValue());
    }

    SocketConnection socketConn = propertySet.getBooleanProperty(PropertyKey.xdevapiUseAsyncProtocol).getValue() ? new XAsyncSocketConnection()
            : new NativeSocketConnection();
    socketConn.connect(host, port, propertySet, null, null, 0);
    init(null, socketConn, propertySet, null);
}
 
Example 17
@Override
public boolean nextAuthenticationStep(NativePacketPayload fromServer, List<NativePacketPayload> toServer) {
    toServer.clear();

    NativePacketPayload bresp = null;

    String pwd = this.password;

    if (fromServer == null || pwd == null || pwd.length() == 0) {
        bresp = new NativePacketPayload(new byte[0]);
    } else {
        bresp = new NativePacketPayload(StringUtils.getBytes(
                newCrypt(pwd, fromServer.readString(StringSelfDataType.STRING_TERM, null).substring(0, 8), this.protocol.getPasswordCharacterEncoding())));

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

    return true;
}
 
Example 18
Source Project: lams   Source File: GeneratedColumnDef.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * column_definition:
 * data_type [GENERATED ALWAYS] AS (expression)
 * [VIRTUAL | STORED] [UNIQUE [KEY]] [COMMENT comment]
 * [NOT NULL | NULL] [[PRIMARY] KEY]
 */
@Override
public String toString() {
    StringBuilder sb = new StringBuilder(this.name);
    sb.append(" ").append(getMysqlType());

    sb.append(" AS (").append(this.expr).append(")");
    if (this.isStored) {
        sb.append(" STORED");
    }
    if (this.uniqueIndex) {
        sb.append(" UNIQUE KEY");
    }
    if (this.comment != null && !this.comment.isEmpty()) {
        sb.append(" COMMENT ").append(StringUtils.quoteIdentifier(this.comment, "'", true));
    }
    if (this.notNull != null) {
        sb.append(this.notNull ? " NOT NULL" : " NULL");
    }
    if (this.primaryKey) {
        sb.append(" PRIMARY KEY");
    }

    return sb.toString();
}
 
Example 19
Source Project: FoxTelem   Source File: StatementImpl.java    License: GNU General Public License v3.0 5 votes vote down vote up
/**
 * Checks if the given SQL query with the given first non-ws char is a DML
 * statement. Throws an exception if it is.
 * 
 * @param sql
 *            the SQL to check
 * @param firstStatementChar
 *            the UC first non-ws char of the statement
 * 
 * @throws SQLException
 *             if the statement contains DML
 */
protected void checkForDml(String sql, char firstStatementChar) throws SQLException {
    if ((firstStatementChar == 'I') || (firstStatementChar == 'U') || (firstStatementChar == 'D') || (firstStatementChar == 'A')
            || (firstStatementChar == 'C') || (firstStatementChar == 'T') || (firstStatementChar == 'R')) {
        String noCommentSql = StringUtils.stripComments(sql, "'\"", "'\"", true, false, true, true);

        if (StringUtils.startsWithIgnoreCaseAndWs(noCommentSql, "INSERT") || StringUtils.startsWithIgnoreCaseAndWs(noCommentSql, "UPDATE")
                || StringUtils.startsWithIgnoreCaseAndWs(noCommentSql, "DELETE") || StringUtils.startsWithIgnoreCaseAndWs(noCommentSql, "DROP")
                || StringUtils.startsWithIgnoreCaseAndWs(noCommentSql, "CREATE") || StringUtils.startsWithIgnoreCaseAndWs(noCommentSql, "ALTER")
                || StringUtils.startsWithIgnoreCaseAndWs(noCommentSql, "TRUNCATE") || StringUtils.startsWithIgnoreCaseAndWs(noCommentSql, "RENAME")) {
            throw SQLError.createSQLException(Messages.getString("Statement.57"), MysqlErrorNumbers.SQL_STATE_ILLEGAL_ARGUMENT, getExceptionInterceptor());
        }
    }
}
 
Example 20
Source Project: lams   Source File: XProtocol.java    License: GNU General Public License v2.0 5 votes vote down vote up
public void beforeHandshake() {
    this.serverSession = new XServerSession();

    if (this.socketConnection.isSynchronous()) {
        this.reader = new SyncMessageReader(this.socketConnection.getMysqlInput());
        this.writer = new SyncMessageSender(this.socketConnection.getMysqlOutput());
        this.managedResource = this.socketConnection.getMysqlSocket();

        this.serverSession.setCapabilities(getCapabilities());
        return;
    }

    XAsyncSocketConnection sc = (XAsyncSocketConnection) this.socketConnection;
    this.reader = new AsyncMessageReader(this.propertySet, sc);
    ((AsyncMessageReader) this.reader).start();
    this.writer = new AsyncMessageSender(sc.getAsynchronousSocketChannel());

    this.managedResource = sc.getAsynchronousSocketChannel();

    this.serverSession.setCapabilities(getCapabilities());

    SslMode sslMode = this.propertySet.<SslMode> getEnumReadableProperty(PropertyDefinitions.PNAME_sslMode).getValue();
    boolean verifyServerCert = sslMode == SslMode.VERIFY_CA || sslMode == SslMode.VERIFY_IDENTITY;
    String trustStoreUrl = this.propertySet.getStringReadableProperty(PropertyDefinitions.PNAME_sslTrustStoreUrl).getValue();

    if (!verifyServerCert && !StringUtils.isNullOrEmpty(trustStoreUrl)) {
        StringBuilder msg = new StringBuilder("Incompatible security settings. The property '");
        msg.append(PropertyDefinitions.PNAME_sslTrustStoreUrl).append("' requires '");
        msg.append(PropertyDefinitions.PNAME_sslMode).append("' as '");
        msg.append(PropertyDefinitions.SslMode.VERIFY_CA).append("' or '");
        msg.append(PropertyDefinitions.SslMode.VERIFY_IDENTITY).append("'.");
        throw new CJCommunicationsException(msg.toString());
    }

    if (sslMode != SslMode.DISABLED) {
        negotiateSSLConnection(0);
    }
}
 
Example 21
Source Project: FoxTelem   Source File: UpdatableResultSet.java    License: GNU General Public License v3.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 22
@Override
public NativePacketPayload readMessage(Optional<NativePacketPayload> reuse, NativePacketHeader header) throws IOException {
    int packetLength = header.getMessageSize();
    NativePacketPayload buf = this.packetReader.readMessage(reuse, header);

    int bytesToDump = Math.min(MAX_PACKET_DUMP_LENGTH, packetLength);
    String PacketPayloadImpl = StringUtils.dumpAsHex(buf.getByteBuffer(), bytesToDump);

    StringBuilder packetDump = new StringBuilder(DEBUG_MSG_LEN + NativeConstants.HEADER_LENGTH + PacketPayloadImpl.length());
    packetDump.append("Server ");
    packetDump.append(reuse.isPresent() ? "(re-used) " : "(new) ");
    packetDump.append(buf.toString());
    packetDump.append(" --------------------> Client\n");
    packetDump.append("\nPacket payload:\n\n");
    packetDump.append(this.lastHeaderPayload);
    packetDump.append(PacketPayloadImpl);

    if (bytesToDump == MAX_PACKET_DUMP_LENGTH) {
        packetDump.append("\nNote: Packet of " + packetLength + " bytes truncated to " + MAX_PACKET_DUMP_LENGTH + " bytes.\n");
    }

    if ((this.packetDebugBuffer.size() + 1) > this.packetDebugBufferSize.getValue()) {
        this.packetDebugBuffer.removeFirst();
    }

    this.packetDebugBuffer.addLast(packetDump);

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

    byte[] hashedPassword = passwordBytes;
    try {
        hashedPassword = Security.scrambleCachingSha2(passwordBytes, nonce);
    } catch (DigestException e) {
        throw new RuntimeException(e);
    }

    hashedPassword = StringUtils.toHexString(hashedPassword, hashedPassword.length).getBytes();

    byte[] reply = new byte[databaseBytes.length + userBytes.length + hashedPassword.length + 2];
    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 24
public String asSql(boolean quoteStreamsAndUnknowns) {
    StringBuilder buf = new StringBuilder();

    Object batchArg = null;
    if (this.batchCommandIndex != -1) {
        batchArg = this.batchedArgs.get(this.batchCommandIndex);
    }

    byte[][] staticSqlStrings = this.parseInfo.getStaticSql();
    for (int i = 0; i < this.parameterCount; ++i) {
        buf.append(this.charEncoding != null ? StringUtils.toString(staticSqlStrings[i], this.charEncoding) : StringUtils.toString(staticSqlStrings[i]));

        byte val[] = null;
        if (batchArg != null && batchArg instanceof String) {
            buf.append((String) batchArg);
            continue;
        }
        val = this.batchCommandIndex == -1 ? (this.queryBindings == null ? null : this.queryBindings.getBindValues()[i].getByteValue())
                : ((QueryBindings<?>) batchArg).getBindValues()[i].getByteValue();

        boolean isStreamParam = this.batchCommandIndex == -1 ? (this.queryBindings == null ? false : this.queryBindings.getBindValues()[i].isStream())
                : ((QueryBindings<?>) batchArg).getBindValues()[i].isStream();

        if ((val == null) && !isStreamParam) {
            buf.append(quoteStreamsAndUnknowns ? "'** NOT SPECIFIED **'" : "** NOT SPECIFIED **");
        } else if (isStreamParam) {
            buf.append(quoteStreamsAndUnknowns ? "'** STREAM DATA **'" : "** STREAM DATA **");
        } else {
            buf.append(StringUtils.toString(val, this.charEncoding));
        }
    }

    buf.append(this.charEncoding != null ? StringUtils.toString(staticSqlStrings[this.parameterCount], this.charEncoding)
            : StringUtils.toAsciiString(staticSqlStrings[this.parameterCount]));

    return buf.toString();
}
 
Example 25
Source Project: FoxTelem   Source File: ConnectionUrlParser.java    License: GNU General Public License v3.0 5 votes vote down vote up
/**
 * Parses the host information using the alternate sub hosts lists syntax "[host1, host2, ...]".
 * 
 * @param user
 *            the user to include in all the resulting {@link HostInfo}
 * @param password
 *            the password to include in all the resulting {@link HostInfo}
 * @param hostInfo
 *            the string containing the host information part
 * @return a list with all {@link HostInfo} instances containing the parsed information or <code>null</code> if unable to parse the host information
 */
private List<HostInfo> buildHostInfoResortingToSubHostsListParser(String user, String password, String hostInfo) {
    Matcher matcher = HOST_LIST_PTRN.matcher(hostInfo);
    if (matcher.matches()) {
        String hosts = matcher.group("hosts");
        List<String> hostsList = StringUtils.split(hosts, HOSTS_SEPARATOR, HOSTS_LIST_OPENING_MARKERS, HOSTS_LIST_CLOSING_MARKERS, true,
                StringUtils.SEARCH_MODE__MRK_WS);
        // One single element could, in fact, be an IPv6 stripped from its delimiters.
        boolean maybeIPv6 = hostsList.size() == 1 && hostsList.get(0).matches("(?i)^[\\dabcdef:]+$");
        List<HostInfo> hostInfoList = new ArrayList<>();
        for (String h : hostsList) {
            HostInfo hi;
            if ((hi = buildHostInfoForEmptyHost(user, password, h)) != null) {
                hostInfoList.add(hi);
            } else if ((hi = buildHostInfoResortingToUriParser(user, password, h)) != null
                    || (maybeIPv6 && (hi = buildHostInfoResortingToUriParser(user, password, "[" + h + "]")) != null)) {
                hostInfoList.add(hi);
            } else if ((hi = buildHostInfoResortingToKeyValueSyntaxParser(user, password, h)) != null) {
                hostInfoList.add(hi);
            } else if ((hi = buildHostInfoResortingToAddressEqualsSyntaxParser(user, password, h)) != null) {
                hostInfoList.add(hi);
            } else if ((hi = buildHostInfoResortingToGenericSyntaxParser(user, password, h)) != null) {
                hostInfoList.add(hi);
            } else {
                return null;
            }
        }
        return hostInfoList;
    }
    return null;
}
 
Example 26
Source Project: lams   Source File: SessionImpl.java    License: GNU General Public License v2.0 5 votes vote down vote up
@Override
public String setSavepoint(String name) {
    if (name == null || name.trim().length() == 0) {
        throw new XDevAPIError(Messages.getString("XSession.0", new String[] { "name" }));
    }

    this.session.sendMessage(this.xbuilder.buildSqlStatement("SAVEPOINT " + StringUtils.quoteIdentifier(name, true)));
    return name;
}
 
Example 27
Source Project: lams   Source File: MysqlTextValueDecoder.java    License: GNU General Public License v2.0 5 votes vote down vote up
public <T> T decodeTimestamp(byte[] bytes, int offset, int length, ValueFactory<T> vf) {
    if (length < TIMESTAMP_NOFRAC_STR_LEN || (length > TIMESTAMP_STR_LEN_MAX && length != TIMESTAMP_STR_LEN_WITH_NANOS)) {
        throw new DataReadException(Messages.getString("ResultSet.InvalidLengthForType", new Object[] { length, "TIMESTAMP" }));
    } else if (length != TIMESTAMP_NOFRAC_STR_LEN) {
        // need at least two extra bytes for fractional, '.' and a digit
        if (bytes[offset + TIMESTAMP_NOFRAC_STR_LEN] != (byte) '.' || length < TIMESTAMP_NOFRAC_STR_LEN + 2) {
            throw new DataReadException(
                    Messages.getString("ResultSet.InvalidFormatForType", new Object[] { StringUtils.toString(bytes, offset, length), "TIMESTAMP" }));
        }
    }

    // delimiter verification
    if (bytes[offset + 4] != (byte) '-' || bytes[offset + 7] != (byte) '-' || bytes[offset + 10] != (byte) ' ' || bytes[offset + 13] != (byte) ':'
            || bytes[offset + 16] != (byte) ':') {
        throw new DataReadException(
                Messages.getString("ResultSet.InvalidFormatForType", new Object[] { StringUtils.toString(bytes, offset, length), "TIMESTAMP" }));
    }

    int year = StringUtils.getInt(bytes, offset, offset + 4);
    int month = StringUtils.getInt(bytes, offset + 5, offset + 7);
    int day = StringUtils.getInt(bytes, offset + 8, offset + 10);
    int hours = StringUtils.getInt(bytes, offset + 11, offset + 13);
    int minutes = StringUtils.getInt(bytes, offset + 14, offset + 16);
    int seconds = StringUtils.getInt(bytes, offset + 17, offset + 19);
    // nanos from MySQL fractional
    int nanos;
    if (length == TIMESTAMP_STR_LEN_WITH_NANOS) {
        nanos = StringUtils.getInt(bytes, offset + 20, offset + length);
    } else {
        nanos = (length == TIMESTAMP_NOFRAC_STR_LEN) ? 0 : StringUtils.getInt(bytes, offset + 20, offset + length);
        // scale out nanos appropriately. mysql supports up to 6 digits of fractional seconds, each additional digit increasing the range by a factor of
        // 10. one digit is tenths, two is hundreths, etc
        nanos = nanos * (int) Math.pow(10, 9 - (length - TIMESTAMP_NOFRAC_STR_LEN - 1));
    }

    return vf.createFromTimestamp(year, month, day, hours, minutes, seconds, nanos);
}
 
Example 28
Source Project: lams   Source File: SessionImpl.java    License: GNU General Public License v2.0 5 votes vote down vote up
@Override
public void releaseSavepoint(String name) {
    if (name == null || name.trim().length() == 0) {
        throw new XDevAPIError(Messages.getString("XSession.0", new String[] { "name" }));
    }

    this.session.sendMessage(this.xbuilder.buildSqlStatement("RELEASE SAVEPOINT " + StringUtils.quoteIdentifier(name, true)));
}
 
Example 29
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 30
@Override
public void setBigDecimal(int parameterIndex, BigDecimal x) {
    if (x == null) {
        setNull(parameterIndex);
    } else {
        ServerPreparedQueryBindValue binding = getBinding(parameterIndex, false);
        this.sendTypesToServer.compareAndSet(false, binding.resetToType(MysqlType.FIELD_TYPE_NEWDECIMAL, this.numberOfExecutions));
        binding.value = StringUtils.fixDecimalExponent(x.toPlainString());
    }
}