Replacing programs with batch issue - java

I want to create auto-updater of my program.
In java part it looks like
int pid = Kernel32.INSTANCE.GetCurrentProcessId();
String cmd = folder + "update.bat" + " " + currentLoc + " " + updateLoc + " " + Integer.toString(pid);
Runtime.getRuntime().exec(cmd);
And the batch contains
SET "name=GameDrive Logs Viewer.exe"
SET "myname=update.bat"
TASKKILL /pid %3
TASKKILL /pid %3
DEL "%1\%name%"
MOVE "%2\%name%" "%1"
"%1\%name%"
DEL "%2\%myname%"
So, I'm killing current program and delete it.
Then i move new version to old folder, run new version, and delete the bat file.
This bat file is perfectly works when i call it from cmd with sending parameters.
But nothing is happend when i'm trying use it from java program.
As i found, that all Dialog windows creating from current program have the same processID. (I tested it from another bat).
So, my guess is the batch which is called from my java program get the same processID and kill himself.
Am I right? And if yes - can how I do that?

I guess you need launch your update.bat in another cmd instance as follows (add path as necessary). In JAVA use updatecall.bat with next content:
Either with CMD.exe: Start a new CMD shell and (optionally) run a command/executable program.
cmd /C ""update.bat" %*"
or with START: Start a program, command or batch script (opens in a new window.)
start "" "update.bat" %*
If started a batch file then the command processor is run with the /K switch to cmd.exe. This means that the window will tend to remain after the batch has been run. To auto close it, add EXIT command to the end of started batch.
I'm sure there is a smarter solution without any auxiliary batch...

Related

Stop AppleScript Running .jar When Java Error Raised

I have an AppleScript which I am using to run a .jar file. The .jar file takes several inputs which were originally entered via the command line but now I enter into a .csv and get read into the .jar automatically. For unknown reasons, sometimes a number in the CSV is not read correctly leading to a NumberFormatException in the Java code. However, instead of breaking, my script continually tries to enter the invalid input in an infinite loop. Is there a way to amend my code so that when an error is raised by the .jar, the script stops?
Here is my current code:
on RunFile(jar_location)
do shell script "cd " & jar_location & " ; cat 'prompt.csv' | sh 'runScript.sh' 'WSO'"
end RunFile
After going over this in the comments, it's clear that the problem is that the .jar file is trying to be interactive — asking for some input at the cursor — and AppleScript's do shell script is not designed for that. AppleScript can get errors and outputs form the shell, but it cannot feed a response back to the shell, or tell if a shell script is waiting for input.
if the .jar file cannot be operated in a non-interactive mode, then the only for AppleScript to make sure the process ends is to grab its process id number, wait a reasonable amount of time, and then send it a kill signal. That script would look like this:
on RunFile(jar_location)
set pid to do shell script "cd " & jar_location & " ; cat 'prompt.csv' | sh 'runScript.sh' 'WSO' &> /dev/null & echo $!"
-- wait 5 seconds, or whatever seems appropriate for the task to complete
delay 5
try
do shell script "kill " & pid
end try
end RunFile
The appended &> /dev/null & echo $! phrase detaches the shell script, allowing the AppleScript to move forward, and returns the process id of the process for later use. I've put the kill signal in a try block so that the script does not throw an error if the process has already exited normally.

Calling batch file from Java shows another directory

I am trying through Java to call a batch file in another folder directory.
String cmd = "cmd /c start /wait " + backupFolder + "\\script_encrypt.bat";
Process p = Runtime.getRuntime().exec(cmd);
p.waitFor();
However, when the batch file runs, it shows me the current directory which the batch is not there, why?.
Are you sure the batch file path and the path called from Java are the same?
According the screenshot from Eclipse and the screenshot from Cmd, they are not matching.
I have done the same, and worked for me.

Calling a .bat file from Java in a restricted (Citrix) Environment

I'm not too familiar with programming for the Windows desktop and I'm trying to figure out how to handle calling .bat files from Java. I'm trying to make desktop Java program using Maven run as a jar file execute a bash script in a Citrix virtualization Environment.
The original initial problems was that UNC paths were causing to the batch file to not be found, but I've modified the paths and now I'm able to find the batch file, but cmd.exe is disabled in the Citrix account I'm using, and I worried that there's nothing I can do.
Here's how it works:
1)
User launches program via program.jar file User checks for updates
2)
If updates are found, a new jar file called program_update.jar is
downloaded, and a batch file called run_update.bat is copied to the
main program directory.
3)
From within the java program, the following command is called:
Runtime.getRuntime().exec("cmd /c pushd " + FileName.installation + " && start run_update.bat && popd");
where FileName.installation is a property that has been previous set indicating the home installation directory.
run_update.bat runs a loop attempting to replace program.jar with program_update.jar and show a success/fail message in the command prompt.
When I run this in the Citrix environment, I get the following message:
'run_update.bat' is not recognized as an internal or external command, operable program, or batch file.
The command prompt has been disabled by your administrator.
At this point, I can click on run_update.bat and it runs the operation successfully.
The automatic update called via program.jar works in a normal windows environment with access to cmd.
My questions
Is my call from java to run cmd /c <commands> simply not going to work when cmd.exe is disabled?
Would renaming run_update.bat to run_update.cmd do any good?
Any alternative techniques? The batch file is necessary AFAIK because the jar file is replacing itself via the mv command.
I solved my own problem with an alternative technique. It turns out running Runtime.getRuntime().exec("cmd /c pushd " + FileName.installation + " && start run_update.bat && popd"); in a Citrix Environment was the problem, becase access to cmd is restricted. I rewrote it to use the the Desktop class:
File exe = new File(FileName.installation + File.separator + "install_update.bat");
if (Desktop.isDesktopSupported()) {
Desktop.getDesktop().open(exe);
} else {
Runtime.getRuntime().exec("cmd /c pushd " + FileName.installation + " && start install_update.bat && popd");
}

