下面列出了org.apache.commons.lang3.StringUtils#split ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/**
* 调用Setter方法, 仅匹配方法名。
* 支持多级,如:对象名.对象名.方法
*/
public static <E> void invokeSetter(Object obj, String propertyName, E 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 });
}
}
}
/**
* Extracts the metric value from the given parts.
*
* @param parts Parts.
* @return Metric value.
* @throws FormatParseException If something went wrong while extracting.
*/
private double getMetricValue(String[] parts) throws FormatParseException {
String value = parts[1];
String[] valueParts = StringUtils.split(value, "=", 2);
if (valueParts.length < 2) {
throw new FormatParseException("Expected at least 2 parts, found " + valueParts.length + " in '" + value + "'");
}
if (!valueParts[0].equals("value")) {
throw new FormatParseException("Expected first part to be 'value', but was '" + valueParts[0] + "' in '" + value + "'");
}
try {
return Double.parseDouble(valueParts[1]);
} catch (NumberFormatException e) {
throw new FormatParseException("Can't convert '" + value + "' to double", e);
}
}
/**
* searchParams中key的格式为OPERATOR_FIELDNAME
*/
public static Map<String, SearchFilter> parse(Map<String, Object> searchParams) {
Map<String, SearchFilter> filters = new HashMap<String, SearchFilter>();
for (Entry<String, Object> entry : searchParams.entrySet()) {
// 过滤掉空值
String key = entry.getKey();
Object value = entry.getValue();
if (StringUtils.isBlank((String) value)) {
continue;
}
// 拆分operator与filedAttribute
String[] names = StringUtils.split(key, "_");
if (names.length != 2) { throw new IllegalArgumentException(key + " is not a valid search filter name"); }
String filedName = names[1];
Operator operator = Operator.valueOf(names[0]);
// 创建searchFilter
SearchFilter filter = new SearchFilter(filedName, operator, parseValue(filedName, value));
filters.put(key, filter);
}
return filters;
}
/**
* If you need to a request parameter that may contain +++
* or other special characters that fails to fetch properly using
* request.getParameter() you can use this method.
*
* @param request to fetch from
* @param name of parameter to fetch
* @return String value from request, null if not found.
*/
public static String getParameterWithSpecialCharacters(HttpServletRequest request,
String name) {
String queryString = request.getQueryString();
if (StringUtils.isEmpty(queryString)) {
return null;
}
String[] pairs = StringUtils.split(queryString, "&");
for (int i = 0; i < pairs.length; i++) {
String[] param = StringUtils.split(pairs[i], "=");
String iname = param[0];
if (StringUtils.equals(name, iname) && param.length > 1) {
return param[1];
}
}
return null;
}
private void buildTagWhitelist() {
if (reportConfig != null && reportConfig.getConfig() != null) {
String value = reportConfig.getConfig().get(TAG_WHITELIST);
if (value == null) {
tagWhitelist = null;
return;
}
tagWhitelist = new HashMap<String, String>();
String[] kvs = StringUtils.split(value, ",");
if (kvs != null) {
for (String kv : kvs) {
if (kv != null && kv.indexOf("=") > 0) {
String[] kvArray = StringUtils.split(kv, "=");
if (StringUtils.isNotEmpty(kvArray[0])
&& StringUtils.isNotEmpty(kvArray[1]))
tagWhitelist.put(kvArray[0].trim(), kvArray[1].trim());
}
}
}
}
}
protected void run(String queryFolder, String[] exclusiveQuerys, boolean needSort) throws Exception {
logger.info("---------- test folder: " + queryFolder);
Set<String> exclusiveSet = buildExclusiveSet(exclusiveQuerys);
List<File> sqlFiles = getFilesFromFolder(new File(queryFolder), ".sql");
for (File sqlFile : sqlFiles) {
String queryName = StringUtils.split(sqlFile.getName(), '.')[0];
if (exclusiveSet.contains(queryName)) {
continue;
}
String sql = getTextFromFile(sqlFile);
// execute Kylin
logger.info("Query Result from Kylin - " + queryName + " (" + queryFolder + ")");
IDatabaseConnection kylinConn = new DatabaseConnection(cubeConnection);
ITable kylinTable = executeQuery(kylinConn, queryName, sql, needSort);
printResult(kylinTable);
}
}
public static String changeJoinType(String sql, String targetType) {
if (targetType.equalsIgnoreCase("default")) {
return sql;
}
String specialStr = "changeJoinType_DELIMITERS";
sql = sql.replaceAll(System.getProperty("line.separator"), " " + specialStr + " ");
String[] tokens = StringUtils.split(sql, null);// split white spaces
for (int i = 0; i < tokens.length - 1; ++i) {
if ((tokens[i].equalsIgnoreCase("inner") || tokens[i].equalsIgnoreCase("left"))
&& tokens[i + 1].equalsIgnoreCase("join")) {
tokens[i] = targetType.toLowerCase(Locale.ROOT);
}
}
String ret = StringUtils.join(tokens, " ");
ret = ret.replaceAll(specialStr, System.getProperty("line.separator"));
logger.info("The actual sql executed is: " + ret);
return ret;
}
/**
* Search component on tree
*
* @param path how many containers is between
* @param componentName component name
* @param elementNumber which component (default 0) it there is more then one
* @param currentScope
* @return
*/
public static WebElement getComponentWebElement(String path, String componentName,
int elementNumber,
WebElement currentScope) {
String[] containers = StringUtils.split(path, "/");
WebElement component = currentScope;
for (String container : containers) {
component = setComponent(component, container);
}
List<WebElement> elements = component.findElement(By.cssSelector(".coral3-Tree-subTree"))
.findElements(
By.xpath(String.format(COMPONENT_ITEM_XPATH_FORMAT, componentName, componentName)));
if (!elements.isEmpty()) {
component = elements.get(elementNumber);
}
return component;
}
private void startGossipService() {
String consenterAddress = NodeConfigFactory.getNodeConfig().getNode().getGossip().getConsenterAddress();
String[] split = StringUtils.split(consenterAddress, ":");
String host = split[0];
Integer port = Integer.parseInt(split[1]);
waitConnectable(host, port);
ManagedChannel managedChannel =
NettyChannelBuilder.forAddress(host, port).maxInboundMessageSize(CommConstant.MAX_GRPC_MESSAGE_SIZE)
.usePlaintext().build();
GossipClientStream gossipClientStream = new GossipClientStream(managedChannel);
GossipClientStream.setGossipClientStream(gossipClientStream);
try {
List<String> ledgerIDs = LedgerManager.getLedgerIDs();
for (String ledgerID : ledgerIDs) {
startPullFromConsenter(gossipClientStream, ledgerID);
}
} catch (LedgerException e) {
log.error(e.getMessage(), e);
}
}
public static String removeJsComments(final String jsSrc) {
final String carriage = "\n";
final String comment = "//";
if (jsSrc == null
|| StringUtils.indexOf(jsSrc, comment) == -1) {
return jsSrc;
}
// i.e single line
if (StringUtils.indexOf(jsSrc, carriage) == -1) {
return StringUtils.substring(jsSrc, 0, StringUtils.indexOf(jsSrc, comment)).trim();
}
final String[] lines = StringUtils.split(jsSrc, carriage);
return Stream.of(lines)
.filter(l ->
!l.trim().startsWith(comment))
.map(l -> {
final int commentInLine = StringUtils.indexOf(l, comment);
return (commentInLine > -1)
? StringUtils.substring(l, 0, commentInLine)
: l;
})
.collect(Collectors.joining(carriage))
.trim();
}
@Override
public void setDocumentVersion(ImmoXmlVersion version) {
try {
Document doc = this.getDocument();
String currentVersion = StringUtils.trimToEmpty(XmlUtils
.newXPath("/io:immoxml/io:uebertragung/@version", doc)
.stringValueOf(doc));
String[] ver = StringUtils.split(currentVersion, "/", 2);
Element node = (Element) XmlUtils
.newXPath("/io:immoxml/io:uebertragung", doc)
.selectSingleNode(doc);
if (node == null) {
Element parentNode = (Element) XmlUtils
.newXPath("/io:immoxml", doc)
.selectSingleNode(doc);
if (parentNode == null) {
LOGGER.warn("Can't find an <immoxml> element in the document!");
return;
}
node = doc.createElement("uebertragung");
parentNode.insertBefore(node, parentNode.getFirstChild());
}
String newVersion = version.toReadableVersion();
if (ver.length > 1) newVersion += "/" + ver[1];
node.setAttribute("version", newVersion);
} catch (JaxenException ex) {
LOGGER.error("Can't evaluate XPath expression!");
LOGGER.error("> " + ex.getLocalizedMessage(), ex);
}
}
private void addRegistyAddress(RpcServiceConfig rpcSerivceConfig) {
String registryAddress = grpcProperties.getRegistryAddress();
if (StringUtils.isBlank(registryAddress)) {
throw new java.lang.IllegalArgumentException("registry address can not be null or empty");
} else {
String[] registryHostAndPort = StringUtils.split(registryAddress, ":");
if (registryHostAndPort.length < 2) {
throw new java.lang.IllegalArgumentException(
"the pattern of registry address is host:port");
}
rpcSerivceConfig.setRegistryAddress(registryHostAndPort[0]);
rpcSerivceConfig.setRegistryPort(Integer.valueOf(registryHostAndPort[1]));
}
}
private static ArrayList<ChrContact> readRawIntraContactInformation(String fileToReads) throws IOException {
ArrayList<ChrContact> chrContactInfo = new ArrayList<ChrContact>();
BufferedReader input = new BufferedReader(new InputStreamReader(new FileInputStream(fileToReads), "UTF-8"));
String row;
while ((row = input.readLine()) != null) {
String[] parts = StringUtils.split(row, '\t');
int posChrX = Integer.parseInt(parts[0]);
int posChrY = Integer.parseInt(parts[1]);
int posChr1;
int posChr2;
if(posChrX<posChrY){
posChr1 = posChrX;
posChr2 = posChrY;
} else {
posChr1 = posChrY;
posChr2 = posChrX;
}
double contact = Double.parseDouble(parts[2]);
chrContactInfo.add(new ChrContact(posChr1, posChr2, contact));
}
input.close();
return chrContactInfo;
}
/**
* xlsx xml contains information for the dimension in a format as "B1:AG142" A1:D5 so the column number is given
* by the letters from the second part. we don't mind about the start we always start from A1 as data-prep doesn't
* want to ignore empty columns
*
* @param dimension
* @return 0 if <code>null</code>
*/
public static int getColumnsNumberFromDimension(String dimension) {
if (StringUtils.isEmpty(dimension)) {
return 0;
}
String[] parts = StringUtils.split(dimension, ':');
if (parts.length < 2) {
return 0;
}
String secondPart = parts[1];
return getColumnNumberFromCellRef(secondPart) + 1;
}
/**
* 初始化函数
* @param title 表格标题,传“空值”,表示无标题
* @param headerList 表头列表
*/
private void initialize(String title, List<String> headerList) {
this.wb = new SXSSFWorkbook(500);
this.sheet = wb.createSheet("Export");
this.styles = createStyles(wb);
// Create title
if (StringUtils.isNotBlank(title)){
Row titleRow = sheet.createRow(rownum++);
titleRow.setHeightInPoints(30);
Cell titleCell = titleRow.createCell(0);
titleCell.setCellStyle(styles.get("title"));
titleCell.setCellValue(title);
sheet.addMergedRegion(new CellRangeAddress(titleRow.getRowNum(),
titleRow.getRowNum(), titleRow.getRowNum(), headerList.size()-1));
}
// Create header
if (headerList == null){
throw new RuntimeException("headerList not null!");
}
Row headerRow = sheet.createRow(rownum++);
headerRow.setHeightInPoints(16);
for (int i = 0; i < headerList.size(); i++) {
Cell cell = headerRow.createCell(i);
cell.setCellStyle(styles.get("header"));
String[] ss = StringUtils.split(headerList.get(i), "**", 2);
if (ss.length==2){
cell.setCellValue(ss[0]);
Comment comment = this.sheet.createDrawingPatriarch().createCellComment(
new XSSFClientAnchor(0, 0, 0, 0, (short) 3, 3, (short) 5, 6));
comment.setString(new XSSFRichTextString(ss[1]));
cell.setCellComment(comment);
}else{
cell.setCellValue(headerList.get(i));
}
sheet.autoSizeColumn(i);
}
for (int i = 0; i < headerList.size(); i++) {
int colWidth = sheet.getColumnWidth(i)*2;
sheet.setColumnWidth(i, colWidth < 3000 ? 3000 : colWidth);
}
log.debug("Initialize success.");
}
private void trimAndAdd(String matcherString) {
for (String part : StringUtils.split(matcherString, SEPARATOR)) {
this.matchers.add(part.trim());
}
}
/**
* Constructs the {@code HtmlTable} used to export the data.
* <p />
* It uses the parameters of the request to check if the column is
* exportable or not, these parameters are named:
* <ul>
* <li>{@code [export_type_extension]ExportColumns}, where
* <emp>[export_type_extension]</emp> is the extension of the format to
* export, for example: {@code csvExportColumns}</li>
* <li>{@code allExportColumns}</li>
* </ul>
* <p />
* Also uses the parameter {@code columnsTitle} to indicate the title of
* each column, this parameter has as value a {@code String} with the format
* of a Map as follows:
*
* <pre>
* {property1||value1, property2||value2, ... , propertyN||valueN}
* </pre>
*
* @param data the data to make the {@code HtmlTable}.
* @param criterias the {@code DatatablesCriterias}.
* @param exportConf the {@code ExportConf}.
* @param request the {@code HttpServletRequest}.
* @return the {@code HtmlTable} used to export the data.
*/
public static HtmlTable makeHtmlTable(List<Map<String, String>> data,
DatatablesCriterias criterias, ExportConf exportConf,
HttpServletRequest request) {
ColumnStep tableBuilder = new HtmlTableBuilder<Map<String, String>>()
.newBuilder("tableId", data, request);
// Obtain exportable columns
String exportTypeExtension = StringUtils.lowerCase(exportConf.getType()
.getExtension());
String thisFormatExportColumnsStr = request
.getParameter(exportTypeExtension.concat("ExportColumns"));
if (StringUtils.isEmpty(thisFormatExportColumnsStr)) {
thisFormatExportColumnsStr = "";
}
String allFormatExportColumnsStr = request
.getParameter("allExportColumns");
if (StringUtils.isEmpty(allFormatExportColumnsStr)) {
allFormatExportColumnsStr = "";
}
List<String> thisFormatExporColumns = Arrays.asList(StringUtils.split(
thisFormatExportColumnsStr, ","));
List<String> allFormatExportColumns = Arrays.asList(StringUtils.split(
allFormatExportColumnsStr, ","));
BeforeEndStep columns = null;
if (!allFormatExportColumns.isEmpty()
|| !thisFormatExporColumns.isEmpty()) {
// Obtain the column titles
Map<String, String> columnsTitleMap = new HashMap<String, String>();
String columnsTitleStr = request.getParameter("columnsTitle");
columnsTitleStr = StringUtils.substring(columnsTitleStr, 1,
(columnsTitleStr.length() - 1));
List<String> columnsTitleList = Arrays.asList(StringUtils.split(
columnsTitleStr, ","));
for (String columnsTitle : columnsTitleList) {
String[] columsTitleArray = StringUtils.split(columnsTitle,
"||");
if (columsTitleArray.length == 2) {
columnsTitleMap.put(columsTitleArray[0].trim(),
columsTitleArray[1].trim());
}
}
List<ColumnDef> columnDefs = criterias.getColumnDefs();
for (ColumnDef columnDef : columnDefs) {
String columnProperty = columnDef.getName();
if (allFormatExportColumns.contains(columnProperty)
|| thisFormatExporColumns.contains(columnProperty)) {
String columnTitle = columnsTitleMap.get(columnProperty);
if (StringUtils.isBlank(columnTitle)) {
columnTitle = columnProperty;
}
columnTitle = StringUtils.replace(columnTitle, "~~", ",");
columns = tableBuilder.column()
.fillWithProperty(columnProperty)
.title(columnTitle);
}
}
}
if (columns == null) {
columns = tableBuilder.column().fillWithProperty("-").title("---");
}
return columns.configureExport(exportConf).build();
}
@Async
public void createTransmission(DownloadList download) {
String link = download.getUri();
String path = download.getDownloadPath();
long currentId = download.getId();
try {
CloseableHttpClient httpClient = HttpClientBuilder.create().build();
URIBuilder builder = new URIBuilder(link);
HttpGet httpGet = new HttpGet(builder.build());
CloseableHttpResponse response = httpClient.execute(httpGet);
Header[] header = response.getHeaders("Content-Disposition");
String content = header[0].getValue();
for(String str: StringUtils.split(content, ";")) {
if(StringUtils.containsIgnoreCase(str, "filename=")) {
log.debug(str);
String[] attachment = StringUtils.split(str, "=");
File directory = new File(path);
if(!directory.isDirectory()) {
FileUtils.forceMkdir(directory);
}
String filename = StringUtils.remove(attachment[1], "\"");
HttpVo vo = new HttpVo();
vo.setId(currentId);
vo.setName(download.getName());
vo.setFilename(filename);
vo.setPath(download.getDownloadPath());
jobs.put(currentId, vo);
download.setFileName(filename);
download.setDbid("http_" + vo.getId());
downloadListRepository.save(download);
BufferedInputStream bis = new BufferedInputStream(response.getEntity().getContent());
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(new File(path, filename)));
int inByte;
while((inByte = bis.read()) != -1) bos.write(inByte);
bis.close();
bos.close();
vo.setDone(true);
vo.setPercentDone(100);
jobs.put(currentId, vo);
downloadListRepository.save(download);
// if(StringUtils.equalsIgnoreCase(FilenameUtils.getExtension(attachment[1]), "torrent")) {
if(StringUtils.containsIgnoreCase(filename, ".torrent")) {
long ret = transmissionService.torrentAdd(path + File.separator + filename, path);
if(ret > 0L) {
download.setId(ret);
downloadListRepository.save(download);
simpMessagingTemplate.convertAndSend("/topic/feed/download", download);
}
}
}
}
response.close();
httpClient.close();
} catch (Exception e) {
log.error(e.getMessage());
}
}
@Test
public void split_string_comma_space_using_apache_commons() {
String[] elementsInString = StringUtils.split(
"Yo,Gabba, Gabba, Keep Trying", ",");
logger.info(Arrays.toString(elementsInString));
assertTrue(elementsInString.length == 4);
}
/**
* Splits an input string using the specified separator. The input string is trimmed before being split, and the same trim operation is applied to all the split tokens
*
* @param input
* @param separator
* @return an array of String tokens that result from the split
*/
public static String[] splitAndTrim(String input, String separator) {
return StringUtils.split(StringUtils.trim(input), separator);
}