Ubuntu giving permissions from java - 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

Related

Backing up MySQL database from java app

I'm trying to backup my MySQL database from my Java app.
Here's the code:
String executeCmd = "mysqldump.exe -u " + dbUser + " -p" + dbPass;
executeCmd += " --all-databases > " + savePath;
System.out.println(executeCmd);
Runtime.getRuntime().exec(executeCmd);
But it do nothing. If I copy output of System.out.println and paste it into cmd it works fine. Can someone say what's wrong in Java?
I strongly suggest that you read this canonical article on JavaWorld about Runtime.getRuntime(). The long story short, you have two major problems with your code. First, you are not waiting for the process to complete, and second you are not handling the output from that process. Taking the following code partially from the above article, we can write a version which should work:
try {
Runtime rt = Runtime.getRuntime();
String executeCmd = "mysqldump.exe -u " + dbUser + " -p" + dbPass;
executeCmd += " --all-databases > " + savePath;
Process proc = rt.exec(executeCmd);
InputStream stderr = proc.getErrorStream();
InputStreamReader isr = new InputStreamReader(stderr);
BufferedReader br = new BufferedReader(isr);
String line = null;
System.out.println("<ERROR>");
while ( (line = br.readLine()) != null)
System.out.println(line);
System.out.println("</ERROR>");
int exitVal = proc.waitFor();
System.out.println("Process exitValue: " + exitVal);
}
catch (Throwable t) {
t.printStackTrace();
}
If, as you say, the call to mysqldump is successful from the same machine where you are running this code, then there should be no error warnings. If there are any errors, then above snippet should put you in a good position to see what they are, and deal with them.
Try to use waitFor(), something like this.
public boolean backupDB(String dbName, String dbUserName, String dbPassword, String path) {
String executeCmd = "mysqldump.exe -u " + dbUserName + " -p "+dbPassword+" --all-databases > " + path;
Process runtimeProcess;
try {
runtimeProcess = Runtime.getRuntime().exec(executeCmd);
int processComplete = runtimeProcess.waitFor();
if (processComplete == 0) {
System.out.println("Backup created successfully");
return true;
} else {
System.out.println("Could not create the backup");
}
} catch (Exception ex) {
ex.printStackTrace();
}
return false;
}
Solved. Problem was in executeCmd.
It works this way:
String executeCmd = "mysqldump.exe -u " + dbUser + " -p" + dbPass+" dbName -r " + savePath;
I don't understand why it don't work with --all-databases, but problem solved. THX for all.

Using gcc directly with ProcessBuilder creates no output files

