Fail to execute linux command in RHEL using java - java

I had developed a java program that able to run the Linux command in Ubuntu, but when I try the same program in rhel, my code cant working,my code not able to execute the Linux command, but if I directly executed the command through the terminal,it's able to show the outputThis is the my sample program Do the Ubuntu having any different with RHEL ?I had checked my bash file for the rhel in under /usr/bin folder
String temp1 = "'/" + t1 + "/,/" + t2 + "/p'";
String command2 = "sed -n " + temp1 + "\t" + confstr2;
System.out.println( "The command2 is : " + command2 );
ProcessBuilder pb1 =
new ProcessBuilder(
"/usr/bin/bash",
"-c",
command2
).directory( new File( confstr3 ) );
Process p2 = pb1.start();
BufferedReader br2 = new BufferedReader( new InputStreamReader( p2.getInputStream() ) );
String line2;
File file1 = new File(confstr4);
if(file1.createNewFile()) {
System.out.println("File is created!");
}
else {
System.out.println("File already exists.");
}

Related

Stop a command run from exec in java from "stealing" colors

as the title suggests i am having troubles with colors with exec, what i am trying to do:
a simple GUI to start/stop mc servers, but when i run the command
java -Xmx1024M -Xms1024M -jar server.jar nogui
its not returning colors, though in the normal windows command prompt it returns colors just fine, i guess mc's color codes are the same for the command prompt and it is interpreting the colors as its own? The strange part for me is that it dosent return colors or color codes, just plain white text, i don't really need the text already colored, just the codes, here is what i got:
Process proc; // Process containing the server itself, i use this when stopping the server (stopping the server is not relevant but i tought id mention it)
File f = new File(path.getText()); // Path is a text field where i input the path to the server's folder
File bat = new File(f.getAbsolutePath() + File.separator + "run.bat"); // The .bat file containing the command
String cmd = ""; // Command to be executed
if(dotbat.exists()) {
cmd = bat.getAbsolutePath(); // Get the .bat with its path, resulting in the .bat file to be launched
} else {
cmd = "java -Xmx1024M -Xms1024M -jar server.jar nogui" // The command in case the .bat file dosent exist
}
proc = Runtime.getRuntime().exec(cmd, null, f); // Executing the command in the specified folder
BufferedReader br = new BufferedReader(new InputStreamReader(proc.getInputStream())); // Reading the input stream
String s = null;
while((s = br.readLine()) != null) {
textPane.setText(textPane.getText() + "\n" + s); // Append to the JTextPane the current line that the program is reading
}
To replicate this:
Put the code above in the main method of a java class, replace the part
String cmd = ""; // Command to be executed
if(dotbat.exists()) {
cmd = bat.getAbsolutePath();
} else {
cmd = "java -Xmx1024M -Xms1024M -jar server.jar nogui"
}
with:
cmd = "java -Xmx1024M -Xms1024M -jar server.jar nogui";
also replace:
File f = new File(path.getText());
File bat = new File(f.getAbsolutePath() + File.separator + "run.bat");
with:
File f = new File("Path\to\your\server");
and lastly, replace:
textPane.setText(textPane.getText() + "\n" + s);
with:
System.out.println(s);
Note: in case you want to use a text pane, leave the
textPane.setText(textPane.getText() + "\n" + s);
and just rename the textPane if you have a diff name
The final code you should have after replacing is:
Process proc; // Process containing the server itself, i use this when stopping the server (stopping the server is not relevant but i tought id mention it)
File f = new File("Path\to\Your\Server"); // The path to your server
String cmd = "java -Xmx1024M -Xms1024M -jar server.jar nogui";
proc = Runtime.getRuntime().exec(cmd, null, f); // Executing the command in the specified folder
BufferedReader br = new BufferedReader(new InputStreamReader(proc.getInputStream())); // Reading the input stream
String s = null;
while((s = br.readLine()) != null) {
//textPane.setText(textPane.getText() + "\n" + s);
System.out.println(s) // Use the line above if you want to use a text pane
}

