Writing cmd output to a file is not working with Tomcat :( - java

I'm using a java process to open cmd to run a command, then save the output to a text file.
ArrayList<String> commands = new ArrayList<>();
commands.add("cmd.exe");
commands.add("/c");
commands.add("cd "+System.getenv("LOGSTASH_PATH")+" && start /B cmd.exe /c \"logstash --config.test_and_exit -f "+configFileName+"\""+" > testing.txt");
ProcessBuilder builder = new ProcessBuilder(commands);
Process subProcess = builder.start();
Thread.sleep(50000);
subProcess.destroy();
This piece of code works when i try this with eclipse,But when i generate a war out of this and deploy in tomcat, it doesn't work. What could be the problem?
How to solve this?

I suspect the problem may be with the CD instruction:
Check that the LOGSTASH_PATH environment variable is available in the Tomcat process.
In case the current Tomcat directory and the LOGSTASH_PATH belong to different drives, add a /d qualifier:
"cd /d "+System.getenv("LOGSTASH_PATH")+ ...
(Tough is much better to replace the cd call by a Java call to directory(File) instead, as #nitind pointed).

Related

Running "ProcessBuilder.start" on Docker fails

Installation of libreoffice package in Docker container.
I'm trying to convert a JAVA application from Excel to a PDF file, but an error occurs.
(The container is running on Google Cloud Run.)
The Dockerfile is below.
FROM maven:3.8-jdk-11
RUN apt-get -y update
RUN apt-get -y install libreoffice
RUN mvn package
FROM adoptopenjdk/openjdk11:alpine-jre
CMD ["java", "-jar", "/app.jar"]
The java code running in the container is below.
ProcessBuilder builder = new ProcessBuilder("/bin/sh", "-c", "soffice --headless -convert-to pdf --outdir '/out' '/out/file.xlsx'");
Process process = builder.start();
The error message that is output is as follows.
line 1: soffice:not found
After installing the package in the Dockerfile, when I executed the which command, usr/bin/libreoffice existed, so I think the path is correct. (I may be wrong)
I'm thinking that there might be information that's missing but I'm not so sure since I'm a newbie with Docker.
Any help would be greatly appreciated.
The error says that /bin/sh does not know where the binary soffice is. The "soffice" binary must be on the PATH for /bin/sh. Launch a shell and check with which soffice, you may be able to fix your shell profile to include the correct PATH directories for soffice before your code will work:
ProcessBuilder builder = new ProcessBuilder("/bin/sh", "-c", "soffice --headless -convert-to pdf --outdir '/out' '/out/file.xlsx'");
But if you know the fully qualified path to the soffice binary you should be able to eliminate the use of sub-process shell and separate the command line arguments:
String soffice = "/full/path/to/soffice"; // eg /usr/lib/libreoffice/program/soffice.bin
// Check with:
System.out.println(soffice +" exists: "+new File(soffice).exists());
ProcessBuilder builder = new ProcessBuilder(soffice, "--headless", "-convert-to pdf", "--outdir", "/out", "/out/file.xlsx");
If "soffice" is in the PATH provided to your JVM, then launch without sub-process shell and path ought to work. You may be able to check which soffice before launching your Java application to see if this may work:
String soffice = "soffice";
ProcessBuilder builder = new ProcessBuilder(soffice, "--headless", "-convert-to pdf", "--outdir", "/out", "/out/file.xlsx");

Running/Sending CMD command in Java

I want to get rid of a .bat file in java and have the code post directly to CMD.
I have tried multiple variances of the below but i'm not getting it right.
The .bat file contains the following:
CD C:\"Program Files (x86)"\"UiPath Platform"\UIRobot.exe -file C:\ProgramData\UiPath\Projects\DM9\Main.xaml
I would like Java to post this directly to CMD instead.
Currently my code looks like:
String test = in.readUTF();
if (test.equals("Start"))
{
String[] command = {"cmd.exe", "/C", "Start", "C:Unipath\\start.bat"};
Process child = Runtime.getRuntime().exec(command);
}
Any advice?
Thanks in advance.
You haven't actually specified the problem, but I can run a batch file no problem without the cmd.exe argument. i.e. batch file
echo off
echo %1
can be run using
String[] command = {"test.bat", "HELLO"};
Process proc = Runtime.getRuntime().exec(command);
So I suspect your problem lies either with the cmd.exe argument or with the fact that your batch command doesn't seem to be valid
CD C:\"Program Files (x86)"\"UiPath Platform"\UIRobot.exe -file C:\ProgramData\UiPath\Projects\DM9\Main.xaml
Is this a Change Directory command with three arguments, a filename, a -file then another filename. Have you tested the batch file by itself?
Refer to this link for detailed example: Run Dos commands using JAVA
Courtesy of #akshay-pethani's answer in below question.
How do I execute Windows commands in Java?

How to run a jar file and launch terminal from java program?

I want to run jar file from my java program.
ProcessBuilder pb = new ProcessBuilder("java", "-jar", "parallel/Parallel.jar", "aug/*.xml");
Process p = pb.start();
BufferedReader in = new BufferedReader(new InputStreamReader(p.getInputStream()));
String s = "";
while((s = in.readLine()) != null){
System.out.println(s);
}
int status = p.waitFor();
System.out.println("Exited with status: " + status);
Here is the error log I get:
[33mProblem found trying to create the log file[0m
[31mCannot locate configuration source aug/*.xml[0m
[31mNo files to work with[0m
Exited with status: 1
Problem 1: I tried using a whole file name instead of the * and it works. But, I want to run the jar on ALL files under the directory.
Problem 2: When run, the jar file will ask for some input "continue" or "cancel". But the jar program just exits in the Eclipse console without giving me chance to input anything. So, I am wondering if there is a way to launch the jar file inside a terminal?
For 1.
aug/*.xml does not work that way because the unfolding of the wildcard is done by cmd/bash. If you want to use it that way your jar would need to be able to unfold that string itself or you would have to call it using cmd/bash.
It would be preferable letting your java program Parallel unfold this so that you do not loose portability.
For 2.
To run it from a terminal you could use ProcessBuilder or Runtime.exec()
Something like that on windows: (windows cmd needs the path or it will not resolve your wildcard)
Process process = Runtime.getRuntime().exec("cmd /k start java -jar <path>/Parallel.jar <path>/aug/*.xml");
"/k" keeps the terminal active. "start" opens the terminal instead of just executing the command.
With ProcessBuilder it should be something like:
ProcessBuilder pb = new ProcessBuilder("cmd", "/k", "start", "java", "-jar", "<path>/Parallel.jar", "<path>/aug/*.xml");
For bash it would be along that lines:
ProcessBuilder pb = new ProcessBuilder("sh", "-c", "java", "-jar", "<path>/Parallel.jar", "<path>/aug/*.xml");
For further reading about Processbuilder/Runtime.exec() I would suggest: http://www.javaworld.com/article/2071275/core-java/when-runtime-exec---won-t.html

Launching batch file from JAVA not working for directory path having spaces

I have created a batch file with the following contents
xcopy "C:\Documents\javascript\src\*" "C:\Program Files (x86)\Apache Group\Apache2\htdocs\docs\8.1\version1\" /s /y
I am running the batch file using Java. Running the script from command line or directly executing it(double clicking) doesn't seem to have any problem. However when I run using java the copy operation doesn't succeed. In the console I see a message More? when the script is executed.
Also running the copy operation for directory path without spaces seems to work fine.
Here is the java method which does the batch file running.
public void run(String input)
{
File dir = new File(input);
ProcessBuilder processBuilder = new ProcessBuilder("cmd");
processBuilder.redirectInput(dir);
Process process = processBuilder.start();
int exitStatus = process.waitFor();
process.destroy();
}
Any suggestions? Thanks in advance.
It depends on the way you are launching the bat file
for me this works fine:
Runtime.getRuntime().exec("cmd /c start xcopy-file.bat"

Does cmd always open a new window when you md

I am in the midst of a Java project, part of which is calling the Windows cmd to make a directory. My code currently looks like this:
Runtime rt = Runtime.getRuntime();
String command;
command = "cmd.exe /c start mkdir \"C:\\Users\\User1\\Documents\\Folder1\\"+folderName+"\" &&exit";
rt.exec(command);
This works fine (creates the folder), but it spawns an additional instance of cmd. (I originally added the "&&exit" thinking it would eliminate the extra window, but I now realize it is unnecessary code.)
1) Can I prevent this additional instance of cmd (which begins in the new directory), or
2) Can I close this extra cmd window without causing other problems? (I have heard that killing cmd can break other things on a machine.)
You should use:
File file = new File("C:\\Users\\User1\\Documents\\Folder1\\"+folderName+"\"");
if(!file.exists())
{
file.mkdir();
}
instead. However, if you want to call the command into cmd without creating a new one, you should not call "cmd.exe /c start". You can check that if you run that very same command from outside java it will also start a new cmd. Try this:
Runtime rt = Runtime.getRuntime();
String command;
command = "mkdir \"C:\\Users\\User1\\Documents\\Folder1\\"+folderName+"\" &&exit";
rt.exec(command);
Why don't you create the dir with File?
new File("C:\\my\\path\\myDir").mkdir();

Categories

Resources