Java Code Examples for com.mysql.jdbc.StringUtils

The following are top voted examples for showing how to use com.mysql.jdbc.StringUtils. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: the-vigilantes   File: StringRegressionTest.java   Source Code and License 7 votes vote down vote up
/**
 * Tests character conversion bug.
 * 
 * @throws Exception
 *             if there is an internal error (which is a bug).
 */
public void testAsciiCharConversion() throws Exception {
    byte[] buf = new byte[10];
    buf[0] = (byte) '?';
    buf[1] = (byte) 'S';
    buf[2] = (byte) 't';
    buf[3] = (byte) 'a';
    buf[4] = (byte) 't';
    buf[5] = (byte) 'e';
    buf[6] = (byte) '-';
    buf[7] = (byte) 'b';
    buf[8] = (byte) 'o';
    buf[9] = (byte) 't';

    String testString = "?State-bot";
    String convertedString = StringUtils.toAsciiString(buf);

    for (int i = 0; i < convertedString.length(); i++) {
        System.out.println((byte) convertedString.charAt(i));
    }

    assertTrue("Converted string != test string", testString.equals(convertedString));
}
 
Example 2
Project: the-vigilantes   File: ConnectionTest.java   Source Code and License 6 votes vote down vote up
public void testUseOldUTF8Behavior() throws Exception {

        Properties props = new Properties();
        props.setProperty("useOldUTF8Behavior", "true");
        props.setProperty("useUnicode", "true");
        props.setProperty("characterEncoding", "UTF-8");
        props.setProperty("logFactory", "com.mysql.jdbc.log.StandardLogger");
        props.setProperty("profileSQL", "true");
        StandardLogger.startLoggingToBuffer();

        try {
            getConnectionWithProps(props);

            assertTrue(StringUtils.indexOfIgnoreCase(StandardLogger.getBuffer().toString(), "SET NAMES utf8") == -1);
        } finally {
            StandardLogger.dropBuffer();
        }
    }
 
Example 3
Project: the-vigilantes   File: BaseTestCase.java   Source Code and License 6 votes vote down vote up
protected Connection getConnectionWithProps(String url, String propsList) throws SQLException {
    Properties props = new Properties();

    if (propsList != null) {
        List<String> keyValuePairs = StringUtils.split(propsList, ",", false);

        for (String kvp : keyValuePairs) {
            List<String> splitUp = StringUtils.split(kvp, "=", false);
            StringBuilder value = new StringBuilder();

            for (int i = 1; i < splitUp.size(); i++) {
                if (i != 1) {
                    value.append("=");
                }

                value.append(splitUp.get(i));

            }

            props.setProperty(splitUp.get(0).toString().trim(), value.toString());
        }
    }

    return getConnectionWithProps(url, props);
}
 
Example 4
Project: the-vigilantes   File: MysqlXAConnection.java   Source Code and License 6 votes vote down vote up
private static void appendXid(StringBuilder builder, Xid xid) {
    byte[] gtrid = xid.getGlobalTransactionId();
    byte[] btrid = xid.getBranchQualifier();

    if (gtrid != null) {
        StringUtils.appendAsHex(builder, gtrid);
    }

    builder.append(',');
    if (btrid != null) {
        StringUtils.appendAsHex(builder, btrid);
    }

    builder.append(',');
    StringUtils.appendAsHex(builder, xid.getFormatId());
}
 
Example 5
Project: SugarOnRest   File: Utils.java   Source Code and License 6 votes vote down vote up
/**
 * Gets integer value from string data.
 *
 * @param value The value to convert.
 * @return The converted string value.
 */
private static int getInteger(String value) {

    if (StringUtils.isNullOrEmpty(value)) {
        return 0;
    }

    if (value.equalsIgnoreCase("null")) {
        return 0;
    }

    try {
        return Integer.parseInt(value);
    }
    catch (Exception exception) {

    }

    return Integer.MAX_VALUE;
}
 
Example 6
Project: OpenVertretung   File: ConnectionTest.java   Source Code and License 6 votes vote down vote up
public void testUseOldUTF8Behavior() throws Exception {

        Properties props = new Properties();
        props.setProperty("useOldUTF8Behavior", "true");
        props.setProperty("useUnicode", "true");
        props.setProperty("characterEncoding", "UTF-8");
        props.setProperty("logFactory", "com.mysql.jdbc.log.StandardLogger");
        props.setProperty("profileSQL", "true");
        StandardLogger.startLoggingToBuffer();

        try {
            getConnectionWithProps(props);

            assertTrue(StringUtils.indexOfIgnoreCase(StandardLogger.getBuffer().toString(), "SET NAMES utf8") == -1);
        } finally {
            StandardLogger.dropBuffer();
        }
    }
 
Example 7
Project: OpenVertretung   File: StringRegressionTest.java   Source Code and License 6 votes vote down vote up
/**
 * Tests character conversion bug.
 * 
 * @throws Exception
 *             if there is an internal error (which is a bug).
 */
public void testAsciiCharConversion() throws Exception {
    byte[] buf = new byte[10];
    buf[0] = (byte) '?';
    buf[1] = (byte) 'S';
    buf[2] = (byte) 't';
    buf[3] = (byte) 'a';
    buf[4] = (byte) 't';
    buf[5] = (byte) 'e';
    buf[6] = (byte) '-';
    buf[7] = (byte) 'b';
    buf[8] = (byte) 'o';
    buf[9] = (byte) 't';

    String testString = "?State-bot";
    String convertedString = StringUtils.toAsciiString(buf);

    for (int i = 0; i < convertedString.length(); i++) {
        System.out.println((byte) convertedString.charAt(i));
    }

    assertTrue("Converted string != test string", testString.equals(convertedString));
}
 
Example 8
Project: OpenVertretung   File: BaseTestCase.java   Source Code and License 6 votes vote down vote up
protected Connection getConnectionWithProps(String url, String propsList) throws SQLException {
    Properties props = new Properties();

    if (propsList != null) {
        List<String> keyValuePairs = StringUtils.split(propsList, ",", false);

        for (String kvp : keyValuePairs) {
            List<String> splitUp = StringUtils.split(kvp, "=", false);
            StringBuilder value = new StringBuilder();

            for (int i = 1; i < splitUp.size(); i++) {
                if (i != 1) {
                    value.append("=");
                }

                value.append(splitUp.get(i));

            }

            props.setProperty(splitUp.get(0).toString().trim(), value.toString());
        }
    }

    return getConnectionWithProps(url, props);
}
 
Example 9
Project: OpenVertretung   File: MysqlXAConnection.java   Source Code and License 6 votes vote down vote up
private static void appendXid(StringBuilder builder, Xid xid) {
    byte[] gtrid = xid.getGlobalTransactionId();
    byte[] btrid = xid.getBranchQualifier();

    if (gtrid != null) {
        StringUtils.appendAsHex(builder, gtrid);
    }

    builder.append(',');
    if (btrid != null) {
        StringUtils.appendAsHex(builder, btrid);
    }

    builder.append(',');
    StringUtils.appendAsHex(builder, xid.getFormatId());
}
 
Example 10
Project: lams   File: MysqlXAConnection.java   Source Code and License 6 votes vote down vote up
private static void appendXid(StringBuilder builder, Xid xid) {
    byte[] gtrid = xid.getGlobalTransactionId();
    byte[] btrid = xid.getBranchQualifier();

    if (gtrid != null) {
        StringUtils.appendAsHex(builder, gtrid);
    }

    builder.append(',');
    if (btrid != null) {
        StringUtils.appendAsHex(builder, btrid);
    }

    builder.append(',');
    StringUtils.appendAsHex(builder, xid.getFormatId());
}
 
Example 11
Project: ProyectoPacientes   File: ConnectionTest.java   Source Code and License 6 votes vote down vote up
public void testUseOldUTF8Behavior() throws Exception {

        Properties props = new Properties();
        props.setProperty("useOldUTF8Behavior", "true");
        props.setProperty("useUnicode", "true");
        props.setProperty("characterEncoding", "UTF-8");
        props.setProperty("logFactory", "com.mysql.jdbc.log.StandardLogger");
        props.setProperty("profileSQL", "true");
        StandardLogger.startLoggingToBuffer();

        try {
            getConnectionWithProps(props);

            assertTrue(StringUtils.indexOfIgnoreCase(StandardLogger.getBuffer().toString(), "SET NAMES utf8") == -1);
        } finally {
            StandardLogger.dropBuffer();
        }
    }
 
Example 12
Project: ProyectoPacientes   File: StringRegressionTest.java   Source Code and License 6 votes vote down vote up
/**
 * Tests character conversion bug.
 * 
 * @throws Exception
 *             if there is an internal error (which is a bug).
 */
public void testAsciiCharConversion() throws Exception {
    byte[] buf = new byte[10];
    buf[0] = (byte) '?';
    buf[1] = (byte) 'S';
    buf[2] = (byte) 't';
    buf[3] = (byte) 'a';
    buf[4] = (byte) 't';
    buf[5] = (byte) 'e';
    buf[6] = (byte) '-';
    buf[7] = (byte) 'b';
    buf[8] = (byte) 'o';
    buf[9] = (byte) 't';

    String testString = "?State-bot";
    String convertedString = StringUtils.toAsciiString(buf);

    for (int i = 0; i < convertedString.length(); i++) {
        System.out.println((byte) convertedString.charAt(i));
    }

    assertTrue("Converted string != test string", testString.equals(convertedString));
}
 
