Created
January 10, 2013 05:50
-
-
Save omnisis/4499767 to your computer and use it in GitHub Desktop.
Mysql CLI Invoker
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package ehcache.examples; | |
import java.io.*; | |
public class MySqlCLI { | |
private String mysqlBinaryPath = "/usr/local/bin/mysql"; | |
public String getMysqlBinaryPath() { | |
return mysqlBinaryPath; | |
} | |
public void setMysqlBinaryPath(String mysqlBinaryPath) { | |
this.mysqlBinaryPath = mysqlBinaryPath; | |
} | |
public void invokeMySqlCli() { | |
} | |
private static void pipeIn(final InputStream src, final OutputStream dest) { | |
new Thread(new Runnable() { | |
public void run() { | |
try { | |
int ret = -1; | |
while ((ret = System.in.read()) != -1) { | |
dest.write(ret); | |
dest.flush(); | |
} | |
} catch (IOException e) { // just exit | |
} | |
} | |
}).start(); | |
} | |
private static class ProcessStatus { | |
private int exitValue; | |
private String output; | |
public void setExitValue(int exitValue) { | |
this.exitValue = exitValue; | |
} | |
public void setOutput(String output) { | |
this.output = output; | |
} | |
public int getExitValue() { | |
return exitValue; | |
} | |
public String getOutput() { | |
return output; | |
} | |
} | |
public static ProcessStatus executeScript(String dbname, | |
String dbuser, | |
String dbpassword, | |
String scriptpath, | |
boolean verbose) throws Exception { | |
ProcessBuilder mysqlPB = new ProcessBuilder(); | |
final File scriptFile = new File(scriptpath); | |
final File scriptWorkingDir = scriptFile.getParentFile(); | |
final FileInputStream scriptIs = new FileInputStream(scriptFile); | |
// format cmdline | |
String cmd = | |
String.format("mysql --user=%s --password=%s %s", dbuser, dbpassword, dbname); | |
// set env + working dir | |
mysqlPB.command(cmd); | |
mysqlPB.directory(scriptWorkingDir); | |
final Process proc = mysqlPB.start(); | |
pipeIn(scriptIs, proc.getOutputStream()); | |
ProcessStatus procStatus = new ProcessStatus(); | |
if (verbose) { | |
BufferedReader procOutReader = new BufferedReader(new InputStreamReader(proc.getInputStream())); | |
StringBuilder sb = new StringBuilder(); | |
String line = null; | |
while ((line = procOutReader.readLine()) != null) { | |
sb.append(line + System.getProperty("line.separator")); | |
} | |
procStatus.setOutput(sb.toString()); | |
} | |
// check for failure | |
int retVal = -1; | |
try { | |
retVal = proc.waitFor(); | |
} catch (InterruptedException e) { | |
System.err.println(e); | |
} | |
procStatus.setExitValue(retVal); | |
return procStatus; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment