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

The following examples show how to use com.mysql.cj.util.StringUtils#split() . These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
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 2
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 3
Source Project: lams   File: NativeSession.java    License: GNU General Public License v2.0 6 votes vote down vote up
public void setSessionVariables() {
    String sessionVariables = getPropertySet().getStringReadableProperty(PropertyDefinitions.PNAME_sessionVariables).getValue();
    if (sessionVariables != null) {
        List<String> variablesToSet = new ArrayList<>();
        for (String part : StringUtils.split(sessionVariables, ",", "\"'(", "\"')", "\"'", true)) {
            variablesToSet.addAll(StringUtils.split(part, ";", "\"'(", "\"')", "\"'", true));
        }

        if (!variablesToSet.isEmpty()) {
            StringBuilder query = new StringBuilder("SET ");
            String separator = "";
            for (String variableToSet : variablesToSet) {
                if (variableToSet.length() > 0) {
                    query.append(separator);
                    if (!variableToSet.startsWith("@")) {
                        query.append("SESSION ");
                    }
                    query.append(variableToSet);
                    separator = ",";
                }
            }
            sendCommand(this.commandBuilder.buildComQuery(null, query.toString()), false, 0);
        }
    }
}
 
Example 4
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 5
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 6
public void setSessionVariables() {
    String sessionVariables = getPropertySet().getStringProperty(PropertyKey.sessionVariables).getValue();
    if (sessionVariables != null) {
        List<String> variablesToSet = new ArrayList<>();
        for (String part : StringUtils.split(sessionVariables, ",", "\"'(", "\"')", "\"'", true)) {
            variablesToSet.addAll(StringUtils.split(part, ";", "\"'(", "\"')", "\"'", true));
        }

        if (!variablesToSet.isEmpty()) {
            StringBuilder query = new StringBuilder("SET ");
            String separator = "";
            for (String variableToSet : variablesToSet) {
                if (variableToSet.length() > 0) {
                    query.append(separator);
                    if (!variableToSet.startsWith("@")) {
                        query.append("SESSION ");
                    }
                    query.append(variableToSet);
                    separator = ",";
                }
            }
            sendCommand(this.commandBuilder.buildComQuery(null, query.toString()), false, 0);
        }
    }
}
 
Example 7
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 8
/**
 * Parses the authority section (user and/or host identification) of the connection string URI.
 */
private void parseAuthoritySection() {
    if (isNullOrEmpty(this.authority)) {
        // Add an empty, default, host.
        this.parsedHosts.add(new HostInfo());
        return;
    }

    List<String> authoritySegments = StringUtils.split(this.authority, HOSTS_SEPARATOR, HOSTS_LIST_OPENING_MARKERS, HOSTS_LIST_CLOSING_MARKERS, true,
            StringUtils.SEARCH_MODE__MRK_WS);
    for (String hi : authoritySegments) {
        parseAuthoritySegment(hi);
    }
}
 
Example 9
/**
 * 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 10
/**
 * Parses the authority section (user and/or host identification) of the connection string URI.
 */
private void parseAuthoritySection() {
    if (isNullOrEmpty(this.authority)) {
        // Add an empty, default, host.
        this.parsedHosts.add(new HostInfo());
        return;
    }

    List<String> authoritySegments = StringUtils.split(this.authority, HOSTS_SEPARATOR, HOSTS_LIST_OPENING_MARKERS, HOSTS_LIST_CLOSING_MARKERS, true,
            StringUtils.SEARCH_MODE__MRK_WS);
    for (String hi : authoritySegments) {
        parseAuthoritySegment(hi);
    }
}
 
Example 11
/**
 * 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 12
/**
 * Fill the authentication plugins map.
 * First this method fill the map with instances of {@link MysqlNativePasswordPlugin}, {@link MysqlClearPasswordPlugin}, {@link Sha256PasswordPlugin}
 * and {@link MysqlOldPasswordPlugin}. Then it creates instances of plugins listed in "authenticationPlugins" connection property and adds them to the map
 * too.
 * 
 * The key for the map entry is got by {@link AuthenticationPlugin#getProtocolPluginName()} thus it is possible to replace built-in plugin with custom
 * implementation. To do it custom plugin should return value "mysql_native_password", "mysql_old_password", "mysql_clear_password" or "sha256_password"
 * from it's own getProtocolPluginName() method.
 * 
 */