Example 13
Project: ProyectoPacientes   File: BaseTestCase.java   Source Code and License 6 votes vote down vote up
protected Connection getConnectionWithProps(String url, String propsList) throws SQLException {
    Properties props = new Properties();

    if (propsList != null) {
        List<String> keyValuePairs = StringUtils.split(propsList, ",", false);

        for (String kvp : keyValuePairs) {
            List<String> splitUp = StringUtils.split(kvp, "=", false);
            StringBuilder value = new StringBuilder();

            for (int i = 1; i < splitUp.size(); i++) {
                if (i != 1) {
                    value.append("=");
                }

                value.append(splitUp.get(i));

            }

            props.setProperty(splitUp.get(0).toString().trim(), value.toString());
        }
    }

    return getConnectionWithProps(url, props);
}
 
Example 14
Project: ProyectoPacientes   File: MysqlXAConnection.java   Source Code and License 6 votes vote down vote up
private static void appendXid(StringBuilder builder, Xid xid) {
    byte[] gtrid = xid.getGlobalTransactionId();
    byte[] btrid = xid.getBranchQualifier();

    if (gtrid != null) {
        StringUtils.appendAsHex(builder, gtrid);
    }

    builder.append(',');
    if (btrid != null) {
        StringUtils.appendAsHex(builder, btrid);
    }

    builder.append(',');
    StringUtils.appendAsHex(builder, xid.getFormatId());
}
 
Example 15
Project: BibliotecaPS   File: ConnectionTest.java   Source Code and License 6 votes vote down vote up
public void testUseOldUTF8Behavior() throws Exception {

        Properties props = new Properties();
        props.setProperty("useOldUTF8Behavior", "true");
        props.setProperty("useUnicode", "true");
        props.setProperty("characterEncoding", "UTF-8");
        props.setProperty("logFactory", "com.mysql.jdbc.log.StandardLogger");
        props.setProperty("profileSQL", "true");
        StandardLogger.startLoggingToBuffer();

        try {
            getConnectionWithProps(props);

            assertTrue(StringUtils.indexOfIgnoreCase(StandardLogger.getBuffer().toString(), "SET NAMES utf8") == -1);
        } finally {
            StandardLogger.dropBuffer();
        }
    }
 
Example 16
Project: BibliotecaPS   File: StringRegressionTest.java   Source Code and License 6 votes vote down vote up
/**
 * Tests character conversion bug.
 * 
 * @throws Exception
 *             if there is an internal error (which is a bug).
 */
public void testAsciiCharConversion() throws Exception {
    byte[] buf = new byte[10];
    buf[0] = (byte) '?';
    buf[1] = (byte) 'S';
    buf[2] = (byte) 't';
    buf[3] = (byte) 'a';
    buf[4] = (byte) 't';
    buf[5] = (byte) 'e';
    buf[6] = (byte) '-';
    buf[7] = (byte) 'b';
    buf[8] = (byte) 'o';
    buf[9] = (byte) 't';

    String testString = "?State-bot";
    String convertedString = StringUtils.toAsciiString(buf);

    for (int i = 0; i < convertedString.length(); i++) {
        System.out.println((byte) convertedString.charAt(i));
    }

    assertTrue("Converted string != test string", testString.equals(convertedString));
}
 
Example 17
Project: BibliotecaPS   File: BaseTestCase.java   Source Code and License 6 votes vote down vote up
protected Connection getConnectionWithProps(String url, String propsList) throws SQLException {
    Properties props = new Properties();

    if (propsList != null) {
        List<String> keyValuePairs = StringUtils.split(propsList, ",", false);

        for (String kvp : keyValuePairs) {
            List<String> splitUp = StringUtils.split(kvp, "=", false);
            StringBuilder value = new StringBuilder();

            for (int i = 1; i < splitUp.size(); i++) {
                if (i != 1) {
                    value.append("=");
                }

                value.append(splitUp.get(i));

            }

            props.setProperty(splitUp.get(0).toString().trim(), value.toString());
        }
    }

    return getConnectionWithProps(url, props);
}
 
Example 18
Project: the-vigilantes   File: StringUtilsTest.java   Source Code and License 5 votes vote down vote up
/**
 * Tests StringUtil.indexOfQuoteDoubleAware() method
 * 
 * @throws Exception
 */
public void testIndexOfQuoteDoubleAware() throws Exception {
    final String[] searchInDoubledQt = new String[] { "A 'strange' \"STRONG\" `SsStRiNg` to be searched in",
            "A ''strange'' \"\"STRONG\"\" ``SsStRiNg`` to be searched in" };

    assertEquals(-1, StringUtils.indexOfQuoteDoubleAware(null, null, 0));
    assertEquals(-1, StringUtils.indexOfQuoteDoubleAware(null, "'", 0));
    assertEquals(-1, StringUtils.indexOfQuoteDoubleAware("abc", null, 0));
    assertEquals(-1, StringUtils.indexOfQuoteDoubleAware("abc", "", 0));
    assertEquals(-1, StringUtils.indexOfQuoteDoubleAware("abc", "bcd", 0));
    assertEquals(0, StringUtils.indexOfQuoteDoubleAware("abc", "abc", 0));

    int qtPos = 0;
    assertEquals(2, qtPos = StringUtils.indexOfQuoteDoubleAware(searchInDoubledQt[0], "'", 0));
    assertEquals(10, qtPos = StringUtils.indexOfQuoteDoubleAware(searchInDoubledQt[0], "'", qtPos + 1));
    assertEquals(-1, StringUtils.indexOfQuoteDoubleAware(searchInDoubledQt[0], "'", qtPos + 1));
    assertEquals(12, qtPos = StringUtils.indexOfQuoteDoubleAware(searchInDoubledQt[0], "\"", 0));
    assertEquals(19, qtPos = StringUtils.indexOfQuoteDoubleAware(searchInDoubledQt[0], "\"", qtPos + 1));
    assertEquals(-1, StringUtils.indexOfQuoteDoubleAware(searchInDoubledQt[0], "\"", qtPos + 1));
    assertEquals(21, qtPos = StringUtils.indexOfQuoteDoubleAware(searchInDoubledQt[0], "`", 0));
    assertEquals(30, qtPos = StringUtils.indexOfQuoteDoubleAware(searchInDoubledQt[0], "`", qtPos + 1));
    assertEquals(-1, StringUtils.indexOfQuoteDoubleAware(searchInDoubledQt[0], "`", qtPos + 1));

    assertEquals(-1, StringUtils.indexOfQuoteDoubleAware(searchInDoubledQt[1], "'", 0));
    assertEquals(-1, StringUtils.indexOfQuoteDoubleAware(searchInDoubledQt[1], "\"", 0));
    assertEquals(-1, StringUtils.indexOfQuoteDoubleAware(searchInDoubledQt[1], "`", 0));
}
 
Example 19
Project: the-vigilantes   File: SyntaxRegressionTest.java   Source Code and License 5 votes vote down vote up
/**
 * WL#7696 - InnoDB: Transparent page compression.
 * 
 * Tests COMPRESSION clause in CREATE|ALTER TABLE syntax.
 * 
 * table_option: (...) | COMPRESSION [=] {'ZLIB'|'LZ4'|'NONE'}
 */
public void testTableCompression() throws Exception {
    if (!versionMeetsMinimum(5, 7, 8)) {
        return;
    }

    // Create table with 'zlib' compression.
    createTable("testTableCompression", "(c VARCHAR(15000)) COMPRESSION='ZLIB'");

    this.rs = this.stmt.executeQuery("show create table testTableCompression");
    assertTrue(this.rs.next());
    assertTrue(StringUtils.indexOfIgnoreCase(this.rs.getString(2), "COMPRESSION='ZLIB'") >= 0);

    // Alter table compression to 'lz4'.
    this.stmt.execute("ALTER TABLE testTableCompression COMPRESSION='LZ4'");

    this.rs = this.stmt.executeQuery("show create table testTableCompression");
    assertTrue(this.rs.next());
    assertTrue(StringUtils.indexOfIgnoreCase(this.rs.getString(2), "COMPRESSION='LZ4'") >= 0);

    // Alter table compression to 'none'.
    this.stmt.execute("ALTER TABLE testTableCompression COMPRESSION='NONE'");

    this.rs = this.stmt.executeQuery("show create table testTableCompression");
    assertTrue(this.rs.next());
    assertTrue(StringUtils.indexOfIgnoreCase(this.rs.getString(2), "COMPRESSION='NONE'") >= 0);
}
 
