Process No Wait for Terminate a Bat File - java

I create a .bat file in my java application(Runtime),then run .bat file and use of waitFor() method to waiting for terminate .bat file,but process no wait for terminate .bat file.
Code:
public boolean restoreDepot() {
try {
InputStreamReader _input = new
InputStreamReader(getClass().getResourceAsStream("/Depot/DBMakaseb.sql"));
BufferedReader _in = new BufferedReader(_input);
String _currentpath = (new File(".")).getCanonicalPath() + File.separator + "DBDepot.sql";
BufferedWriter _out = new BufferedWriter(new FileWriter(_currentpath));
while (_in.ready()) {
_out.write(_in.readLine());
_out.newLine();
}
_in.close();
_out.close();
String _comCur = "set cur=%cd%";
String _comCD = "Cd /d %PROGRAMFILES%\\MySQL\\MySQL Server 5.5\\bin";
String _comando = "mysql -u root -pm117988m < %cur%" + "\\DBDepot.sql";
String _comExit = "exit";
BufferedWriter _out1 = new BufferedWriter(new FileWriter("restore.bat"));
_out1.write(_comCur);
_out1.newLine();
_out1.write(_comCD);
_out1.newLine();
_out1.write(_comando);
_out1.newLine();
_out1.write(_comExit);
_out1.close();
Process _p = Runtime.getRuntime().exec("cmd /C start restore.bat");
int _res = _p.waitFor();
while (!(((new File(_currentpath)).delete()) && ((new File((new File(".")).getCanonicalPath() + File.separator + "restore.bat")).delete()))) {
}
if (_res != 0) {
return false;
}
return true;
} catch (Exception err) {
System.out.println(err);
}
return false;
}
Please Help me!

It has to do with your usage of start.
Remove start, only to leave
Process _p = Runtime.getRuntime().exec("cmd /C restore.bat");

Related

How to execute `docker exec -it netvertex bash` by Java Program

How to execute docker exec -it netvertex bash by Java Program.
By this i am trying to execute but not working
public void execute(String command) {
try {
System.out.println("===========>" + command);
Channel channel1 = session.openChannel("exec");
((ChannelExec) channel1).setPty(true);
((ChannelExec) channel1).setCommand(command);
// X Forwarding
// channel.setXForwarding(true);
//channel.setInputStream(System.in);
channel1.setInputStream(null);
//channel.setOutputStream(System.out);
//FileOutputStream fos=new FileOutputStream("/tmp/stderr");
//((ChannelExec)channel).setErrStream(fos);
((ChannelExec) channel1).setErrStream(System.err);
InputStream in1 = channel1.getInputStream();
channel1.connect();
byte[] tmp1 = new byte[1024];
while (true) {
while (in1.available() > 0) {
int i = in1.read(tmp1, 0, 1024);
if (i < 0) break;
System.out.print(new String(tmp1, 0, i));
}
if (channel1.isClosed()) {
if (in1.available() > 0) continue;
System.out.println("exit-status: " + channel1.getExitStatus());
break;
}
try {
Thread.sleep(1000);
} catch (Exception ee) {
}
}
} catch (Exception e) {
}
}
By above code my other Linux command are working. But docker exec it not working.
And the other option i tried
try {
String host = "root#10.121.21.224";
String passwd = "root#10";
Terminal exec = new Terminal(pageUiUtils);
exec.loginSSH(host, passwd);
String[] command = {"docker", "exec", "-it", "netvertex", "bash"};
ProcessBuilder pb = new ProcessBuilder(command);
pb.inheritIO();
Process proc = pb.start();
InputStream is = proc.getInputStream();
OutputStream os = proc.getOutputStream();
BufferedReader reader
= new BufferedReader(new InputStreamReader(is));
BufferedWriter writer
= new BufferedWriter(new OutputStreamWriter(os));
writer.write("pwd");
writer.flush();
String line = "";
while ((line = reader.readLine()) != null) {
System.out.print(line + "\n");
}
exec.execute("docker exec -it netvertex bash");
pageUiUtils.pause(1000);
exec.execute("pwd");
//proc.waitFor();
} catch (Exception e) {
e.printStackTrace();
}
by above code also showing error that
The input device is not a TTY

How to asynchronously run JBoss server application from Java

In my java application, I need to run a Jboss server with the file standalone.bat.
I tried ProcessBuilder, and though it did start the server, my application is blocked waiting for the server to go down
#RequestMapping(value = "api/project/liststart", method = RequestMethod.POST)
public HttpEntity<Boolean> postListServer(#RequestBody ListStart modules) throws Throwable {
String cmd = "";
Boolean response = false;
ProcessBuilder processBuilder = new ProcessBuilder();
String path = "C:\\jboss-as-7.1.1.Final\\bin\\";
String command = standelone.bat+ " >sometext.txt" ;
processBuilder.command("cmd.exe", "/c", command);
processBuilder.directory(new File(path));
Process process = processBuilder.start();
BufferedReader reader =
new BufferedReader(new InputStreamReader(process.getInputStream()));
String ligne;
while ((ligne = reader.readLine()) != null) {
System.out.println(ligne);
}
int exitCode = process.waitFor();
System.out.println("\nExited with error code : " + exitCode);
String F = path + "\\SomeFile.txt";
System.out.println("------------------------file: " + F);
File file = new File(F);
Scanner scanner = new Scanner(file);
//now read the file line by line...
int lineNum = 0;
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
lineNum++;
if (line.contains("Started server")) {
response = true;
System.out.println("-------------------------------------" + response.toString());
}
}
ResponseEntity responseEntity = new ResponseEntity<Boolean>(response, HttpStatus.OK);
return responseEntity;
}
}
I expect the method above to return true value, but it's being blocked before a value can be returned.
It seems like scanner.hasNextLine() can't get out from while cycle, so try like this :
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
lineNum++;
if (line.contains("Started server")) {
response = true;
System.out.println("-------------------------------------" + response.toString());
return new ResponseEntity<Boolean>(response, HttpStatus.OK);
} else {
return new ResponseEntity<Boolean>(response, HttpStatus.OK);
}
}