@SuppressWarnings("unchecked")
private void loadAuthenticationPlugins() {

    // default plugin
    this.clientDefaultAuthenticationPlugin = this.propertySet.getStringReadableProperty(PropertyDefinitions.PNAME_defaultAuthenticationPlugin).getValue();
    if (this.clientDefaultAuthenticationPlugin == null || "".equals(this.clientDefaultAuthenticationPlugin.trim())) {
        throw ExceptionFactory.createException(WrongArgumentException.class,
                Messages.getString("AuthenticationProvider.BadDefaultAuthenticationPlugin", new Object[] { this.clientDefaultAuthenticationPlugin }),
                getExceptionInterceptor());
    }

    // disabled plugins
    String disabledPlugins = this.propertySet.getStringReadableProperty(PropertyDefinitions.PNAME_disabledAuthenticationPlugins).getValue();
    if (disabledPlugins != null && !"".equals(disabledPlugins)) {
        this.disabledAuthenticationPlugins = new ArrayList<>();
        List<String> pluginsToDisable = StringUtils.split(disabledPlugins, ",", true);
        Iterator<String> iter = pluginsToDisable.iterator();
        while (iter.hasNext()) {
            this.disabledAuthenticationPlugins.add(iter.next());
        }
    }

    this.authenticationPlugins = new HashMap<>();
    boolean defaultIsFound = false;

    List<AuthenticationPlugin<NativePacketPayload>> pluginsToInit = new LinkedList<>();

    // embedded plugins
    pluginsToInit.add(new MysqlNativePasswordPlugin());
    pluginsToInit.add(new MysqlClearPasswordPlugin());
    pluginsToInit.add(new Sha256PasswordPlugin());
    pluginsToInit.add(new CachingSha2PasswordPlugin());
    pluginsToInit.add(new MysqlOldPasswordPlugin());

    // plugins from authenticationPluginClasses connection parameter
    String authenticationPluginClasses = this.propertySet.getStringReadableProperty(PropertyDefinitions.PNAME_authenticationPlugins).getValue();
    if (authenticationPluginClasses != null && !"".equals(authenticationPluginClasses)) {
        List<String> pluginsToCreate = StringUtils.split(authenticationPluginClasses, ",", true);
        String className = null;
        try {
            for (int i = 0, s = pluginsToCreate.size(); i < s; i++) {
                className = pluginsToCreate.get(i);
                pluginsToInit.add((AuthenticationPlugin<NativePacketPayload>) Class.forName(className).newInstance());
            }
        } catch (Throwable t) {
            throw ExceptionFactory.createException(WrongArgumentException.class,
                    Messages.getString("AuthenticationProvider.BadAuthenticationPlugin", new Object[] { className }), t, this.exceptionInterceptor);
        }
    }

    // initialize plugin instances
    for (AuthenticationPlugin<NativePacketPayload> plugin : pluginsToInit) {
        plugin.init(this.protocol);
        if (addAuthenticationPlugin(plugin)) {
            defaultIsFound = true;
        }
    }

    // check if default plugin is listed
    if (!defaultIsFound) {
        throw ExceptionFactory.createException(WrongArgumentException.class, Messages
                .getString("AuthenticationProvider.DefaultAuthenticationPluginIsNotListed", new Object[] { this.clientDefaultAuthenticationPlugin }),
                getExceptionInterceptor());
    }

}
 