Example 20
Project: the-vigilantes   File: MetaDataRegressionTest.java   Source Code and License 5 votes vote down vote up
@Override
public ResultSetInternalMethods preProcess(String sql, com.mysql.jdbc.Statement interceptedStatement, com.mysql.jdbc.Connection conn)
        throws SQLException {
    if (interceptedStatement instanceof com.mysql.jdbc.PreparedStatement) {
        sql = ((com.mysql.jdbc.PreparedStatement) interceptedStatement).getPreparedSql();
        assertTrue("Assereet failed on: " + sql,
                StringUtils.indexOfIgnoreCase(0, sql, "WHERE TABLE_SCHEMA = ? AND TABLE_NAME = ? AND COLUMN_NAME LIKE ?") > -1);
    }
    return null;
}
 
Example 21
Project: the-vigilantes   File: MetaDataRegressionTest.java   Source Code and License 5 votes vote down vote up
private void testBug65871_testCatalogs(Connection conn1) throws Exception {
    testBug65871_testCatalog("db1`testbug65871", StringUtils.quoteIdentifier("db1`testbug65871", ((ConnectionProperties) conn1).getPedantic()), conn1);

    testBug65871_testCatalog("db2`testbug65871", StringUtils.quoteIdentifier("db2`testbug65871", "\"", ((ConnectionProperties) conn1).getPedantic()),
            conn1);

    testBug65871_testCatalog("`db3`testbug65871`", StringUtils.quoteIdentifier("`db3`testbug65871`", "\"", ((ConnectionProperties) conn1).getPedantic()),
            conn1);
}
 
Example 22
Project: the-vigilantes   File: MetaDataRegressionTest.java   Source Code and License 5 votes vote down vote up
private void testBug65871_testCatalog(String unquotedDbName, String quotedDbName, Connection conn1) throws Exception {

        Statement st1 = null;

        try {
            st1 = conn1.createStatement();

            // 1. catalog
            st1.executeUpdate("DROP DATABASE IF EXISTS " + quotedDbName);
            st1.executeUpdate("CREATE DATABASE " + quotedDbName);
            this.rs = st1.executeQuery("show databases like '" + unquotedDbName + "'");
            if (this.rs.next()) {
                assertEquals(unquotedDbName, this.rs.getString(1));
            } else {
                fail("Database " + unquotedDbName + " (quoted " + quotedDbName + ") not found.");
            }

            testBug65871_testTable(unquotedDbName, quotedDbName, "table1`testbug65871",
                    StringUtils.quoteIdentifier("table1`testbug65871", ((ConnectionProperties) conn1).getPedantic()), conn1, st1);

            testBug65871_testTable(unquotedDbName, quotedDbName, "table2`testbug65871",
                    StringUtils.quoteIdentifier("table2`testbug65871", "\"", ((ConnectionProperties) conn1).getPedantic()), conn1, st1);

            testBug65871_testTable(unquotedDbName, quotedDbName, "table3\"testbug65871",
                    StringUtils.quoteIdentifier("table3\"testbug65871", "\"", ((ConnectionProperties) conn1).getPedantic()), conn1, st1);

            testBug65871_testTable(unquotedDbName, quotedDbName, "`table4`testbug65871`",
                    StringUtils.quoteIdentifier("`table4`testbug65871`", "\"", ((ConnectionProperties) conn1).getPedantic()), conn1, st1);

        } finally {
            if (st1 != null) {
                st1.executeUpdate("DROP DATABASE IF EXISTS " + quotedDbName);
                st1.close();
            }
        }

    }
 
Example 23
Project: DDNS_Server   File: UpdateServlet.java   Source Code and License 5 votes vote down vote up
public static boolean isValidInetAddress(final String address) {
    if (StringUtils.isEmptyOrWhitespaceOnly(address)) {
        return false;
    }
    if (InetAddressValidator.getInstance().isValid(address)) {
        return true;
    }
        return false;
}
 
Example 24
Project: the-vigilantes   File: StringRegressionTest.java   Source Code and License 5 votes vote down vote up
/**
 * Tests fix for BUG#25047 - StringUtils.indexOfIgnoreCaseRespectQuotes() isn't case-insensitive on the first character of the target.
 * 
 * UPD: Method StringUtils.indexOfIgnoreCaseRespectQuotes() was replaced by StringUtils.indexOfIgnoreCase()
 * 
 * @throws Exception
 *             if the test fails.
 */
public void testBug25047() throws Exception {
    assertEquals(26, StringUtils.indexOfIgnoreCase(0, "insert into Test (TestID) values (?)", "VALUES", "`", "`", StringUtils.SEARCH_MODE__MRK_COM_WS));
    assertEquals(26, StringUtils.indexOfIgnoreCase(0, "insert into Test (TestID) VALUES (?)", "values", "`", "`", StringUtils.SEARCH_MODE__MRK_COM_WS));

    assertEquals(StringUtils.indexOfIgnoreCase(0, "insert into Test (TestID) values (?)", "VALUES", "`", "`", StringUtils.SEARCH_MODE__MRK_COM_WS),
            StringUtils.indexOfIgnoreCase(0, "insert into Test (TestID) VALUES (?)", "VALUES", "`", "`", StringUtils.SEARCH_MODE__MRK_COM_WS));
    assertEquals(StringUtils.indexOfIgnoreCase(0, "insert into Test (TestID) values (?)", "values", "`", "`", StringUtils.SEARCH_MODE__MRK_COM_WS),
            StringUtils.indexOfIgnoreCase(0, "insert into Test (TestID) VALUES (?)", "values", "`", "`", StringUtils.SEARCH_MODE__MRK_COM_WS));
}
 
Example 25
Project: the-vigilantes   File: Sha256PasswordPlugin.java   Source Code and License 5 votes vote down vote up
private static byte[] encryptPassword(String password, String seed, Connection connection, String key) throws SQLException {
    byte[] input = null;
    try {
        input = password != null ? StringUtils.getBytesNullTerminated(password, connection.getPasswordCharacterEncoding()) : new byte[] { 0 };
    } catch (UnsupportedEncodingException e) {
        throw SQLError.createSQLException(Messages.getString("Sha256PasswordPlugin.3", new Object[] { connection.getPasswordCharacterEncoding() }),
                SQLError.SQL_STATE_GENERAL_ERROR, null);
    }
    byte[] mysqlScrambleBuff = new byte[input.length];
    Security.xorString(input, mysqlScrambleBuff, seed.getBytes(), input.length);
    return ExportControlled.encryptWithRSAPublicKey(mysqlScrambleBuff,
            ExportControlled.decodeRSAPublicKey(key, ((MySQLConnection) connection).getExceptionInterceptor()),
            ((MySQLConnection) connection).getExceptionInterceptor());
}
 
Example 26
Project: SugarOnRest   File: Main.java   Source Code and License 5 votes vote down vote up
private static String ensureBaseFolderExist(String[] args) throws Exception {
    String baseFolder = "";

    if (args.length > 0 ){
        baseFolder = args[0];
    }

    if (StringUtils.isNullOrEmpty(baseFolder)) {
        baseFolder =  System.getProperty("user.dir");
    }

    return ensureFolderExist(baseFolder, "");
}
 
Example 27
Project: SugarOnRest   File: Utils.java   Source Code and License 5 votes vote down vote up
/**
 * Make get property name prettier.
 *
 * @param name Value to convert.
 * @return Name in Pascal case
 * @throws Exception
 */
public static String toPascalCase(String name) throws Exception {
    if (StringUtils.isNullOrEmpty(name)) {
        return name;
    }

    String pascalCase = "";
    char newChar;
    boolean toUpper = false;
    char[] charArray = name.toCharArray();
    for (int ctr = 0; ctr <= charArray.length - 1; ctr++)
    {
        if (ctr == 0)
        {
            newChar = Character.toUpperCase(charArray[ctr]);
            pascalCase = Character.toString(newChar);
            continue;
        }

        if (charArray[ctr] == '_')
        {
            toUpper = true;
            continue;
        }

        if (toUpper)
        {
            newChar = Character.toUpperCase(charArray[ctr]);
            pascalCase += Character.toString(newChar);
            toUpper = false;
            continue;
        }

        pascalCase += Character.toString(charArray[ctr]);
    }

    return pascalCase;
}
 
Example 28
Project: SugarOnRest   File: Utils.java   Source Code and License 5 votes vote down vote up
/**
 *  Is table a view?
 *
 * @param value The value from sql.
 * @return True or false.
 */
public static boolean getIsView(String value) {

    if (StringUtils.isNullOrEmpty(value)) {
        return false;
    }

    if (value.equalsIgnoreCase("View")) {
        return true;
    }

    return false;
}
 
Example 29
Project: SugarOnRest   File: Utils.java   Source Code and License 5 votes vote down vote up
/**
 * Is column a primary key?
 *
 * @param value The value from sql query.
 * @return True or false.
 */
public static boolean getIsVPrimaryKey(String value) {

    if (StringUtils.isNullOrEmpty(value)) {
        return false;
    }

    if (value.equalsIgnoreCase("PRI")) {
        return true;
    }

    return false;
}
 
Example 30
Project: SugarOnRest   File: Utils.java   Source Code and License 5 votes vote down vote up
/**
 * Is column nullable?
 *
 * @param value The value from sql query.
 * @return True or false.
 */