How can I close a Java application from another Java application?

I am using the following code for running an application:
private void RunApp2() throws IOException
{
StringBuilder sb = new StringBuilder();
String filePath = System.getProperty("user.dir");
String jarfile = filePath + "\\MyAppV2.jar";
File f = new File(jarfile);
if(f.exists() && !f.isDirectory()) {
// do something
}
else
{
AreThereProblem = true;
}
try { // jarname arguments has to be saperated by spaces
Process process = Runtime.getRuntime().exec("cmd.exe start /C java -jar \""+jarfile + "\"");
//.exec("cmd.exe /C start dir java -jar "+jarfile+" "+name+" "+id+" dir");
BufferedReader br = new BufferedReader(new InputStreamReader(process.getInputStream ()));
String line = null;
while ((line = br.readLine()) != null){
sb.append(line).append("\n");
}
System.out.println("Console OUTPUT : \n"+sb.toString());
//process.destroy();
}catch (Exception e){
lblInformation.setText(e.getMessage());
}
}
But how can I close MyAppV2.jar application if it is already running before I'm running it again?

How do i create .o file?

Here is a part of code written in eclipse.
I am making a GUI for a compiler and this is the action performed when a compile button is pressed.
File file = fileChooser.getSelectedFile();
try {
FileWriter out = new FileWriter(file);
textContent.write(out);
out.close();
} catch (IOException e1) {
e1.printStackTrace();
}
String filepath = file.getPath();
String filepath2 = filepath.substring(0, filepath.lastIndexOf(File.separator));
System.out.println(filepath);
System.out.println(filepath2);
String name = file.getName();
String name2 = file.getName().substring(0, file.getName().lastIndexOf("."));
String folder = filepath2+"\\";
String o = folder+name2+".o";
System.out.println(o);
ProcessBuilder pb=new ProcessBuilder();
try {
pb = new ProcessBuilder("cmd", "/C", "arm-none-eabi-gcc "+"-c "+"-march=armv8-a "+"-g " + "\"" + filepath2 + "\\" +name + "\"" + " -o \""+ name2+"\"");
pb = new ProcessBuilder("cmd", "/C", "arm-none-eabi-g++ "+"-c "+"-march=armv8-a "+"-g " + "\"" + filepath2 + "\\" +name + "\"" + " -o \""+ name2+"\"");
pb.directory(new File(filepath2));
Process p = pb.start();
p.waitFor();
int x = p.exitValue();
if (x == 0) {
area.setForeground(red);
area.setText(" == 0 error.. Compilation Finished");
} else {
BufferedReader r = new BufferedReader(new InputStreamReader(p.getErrorStream()));
//BufferedWriter rm=new BufferedWriter(new OutputStreamWriter(p.getOutputStream()));
String out;
area.setText("");
while ((out = r.readLine()) != null)
{
area.setForeground(RED);
area.append(out + System.getProperty("line.separator"));
}
}
} catch (Exception ex) {
ex.printStackTrace();
Output:
When I compile the program (test.cpp), it is simply creating a test file, and I want the output to be test.
Console:
In fact, it shows in the console that it has created a test.o file

execute sql statements in java at runtime using Runtime.getRuntime().exec()

In the below code while loop is not running. Can someone suggest me what is going wrong with this code.
import java.io.*;
public class A
{
public static void main(String args[]) {
int value = 0;
String sql = "SELECT * FROM A2A_TP_INFO";
String filename="file.txt";
String filepath="/home/mit"+"export/file.txt";
String exportQuery = "/home/mit/JavaProj/proj/export/query";
String cmd[] = {
"/bin/ksh",
"-c",
"" + exportQuery + " " +filepath+ " \""
+ sql + ";\" "
};
try {
//Process p = Runtime.getRuntime().exec(cmd);
Process p1=Runtime.getRuntime().exec(sql);
// p.waitFor();
BufferedReader input = new BufferedReader(new InputStreamReader(
p1.getInputStream()));
while ((value = input.read()) != -1) {
char c = (char) value;
System.out.println(c);
}
input.close();
} catch (Exception exp) {
exp.printStackTrace();
}
}
}
Don't use an intermediary shell. And use a ProcessBuilder:
final List<String> fullCommand = Arrays.asList(exportQuery, filePath, sql + ';')
final ProcessBuilder builder = new ProcessBuilder(fullCommand);
final Process p = builder.start();
Note that using ProcessBuilder you can send stdout/stderr to a file, and even customize stdin. You can set the working directory, customize the environment etc. Use that. Really. Runtime.exec() has no reason to be used anymore.

Categories

Resources