92 lines
2.5 KiB
Java
92 lines
2.5 KiB
Java
import org.antlr.v4.runtime.*;
|
|
import org.antlr.v4.runtime.tree.*;
|
|
|
|
import java.io.FileOutputStream;
|
|
import java.io.FileInputStream;
|
|
import java.io.OutputStreamWriter;
|
|
import java.nio.charset.StandardCharsets;
|
|
import java.nio.charset.Charset;
|
|
|
|
public class MainRunner {
|
|
|
|
private static void printHelp() {
|
|
System.out.println("NlpParser Usage");
|
|
System.out.println("NlpParser <src> <dest>");
|
|
System.out.println();
|
|
System.out.println("<src> - the decoded NLP text file.");
|
|
System.out.println("<dest> - the output json file.");
|
|
}
|
|
|
|
private static class UserRequest {
|
|
public UserRequest(String input_filepath, String output_filepath) {
|
|
this.mInputFilePath = input_filepath;
|
|
this.mOutputFilePath = output_filepath;
|
|
}
|
|
|
|
String mInputFilePath;
|
|
String mOutputFilePath;
|
|
|
|
public String getInputFilePath() {
|
|
return this.mInputFilePath;
|
|
}
|
|
|
|
public String getOutputFilePath() {
|
|
return this.mOutputFilePath;
|
|
}
|
|
|
|
}
|
|
|
|
private static UserRequest resolveArguments(String[] args) throws Exception {
|
|
// Check parameter
|
|
if (args.length != 2) {
|
|
throw new Exception("Invalid arguments count!");
|
|
}
|
|
// Return fetched argumnts
|
|
return new UserRequest(args[0], args[1]);
|
|
}
|
|
|
|
private static void executeWorker(UserRequest user_request) throws Exception {
|
|
// Use try-with-resources to safely manage file stream.
|
|
try (FileInputStream fin = new FileInputStream(user_request.getInputFilePath());
|
|
FileOutputStream fout = new FileOutputStream(user_request.getOutputFilePath());
|
|
OutputStreamWriter fw = new OutputStreamWriter(fout, StandardCharsets.UTF_8);) {
|
|
// Start lex and parse
|
|
CharStream input = CharStreams.fromStream(fin, Charset.forName("windows-1252"));
|
|
NlpLexer lexer = new NlpLexer(input);
|
|
CommonTokenStream tokens = new CommonTokenStream(lexer);
|
|
NlpParser parser = new NlpParser(tokens);
|
|
|
|
// Walk tree to build json
|
|
ParseTree tree = parser.document();
|
|
ParseTreeWalker walker = new ParseTreeWalker();
|
|
JsonConverter converter = new JsonConverter();
|
|
walker.walk(converter, tree);
|
|
|
|
// Write json
|
|
fw.write(converter.buildJsonString());
|
|
}
|
|
}
|
|
|
|
public static void main(String[] args) throws Exception {
|
|
// Check argument
|
|
UserRequest user_request = null;
|
|
try {
|
|
user_request = resolveArguments(args);
|
|
} catch (Exception e) {
|
|
System.out.print("[Argument Error] ");
|
|
System.out.println(e.getMessage());
|
|
printHelp();
|
|
return;
|
|
}
|
|
|
|
// Call converter
|
|
try {
|
|
executeWorker(user_request);
|
|
} catch (Exception e) {
|
|
System.out.print("[Converter Error] ");
|
|
System.out.println(e.getMessage());
|
|
return;
|
|
}
|
|
}
|
|
}
|