Issues while Invoking Python process using java process builder

I am using java process builder to start python process with one flag and with one argument as shown below. But i don't see any exception nor process starts up.
Command i want to run is
python oc_db5.py -c input.json
location of file oc_db5.py is
/opt/jvision/grpc/gui
My code is shown below
processBuilder = new ProcessBuilder(
Arrays.asList(
"python",
"oc_db5.py",
"-c",
"input.json"));
processBuilder.directory(new File("/opt/jvision/grpc/gui"));
processBuilder.start();
logger.info("Process started ..." + new Date());
int count = 0;
BufferedReader br = new BufferedReader(new InputStreamReader(
process.getInputStream()));
while ((lineData = br.readLine()) != null) {
System.out.println("line: " + ++count + " " + lineData);
logger.info("line: " + ++count + " " + lineData);
}
process.waitFor();
process.getErrorStream();
process.waitFor();
process.exitValue();
I can see that log file contains entry "process start..." but i don't really see that process is started. Wondering what i am missing.
Can you check if python is in your PATH? I have similar problem with custom command long long time ago. You can use absolute path to try it :).
You can also check you enviromental variables via
Map env = System.getenv();
If you are using Linux you can start process like "sleep 1000" then check it is present in system process table via "ps aux | grep sleep" or something like it :)

Using `Runtime.getRuntime().exec()` to get the output from `top`

I'd like run the top -n 1 command using Runtime.getRuntime().exec(String) method and get the output of top -n 1 into my Java program.
I've tried the standard way of getting a processes output with a BufferedReader and using the returned Processes InputStream but that returned no data.
I also tried the following...
String path = "/home/user/Desktop/";
String cmd = "#!/bin/sh\ntop -n 1 > " + path + "output";
File shellCmd = new File(path + "topscript.sh");
PrintWriter writer = new PrintWriter(shellCmd);
writer.write(cmd);
writer.flush();
Runtime.getRuntime().exec("chmod +x " + shellCmd.getAbsolutePath());
Runtime.getRuntime().exec(shellCmd.getAbsolutePath());
Which creates the shell script and the output but the output is empty. However, if I then load up my local shell and run the script that the code above made, I get the correct output in the output file.
What's going wrong?
String cmd = "#!/bin/sh\ntop -n1 -b > " + path + "output";
File shellCmd = new File(path + "topscript.sh");
PrintWriter writer = new PrintWriter(shellCmd);
writer.write(cmd);
writer.flush();
Runtime.getRuntime().exec("chmod +x " + shellCmd.getAbsolutePath());
ProcessBuilder pb = new ProcessBuilder(shellCmd.getAbsolutePath());
Map<String, String> enviornments = pb.environment();
enviornments.put("TERM", "xterm-256color");
Process process = pb.start();
BufferedReader inputStreamReader = new BufferedReader(new InputStreamReader(process.getInputStream()));
BufferedReader errorStreamReader = new BufferedReader(new InputStreamReader(process.getErrorStream()));
String str = inputStreamReader.readLine();
System.out.println(str);
System.out.println(errorStreamReader.readLine());
Use ProcessBuilder with setting TERM variables.
and if want to redirect top to file. need to add -b option to avoid error: initializing curses.

Open a cmd window and issue multiple commands