public static boolean getIsNullable(String value) {

    if (StringUtils.isNullOrEmpty(value)) {
        return false;
    }

    if (value.equalsIgnoreCase("YES")) {
        return true;
    }

    return false;
}
 
Example 31
Project: SugarOnRest   File: Utils.java   Source Code and License 5 votes vote down vote up
/**
 * Returns empty string if string value is null.
 *
 * @param value The value to convert.
 * @return The converted string value.
 */
private static String getEmptyIfNull(String value) {

    if (StringUtils.isNullOrEmpty(value)) {
        return "";
    }

    return value;
}
 
Example 32
Project: mongosql-auth-java   File: MongoSqlAuthenticationPlugin.java   Source Code and License 5 votes vote down vote up
private String readString(final ByteBuffer byteBuffer) {
    int i = byteBuffer.position();
    int len = 0;
    int maxLen = byteBuffer.limit();

    while ((i < maxLen) && (byteBuffer.get(i) != 0)) {
        len++;
        i++;
    }

    String s = StringUtils.toString(byteBuffer.array(), byteBuffer.position(), len);
    byteBuffer.position(byteBuffer.position() + len + 1);

    return s;
}
 
Example 33
Project: OpenVertretung   File: StringUtilsTest.java   Source Code and License 5 votes vote down vote up
/**
 * Tests StringUtil.indexOfQuoteDoubleAware() method
 * 
 * @throws Exception
 */
public void testIndexOfQuoteDoubleAware() throws Exception {
    final String[] searchInDoubledQt = new String[] { "A 'strange' \"STRONG\" `SsStRiNg` to be searched in",
            "A ''strange'' \"\"STRONG\"\" ``SsStRiNg`` to be searched in" };

    assertEquals(-1, StringUtils.indexOfQuoteDoubleAware(null, null, 0));
    assertEquals(-1, StringUtils.indexOfQuoteDoubleAware(null, "'", 0));
    assertEquals(-1, StringUtils.indexOfQuoteDoubleAware("abc", null, 0));
    assertEquals(-1, StringUtils.indexOfQuoteDoubleAware("abc", "", 0));
    assertEquals(-1, StringUtils.indexOfQuoteDoubleAware("abc", "bcd", 0));
    assertEquals(0, StringUtils.indexOfQuoteDoubleAware("abc", "abc", 0));

    int qtPos = 0;
    assertEquals(2, qtPos = StringUtils.indexOfQuoteDoubleAware(searchInDoubledQt[0], "'", 0));
    assertEquals(10, qtPos = StringUtils.indexOfQuoteDoubleAware(searchInDoubledQt[0], "'", qtPos + 1));
    assertEquals(-1, StringUtils.indexOfQuoteDoubleAware(searchInDoubledQt[0], "'", qtPos + 1));
    assertEquals(12, qtPos = StringUtils.indexOfQuoteDoubleAware(searchInDoubledQt[0], "\"", 0));
    assertEquals(19, qtPos = StringUtils.indexOfQuoteDoubleAware(searchInDoubledQt[0], "\"", qtPos + 1));
    assertEquals(-1, StringUtils.indexOfQuoteDoubleAware(searchInDoubledQt[0], "\"", qtPos + 1));
    assertEquals(21, qtPos = StringUtils.indexOfQuoteDoubleAware(searchInDoubledQt[0], "`", 0));
    assertEquals(30, qtPos = StringUtils.indexOfQuoteDoubleAware(searchInDoubledQt[0], "`", qtPos + 1));
    assertEquals(-1, StringUtils.indexOfQuoteDoubleAware(searchInDoubledQt[0], "`", qtPos + 1));

    assertEquals(-1, StringUtils.indexOfQuoteDoubleAware(searchInDoubledQt[1], "'", 0));
    assertEquals(-1, StringUtils.indexOfQuoteDoubleAware(searchInDoubledQt[1], "\"", 0));
    assertEquals(-1, StringUtils.indexOfQuoteDoubleAware(searchInDoubledQt[1], "`", 0));
}
 
Example 34
Project: OpenVertretung   File: MetaDataRegressionTest.java   Source Code and License 5 votes vote down vote up
@Override
public ResultSetInternalMethods preProcess(String sql, com.mysql.jdbc.Statement interceptedStatement, com.mysql.jdbc.Connection conn)
        throws SQLException {
    if (interceptedStatement instanceof com.mysql.jdbc.PreparedStatement) {
        sql = ((com.mysql.jdbc.PreparedStatement) interceptedStatement).getPreparedSql();
        assertTrue("Assereet failed on: " + sql,
                StringUtils.indexOfIgnoreCase(0, sql, "WHERE TABLE_SCHEMA = ? AND TABLE_NAME = ? AND COLUMN_NAME LIKE ?") > -1);
    }
    return null;
}
 
Example 35
Project: OpenVertretung   File: MetaDataRegressionTest.java   Source Code and License 5 votes vote down vote up
private void testBug65871_testCatalogs(Connection conn1) throws Exception {
    testBug65871_testCatalog("db1`testbug65871", StringUtils.quoteIdentifier("db1`testbug65871", ((ConnectionProperties) conn1).getPedantic()), conn1);

    testBug65871_testCatalog("db2`testbug65871", StringUtils.quoteIdentifier("db2`testbug65871", "\"", ((ConnectionProperties) conn1).getPedantic()),
            conn1);

    testBug65871_testCatalog("`db3`testbug65871`", StringUtils.quoteIdentifier("`db3`testbug65871`", "\"", ((ConnectionProperties) conn1).getPedantic()),
            conn1);
}
 
Example 36
Project: DDNS_Server   File: AdminServlet.java   Source Code and License 5 votes vote down vote up
public static boolean isValidInetAddress(final String address) {
    if (StringUtils.isEmptyOrWhitespaceOnly(address)) {
        return false;
    }
    if (InetAddressValidator.getInstance().isValid(address)) {
        return true;
    }

    return false;
}
 
Example 37
Project: BibliotecaPS   File: JDBC4UpdatableResultSet.java   Source Code and License 5 votes vote down vote up
/**
 * JDBC 4.0 Update a column with NATIONAL CHARACTER. The updateXXX() methods
 * are used to update column values in the current row, or the insert row.
 * The updateXXX() methods do not update the underlying database, instead
 * the updateRow() or insertRow() methods are called to update the database.
 * 
 * @param columnIndex
 *            the first column is 1, the second is 2, ...
 * @param x
 *            the new column value
 * 
 * @exception SQLException
 *                if a database-access error occurs
 */
public void updateNString(int columnIndex, String x) throws SQLException {
    synchronized (checkClosed().getConnectionMutex()) {
        String fieldEncoding = this.fields[columnIndex - 1].getEncoding();
        if (fieldEncoding == null || !fieldEncoding.equals("UTF-8")) {
            throw new SQLException("Can not call updateNString() when field's character set isn't UTF-8");
        }

        if (!this.onInsertRow) {
            if (!this.doingUpdates) {
                this.doingUpdates = true;
                syncUpdate();
            }

            ((com.mysql.jdbc.JDBC4PreparedStatement) this.updater).setNString(columnIndex, x);
        } else {
            ((com.mysql.jdbc.JDBC4PreparedStatement) this.inserter).setNString(columnIndex, x);

            if (x == null) {
                this.thisRow.setColumnValue(columnIndex - 1, null);
            } else {
                this.thisRow.setColumnValue(columnIndex - 1, StringUtils.getBytes(x, this.charConverter, fieldEncoding, this.connection.getServerCharset(),
                        this.connection.parserKnowsUnicode(), getExceptionInterceptor()));
            }
        }
    }
}
 
Example 38
Project: OpenVertretung   File: StringRegressionTest.java   Source Code and License 5 votes vote down vote up
/**
 * Tests fix for BUG#25047 - StringUtils.indexOfIgnoreCaseRespectQuotes() isn't case-insensitive on the first character of the target.
 * 
 * UPD: Method StringUtils.indexOfIgnoreCaseRespectQuotes() was replaced by StringUtils.indexOfIgnoreCase()
 * 
 * @throws Exception
 *             if the test fails.
 */
public void testBug25047() throws Exception {
    assertEquals(26, StringUtils.indexOfIgnoreCase(0, "insert into Test (TestID) values (?)", "VALUES", "`", "`", StringUtils.SEARCH_MODE__MRK_COM_WS));
    assertEquals(26, StringUtils.indexOfIgnoreCase(0, "insert into Test (TestID) VALUES (?)", "values", "`", "`", StringUtils.SEARCH_MODE__MRK_COM_WS));

    assertEquals(StringUtils.indexOfIgnoreCase(0, "insert into Test (TestID) values (?)", "VALUES", "`", "`", StringUtils.SEARCH_MODE__MRK_COM_WS),
            StringUtils.indexOfIgnoreCase(0, "insert into Test (TestID) VALUES (?)", "VALUES", "`", "`", StringUtils.SEARCH_MODE__MRK_COM_WS));
    assertEquals(StringUtils.indexOfIgnoreCase(0, "insert into Test (TestID) values (?)", "values", "`", "`", StringUtils.SEARCH_MODE__MRK_COM_WS),
            StringUtils.indexOfIgnoreCase(0, "insert into Test (TestID) VALUES (?)", "values", "`", "`", StringUtils.SEARCH_MODE__MRK_COM_WS));
}
 
