public void testSplit() throws Exception { assertEquals(NULL_STR, StringUtils.split(NULL_STR)); String[] splits = StringUtils.split(EMPTY_STR); assertEquals(0, splits.length); splits = StringUtils.split(",,"); assertEquals(0, splits.length); splits = StringUtils.split(STR_WO_SPECIAL_CHARS); assertEquals(1, splits.length); assertEquals(STR_WO_SPECIAL_CHARS, splits[0]); splits = StringUtils.split(STR_WITH_COMMA); assertEquals(2, splits.length); assertEquals("A", splits[0]); assertEquals("B", splits[1]); splits = StringUtils.split(ESCAPED_STR_WITH_COMMA); assertEquals(1, splits.length); assertEquals(ESCAPED_STR_WITH_COMMA, splits[0]); splits = StringUtils.split(STR_WITH_ESCAPE); assertEquals(1, splits.length); assertEquals(STR_WITH_ESCAPE, splits[0]); splits = StringUtils.split(STR_WITH_BOTH2); assertEquals(3, splits.length); assertEquals(EMPTY_STR, splits[0]); assertEquals("A\\,", splits[1]); assertEquals("B\\\\", splits[2]); splits = StringUtils.split(ESCAPED_STR_WITH_BOTH2); assertEquals(1, splits.length); assertEquals(ESCAPED_STR_WITH_BOTH2, splits[0]); }
/** * 返回一个随机区段,例如:100:1:32:200:16:30,返回0的概率为100/(100+1+32+200+16+30) * * @param conf 区段配置字符串 * @return 随机区段下标 */ public static int randomSegment(String conf) { String[] tmp = StringUtils.split(conf, ":"); int[] probability = new int[tmp.length]; for (int i = 0; i < probability.length; i++) probability[i] = Integer.parseInt(tmp[i].trim()); return randomSegment(probability); }
/** * Gets the information about an element's handlers in the current router configuration. * * @param el The element name. * @return Vector of HandlerInfo structures. * @exception NoSuchElementException If there is no such element in the current configuration. * @exception HandlerErrorException If the handler returned an error. * @exception PermissionDeniedException If the router would not let us access the handler. * @exception IOException If there was some other error accessing the handler (e.g., there was a * stream or socket error, the ControlSocket returned an unknwon unknown error code, or the * response could otherwise not be understood). * @see #HandlerInfo * @see #getConfigElementNames * @see #getRouterConfig * @see #getRouterFlatConfig */ public Vector getElementHandlers(String elementName) throws ClickException, IOException { Vector v = new Vector(); Vector vh; try { char[] buf = read(elementName, "handlers"); vh = StringUtils.split(buf, 0, '\n'); } catch (ClickException.NoSuchHandlerException e) { return v; } for (int i = 0; i < vh.size(); i++) { String s = (String) vh.elementAt(i); int j; for (j = 0; j < s.length() && !Character.isWhitespace(s.charAt(j)); j++) ; // find record split if (j == s.length()) throw new ClickException.HandlerFormatException(elementName + ".handlers"); HandlerInfo hi = new HandlerInfo(elementName, s.substring(0, j).trim()); while (j < s.length() && Character.isWhitespace(s.charAt(j))) j++; for (; j < s.length(); j++) { char c = s.charAt(j); if (Character.toLowerCase(c) == 'r') hi.canRead = true; else if (Character.toLowerCase(c) == 'w') hi.canWrite = true; else if (Character.isWhitespace(c)) break; } v.addElement(hi); } return v; }
private java.sql.Connection connectLoadBalanced(String url, Properties info) throws SQLException { Properties parsedProps = parseURL(url, info); if (parsedProps == null) { return null; } String hostValues = parsedProps.getProperty(HOST_PROPERTY_KEY); List hostList = null; if (hostValues != null) { hostList = StringUtils.split(hostValues, ",", true); } if (hostList == null) { hostList = new ArrayList(); hostList.add("localhost:3306"); } LoadBalancingConnectionProxy proxyBal = new LoadBalancingConnectionProxy(hostList, parsedProps); return (java.sql.Connection) java.lang.reflect.Proxy.newProxyInstance( this.getClass().getClassLoader(), new Class[] {java.sql.Connection.class}, proxyBal); }
/** 调用Getter方法. 支持多级,如:对象名.对象名.方法 */ public static Object invokeGetter(Object obj, String propertyName) { Object object = obj; for (String name : StringUtils.split(propertyName, ".")) { String getterMethodName = GETTER_PREFIX + StringUtils.capitalize(name); object = invokeMethod(object, getterMethodName, new Class[] {}, new Object[] {}); } return object; }
/** * Expands hosts of the form address=(protocol=tcp)(host=localhost)(port=3306) into a * java.util.Properties. Special characters (in this case () and =) must be quoted. Any values * that are string-quoted ("" or '') are also stripped of quotes. */ public static Properties expandHostKeyValues(String host) { Properties hostProps = new Properties(); if (isHostPropertiesList(host)) { host = host.substring("address=".length() + 1); List<String> hostPropsList = StringUtils.split(host, ")", "'\"", "'\"", true); for (String propDef : hostPropsList) { if (propDef.startsWith("(")) { propDef = propDef.substring(1); } List<String> kvp = StringUtils.split(propDef, "=", "'\"", "'\"", true); String key = kvp.get(0); String value = kvp.size() > 1 ? kvp.get(1) : null; if (value != null && ((value.startsWith("\"") && value.endsWith("\"")) || (value.startsWith("'") && value.endsWith("'")))) { value = value.substring(1, value.length() - 1); } if (value != null) { if (HOST_PROPERTY_KEY.equalsIgnoreCase(key) || DBNAME_PROPERTY_KEY.equalsIgnoreCase(key) || PORT_PROPERTY_KEY.equalsIgnoreCase(key) || PROTOCOL_PROPERTY_KEY.equalsIgnoreCase(key) || PATH_PROPERTY_KEY.equalsIgnoreCase(key)) { key = key.toUpperCase(Locale.ENGLISH); } else if (USER_PROPERTY_KEY.equalsIgnoreCase(key) || PASSWORD_PROPERTY_KEY.equalsIgnoreCase(key)) { key = key.toLowerCase(Locale.ENGLISH); } hostProps.setProperty(key, value); } } } return hostProps; }
/** * 修复路径,将 \\ 或 / 等替换为 File.separator * * @param path * @return */ public static String path(String path) { String p = StringUtils.replace(path, "\\", "/"); p = StringUtils.join(StringUtils.split(p, "/"), "/"); if (!StringUtils.startsWithAny(p, "/") && StringUtils.startsWithAny(path, "\\", "/")) { p += "/"; } if (!StringUtils.endsWithAny(p, "/") && StringUtils.endsWithAny(path, "\\", "/")) { p = p + "/"; } return p; }
/** Test of testSplit method, of class StringUtils. */ public void testSplit() throws AssertionFailedException { System.out.println("split"); String original_1 = "1,2,3"; String separator_1 = ","; Vector expResult_1 = new Vector(); expResult_1.addElement("1"); expResult_1.addElement("2"); expResult_1.addElement("3"); Vector result_1 = StringUtils.split(original_1, separator_1); assertEquals(expResult_1, result_1); }
@Test public void testSplit() { assertTrue(StringUtils.split(null, '/').isEmpty()); assertThat(StringUtils.split("a\tb\nc", null), is(Arrays.asList("a", "b", "c"))); assertThat(StringUtils.split("a\tb\n\tc", null), is(Arrays.asList("a", "b", "c"))); assertThat(StringUtils.split("a.b.c", '.'), is(Arrays.asList("a", "b", "c"))); assertThat(StringUtils.split("a..b.c", '.'), is(Arrays.asList("a", "b", "c"))); assertThat(StringUtils.split("a:b:c", '.'), is(Arrays.asList("a:b:c"))); assertThat(StringUtils.split("a b c", ' '), is(Arrays.asList("a", "b", "c"))); }
/** 调用Setter方法, 仅匹配方法名。 支持多级,如:对象名.对象名.方法 */ public static void invokeSetter(Object obj, String propertyName, Object value) { Object object = obj; String[] names = StringUtils.split(propertyName, "."); for (int i = 0; i < names.length; i++) { if (i < names.length - 1) { String getterMethodName = GETTER_PREFIX + StringUtils.capitalize(names[i]); object = invokeMethod(object, getterMethodName, new Class[] {}, new Object[] {}); } else { String setterMethodName = SETTER_PREFIX + StringUtils.capitalize(names[i]); invokeMethodByName(object, setterMethodName, new Object[] {value}); } } }
/** * Gets the names of elements in the current router configuration. * * @return Vector of Strings of the element names. * @exception NoSuchHandlerException If there is no element list read handler. * @exception HandlerErrorException If the handler returned an error. * @exception PermissionDeniedException If the router would not let us access the handler. * @exception IOException If there was some other error accessing the handler (e.g., there was a * stream or socket error, the ControlSocket returned an unknwon unknown error code, or the * response could otherwise not be understood). * @see #getElementHandlers * @see #getRouterConfig * @see #getRouterFlatConfig */ public Vector getConfigElementNames() throws ClickException, IOException { char[] buf = read(null, "list"); // how many elements? int i; for (i = 0; i < buf.length && buf[i] != '\n'; i++) ; // do it int numElements = 0; try { numElements = Integer.parseInt(new String(buf, 0, i)); } catch (NumberFormatException ex) { throw new ClickException.HandlerFormatException("element list"); } Vector v = StringUtils.split(buf, i + 1, '\n'); if (v.size() != numElements) throw new ClickException.HandlerFormatException("element list"); return v; }
/* */ public static ClassLoader createClassLoader(String classpath, ClassLoader parent) /* */ throws SecurityException /* */ { /* 289 */ String[] names = StringUtils.split(classpath, System.getProperty("path.separator").charAt(0)); /* */ /* 291 */ URL[] urls = new URL[names.length]; /* */ try { /* 293 */ for (int i = 0; i < urls.length; i++) { /* 294 */ urls[i] = new File(names[i]).toURL(); /* */ } /* */ } /* */ catch (MalformedURLException e) /* */ { /* 299 */ throw new IllegalArgumentException("Unable to parse classpath: " + classpath); /* */ } /* */ /* 303 */ return new URLClassLoader(urls, parent); /* */ }
public void init(Options options) { this.options = options; timexPatterns = new TimeExpressionPatterns(options); // TODO: does not allow for multiple loggers if (options.verbose) { logger.setLevel(Level.FINE); } else { logger.setLevel(Level.SEVERE); } NumberNormalizer.setVerbose(options.verbose); if (options.grammarFilename != null) { List<String> filenames = StringUtils.split(options.grammarFilename, "\\s*[,;]\\s*"); this.expressionExtractor = CoreMapExpressionExtractor.createExtractorFromFiles(timexPatterns.env, filenames); // this.expressionExtractor = // CoreMapExpressionExtractor.createExtractorFromFile(timexPatterns.env, // options.grammarFilename); } else { this.expressionExtractor = new CoreMapExpressionExtractor(); this.expressionExtractor.setExtractRules( timexPatterns.getTimeExtractionRule(), timexPatterns.getCompositeTimeExtractionRule()); } this.expressionExtractor.setLogger(logger); }
public Properties parseURL(String url, Properties defaults) throws java.sql.SQLException { Properties urlProps = (defaults != null) ? new Properties(defaults) : new Properties(); if (url == null) { return null; } if (!StringUtils.startsWithIgnoreCase(url, URL_PREFIX) && !StringUtils.startsWithIgnoreCase(url, MXJ_URL_PREFIX) && !StringUtils.startsWithIgnoreCase(url, LOADBALANCE_URL_PREFIX) && !StringUtils.startsWithIgnoreCase(url, REPLICATION_URL_PREFIX)) { // $NON-NLS-1$ return null; } int beginningOfSlashes = url.indexOf("//"); if (StringUtils.startsWithIgnoreCase(url, MXJ_URL_PREFIX)) { urlProps.setProperty( "socketFactory", "com.mysql.management.driverlaunched.ServerLauncherSocketFactory"); } /* * Parse parameters after the ? in the URL and remove them from the * original URL. */ int index = url.indexOf("?"); // $NON-NLS-1$ if (index != -1) { String paramString = url.substring(index + 1, url.length()); url = url.substring(0, index); StringTokenizer queryParams = new StringTokenizer(paramString, "&"); // $NON-NLS-1$ while (queryParams.hasMoreTokens()) { String parameterValuePair = queryParams.nextToken(); int indexOfEquals = StringUtils.indexOfIgnoreCase(0, parameterValuePair, "="); String parameter = null; String value = null; if (indexOfEquals != -1) { parameter = parameterValuePair.substring(0, indexOfEquals); if (indexOfEquals + 1 < parameterValuePair.length()) { value = parameterValuePair.substring(indexOfEquals + 1); } } if ((value != null && value.length() > 0) && (parameter != null && parameter.length() > 0)) { try { urlProps.put(parameter, URLDecoder.decode(value, "UTF-8")); } catch (UnsupportedEncodingException badEncoding) { // punt urlProps.put(parameter, URLDecoder.decode(value)); } catch (NoSuchMethodError nsme) { // punt again urlProps.put(parameter, URLDecoder.decode(value)); } } } } url = url.substring(beginningOfSlashes + 2); String hostStuff = null; int slashIndex = StringUtils.indexOfIgnoreCaseRespectMarker( 0, url, "/", ALLOWED_QUOTES, ALLOWED_QUOTES, true); // $NON-NLS-1$ if (slashIndex != -1) { hostStuff = url.substring(0, slashIndex); if ((slashIndex + 1) < url.length()) { urlProps.put( DBNAME_PROPERTY_KEY, //$NON-NLS-1$ url.substring((slashIndex + 1), url.length())); } } else { hostStuff = url; } int numHosts = 0; if ((hostStuff != null) && (hostStuff.trim().length() > 0)) { List<String> hosts = StringUtils.split(hostStuff, ",", ALLOWED_QUOTES, ALLOWED_QUOTES, false); for (String hostAndPort : hosts) { numHosts++; String[] hostPortPair = parseHostPortPair(hostAndPort); if (hostPortPair[HOST_NAME_INDEX] != null && hostPortPair[HOST_NAME_INDEX].trim().length() > 0) { urlProps.setProperty(HOST_PROPERTY_KEY + "." + numHosts, hostPortPair[HOST_NAME_INDEX]); } else { urlProps.setProperty(HOST_PROPERTY_KEY + "." + numHosts, "localhost"); } if (hostPortPair[PORT_NUMBER_INDEX] != null) { urlProps.setProperty(PORT_PROPERTY_KEY + "." + numHosts, hostPortPair[PORT_NUMBER_INDEX]); } else { urlProps.setProperty(PORT_PROPERTY_KEY + "." + numHosts, "3306"); } } } else { numHosts = 1; urlProps.setProperty(HOST_PROPERTY_KEY + ".1", "localhost"); urlProps.setProperty(PORT_PROPERTY_KEY + ".1", "3306"); } urlProps.setProperty(NUM_HOSTS_PROPERTY_KEY, String.valueOf(numHosts)); urlProps.setProperty(HOST_PROPERTY_KEY, urlProps.getProperty(HOST_PROPERTY_KEY + ".1")); urlProps.setProperty(PORT_PROPERTY_KEY, urlProps.getProperty(PORT_PROPERTY_KEY + ".1")); String propertiesTransformClassName = urlProps.getProperty(PROPERTIES_TRANSFORM_KEY); if (propertiesTransformClassName != null) { try { ConnectionPropertiesTransform propTransformer = (ConnectionPropertiesTransform) Class.forName(propertiesTransformClassName).newInstance(); urlProps = propTransformer.transformProperties(urlProps); } catch (InstantiationException e) { throw SQLError.createSQLException( "Unable to create properties transform instance '" + propertiesTransformClassName + "' due to underlying exception: " + e.toString(), SQLError.SQL_STATE_INVALID_CONNECTION_ATTRIBUTE, null); } catch (IllegalAccessException e) { throw SQLError.createSQLException( "Unable to create properties transform instance '" + propertiesTransformClassName + "' due to underlying exception: " + e.toString(), SQLError.SQL_STATE_INVALID_CONNECTION_ATTRIBUTE, null); } catch (ClassNotFoundException e) { throw SQLError.createSQLException( "Unable to create properties transform instance '" + propertiesTransformClassName + "' due to underlying exception: " + e.toString(), SQLError.SQL_STATE_INVALID_CONNECTION_ATTRIBUTE, null); } } if (Util.isColdFusion() && urlProps.getProperty("autoConfigureForColdFusion", "true").equalsIgnoreCase("true")) { String configs = urlProps.getProperty(USE_CONFIG_PROPERTY_KEY); StringBuffer newConfigs = new StringBuffer(); if (configs != null) { newConfigs.append(configs); newConfigs.append(","); } newConfigs.append("coldFusion"); urlProps.setProperty(USE_CONFIG_PROPERTY_KEY, newConfigs.toString()); } // If we use a config, it actually should get overridden by anything in // the URL or passed-in properties String configNames = null; if (defaults != null) { configNames = defaults.getProperty(USE_CONFIG_PROPERTY_KEY); } if (configNames == null) { configNames = urlProps.getProperty(USE_CONFIG_PROPERTY_KEY); } if (configNames != null) { List splitNames = StringUtils.split(configNames, ",", true); Properties configProps = new Properties(); Iterator namesIter = splitNames.iterator(); while (namesIter.hasNext()) { String configName = (String) namesIter.next(); try { InputStream configAsStream = getClass().getResourceAsStream("configs/" + configName + ".properties"); if (configAsStream == null) { throw SQLError.createSQLException( "Can't find configuration template named '" + configName + "'", SQLError.SQL_STATE_INVALID_CONNECTION_ATTRIBUTE, null); } configProps.load(configAsStream); } catch (IOException ioEx) { SQLException sqlEx = SQLError.createSQLException( "Unable to load configuration template '" + configName + "' due to underlying IOException: " + ioEx, SQLError.SQL_STATE_INVALID_CONNECTION_ATTRIBUTE, null); sqlEx.initCause(ioEx); throw sqlEx; } } Iterator propsIter = urlProps.keySet().iterator(); while (propsIter.hasNext()) { String key = propsIter.next().toString(); String property = urlProps.getProperty(key); configProps.setProperty(key, property); } urlProps = configProps; } // Properties passed in should override ones in URL if (defaults != null) { Iterator propsIter = defaults.keySet().iterator(); while (propsIter.hasNext()) { String key = propsIter.next().toString(); if (!key.equals(NUM_HOSTS_PROPERTY_KEY)) { String property = defaults.getProperty(key); urlProps.setProperty(key, property); } } } return urlProps; }
/** * Gets the names of the current router configuration requirements. * * @return Vector of Strings of the package names. * @exception NoSuchHandlerException If there is no element list read handler. * @exception HandlerErrorException If the handler returned an error. * @exception PermissionDeniedException If the router would not let us access the handler. * @exception IOException If there was some other error accessing the handler (e.g., there was a * stream or socket error, the ControlSocket returned an unknwon unknown error code, or the * response could otherwise not be understood). * @see #getRouterConfig * @see #getRouterFlatConfig */ public Vector getConfigRequirements() throws ClickException, IOException { char[] buf = read(null, "requirements"); return StringUtils.split(buf, 0, '\n'); }
/** * Gets the names of packages that the router knows about. * * @return Vector of Strings of the package names. * @exception NoSuchHandlerException If there is no element list read handler. * @exception HandlerErrorException If the handler returned an error. * @exception PermissionDeniedException If the router would not let us access the handler. * @exception IOException If there was some other error accessing the handler (e.g., there was a * stream or socket error, the ControlSocket returned an unknwon unknown error code, or the * response could otherwise not be understood). */ public Vector getRouterPackages() throws ClickException, IOException { char[] buf = read(null, "packages"); return StringUtils.split(buf, 0, '\n'); }