Example 13
private void generateParameterMap() throws SQLException {
    synchronized (checkClosed().getConnectionMutex()) {
        if (this.paramInfo == null) {
            return;
        }

        // if the user specified some parameters as literals, we need to provide a map from the specified placeholders to the actual parameter numbers

        int parameterCountFromMetaData = this.paramInfo.getParameterCount();

        // Ignore the first ? if this is a stored function, it doesn't count

        if (this.callingStoredFunction) {
            parameterCountFromMetaData--;
        }

        PreparedQuery<?> q = ((PreparedQuery<?>) this.query);
        if (this.paramInfo != null && q.getParameterCount() != parameterCountFromMetaData) {
            this.placeholderToParameterIndexMap = new int[q.getParameterCount()];

            int startPos = this.callingStoredFunction ? StringUtils.indexOfIgnoreCase(q.getOriginalSql(), "SELECT")
                    : StringUtils.indexOfIgnoreCase(q.getOriginalSql(), "CALL");

            if (startPos != -1) {
                int parenOpenPos = q.getOriginalSql().indexOf('(', startPos + 4);

                if (parenOpenPos != -1) {
                    int parenClosePos = StringUtils.indexOfIgnoreCase(parenOpenPos, q.getOriginalSql(), ")", "'", "'", StringUtils.SEARCH_MODE__ALL);

                    if (parenClosePos != -1) {
                        List<?> parsedParameters = StringUtils.split(q.getOriginalSql().substring(parenOpenPos + 1, parenClosePos), ",", "'\"", "'\"",
                                true);

                        int numParsedParameters = parsedParameters.size();

                        // sanity check

                        if (numParsedParameters != q.getParameterCount()) {
                            // bail?
                        }

                        int placeholderCount = 0;

                        for (int i = 0; i < numParsedParameters; i++) {
                            if (((String) parsedParameters.get(i)).equals("?")) {
                                this.placeholderToParameterIndexMap[placeholderCount++] = i;
                            }
                        }
                    }
                }
            }
        }
    }
}
 
Example 14
private void generateParameterMap() throws SQLException {
    synchronized (checkClosed().getConnectionMutex()) {
        if (this.paramInfo == null) {
            return;
        }

        // if the user specified some parameters as literals, we need to provide a map from the specified placeholders to the actual parameter numbers

        int parameterCountFromMetaData = this.paramInfo.getParameterCount();

        // Ignore the first ? if this is a stored function, it doesn't count

        if (this.callingStoredFunction) {
            parameterCountFromMetaData--;
        }

        PreparedQuery<?> q = ((PreparedQuery<?>) this.query);
        if (this.paramInfo != null && q.getParameterCount() != parameterCountFromMetaData) {
            this.placeholderToParameterIndexMap = new int[q.getParameterCount()];

            int startPos = this.callingStoredFunction ? StringUtils.indexOfIgnoreCase(q.getOriginalSql(), "SELECT")
                    : StringUtils.indexOfIgnoreCase(q.getOriginalSql(), "CALL");

            if (startPos != -1) {
                int parenOpenPos = q.getOriginalSql().indexOf('(', startPos + 4);

                if (parenOpenPos != -1) {
                    int parenClosePos = StringUtils.indexOfIgnoreCase(parenOpenPos, q.getOriginalSql(), ")", "'", "'", StringUtils.SEARCH_MODE__ALL);

                    if (parenClosePos != -1) {
                        List<?> parsedParameters = StringUtils.split(q.getOriginalSql().substring(parenOpenPos + 1, parenClosePos), ",", "'\"", "'\"",
                                true);

                        int numParsedParameters = parsedParameters.size();

                        // sanity check

                        if (numParsedParameters != q.getParameterCount()) {
                            // bail?
                        }

                        int placeholderCount = 0;

                        for (int i = 0; i < numParsedParameters; i++) {
                            if (((String) parsedParameters.get(i)).equals("?")) {
                                this.placeholderToParameterIndexMap[placeholderCount++] = i;
                            }
                        }
                    }
                }
            }
        }
    }
}
 
Example 15
/**
 * Fill the authentication plugins map.
 * First this method fill the map with instances of {@link MysqlNativePasswordPlugin}, {@link MysqlClearPasswordPlugin}, {@link Sha256PasswordPlugin}
 * and {@link MysqlOldPasswordPlugin}. Then it creates instances of plugins listed in "authenticationPlugins" connection property and adds them to the map
 * too.
 * 
 * The key for the map entry is got by {@link AuthenticationPlugin#getProtocolPluginName()} thus it is possible to replace built-in plugin with custom
 * implementation. To do it custom plugin should return value "mysql_native_password", "mysql_old_password", "mysql_clear_password" or "sha256_password"
 * from it's own getProtocolPluginName() method.
 * 
 */