Example 39
Project: OpenVertretung   File: Sha256PasswordPlugin.java   Source Code and License 5 votes vote down vote up
private static byte[] encryptPassword(String password, String seed, Connection connection, String key) throws SQLException {
    byte[] input = null;
    try {
        input = password != null ? StringUtils.getBytesNullTerminated(password, connection.getPasswordCharacterEncoding()) : new byte[] { 0 };
    } catch (UnsupportedEncodingException e) {
        throw SQLError.createSQLException(Messages.getString("Sha256PasswordPlugin.3", new Object[] { connection.getPasswordCharacterEncoding() }),
                SQLError.SQL_STATE_GENERAL_ERROR, null);
    }
    byte[] mysqlScrambleBuff = new byte[input.length];
    Security.xorString(input, mysqlScrambleBuff, seed.getBytes(), input.length);
    return ExportControlled.encryptWithRSAPublicKey(mysqlScrambleBuff,
            ExportControlled.decodeRSAPublicKey(key, ((MySQLConnection) connection).getExceptionInterceptor()),
            ((MySQLConnection) connection).getExceptionInterceptor());
}
 
Example 40
Project: OpenVertretung   File: JDBC4UpdatableResultSet.java   Source Code and License 5 votes vote down vote up
/**
 * JDBC 4.0 Update a column with NATIONAL CHARACTER. The updateXXX() methods
 * are used to update column values in the current row, or the insert row.
 * The updateXXX() methods do not update the underlying database, instead
 * the updateRow() or insertRow() methods are called to update the database.
 * 
 * @param columnIndex
 *            the first column is 1, the second is 2, ...
 * @param x
 *            the new column value
 * 
 * @exception SQLException
 *                if a database-access error occurs
 */
public void updateNString(int columnIndex, String x) throws SQLException {
    synchronized (checkClosed().getConnectionMutex()) {
        String fieldEncoding = this.fields[columnIndex - 1].getEncoding();
        if (fieldEncoding == null || !fieldEncoding.equals("UTF-8")) {
            throw new SQLException("Can not call updateNString() when field's character set isn't UTF-8");
        }

        if (!this.onInsertRow) {
            if (!this.doingUpdates) {
                this.doingUpdates = true;
                syncUpdate();
            }

            ((com.mysql.jdbc.JDBC4PreparedStatement) this.updater).setNString(columnIndex, x);
        } else {
            ((com.mysql.jdbc.JDBC4PreparedStatement) this.inserter).setNString(columnIndex, x);

            if (x == null) {
                this.thisRow.setColumnValue(columnIndex - 1, null);
            } else {
                this.thisRow.setColumnValue(columnIndex - 1, StringUtils.getBytes(x, this.charConverter, fieldEncoding, this.connection.getServerCharset(),
                        this.connection.parserKnowsUnicode(), getExceptionInterceptor()));
            }
        }
    }
}
 
Example 41
Project: lams   File: Sha256PasswordPlugin.java   Source Code and License 5 votes vote down vote up
private static byte[] encryptPassword(String password, String seed, Connection connection, String key) throws SQLException {
    byte[] input = null;
    try {
        input = password != null ? StringUtils.getBytesNullTerminated(password, connection.getPasswordCharacterEncoding()) : new byte[] { 0 };
    } catch (UnsupportedEncodingException e) {
        throw SQLError.createSQLException(Messages.getString("Sha256PasswordPlugin.3", new Object[] { connection.getPasswordCharacterEncoding() }),
                SQLError.SQL_STATE_GENERAL_ERROR, null);
    }
    byte[] mysqlScrambleBuff = new byte[input.length];
    Security.xorString(input, mysqlScrambleBuff, seed.getBytes(), input.length);
    return ExportControlled.encryptWithRSAPublicKey(mysqlScrambleBuff,
            ExportControlled.decodeRSAPublicKey(key, ((MySQLConnection) connection).getExceptionInterceptor()),
            ((MySQLConnection) connection).getExceptionInterceptor());
}
 
Example 42
Project: ProyectoPacientes   File: StringUtilsTest.java   Source Code and License 5 votes vote down vote up
/**
 * Tests StringUtil.indexOfQuoteDoubleAware() method
 * 
 * @throws Exception
 */
public void testIndexOfQuoteDoubleAware() throws Exception {
    final String[] searchInDoubledQt = new String[] { "A 'strange' \"STRONG\" `SsStRiNg` to be searched in",
            "A ''strange'' \"\"STRONG\"\" ``SsStRiNg`` to be searched in" };

    assertEquals(-1, StringUtils.indexOfQuoteDoubleAware(null, null, 0));
    assertEquals(-1, StringUtils.indexOfQuoteDoubleAware(null, "'", 0));
    assertEquals(-1, StringUtils.indexOfQuoteDoubleAware("abc", null, 0));
    assertEquals(-1, StringUtils.indexOfQuoteDoubleAware("abc", "", 0));
    assertEquals(-1, StringUtils.indexOfQuoteDoubleAware("abc", "bcd", 0));
    assertEquals(0, StringUtils.indexOfQuoteDoubleAware("abc", "abc", 0));

    int qtPos = 0;
    assertEquals(2, qtPos = StringUtils.indexOfQuoteDoubleAware(searchInDoubledQt[0], "'", 0));
    assertEquals(10, qtPos = StringUtils.indexOfQuoteDoubleAware(searchInDoubledQt[0], "'", qtPos + 1));
    assertEquals(-1, StringUtils.indexOfQuoteDoubleAware(searchInDoubledQt[0], "'", qtPos + 1));
    assertEquals(12, qtPos = StringUtils.indexOfQuoteDoubleAware(searchInDoubledQt[0], "\"", 0));
    assertEquals(19, qtPos = StringUtils.indexOfQuoteDoubleAware(searchInDoubledQt[0], "\"", qtPos + 1));
    assertEquals(-1, StringUtils.indexOfQuoteDoubleAware(searchInDoubledQt[0], "\"", qtPos + 1));
    assertEquals(21, qtPos = StringUtils.indexOfQuoteDoubleAware(searchInDoubledQt[0], "`", 0));
    assertEquals(30, qtPos = StringUtils.indexOfQuoteDoubleAware(searchInDoubledQt[0], "`", qtPos + 1));
    assertEquals(-1, StringUtils.indexOfQuoteDoubleAware(searchInDoubledQt[0], "`", qtPos + 1));

    assertEquals(-1, StringUtils.indexOfQuoteDoubleAware(searchInDoubledQt[1], "'", 0));
    assertEquals(-1, StringUtils.indexOfQuoteDoubleAware(searchInDoubledQt[1], "\"", 0));
    assertEquals(-1, StringUtils.indexOfQuoteDoubleAware(searchInDoubledQt[1], "`", 0));
}
 
Example 43
Project: ProyectoPacientes   File: SyntaxRegressionTest.java   Source Code and License 5 votes vote down vote up
/**
 * WL#7696 - InnoDB: Transparent page compression.
 * 
 * Tests COMPRESSION clause in CREATE|ALTER TABLE syntax.
 * 
 * table_option: (...) | COMPRESSION [=] {'ZLIB'|'LZ4'|'NONE'}
 */
public void testTableCompression() throws Exception {
    if (!versionMeetsMinimum(5, 7, 8)) {
        return;
    }

    // Create table with 'zlib' compression.
    createTable("testTableCompression", "(c VARCHAR(15000)) COMPRESSION='ZLIB'");

    this.rs = this.stmt.executeQuery("show create table testTableCompression");
    assertTrue(this.rs.next());
    assertTrue(StringUtils.indexOfIgnoreCase(this.rs.getString(2), "COMPRESSION='ZLIB'") >= 0);

    // Alter table compression to 'lz4'.
    this.stmt.execute("ALTER TABLE testTableCompression COMPRESSION='LZ4'");

    this.rs = this.stmt.executeQuery("show create table testTableCompression");
    assertTrue(this.rs.next());
    assertTrue(StringUtils.indexOfIgnoreCase(this.rs.getString(2), "COMPRESSION='LZ4'") >= 0);

    // Alter table compression to 'none'.
    this.stmt.execute("ALTER TABLE testTableCompression COMPRESSION='NONE'");

    this.rs = this.stmt.executeQuery("show create table testTableCompression");
    assertTrue(this.rs.next());
    assertTrue(StringUtils.indexOfIgnoreCase(this.rs.getString(2), "COMPRESSION='NONE'") >= 0);
}
 
