I have a impl class which has several methods, they all basically call the script using runtime.exec with different argument list e.g.
public String doExport(String ruleIds, String fileName) throws Exception{
StringBuffer cmd = new StringBuffer();
cmd.append(SOME_SCRIPT + " -a export ");
cmd.append(" -f " );
cmd.append(fileName);
cmd.append(" -r " );
cmd.append(ruleIds);
cmd.append(" 2>/dev/null");
return execCmd(cmd.toString());
}
public String doImport(String fileName, String user, String iface) throws Exception {
StringBuffer cmd = new StringBuffer();
cmd.append(SOME_SCRIPT + " -a import ");
cmd.append(" -f " );
cmd.append(fileName);
cmd.append(" -m " );
cmd.append("user");
cmd.append(" -u " );
cmd.append(user);
cmd.append(" -I " );
cmd.append(iface);
return execCmd(cmd.toString());
}
public String setRulesMode(String mode) throws Exception {
String cmd = SOME_SCRIPT + " -a ";
return execCmd(cmd.toString());
}
Is there better way to do this? like encapsulate commands and arguments or more generic way of doing it? I tried to use enum but found it enum is better used when there are static/constant parameter list, so looking for better alaternative.
I ‘d create “CommandBuilder” that wraps
ProcessBuilderand is able to compose and run command line.Please pay attention that your attempt to redirect STDOUt to file will not work. Redirection is a shell feature. You can either run your command via shell (e.g.
/bin/sh YOUR COMMAND >YOURFILEon unix orcmd -c YOUR COMMAND >YOURFILEon windows.Better way is to use
Process.setOutputStream()from java. It is portable, easier to debug and maintain. This can be functionality of yourCommandBuilder.EDIT
Here are some tips to the CommandBuilder structure.