I'm trying to compile C source file with gcc using ProcessBuilder. I managed to make it running but there is no output file.
Here is my code (based on this answer) :
public void compileWithGccNoCmd(Path sourcePath) throws IOException {
String sourcePathString = sourcePath.toString();
String outputPathString = sourcePath.getParent().toString() + "\\" + Files.getNameWithoutExtension(sourcePath.toString());
try {
ProcessBuilder pb = new ProcessBuilder("gcc", "-fprofile-arcs -ftest-coverage -o " + outputPathString, sourcePathString);
pb.directory(sourcePath.getParent().toFile()); // this was added later
Process compile = pb.start();
compile.waitFor();
if (compile.exitValue() == -1) {
// if error
System.out.print("COMPILE ERROR");
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
My first thought that it has something to do with the working directory so I add pb.directory() but the output file still not there.
Since I can't find any solution to this, I tried another way by running gcc with cmd. I set the working directory to make sure the output files on the right place. This is the alternative code (based on this answer):
public void compileWithGcc(Path sourcePath) throws IOException {
String sourcePathString = sourcePath.toString();
String outputPathString = sourcePath.getParent().toString() + "\\" + Files.getNameWithoutExtension(sourcePath.toString());
ProcessBuilder pb;
try {
pb = new ProcessBuilder("cmd", "/C", "gcc " + sourcePathString + " -o " + outputPathString + " -fprofile-arcs -ftest-coverage");
pb.directory(sourcePath.getParent().toFile());
Process p = pb.start();
p.waitFor();
int x = p.exitValue();
} catch (Exception ex) {
ex.printStackTrace();
}
}
For some reason it works! Why is this happened? I'm pretty sure both is running gcc with the same parameter
This line:
ProcessBuilder pb = new ProcessBuilder("gcc", "-fprofile-arcs -ftest-coverage -o " + outputPathString, sourcePathString)
needs to look like this:
ProcessBuilder pb = new ProcessBuilder("gcc", "-fprofile-arcs", "-ftest-coverage", "-o", outputPathString, sourcePathString)
What you are doing with the first line is passing two arguments to gcc, one of which is "-fprofile-arcs -ftest-coverage -o " + outputPathString, instead of passing the five arguments of my edited line. gcc won't understand that.
When you use cmd like you did, it parses the command that you gave it and passes the arguments correctly, that's why it works.

Fail to execute linux command in RHEL using 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.");
}

Why do my Bash scripts stop?

Bellow is a Bash script that I create and execute through java. It utilises several different scripts to produce statistics for RNA-Seq data. My problem is that when the script is executed it reaches the second stage of the script before the processes stops (the program does not error out, the required programs just stop processing). I have tried running the created script separately from the command line and it completes with no errors. An suggestions would be appreciated.
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();
}
To All
Thankyou very much for your comments
I managed to solve the problem. I discovered it was a java memory limitation. I solved this by using the Xmx20000m command in the project properties in my IDE (netbeans).
this appears to have solved my problem.

Get Motherboard Serial/ID On Linux Machine With Java For Anti-Piracy Usage

I am using this code to get Motherboard ID in windows :
public static String getMotherboardSN() {
String result = "";
try {
File file = File.createTempFile("realhowto", ".vbs");
file.deleteOnExit();
FileWriter fw = new java.io.FileWriter(file);
String vbs = "Set objWMIService = GetObject(\"winmgmts:\\\\.\\root\\cimv2\")\n"
+ "Set colItems = objWMIService.ExecQuery _ \n"
+ " (\"Select * from Win32_BaseBoard\") \n"
+ "For Each objItem in colItems \n"
+ " Wscript.Echo objItem.SerialNumber \n"
+ " exit for ' do the first cpu only! \n" + "Next \n";
fw.write(vbs);
fw.close();
Process p = Runtime.getRuntime().exec(
"cscript //NoLogo " + file.getPath());
BufferedReader input = new BufferedReader(new InputStreamReader(p
.getInputStream()));
String line;
while ((line = input.readLine()) != null) {
result = line;
}
input.close();
} catch (Exception e) {
e.printStackTrace();
}
return result.trim();
}
Trying this code in ubuntu server throws an exception :
java.io.IOException: Cannot run program "cscript": error=2, No such file or directory
at java.lang.ProcessBuilder.start(ProcessBuilder.java:1029)
at java.lang.Runtime.exec(Runtime.java:615)
at java.lang.Runtime.exec(Runtime.java:448)
at java.lang.Runtime.exec(Runtime.java:345)
at tcs.util.MiscUtils.getMotherboardSN(MiscUtils.java:31)
at tcs.util.Validator.validate(Validator.java:13)
at test.Shoot.main(Shoot.java:31)
Caused by: java.io.IOException: error=2, No such file or directory
at java.lang.UNIXProcess.forkAndExec(Native Method)
at java.lang.UNIXProcess.<init>(UNIXProcess.java:135)
at java.lang.ProcessImpl.start(ProcessImpl.java:130)
at java.lang.ProcessBuilder.start(ProcessBuilder.java:1021)
I have googled about it but found no solution for linux . I also tried solutions here Printing my Mac's serial number in java using Unix commands and still no luck.
I am aware that there are solutions written in C/C++ but using JNI is not an option because we have no experience in it and cant meet the deadline on time.
any suggestions will be appreciated,
use "cscript" command with absolute path
FULL_PATH/cscript //NoLogo " + file.getPath())
example: /home/myprojext/cscript //NoLogo " + file.getPath())

Categories