I can get a terminal window or command prompt to open on either Mac OS or Windows. I want to send a string to that terminal or cmd window using my java.
String in = " -i " + "\"" + tfIntdta.getText() + "\"";
String rst = " - r " + "\"" + tfRstplt.getText() + "\"";
String out = " -o " + "\"" + tfOutdta.getText() + "\"";
String strip = " -s" + "\"" + tfStpdta.getText() + "\"";
String guistring = "-n gui";
String wd = "\"" + System.getProperty("user.dir");
String osver = System.getProperty("os.name");
String app = "";
if (osver.contains("Mac")){
app = wd + "/relap5.x\"";
} else if (osver.contains("Windows")){
app = "\\relap5.exe";
} else if (osver.contains("linux")) {
app = "/relap5.x";
}
String run = app + in + rst + out;
So the string would look something like this.
"/Users/brianallison/Documents/Java/RELAP5 GUI/issrs/relap5.x" -i "" - r "" -o ""
I want the line above to appear on the terminal or cmd window and execute.
Put your command and parameters in an array:
String[] command = {
"/Users/brianallison/Documents/Java/RELAP5 GUI/issrs/relap5.x",
"-i", "Choose your input file",
"-r", "",
"-o", ""
};
Then execute using Runtime#exec(String[] cmdarray):
Runtime.getRuntime().exec(command);
This answer has been put together after reading your other two questions from today, here and here.
Related
I am currently heeding advice from this Stack Overflow post:
Call and receive output from Python script in Java? (which links to http://www.devdaily.com/java/edu/pj/pj010016 for getting the output)
So, that's great and all, and I used it for the following code successfully:
String directPath;
if (Files.exists(Paths.get("C:/Users/jiaqin/Documents/NetBeansProjects/NCHandler/nchandlerv2/NCPythonFiles/"))) {
directPath = "C:/Users/jiaqin/Documents/NetBeansProjects/NCHandler/nchandlerv2/NCPythonFiles/";
}
else {
directPath = "/home/lab/testNetconf/NCPythonFiles/net_back_end/";
}
Process p = Runtime.getRuntime().exec("python " + directPath + "get_platform_and_OS.py -ssh_ip " + ui.ssh_ip
+ " -username " + ui.username + " -password " + ui.password);
Scanner threeInfo = new Scanner(p.getInputStream());
String hostName = "";
String IP_Address = ui.ssh_ip;
String OS = "";
String platform = "";
int iter = 0;
while (threeInfo.hasNextLine()) {
switch(iter) {
case 0:
hostName = threeInfo.nextLine();
break;
case 1:
OS = threeInfo.nextLine();
break;
case 2:
platform = threeInfo.nextLine();
break;
default:
break;
}
iter ++;
}
threeInfo.close();
Label hostNameLabel = new Label(hostName);
Label sshLabel = new Label("SSH IP Address: " + IP_Address);
Label OSLabel = new Label(OS);
Label platformLabel = new Label(platform);
Essentially, I run a python script by determining its path first, then I read the output using a Scanner (instead of a BufferedReader like in the post). Based on that case, I have a later method that uses the exact same concept:
public static String verifyShowCommands(String[] showCommands, MainUI ui) {
try {
String errorText = "";
String retErrors = "";
System.out.println("Python exec command is:\n" + "python /home/lab/testNetconf/NCPythonFiles/net_back_end/verify_show_commands.py -ssh_ip " + ui.ssh_ip + " -username "
+ ui.username + " -password " + ui.password + " -show_commands \"" + String.join(", ", showCommands) + "\"");
Process p = Runtime.getRuntime().exec("python /home/lab/testNetconf/NCPythonFiles/net_back_end/verify_show_commands.py -ssh_ip " + ui.ssh_ip + " -username "
+ ui.username + " -password " + ui.password + " -show_commands \"" + String.join(", ", showCommands) + "\"");
BufferedReader obtainedInfo = new BufferedReader(new InputStreamReader(p.getInputStream()));
String read = null;
while ((read = obtainedInfo.readLine()) != null) {
System.out.println("New line found");
retErrors += read;
}
System.out.println("Obtained Info is:" + retErrors + " and that's it");
obtainedInfo.close();
for (int i = 0; i < showCommands.length; i ++) {
if (i < showCommands.length - 1) {
int thisSCStart = retErrors.indexOf(showCommands[i]);
int nextSCStart = retErrors.indexOf(showCommands[i+1]);
String outputSC = retErrors.substring(thisSCStart, nextSCStart);
if (outputSC.contains("'Valid': 'No'")) {
errorText += outputSC + "\n";
}
}
else {
String outputSC = retErrors.substring(retErrors.indexOf(showCommands[i]));
if (outputSC.contains("'Valid': 'No'")) {
errorText += outputSC + "\n";
}
}
}
return errorText;
}
catch (IOException e) {
return null;
}
}
As you can see, I'm once again running a python script and reading the output. The error occurs when I attempt to get the substring of retErrors - because retErrors is an empty string; that's right, for some reason, this time the output is NOT getting read. Note that the above uses BufferedReader; I was originally using Scanner, and when that failed I changed over because I thought maybe for god-knows-what reason, synchronization might affect the situation. Unfortunately, it seemed there was STILL no output to read.
As for how I know, I simply observed in the Netbeans output and searched for the line
System.out.println("Obtained Info is:" + retErrors + " and that's it");
Then, you might ask the obvious question: what if the command is invalid? Well, I printed out the entire exec command at the top as well:
System.out.println("Python exec command is:\n" + "python /home/lab/testNetconf/NCPythonFiles/net_back_end/verify_show_commands.py -ssh_ip " + ui.ssh_ip + " -username "
+ ui.username + " -password " + ui.password + " -show_commands \"" + String.join(", ", showCommands) + "\"");
So, I looked for that line in the Netbeans output, and there it was:
Info: Python exec command is:
python /home/lab/testNetconf/NCPythonFiles/net_back_end/verify_show_commands.py -ssh_ip 9.0.0.12 -username root -password lab -show_commands "show bgp scale"
And then I copy-pasted that exact command into a terminal and ran it, and I got an output (the actual type of the printed result in the output is a dictionary, hence the brackets):
Anyone have some advice? This is extraordinarily frustrating to me because I'm following the exact format of the first case with get_platform_and_os.py but then with verify_show_commands.py, it just doesn't read anything.
As a side note, if this information helps, when I run the command manually in the terminal, it takes roughly 2-3 seconds to complete. However, running it in my project takes much less than a second before it errors out.
So...
Using Quotes within getRuntime().exec
Apparently this is a thing. I just made every word in the command an array element instead, and inside the array, "show bgp scale" was entered without the quotes. After that, it worked.
I have developed a Java application and it's in last stage.
The problem is that I cannot execute the mysqldump with Runtime.getRuntime().exec().
try {
String[] command = new String[] {
"cmd.exe",
"/c",
"mysqldump --host=" + host + " --user=" + dbuser + " --password=" + dbpass + " " + dbname + " > " + filename
};
Process runtimeProcess = Runtime.getRuntime().exec(command);
int ProcessComplete = runtimeProcess.waitFor();
if (ProcessComplete == 0) {
JOptionPane.showMessageDialog(null, "Database backup has been done successfully");
}
else {
JOptionPane.showMessageDialog(null, "Database backup was unsuccessfull");
JOptionPane.showMessageDialog(null, command);
}
}
catch (IOException | InterruptedException exc) {
Logger.getLogger(Backup.class.getName()).log(Level.SEVERE, null, exc);
}
Can anyone help me with this?
I tried your code in Windows and it works fine for me.
Open cmd, type mysqldump and hit enter.
If it is executed successfully, that means your code should work properly if your database configuration is correct.
If you get 'mysqldump' is not recognized as an internal or external command then either you have to set the MySQL path in your environment variable, or specify the full path for mysqldump in your Java code like this:
String[] command = new String[] {
"cmd.exe",
"/c",
"c://mysql/bin/mysqldump --host=" + host + " --user=" + dbuser + " --password=" + dbpass + " " + dbname + " > " + filename
};
I am using Java to format a poem in LaTeX and then compile it. The LaTeX-ization works perfectly fine, but I somehow can't run the command. Is this a problem with my LaTeX invocation? For some reason, when I use Java to write an equivalent batch file and then run it, Java will do nothing but when I run the batch file from the shell, it works.
/**
*
* #param title the title of the poem
* #param poem a <code>List</code> with one string for each line of the
* poem.
* #throws FileNotFoundException
*/
protected static void writePDF(final String title, List<String> poem) throws FileNotFoundException {
final StringBuilder latex = new StringBuilder(0);
// I know I shouldn't concatenate like this; I'll fix it later.
// eeeewww escapes
latex.append(
"\\documentclass[letterpaper,12pt,article,oneside]{memoir}\n"
+ "\\usepackage[utf8]{inputenc}\n"
+ "\\usepackage{ebgaramond}\n"
+ "\\usepackage{hyperref}\n"
+ "\\usepackage[protrusion,expansion,kerning,tracking,spacing]{microtype}\n"
+ "\\linespread{1.3}\n"
+ "\\nonfrenchspacing\n"
+ "\\microtypecontext{spacing=nonfrench}\n"
+ "\\begin{document}\n"
+ "\\title{" + title + "}\n"
+ "\\author{}\n"
+ "\\date{\\today}\n"
+ "\\maketitle\n"
+ "\\setlength{\\parindent}{0pt}\n"
+ "\\setlength{\\parskip}{\\baselineskip}\n");
// Go Java 8!
poem
.stream()
.map((String s)
// Original poem's in HTML
-> s.replace("<p>", "\n\n").replace("<br>", "\\\\\n"))
.forEach(latex::append);
latex.append("\n\\end{document}");
final String latexstr = latex.toString().replace("...", "\\ldots");
final String filename = title + ".tex";
final File file = new File(filename);
try (final PrintWriter pw = new PrintWriter(new BufferedOutputStream(new FileOutputStream(file)))) {
pw.print(latexstr);
}
final String path = file.getAbsolutePath()
.substring(0, file.getAbsolutePath().lastIndexOf("\\")) + "\\";
System.out.println("Path: " + path);
final String LaTeXcmd = "pdflatex \""
+ path
+ title + "\"";
final File script = new File(""
+ rand.nextDouble()
+ "compile"
+ title.replace(" ", "_")
+ ".bat");
//I originally wanted just to write a batch file and run it from Java.
// try (final PrintWriter pw = new PrintWriter(new BufferedOutputStream(new FileOutputStream(script)))) {
// pw.print(""
// //"#echo off\n"
// + "cd " + path + "\n"
// + LaTeXcmd + "\n"
// // + "del \"" + path + title + ".aux\"\n"
// // + "del \"" + path + title + ".log\"\n"
// // + "del \"" + path + title + ".out\"\n"
// // + "del \"" + path + title + ".tex\"\n"
// // + "start /b \"\" cmd /c del \"%~f0\"&exit /b\n"
//
// + "msg * all\n"
// );
// }
try {
System.out.println("latexcmd " + LaTeXcmd);
final File workingdir = new File(path);
System.out.println("workingdir " + workingdir);
// >>>>>>>>>>>>>>>> IS THIS CORRECT? <<<<<<<<<<<<<<<<
Runtime.getRuntime().exec(LaTeXcmd, new String[]{}, workingdir);
// This statement works perfectly fine (Windows).
// Runtime.getRuntime().exec("msg * all");
} catch (IOException ex) {
Logger.getLogger(PoetryBackend.class.getName()).log(Level.SEVERE, null, ex);
}
}
It's not correct. Try
String command = new String[] {"cmd", "/c", LaTeXcmd };
Runtime.getRuntime().exec(command, new String[]{}, workingdir);
since otherwise you're not executing it through command interpreter, which is what you want if you want it to behave like you would run it from cmd prompt.
This applies to running .bat files as well.
What are the possible reasons why i can't backup my DB using MYSQLDUMP?
In my localhost, i can backup the db but when I use the db in my hosting, there seems to be a problem. Is it possible that my hosting can't backup db? Btw, im using cloudbees in my database. I'm 100% sure that I change all the username, password and the name of the db when using my hosting MySQL. Actually it creates the .sql file but it is empty.
String executeCmd = "C:/xampp/mysql/bin/mysqldump -u " + username
+ " -p" + password + " somedbname" + " -r "
+ "C:/tech-report-db/backup"
+ c.getTimeInMillis() + c.getWeekYear() + ".sql";
try {
Process runtimeProcess;
runtimeProcess = Runtime.getRuntime().exec(executeCmd);
int processComplete = runtimeProcess.waitFor();
if (processComplete == 0) {
System.out.println("Backup created successfully");
} else {
System.out.println("Could not create the backup");
}
it returns the error "Could not create the backup"
I fixed the problem. Sorry for incomplete question. I'm using a remote mysql so i need to include the hostip and the port
before:
String executeCmd = "C:/xampp/mysql/bin/mysqldump -u " + username
+ " -p" + password + " somedbname" + " -r "
+ "C:/tech-report-db/backup"
+ c.getTimeInMillis() + c.getWeekYear() + ".sql";
now:
String executeCmd = "C:/xampp/mysql/bin/mysqldump -P "+port+ " -h "+hostIP+ " -u " + username
+ " -p" + password + " somedbname" + " -r "
+ "C:/tech-report-db/backup"
+ c.getTimeInMillis() + c.getWeekYear() + ".sql";
I am going to take database backup by using java code.This code is excuting fine but I am getting int processComplete = runtimeProcess.waitFor(); This method calling is returning the integer as 1. So finally I am getting the message as could not create backup as sop.
public static void main(String[] args) {
String path = "D:/databasebackup/databasbac.sql";
String username = "root";
String password = "";
String dbname = "rac";
String executeCmd = "<Path to MySQL>/bin/mysqldump -u " + username + " -p" + password + " --add-drop-database -B " + dbname + " -r " + path;
Process runtimeProcess;
try {
// System.out.println(executeCmd);//this out put works in mysql shell
runtimeProcess = Runtime.getRuntime().exec(new String[] { "cmd.exe", "/c", executeCmd });
System.out.println(executeCmd);
// runtimeProcess = Runtime.getRuntime().exec(executeCmd);
int processComplete = runtimeProcess.waitFor();
System.out.println("processComplete"+processComplete);
if (processComplete == 0) {
System.out.println("Backup created successfully");
} else {
System.out.println("Could not create the backup");
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
I was facing similar problem in database backup from MYSQL through JDBC. So I ran the below code.
String path = C:\Program Files\MySQL\MySQL Server 5.7\bin\mysqldump
String command= "cmd.exe /c "
+ "\"\""+path+"\" "
+ " --user="+UserInputs.getDbUserName()
+ " --password="+UserInputs.getDbPassword()
+ " --host="+UserInputs.getDbConnectionIP()
+ " --protocol=tcp "
+ " --port="+UserInputs.getDbConnectionPort()
+ " --default-character-set=utf8 "
+ " --single-transaction=TRUE "
+ " --routines "
+ " --events "
+ "\""+UserInputs.getDbName()
+"\" "
+ ">"
+ " \""
+ "D:\\MY DATA\\DB_Backup.sql"
+ "\""
+ " \"";
Runtime runtime = Runtime.getRuntime(command);
In case password is blank remove the --password line.
This will create your database backup.
In case you are running this on LINUX replace
cmd.exe /c
by
/bin/sh -c
Thanks!
Try out my code for backup the database using java. It works well for me.
try {
String filename = null;
FileChooser.setVisible(true);
int result = FileChooser.showSaveDialog(null);
if (result == JFileChooser.APPROVE_OPTION) {
filename = FileChooser.getSelectedFile().toString().concat(".sql");
File file = new File(filename);
if (file.exists()) {
Object option[] = {"Sim", "Nao"};
int opcao = JOptionPane.showOptionDialog(null, "aaa", "bbbb", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, option, option[0]);
if (opcao == JOptionPane.YES_OPTION) {
Runtime backup = Runtime.getRuntime();
backup.exec("C:\\wamp\\bin\\mysql\\mysql5.6.17\\bin\\mysqldump.exe -v -v -v --host=localhost --user=root --port=3306 --protocol=tcp --force --allow-keywords --compress --add-drop-table --result-file=" + filename + " --databases GIVE YOUR DATABSE NAME");
JOptionPane.showMessageDialog(null, "Backup succesfully");
} else {
FileChooserActionPerformed(evt);
}
} else {
Runtime backup = Runtime.getRuntime();
backup.exec("C:\\wamp\\bin\\mysql\\mysql5.6.17\\bin\\mysqldump.exe -v -v -v --host=localhost --user=root --port=3306 --protocol=tcp --force --allow-keywords --compress --add-drop-table --result-file=" + filename + " --databases GIVE YOUR DATABASE NAME");
JOptionPane.showMessageDialog(null, "Backup succesfully");
}
}
} catch (Exception e) {
JOptionPane.showMessageDialog(null, e, "Error.!", 2);
}
And this is the DbOperation class That i have written.
import com.mysql.jdbc.PreparedStatement;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
public class DbOperation {
String url = "jdbc:mysql://localhost:3306/give your database name";
String username = "your username";
String password = "your password";
Connection con = null;
PreparedStatement pst = null;
ResultSet rs = null;
public Connection backupDB(){
try{
con=DriverManager.getConnection(url, username, password);
}catch(SQLException e){
System.out.println(e.getMessage());
}
return con;
}
}
Try this:
int processComplete = runtimeProcess.exitValue();
runtime info
Hope this helps