I have to open (or execute in the background) a cmd window out of my java application. It did this before and it worked totally fine:
public String getEnvVar(String envVarName) throws Exception {
String varName = "%" + envVarName + "%";
Process process = Runtime.getRuntime().exec(
new String[]{"cmd.exe", "/C", "echo " + varName}
);
BufferedReader input = new BufferedReader(
new InputStreamReader(process.getInputStream())
);
varName = input.readLine();
process.destroy();
...
My problem is: I have a different instance of a different class and tried to open a cmd window just the way it is done in the code above:
private void execute() {
try {
String batchData = batchContent();
Process process = Runtime.getRuntime().exec(new String[]{"cmd.exe", "/C", batchData});
new File(sourceFile).delete();
new File(sourceFolder).delete();
process.destroy();
} catch (IOException ie) {
}
}
But this doesn't work...I used google to figure out why, couldn't find a real reason for this.
Even
Process process = Runtime.getRuntime().exec(new String[]{"cmd.exe", "cd c:\\temp"});
does not change into the temp folder (which i created beforehand for testing reasons)
What's wrong?
EDIT//
I now tried:
private void upload() {
try {
//Process process = Runtime.getRuntime().exec(batchDataFile);
//Process process = Runtime.getRuntime().exec("cmd.exe /C " + batchDataFile);
Process process = Runtime.getRuntime().exec("cmd.exe /C " + "\"" + batchDataFile + "\"");
//new File(sourceCodeFile).delete();
//new File(batchDataFile).delete();
//new File(sourceCodeFolder).delete();
process.destroy();
} catch (IOException ie) {
ie.printStackTrace();
}
}
I additionally tried to run the generated batch skript without the Java app, it works as intended

Ubuntu giving permissions from java

This is one of a few Bash scripts I create in my pipeline. My Difficulty is I would like to make the created file executable without the user having to enter into the terminal "sudo chmod 777 /file/path/"
String Trans_ref =
"#!/bin/bash \n" +
"mkdir -p "+Output+"/"+Sample+"_RSEM \n" +
"cd "+Output+"/"+Sample+"_RSEM \n" +
"PATH=$PATH:"+RSEMprep+" \n" +
"export PATH=$PATH \n" +
""+RSEMprep+"/rsem-prepare-reference --no-polyA --bowtie "+Output+"/Trans_CDHIT.fast Trans_CDHIT.RSEM \n" +
""+RSEMprep+"/rsem-calculate-expression --paired-end -p "+CPU+" "+Output+"/SRR617145_1.fastq "+Output+"/SRR617145_2.fastq Trans_CDHIT.RSEM Trans_CDHIT.genes.results \n"+
""+Trinprep+"/util/misc/count_features_given_MIN_FPKM_threshold.pl "+Output+"/"+Sample+"_RSEM/RSEM.genes.results > "+Output+"/"+Sample+"_RSEM/cumul_counts.txt \n"+
""+Trinprep+"/util/filter_fasta_by_rsem_values.pl --rsem_output= "+Output+"/"+Sample+"_RSEM/RSEM.isoforms.results --fasta="+Output+"/Trans_CDHIT.fasta -t 100 --output="+Output+"/"+Sample+"_RSEM/Trans_RSEMfilters.fasta \n" +
""+Trinprep+"/util/bowtie_PE_separate_then_join.pl --seqType fq --left "+Output+"/"+Sample+"_1.fasta --right "+Output+"/"+Sample+"_2.fasta --target "+Output+"/Trans_CDHIT.fasta --aligner bowtie --SS_lib_type FR -- -p 4 --all --best --strata -m 300 \n";
System.out.println(Trans_ref);
FileUtils.writeStringToFile(new File(Output+"/TranRSEM"), Trans_ref);
StringBuffer Trim = new StringBuffer();
String cmd = (Output+"/TranRSEM");
Process p;
try{
p = Runtime.getRuntime().exec(new String[]{"/bin/sh","-c", cmd});
p.waitFor();
BufferedReader reader1 =
new BufferedReader(new InputStreamReader(p.getInputStream()));
System.out.println("Merg Finished");
} catch (Exception e) {
e.printStackTrace();
}
many thanks
There are a couple ways, but the best would be to use SetExecutable
once you created the file. It would look something like this.
if (file.exists()) {
boolean bval = file.setExecutable(true);
..... set the owner's execute permission
} else {
...... File does not exist;
}
if (file.exists()) {
boolean bval = file.setExecutable(true, false);
..... set everybody's execute permission
} else {
...... File does not exist;
}
Hope this helps

Categories