Files
ProjectOctopus/server/src/main/java/io/wdd/common/utils/FunctionReader.java
2023-06-14 11:21:31 +08:00

118 lines
2.9 KiB
Java

package io.wdd.common.utils;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
@Component
public class FunctionReader {
public static List<List<String>> ReadFileToCommandList(String functionFilePath) {
// https://www.digitalocean.com/community/tutorials/java-read-file-line-by-line
List<List<String>> result = null;
try {
BufferedReader bufferedReader = new BufferedReader(new FileReader(functionFilePath));
result = doReadContent(
result,
bufferedReader
);
} catch (IOException e) {
throw new RuntimeException(e);
}
return result;
}
public static List<List<String>> ReadStringToCommandList(String functionContent) {
List<List<String>> result = null;
try {
// 构造一个 buffered Reader
BufferedReader bufferedReader = new BufferedReader(
new StringReader(functionContent)
);
// 执行read操作
result = doReadContent(
result,
bufferedReader
);
} catch (IOException e) {
throw new RuntimeException(e);
}
return result;
}
/**
* 实际解析从前端传入的 脚本命令, 将其转换为 List<List<String>>
*
* @param result
* @param bufferedReader
* @return
* @throws IOException
*/
private static List<List<String>> doReadContent(List<List<String>> result, BufferedReader bufferedReader) throws IOException {
String line = bufferedReader.readLine();
if (line != null) {
result = new ArrayList<>(64);
}
while (line != null) {
if (!StringUtils.isEmpty(line)) {
result.add(SplitSpaceIndentToCommandList(line));
}
line = bufferedReader.readLine();
}
return result;
}
public static List<String> SplitSpaceIndentToCommandList(String commandLine) {
return Arrays
.stream(commandLine
.split(" "))
.collect(Collectors.toList());
}
public static List<String> SplitCommaIndentToCommandList(String commandLine) {
// 需要进行归一化,去除掉多余的空格
return Arrays
.stream(commandLine.split(","))
.map(
split -> split.replace(
" ",
""
)
)
.collect(Collectors.toList());
}
}