Example 44
Project: ProyectoPacientes   File: MetaDataRegressionTest.java   Source Code and License 5 votes vote down vote up
@Override
public ResultSetInternalMethods preProcess(String sql, com.mysql.jdbc.Statement interceptedStatement, com.mysql.jdbc.Connection conn)
        throws SQLException {
    if (interceptedStatement instanceof com.mysql.jdbc.PreparedStatement) {
        sql = ((com.mysql.jdbc.PreparedStatement) interceptedStatement).getPreparedSql();
        assertTrue("Assereet failed on: " + sql,
                StringUtils.indexOfIgnoreCase(0, sql, "WHERE TABLE_SCHEMA = ? AND TABLE_NAME = ? AND COLUMN_NAME LIKE ?") > -1);
    }
    return null;
}
 
Example 45
Project: ProyectoPacientes   File: MetaDataRegressionTest.java   Source Code and License 5 votes vote down vote up
private void testBug65871_testCatalogs(Connection conn1) throws Exception {
    testBug65871_testCatalog("db1`testbug65871", StringUtils.quoteIdentifier("db1`testbug65871", ((ConnectionProperties) conn1).getPedantic()), conn1);

    testBug65871_testCatalog("db2`testbug65871", StringUtils.quoteIdentifier("db2`testbug65871", "\"", ((ConnectionProperties) conn1).getPedantic()),
            conn1);

    testBug65871_testCatalog("`db3`testbug65871`", StringUtils.quoteIdentifier("`db3`testbug65871`", "\"", ((ConnectionProperties) conn1).getPedantic()),
            conn1);
}
 
Example 46
Project: ProyectoPacientes   File: MetaDataRegressionTest.java   Source Code and License 5 votes vote down vote up
private void testBug65871_testCatalog(String unquotedDbName, String quotedDbName, Connection conn1) throws Exception {

        Statement st1 = null;

        try {
            st1 = conn1.createStatement();

            // 1. catalog
            st1.executeUpdate("DROP DATABASE IF EXISTS " + quotedDbName);
            st1.executeUpdate("CREATE DATABASE " + quotedDbName);
            this.rs = st1.executeQuery("show databases like '" + unquotedDbName + "'");
            if (this.rs.next()) {
                assertEquals(unquotedDbName, this.rs.getString(1));
            } else {
                fail("Database " + unquotedDbName + " (quoted " + quotedDbName + ") not found.");
            }

            testBug65871_testTable(unquotedDbName, quotedDbName, "table1`testbug65871",
                    StringUtils.quoteIdentifier("table1`testbug65871", ((ConnectionProperties) conn1).getPedantic()), conn1, st1);

            testBug65871_testTable(unquotedDbName, quotedDbName, "table2`testbug65871",
                    StringUtils.quoteIdentifier("table2`testbug65871", "\"", ((ConnectionProperties) conn1).getPedantic()), conn1, st1);

            testBug65871_testTable(unquotedDbName, quotedDbName, "table3\"testbug65871",
                    StringUtils.quoteIdentifier("table3\"testbug65871", "\"", ((ConnectionProperties) conn1).getPedantic()), conn1, st1);

            testBug65871_testTable(unquotedDbName, quotedDbName, "`table4`testbug65871`",
                    StringUtils.quoteIdentifier("`table4`testbug65871`", "\"", ((ConnectionProperties) conn1).getPedantic()), conn1, st1);

        } finally {
            if (st1 != null) {
                st1.executeUpdate("DROP DATABASE IF EXISTS " + quotedDbName);
                st1.close();
            }
        }

    }
 
Example 47
Project: ProyectoPacientes   File: StringRegressionTest.java   Source Code and License 5 votes vote down vote up
/**
 * Tests fix for BUG#25047 - StringUtils.indexOfIgnoreCaseRespectQuotes() isn't case-insensitive on the first character of the target.
 * 
 * UPD: Method StringUtils.indexOfIgnoreCaseRespectQuotes() was replaced by StringUtils.indexOfIgnoreCase()
 * 
 * @throws Exception
 *             if the test fails.
 */
public void testBug25047() throws Exception {
    assertEquals(26, StringUtils.indexOfIgnoreCase(0, "insert into Test (TestID) values (?)", "VALUES", "`", "`", StringUtils.SEARCH_MODE__MRK_COM_WS));
    assertEquals(26, StringUtils.indexOfIgnoreCase(0, "insert into Test (TestID) VALUES (?)", "values", "`", "`", StringUtils.SEARCH_MODE__MRK_COM_WS));

    assertEquals(StringUtils.indexOfIgnoreCase(0, "insert into Test (TestID) values (?)", "VALUES", "`", "`", StringUtils.SEARCH_MODE__MRK_COM_WS),
            StringUtils.indexOfIgnoreCase(0, "insert into Test (TestID) VALUES (?)", "VALUES", "`", "`", StringUtils.SEARCH_MODE__MRK_COM_WS));
    assertEquals(StringUtils.indexOfIgnoreCase(0, "insert into Test (TestID) values (?)", "values", "`", "`", StringUtils.SEARCH_MODE__MRK_COM_WS),
            StringUtils.indexOfIgnoreCase(0, "insert into Test (TestID) VALUES (?)", "values", "`", "`", StringUtils.SEARCH_MODE__MRK_COM_WS));
}
 
Example 48
Project: ProyectoPacientes   File: Sha256PasswordPlugin.java   Source Code and License 5 votes vote down vote up
private static byte[] encryptPassword(String password, String seed, Connection connection, String key) throws SQLException {
    byte[] input = null;
    try {
        input = password != null ? StringUtils.getBytesNullTerminated(password, connection.getPasswordCharacterEncoding()) : new byte[] { 0 };
    } catch (UnsupportedEncodingException e) {
        throw SQLError.createSQLException(Messages.getString("Sha256PasswordPlugin.3", new Object[] { connection.getPasswordCharacterEncoding() }),
                SQLError.SQL_STATE_GENERAL_ERROR, null);
    }
    byte[] mysqlScrambleBuff = new byte[input.length];
    Security.xorString(input, mysqlScrambleBuff, seed.getBytes(), input.length);
    return ExportControlled.encryptWithRSAPublicKey(mysqlScrambleBuff,
            ExportControlled.decodeRSAPublicKey(key, ((MySQLConnection) connection).getExceptionInterceptor()),
            ((MySQLConnection) connection).getExceptionInterceptor());
}
 
Example 49
Project: BibliotecaPS   File: Sha256PasswordPlugin.java   Source Code and License 5 votes vote down vote up
private static byte[] encryptPassword(String password, String seed, Connection connection, String key) throws SQLException {
    byte[] input = null;
    try {
        input = password != null ? StringUtils.getBytesNullTerminated(password, connection.getPasswordCharacterEncoding()) : new byte[] { 0 };
    } catch (UnsupportedEncodingException e) {
        throw SQLError.createSQLException(Messages.getString("Sha256PasswordPlugin.3", new Object[] { connection.getPasswordCharacterEncoding() }),
                SQLError.SQL_STATE_GENERAL_ERROR, null);
    }
    byte[] mysqlScrambleBuff = new byte[input.length];
    Security.xorString(input, mysqlScrambleBuff, seed.getBytes(), input.length);
    return ExportControlled.encryptWithRSAPublicKey(mysqlScrambleBuff,
            ExportControlled.decodeRSAPublicKey(key, ((MySQLConnection) connection).getExceptionInterceptor()),
            ((MySQLConnection) connection).getExceptionInterceptor());
}
 
Example 50
Project: ProyectoPacientes   File: JDBC4UpdatableResultSet.java   Source Code and License 5 votes vote down vote up
/**
 * JDBC 4.0 Update a column with NATIONAL CHARACTER. The updateXXX() methods
 * are used to update column values in the current row, or the insert row.
 * The updateXXX() methods do not update the underlying database, instead
 * the updateRow() or insertRow() methods are called to update the database.
 * 
 * @param columnIndex
 *            the first column is 1, the second is 2, ...
 * @param x
 *            the new column value
 * 
 * @exception SQLException
 *                if a database-access error occurs
 */
public void updateNString(int columnIndex, String x) throws SQLException {
    synchronized (checkClosed().getConnectionMutex()) {
        String fieldEncoding = this.fields[columnIndex - 1].getEncoding();
        if (fieldEncoding == null || !fieldEncoding.equals("UTF-8")) {
            throw new SQLException("Can not call updateNString() when field's character set isn't UTF-8");
        }

        if (!this.onInsertRow) {
            if (!this.doingUpdates) {
                this.doingUpdates = true;
                syncUpdate();
            }

            ((com.mysql.jdbc.JDBC4PreparedStatement) this.updater).setNString(columnIndex, x);
        } else {
            ((com.mysql.jdbc.JDBC4PreparedStatement) this.inserter).setNString(columnIndex, x);

            if (x == null) {
                this.thisRow.setColumnValue(columnIndex - 1, null);
            } else {
                this.thisRow.setColumnValue(columnIndex - 1, StringUtils.getBytes(x, this.charConverter, fieldEncoding, this.connection.getServerCharset(),
                        this.connection.parserKnowsUnicode(), getExceptionInterceptor()));
            }
        }
    }
}
 
Example 51
Project: BibliotecaPS   File: StringUtilsTest.java   Source Code and License 5 votes vote down vote up
/**
 * Tests StringUtil.indexOfQuoteDoubleAware() method
 * 
 * @throws Exception
 */