@SuppressWarnings("unchecked")
private void loadAuthenticationPlugins() {

    // default plugin
    this.clientDefaultAuthenticationPlugin = this.propertySet.getStringProperty(PropertyKey.defaultAuthenticationPlugin).getValue();
    if (this.clientDefaultAuthenticationPlugin == null || "".equals(this.clientDefaultAuthenticationPlugin.trim())) {
        throw ExceptionFactory.createException(WrongArgumentException.class,
                Messages.getString("AuthenticationProvider.BadDefaultAuthenticationPlugin", new Object[] { this.clientDefaultAuthenticationPlugin }),
                getExceptionInterceptor());
    }

    // disabled plugins
    String disabledPlugins = this.propertySet.getStringProperty(PropertyKey.disabledAuthenticationPlugins).getValue();
    if (disabledPlugins != null && !"".equals(disabledPlugins)) {
        this.disabledAuthenticationPlugins = new ArrayList<>();
        List<String> pluginsToDisable = StringUtils.split(disabledPlugins, ",", true);
        Iterator<String> iter = pluginsToDisable.iterator();
        while (iter.hasNext()) {
            this.disabledAuthenticationPlugins.add(iter.next());
        }
    }

    this.authenticationPlugins = new HashMap<>();
    boolean defaultIsFound = false;

    List<AuthenticationPlugin<NativePacketPayload>> pluginsToInit = new LinkedList<>();

    // embedded plugins
    pluginsToInit.add(new MysqlNativePasswordPlugin());
    pluginsToInit.add(new MysqlClearPasswordPlugin());
    pluginsToInit.add(new Sha256PasswordPlugin());
    pluginsToInit.add(new CachingSha2PasswordPlugin());
    pluginsToInit.add(new MysqlOldPasswordPlugin());

    // plugins from authenticationPluginClasses connection parameter
    String authenticationPluginClasses = this.propertySet.getStringProperty(PropertyKey.authenticationPlugins).getValue();
    if (authenticationPluginClasses != null && !"".equals(authenticationPluginClasses)) {
        List<String> pluginsToCreate = StringUtils.split(authenticationPluginClasses, ",", true);
        String className = null;
        try {
            for (int i = 0, s = pluginsToCreate.size(); i < s; i++) {
                className = pluginsToCreate.get(i);
                pluginsToInit.add((AuthenticationPlugin<NativePacketPayload>) Class.forName(className).newInstance());
            }
        } catch (Throwable t) {
            throw ExceptionFactory.createException(WrongArgumentException.class,
                    Messages.getString("AuthenticationProvider.BadAuthenticationPlugin", new Object[] { className }), t, this.exceptionInterceptor);
        }
    }

    // initialize plugin instances
    for (AuthenticationPlugin<NativePacketPayload> plugin : pluginsToInit) {
        plugin.init(this.protocol);
        if (addAuthenticationPlugin(plugin)) {
            defaultIsFound = true;
        }
    }

    // check if default plugin is listed
    if (!defaultIsFound) {
        throw ExceptionFactory.createException(WrongArgumentException.class, Messages
                .getString("AuthenticationProvider.DefaultAuthenticationPluginIsNotListed", new Object[] { this.clientDefaultAuthenticationPlugin }),
                getExceptionInterceptor());
    }

}
 
Example 16
/**
 * Tests the implementation of Information Schema for column privileges.
 */
public void testGetColumnPrivilegesUsingInfoSchema() throws Exception {

    if (!runTestIfSysPropDefined(PropertyDefinitions.SYSP_testsuite_cantGrant)) {
        Properties props = new Properties();

        props.setProperty(PropertyKey.useInformationSchema.getKeyName(), "true");
        props.setProperty(PropertyKey.nullCatalogMeansCurrent.getKeyName(), "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 CURRENT_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 " + PropertyDefinitions.SYSP_testsuite_cantGrant);
            }
            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 \""
                        + PropertyDefinitions.SYSP_testsuite_cantGrant + "\".");
            }

            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 17
/**
 * 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));
}