com.mysql.cj.util.StringUtils Java Examples

The following examples show how to use com.mysql.cj.util.StringUtils. 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: GeneratedColumnDef.java    From lams with 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 #2
Source File: StandardLoadBalanceExceptionChecker.java    From FoxTelem with GNU General Public License v3.0 6 votes vote down vote up
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 #3
Source File: MemorySizePropertyDefinition.java    From FoxTelem with GNU General Public License v3.0 6 votes vote down vote up
@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 #4
Source File: DebugBufferingPacketSender.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/**
 * 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 File: UpdatableResultSet.java    From FoxTelem with 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 File: ResultSetImpl.java    From lams with 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 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 #8
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 #9
Source File: TracingPacketSender.java    From FoxTelem with 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 File: UpdatableResultSet.java    From lams with 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 #11
Source File: StatementImpl.java    From lams with 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 #12
Source File: ExportControlled.java    From FoxTelem with 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 #13
Source File: StandardLoadBalanceExceptionChecker.java    From FoxTelem with GNU General Public License v3.0 6 votes vote down vote up
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 #14
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 #15
Source File: XProtocol.java    From FoxTelem with 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 #16
Source File: TracingPacketSender.java    From lams with 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 #17
Source File: MysqlOldPasswordPlugin.java    From FoxTelem with GNU General Public License v3.0 6 votes vote down vote up
@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 File: StatementImpl.java    From FoxTelem with 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 #19
Source File: CallableStatement.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
private String extractProcedureName() throws SQLException {
    String sanitizedSql = StringUtils.stripComments(((PreparedQuery<?>) this.query).getOriginalSql(), "`\"'", "`\"'", true, false, true, true);

    // TODO: Do this with less memory allocation
    int endCallIndex = StringUtils.indexOfIgnoreCase(sanitizedSql, "CALL ");
    int offset = 5;

    if (endCallIndex == -1) {
        endCallIndex = StringUtils.indexOfIgnoreCase(sanitizedSql, "SELECT ");
        offset = 7;
    }

    if (endCallIndex != -1) {
        StringBuilder nameBuf = new StringBuilder();

        String trimmedStatement = sanitizedSql.substring(endCallIndex + offset).trim();

        int statementLength = trimmedStatement.length();

        for (int i = 0; i < statementLength; i++) {
            char c = trimmedStatement.charAt(i);

            if (Character.isWhitespace(c) || (c == '(') || (c == '?')) {
                break;
            }
            nameBuf.append(c);

        }

        return nameBuf.toString();
    }

    throw SQLError.createSQLException(Messages.getString("CallableStatement.1"), MysqlErrorNumbers.SQL_STATE_GENERAL_ERROR, getExceptionInterceptor());
}
 
Example #20
Source File: ClientPreparedQueryBindings.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
public void setDouble(int parameterIndex, double x) {
    if (!this.session.getPropertySet().getBooleanReadableProperty(PropertyDefinitions.PNAME_allowNanAndInf).getValue()
            && (x == Double.POSITIVE_INFINITY || x == Double.NEGATIVE_INFINITY || Double.isNaN(x))) {
        throw ExceptionFactory.createException(WrongArgumentException.class, Messages.getString("PreparedStatement.64", new Object[] { x }),
                this.session.getExceptionInterceptor());
    }
    setValue(parameterIndex, StringUtils.fixDecimalExponent(String.valueOf(x)), MysqlType.DOUBLE);
}
 
Example #21
Source File: DebugBufferingPacketReader.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@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 #22
Source File: ConnectionUrlParser.java    From FoxTelem with 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 #23
Source File: DbDocValueFactory.java    From FoxTelem with GNU General Public License v3.0 5 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 interpret the
 * byte array using the platform encoding.
 */
@Override
public DbDoc createFromBytes(byte[] bytes, int offset, int length) {
    try {
        return JsonParser.parseDoc(new StringReader(StringUtils.toString(bytes, offset, length, this.encoding)));
    } catch (IOException ex) {
        throw AssertionFailedException.shouldNotHappen(ex);
    }
}
 
Example #24
Source File: StatementImpl.java    From lams with GNU General Public License v2.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 #25
Source File: CallableStatement.java    From FoxTelem with GNU General Public License v3.0 5 votes vote down vote up
private String extractProcedureName() throws SQLException {
    String sanitizedSql = StringUtils.stripComments(((PreparedQuery<?>) this.query).getOriginalSql(), "`\"'", "`\"'", true, false, true, true);

    // TODO: Do this with less memory allocation
    int endCallIndex = StringUtils.indexOfIgnoreCase(sanitizedSql, "CALL ");
    int offset = 5;

    if (endCallIndex == -1) {
        endCallIndex = StringUtils.indexOfIgnoreCase(sanitizedSql, "SELECT ");
        offset = 7;
    }

    if (endCallIndex != -1) {
        StringBuilder nameBuf = new StringBuilder();

        String trimmedStatement = sanitizedSql.substring(endCallIndex + offset).trim();

        int statementLength = trimmedStatement.length();

        for (int i = 0; i < statementLength; i++) {
            char c = trimmedStatement.charAt(i);

            if (Character.isWhitespace(c) || (c == '(') || (c == '?')) {
                break;
            }
            nameBuf.append(c);

        }

        return nameBuf.toString();
    }

    throw SQLError.createSQLException(Messages.getString("CallableStatement.1"), MysqlErrorNumbers.SQL_STATE_GENERAL_ERROR, getExceptionInterceptor());
}
 
Example #26
Source File: ServerPreparedQueryBindings.java    From FoxTelem with GNU General Public License v3.0 5 votes vote down vote up
@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());
    }
}
 
Example #27
Source File: UpdatableResultSet.java    From FoxTelem with 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 #28
Source File: XMessageBuilder.java    From FoxTelem with 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 #29
Source File: ServerPreparedQueryBindings.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@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());
    }
}
 
Example #30
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;
}