public void testIndexOfQuoteDoubleAware() throws Exception {
    final String[] searchInDoubledQt = new String[] { "A 'strange' \"STRONG\" `SsStRiNg` to be searched in",
            "A ''strange'' \"\"STRONG\"\" ``SsStRiNg`` to be searched in" };

    assertEquals(-1, StringUtils.indexOfQuoteDoubleAware(null, null, 0));
    assertEquals(-1, StringUtils.indexOfQuoteDoubleAware(null, "'", 0));
    assertEquals(-1, StringUtils.indexOfQuoteDoubleAware("abc", null, 0));
    assertEquals(-1, StringUtils.indexOfQuoteDoubleAware("abc", "", 0));
    assertEquals(-1, StringUtils.indexOfQuoteDoubleAware("abc", "bcd", 0));
    assertEquals(0, StringUtils.indexOfQuoteDoubleAware("abc", "abc", 0));

    int qtPos = 0;
    assertEquals(2, qtPos = StringUtils.indexOfQuoteDoubleAware(searchInDoubledQt[0], "'", 0));
    assertEquals(10, qtPos = StringUtils.indexOfQuoteDoubleAware(searchInDoubledQt[0], "'", qtPos + 1));
    assertEquals(-1, StringUtils.indexOfQuoteDoubleAware(searchInDoubledQt[0], "'", qtPos + 1));
    assertEquals(12, qtPos = StringUtils.indexOfQuoteDoubleAware(searchInDoubledQt[0], "\"", 0));
    assertEquals(19, qtPos = StringUtils.indexOfQuoteDoubleAware(searchInDoubledQt[0], "\"", qtPos + 1));
    assertEquals(-1, StringUtils.indexOfQuoteDoubleAware(searchInDoubledQt[0], "\"", qtPos + 1));
    assertEquals(21, qtPos = StringUtils.indexOfQuoteDoubleAware(searchInDoubledQt[0], "`", 0));
    assertEquals(30, qtPos = StringUtils.indexOfQuoteDoubleAware(searchInDoubledQt[0], "`", qtPos + 1));
    assertEquals(-1, StringUtils.indexOfQuoteDoubleAware(searchInDoubledQt[0], "`", qtPos + 1));

    assertEquals(-1, StringUtils.indexOfQuoteDoubleAware(searchInDoubledQt[1], "'", 0));
    assertEquals(-1, StringUtils.indexOfQuoteDoubleAware(searchInDoubledQt[1], "\"", 0));
    assertEquals(-1, StringUtils.indexOfQuoteDoubleAware(searchInDoubledQt[1], "`", 0));
}
 
Example 52
Project: BibliotecaPS   File: SyntaxRegressionTest.java   Source Code and License 5 votes vote down vote up
/**
 * WL#7696 - InnoDB: Transparent page compression.
 * 
 * Tests COMPRESSION clause in CREATE|ALTER TABLE syntax.
 * 
 * table_option: (...) | COMPRESSION [=] {'ZLIB'|'LZ4'|'NONE'}
 */
public void testTableCompression() throws Exception {
    if (!versionMeetsMinimum(5, 7, 8)) {
        return;
    }

    // Create table with 'zlib' compression.
    createTable("testTableCompression", "(c VARCHAR(15000)) COMPRESSION='ZLIB'");

    this.rs = this.stmt.executeQuery("show create table testTableCompression");
    assertTrue(this.rs.next());
    assertTrue(StringUtils.indexOfIgnoreCase(this.rs.getString(2), "COMPRESSION='ZLIB'") >= 0);

    // Alter table compression to 'lz4'.
    this.stmt.execute("ALTER TABLE testTableCompression COMPRESSION='LZ4'");

    this.rs = this.stmt.executeQuery("show create table testTableCompression");
    assertTrue(this.rs.next());
    assertTrue(StringUtils.indexOfIgnoreCase(this.rs.getString(2), "COMPRESSION='LZ4'") >= 0);

    // Alter table compression to 'none'.
    this.stmt.execute("ALTER TABLE testTableCompression COMPRESSION='NONE'");

    this.rs = this.stmt.executeQuery("show create table testTableCompression");
    assertTrue(this.rs.next());
    assertTrue(StringUtils.indexOfIgnoreCase(this.rs.getString(2), "COMPRESSION='NONE'") >= 0);
}
 
Example 53
Project: BibliotecaPS   File: MetaDataRegressionTest.java   Source Code and License 5 votes vote down vote up
@Override
public ResultSetInternalMethods preProcess(String sql, com.mysql.jdbc.Statement interceptedStatement, com.mysql.jdbc.Connection conn)
        throws SQLException {
    if (interceptedStatement instanceof com.mysql.jdbc.PreparedStatement) {
        sql = ((com.mysql.jdbc.PreparedStatement) interceptedStatement).getPreparedSql();
        assertTrue("Assereet failed on: " + sql,
                StringUtils.indexOfIgnoreCase(0, sql, "WHERE TABLE_SCHEMA = ? AND TABLE_NAME = ? AND COLUMN_NAME LIKE ?") > -1);
    }
    return null;
}
 
Example 54
Project: BibliotecaPS   File: MetaDataRegressionTest.java   Source Code and License 5 votes vote down vote up
private void testBug65871_testCatalogs(Connection conn1) throws Exception {
    testBug65871_testCatalog("db1`testbug65871", StringUtils.quoteIdentifier("db1`testbug65871", ((ConnectionProperties) conn1).getPedantic()), conn1);

    testBug65871_testCatalog("db2`testbug65871", StringUtils.quoteIdentifier("db2`testbug65871", "\"", ((ConnectionProperties) conn1).getPedantic()),
            conn1);

    testBug65871_testCatalog("`db3`testbug65871`", StringUtils.quoteIdentifier("`db3`testbug65871`", "\"", ((ConnectionProperties) conn1).getPedantic()),
            conn1);
}
 
Example 55
Project: BibliotecaPS   File: MetaDataRegressionTest.java   Source Code and License 5 votes vote down vote up
private void testBug65871_testCatalog(String unquotedDbName, String quotedDbName, Connection conn1) throws Exception {

        Statement st1 = null;

        try {
            st1 = conn1.createStatement();

            // 1. catalog
            st1.executeUpdate("DROP DATABASE IF EXISTS " + quotedDbName);
            st1.executeUpdate("CREATE DATABASE " + quotedDbName);
            this.rs = st1.executeQuery("show databases like '" + unquotedDbName + "'");
            if (this.rs.next()) {
                assertEquals(unquotedDbName, this.rs.getString(1));
            } else {
                fail("Database " + unquotedDbName + " (quoted " + quotedDbName + ") not found.");
            }

            testBug65871_testTable(unquotedDbName, quotedDbName, "table1`testbug65871",
                    StringUtils.quoteIdentifier("table1`testbug65871", ((ConnectionProperties) conn1).getPedantic()), conn1, st1);

            testBug65871_testTable(unquotedDbName, quotedDbName, "table2`testbug65871",
                    StringUtils.quoteIdentifier("table2`testbug65871", "\"", ((ConnectionProperties) conn1).getPedantic()), conn1, st1);

            testBug65871_testTable(unquotedDbName, quotedDbName, "table3\"testbug65871",
                    StringUtils.quoteIdentifier("table3\"testbug65871", "\"", ((ConnectionProperties) conn1).getPedantic()), conn1, st1);

            testBug65871_testTable(unquotedDbName, quotedDbName, "`table4`testbug65871`",
                    StringUtils.quoteIdentifier("`table4`testbug65871`", "\"", ((ConnectionProperties) conn1).getPedantic()), conn1, st1);

        } finally {
            if (st1 != null) {
                st1.executeUpdate("DROP DATABASE IF EXISTS " + quotedDbName);
                st1.close();
            }
        }

    }
 
Example 56
Project: BibliotecaPS   File: StringRegressionTest.java   Source Code and License 5 votes vote down vote up
/**
 * Tests fix for BUG#25047 - StringUtils.indexOfIgnoreCaseRespectQuotes() isn't case-insensitive on the first character of the target.
 * 
 * UPD: Method StringUtils.indexOfIgnoreCaseRespectQuotes() was replaced by StringUtils.indexOfIgnoreCase()
 * 
 * @throws Exception
 *             if the test fails.
 */
public void testBug25047() throws Exception {
    assertEquals(26, StringUtils.indexOfIgnoreCase(0, "insert into Test (TestID) values (?)", "VALUES", "`", "`", StringUtils.SEARCH_MODE__MRK_COM_WS));
    assertEquals(26, StringUtils.indexOfIgnoreCase(0, "insert into Test (TestID) VALUES (?)", "values", "`", "`", StringUtils.SEARCH_MODE__MRK_COM_WS));

    assertEquals(StringUtils.indexOfIgnoreCase(0, "insert into Test (TestID) values (?)", "VALUES", "`", "`", StringUtils.SEARCH_MODE__MRK_COM_WS),
            StringUtils.indexOfIgnoreCase(0, "insert into Test (TestID) VALUES (?)", "VALUES", "`", "`", StringUtils.SEARCH_MODE__MRK_COM_WS));
    assertEquals(StringUtils.indexOfIgnoreCase(0, "insert into Test (TestID) values (?)", "values", "`", "`", StringUtils.SEARCH_MODE__MRK_COM_WS),
            StringUtils.indexOfIgnoreCase(0, "insert into Test (TestID) VALUES (?)", "values", "`", "`", StringUtils.SEARCH_MODE__MRK_COM_WS));
}
 
