|
import okhttp3.*; |
|
|
|
import java.io.File; |
|
import java.io.FileReader; |
|
import java.io.IOException; |
|
import java.util.ArrayList; |
|
import java.util.List; |
|
import java.util.regex.Pattern; |
|
|
|
/** |
|
* Created by tak on 4/26/17. |
|
*/ |
|
public class Test1 { |
|
private static Pattern fileTarget = Pattern.compile("\\.c$"); |
|
|
|
public static void main(String[] args) throws IOException { |
|
final MediaType JSON = MediaType.parse("application/json; charset=utf-8"); |
|
if(args.length == 0) { |
|
System.err.println("FileDir is required."); |
|
System.exit(1); |
|
} |
|
String startDir = args[0]; |
|
List<String[]> foundFiles = new ArrayList<>(); |
|
search(new File(startDir), foundFiles); |
|
System.out.println(foundFiles.size()); |
|
OkHttpClient client = new OkHttpClient(); |
|
for(int i = 0;i < 10;i++) { |
|
String fileName = foundFiles.get(i)[0]; |
|
String fullPath = foundFiles.get(i)[1]; |
|
String content = fileRead(fullPath); |
|
content = content.replaceAll("\"", "\\\\\""); |
|
|
|
String json = String.format( |
|
"[{\"id\": %d, \"name\": \"%s\", \"file_path\": \"%s\", \"content\": \"%s\"}]", |
|
i, fileName, fullPath, content |
|
); |
|
System.out.println(json); |
|
RequestBody body = RequestBody.create(JSON, json); |
|
Request request = new Request.Builder() |
|
.url("http://localhost:8984/solr/mycore1/update/json?commit=true") |
|
.post(body) |
|
.build(); |
|
|
|
try (Response response = client.newCall(request).execute()) { |
|
System.out.println(response.body().string()); |
|
} |
|
} |
|
} |
|
|
|
private static void search(File dir, List<String[]> foundFile) { |
|
File[] children = dir.listFiles(); |
|
if(children == null) return; |
|
|
|
for(File file: children) { |
|
if(file.isFile()) { |
|
String fileName = file.getName(); |
|
if (fileTarget.matcher(fileName).find() && file.length() < 1000) { |
|
foundFile.add(new String[]{fileName, file.getAbsoluteFile().toString()}); |
|
} |
|
} else { |
|
search(file, foundFile); |
|
} |
|
} |
|
} |
|
|
|
private static String fileRead(String filePath) throws IOException { |
|
File file = new File(filePath); |
|
FileReader filereader = new FileReader(file); |
|
char[] buf = new char[1000000]; |
|
StringBuilder sb = new StringBuilder(); |
|
while(true) { |
|
int len = filereader.read(buf); |
|
if (len <= 0) { |
|
break; |
|
} |
|
sb.append(new String(buf, 0, len)); |
|
} |
|
return sb.toString(); |
|
} |
|
} |