Command prompt do not close after running batch file which have 'exit' in last line

I am running a batch (ScanProject.bat) file using java by following code
Process p= Runtime.getRuntime().exec("cmd /c start /wait ScanProject.bat "+ BaseProjDir+"\\"+jo.getString("Name")+" "+st.nextToken());
System.out.println("Exit value : "+p.waitFor());
And following is the batch file code :-
%2:
cd %1
ant -f ..\antbuild.xml analyse
exit
Batch file run successfully but problem is command prompt window do not closes automatically and hence Process do not terminated automatically and my program wait for infinite time to complete this process.Please suggest me any technique so that cmd exit after running ant -f ..\antbuild.xml analyse command.
Thanks.
cd /D "Full path of directory" or pushd "Full path of directory" with popd before exit is better to switch the current directory to any directory on any drive (cd and pushd/popd) or even to a network share (just pushd/popd). Run in a command prompt window cd /? and pushd /? for details.
cmd /C starts a new Windows command process with closing the process automatically after last command was executed. Run in a command prompt window cmd /? for details on options of Windows command interpreter.
start is a command to start a new Windows command process or a GUI/hybrid application in a separate process.
So what you do here is starting a new Windows command process which starts a new Windows command process.
Running in a command prompt window start /? outputs the help for this command. start interprets often the first double quoted string as title string for the new command process. This causes often troubles on command lines with at least 1 double quoted string. Therefore usage of start requires often an explicit definition of a title string in double quotes as first argument for start which can be even an empty string, i.e. simply "" as first argument after start.
As it can be read after running exit /? in a command prompt window, this command without /B always exits the current Windows command process immediately. So when ant.exe finished, the command process in which the batch file was processed is definitely terminated.
I'm having no experience on Java development, but in my point of view it should be enough to use the following execution command which does not need a batch file at all.
The Java code line
Process p= Runtime.getRuntime().exec("cmd.exe /C cd /D \"" + jo.getString("Name") + "\" && ant.exe -f ..\\antbuild.xml analyse");
should be enough to
start a new Windows command process,
set the current directory within this command process to the drive and directory specified by jo.getString("Name") which of course must return a directory path with drive letter and using backslashes as directory separators, and on success
execute ant in this directory with the specified parameters
with terminating the Windows command process automatically after console application ant.exe finished if ant.exe is a console application.
I'm not sure if cmd.exe /C is needed at all.
I suggest to test this command first manually from within a command prompt window. Then use it in the Java application if really working and producing the expected result. And finally I would further test if cmd.exe /C is needed at all in Java code.
See Single line with multiple commands using Windows batch file for details about the operator && to run a command after previous command was successful. And see also Why do not all started applications save the wanted information in the text files as expected? for an explanation of console / GUI / hybrid application.
NOTE: There is also Java Runtime method exec(String[] cmdarray, String[] envp, File dir) to execute a command like ant.exe with its parameters -f and ..\antbuild.xml and analyse in the directory defined with third parameter which might be better for this task.
Swap out exit for taskkill, assuming you do not have any other cmd processes running. Not very graceful but it will get the job done.
%2:
cd %1
ant -f ..\antbuild.xml analyse
taskkill /im cmd.exe

Waiting for batch-end

I have 4 lines in my bat file, but my thread goes on before the cmd closes.
Here's my code:
rt = Runtime.getRuntime();
proc = rt.exec("cmd /c start C:\\temp\\test.bat");
if(proc.waitFor() == 0) {
return "did it";
} else {
return "nooope";
}
I always get the did it before cmd closes.
Here is my batch-file:
#ECHO off
taskkill /IM "Process.exe" /F
cd "C:\Program Files\ProcessFolder"
START /WAIT Process.exe
START otherProcess.exe
EXIT
any help?
The problem is that you're using start - which will start a new shell in which to run the batch file. The original shell then closes, so the process terminates, and your Java program continues.
Remove the start and it should work, in terms of waiting for the batch file to end. However, you've then got the same problem again within the batch file when you start otherProcess.
Either don't use start, or always use start /wait within the batch file.
If you use start /wait within the Java code, however, you'll end up with a command prompt sitting there at the end of the batch file execution, as far as I can tell by experimentation.

Categories