Example 57
Project: the-vigilantes   File: MetadataTest.java   Source Code and License 4 votes vote down vote up
/**
 * Tests the implementation of Information Schema for column privileges.
 */
public void testGetColumnPrivilegesUsingInfoSchema() throws Exception {
    String dontRunPropertyName = "com.mysql.jdbc.testsuite.cantGrant";

    if (!runTestIfSysPropDefined(dontRunPropertyName)) {
        if (versionMeetsMinimum(5, 0, 7)) {
            Properties props = new Properties();

            props.put("useInformationSchema", "true");
            Connection conn1 = null;
            Statement stmt1 = null;
            String userHostQuoted = null;

            boolean grantFailed = true;

            try {
                conn1 = getConnectionWithProps(props);
                stmt1 = conn1.createStatement();
                createTable("t1", "(c1 int)");
                this.rs = stmt1.executeQuery("SELECT USER()");
                this.rs.next();
                String user = this.rs.getString(1);
                List<String> userHost = StringUtils.split(user, "@", false);
                if (userHost.size() < 2) {
                    fail("This test requires a JDBC URL with a user, and won't work with the anonymous user. "
                            + "You can skip this test by setting the system property " + dontRunPropertyName);
                }
                userHostQuoted = "'" + userHost.get(0) + "'@'" + userHost.get(1) + "'";

                try {
                    stmt1.executeUpdate("GRANT update (c1) on t1 to " + userHostQuoted);

                    grantFailed = false;

                } catch (SQLException sqlEx) {
                    fail("This testcase needs to be run with a URL that allows the user to issue GRANTs "
                            + " in the current database. You can skip this test by setting the system property \"" + dontRunPropertyName + "\".");
                }

                if (!grantFailed) {
                    DatabaseMetaData metaData = conn1.getMetaData();
                    this.rs = metaData.getColumnPrivileges(null, null, "t1", null);
                    this.rs.next();
                    assertEquals("t1", this.rs.getString("TABLE_NAME"));
                    assertEquals("c1", this.rs.getString("COLUMN_NAME"));
                    assertEquals(userHostQuoted, this.rs.getString("GRANTEE"));
                    assertEquals("UPDATE", this.rs.getString("PRIVILEGE"));
                }
            } finally {
                if (stmt1 != null) {

                    if (!grantFailed) {
                        stmt1.executeUpdate("REVOKE UPDATE (c1) ON t1 FROM " + userHostQuoted);
                    }

                    stmt1.close();
                }

                if (conn1 != null) {
                    conn1.close();
                }
            }
        }
    }
}
 
Example 58
Project: the-vigilantes   File: StringUtilsTest.java   Source Code and License 4 votes vote down vote up
/**
 * Tests StringUtils.split() methods.
 */
public void testSplit() throws Exception {
    String testString = "  abstract, (contents, table of \"['figure''s'],(tables\"),  introduction  , \"methods(), ()results\", ['discussion'']', conclusion]   ";
    List<String> stringParts;

    // non existing split char, trim
    stringParts = StringUtils.split(testString, ";", true);
    assertEquals(1, stringParts.size());
    assertEquals(testString.trim(), stringParts.get(0));

    // non existing split char, don't trim
    stringParts = StringUtils.split(testString, ";", false);
    assertEquals(1, stringParts.size());
    assertEquals(testString, stringParts.get(0));

    // full split, trim
    stringParts = StringUtils.split(testString, ",", true);
    assertEquals(9, stringParts.size());
    assertEquals("abstract", stringParts.get(0));
    assertEquals("(contents", stringParts.get(1));
    assertEquals("table of \"['figure''s']", stringParts.get(2));
    assertEquals("(tables\")", stringParts.get(3));
    assertEquals("introduction", stringParts.get(4));
    assertEquals("\"methods()", stringParts.get(5));
    assertEquals("()results\"", stringParts.get(6));
    assertEquals("['discussion'']'", stringParts.get(7));
    assertEquals("conclusion]", stringParts.get(8));

    // full split, don't trim
    stringParts = StringUtils.split(testString, ",", false);
    assertEquals(9, stringParts.size());
    assertEquals("  abstract", stringParts.get(0));
    assertEquals(" (contents", stringParts.get(1));
    assertEquals(" table of \"['figure''s']", stringParts.get(2));
    assertEquals("(tables\")", stringParts.get(3));
    assertEquals("  introduction  ", stringParts.get(4));
    assertEquals(" \"methods()", stringParts.get(5));
    assertEquals(" ()results\"", stringParts.get(6));
    assertEquals(" ['discussion'']'", stringParts.get(7));
    assertEquals(" conclusion]   ", stringParts.get(8));

    // most common markers, trim
    stringParts = StringUtils.split(testString, ",", "'\"", "'\"", true);
    assertEquals(7, stringParts.size());
    assertEquals("abstract", stringParts.get(0));
    assertEquals("(contents", stringParts.get(1));
    assertEquals("table of \"['figure''s'],(tables\")", stringParts.get(2));
    assertEquals("introduction", stringParts.get(3));
    assertEquals("\"methods(), ()results\"", stringParts.get(4));
    assertEquals("['discussion'']'", stringParts.get(5));
    assertEquals("conclusion]", stringParts.get(6));

    // extended markers, trim
    stringParts = StringUtils.split(testString, ",", "'\"([{", "'\")]}", true);
    assertEquals(2, stringParts.size());
    assertEquals("abstract", stringParts.get(0));
    assertEquals("(contents, table of \"['figure''s'],(tables\"),  introduction  , \"methods(), ()results\", ['discussion'']', conclusion]",
            stringParts.get(1));

    // extended markers with overridable markers, trim
    stringParts = StringUtils.split(testString, ",", "'\"([{", "'\")]}", "'\"", true);
    assertEquals(5, stringParts.size());
    assertEquals("abstract", stringParts.get(0));
    assertEquals("(contents, table of \"['figure''s'],(tables\")", stringParts.get(1));
    assertEquals("introduction", stringParts.get(2));
    assertEquals("\"methods(), ()results\"", stringParts.get(3));
    assertEquals("['discussion'']', conclusion]", stringParts.get(4));
}
 
Example 59
Project: the-vigilantes   File: SplitDBdotNameTest.java   Source Code and License 4 votes vote down vote up
/**
 * Tests sanitation and SplitDBdotName
 * 
 * @throws Exception
 *             if an error occurs
 */
public void testSplit() throws Exception {
    String src = null;
    String resString = null;
    List<String> results = new ArrayList<String>();

    //Test 1.1, weird DB.SP name
    src = "`MyDatabase 1.0.1.0`.`Proc 1.v1`";
    resString = StringUtils.sanitizeProcOrFuncName(src);
    if ((resString != null)) {
        results = StringUtils.splitDBdotName(resString, null, "`", true);
        assertEquals(results.get(0), "MyDatabase 1.0.1.0");
        assertEquals(results.get(1), "Proc 1.v1");
    } else {
        fail("Test 1.1 returned null resString");
    }

    //Test 1.2, toggle isNoBslashEscSet
    src = "`MyDatabase 1.0.1.0`.`Proc 1.v1`";
    resString = StringUtils.sanitizeProcOrFuncName(src);
    if ((resString != null)) {
        results = StringUtils.splitDBdotName(resString, null, "`", false);
        assertEquals(results.get(0), "MyDatabase 1.0.1.0");
        assertEquals(results.get(1), "Proc 1.v1");
    } else {
        fail("Test 1.2 returned null resString");
    }

    //Test 2.1, weird SP name, no DB parameter
    src = "`Proc 1.v1`";
    resString = StringUtils.sanitizeProcOrFuncName(src);
    if ((resString != null)) {
        results = StringUtils.splitDBdotName(resString, null, "`", true);
        assertEquals(results.get(0), null);
        assertEquals(results.get(1), "Proc 1.v1");
    } else {
        fail("Test 2.1 returned null resString");
    }

    //Test 2.2, toggle isNoBslashEscSet
    src = "`Proc 1.v1`";
    resString = StringUtils.sanitizeProcOrFuncName(src);
    if ((resString != null)) {
        results = StringUtils.splitDBdotName(resString, null, "`", false);
        assertEquals(results.get(0), null);
        assertEquals(results.get(1), "Proc 1.v1");
    } else {
        fail("Test 2.2 returned null resString");
    }
}
 
Example 60
Project: the-vigilantes   File: ConnectionRegressionTest.java   Source Code and License 4 votes vote down vote up
public boolean nextAuthenticationStep(Buffer fromServer, List<Buffer> toServer) throws SQLException {
    toServer.clear();
    Buffer bresp = new Buffer(StringUtils.getBytes(this.password));
    toServer.add(bresp);
    return true;
}