How to load bashrc in java program and execute command - java

public CGAOperationStatus downloadMetaData() {
CGAOperationStatus retCgaOperationStatus = new CGAOperationStatus();
try {
createDirectoryIfNeeded("/sure/replication/metadata");
String prepareRsyncCommand = "gsutil -m rsync -d -r gs://"
+ storeCredentials.getStoreAccount()
+ "/sure/metadata /sure/replication/metadata'";
Process p = Runtime.getRuntime().exec(prepareRsyncCommand);
p.waitFor();
} catch (Exception e) {
System.out.print("Exception in downloading metadata from GoogleBucket");
retCgaOperationStatus
.setScgaError(CGAError.SCGA_EXCEPTION_OCCURRED);
ExceptionHandler.logException(logger, e);
retCgaOperationStatus.setErrorMessage(e.getMessage());
}
return retCgaOperationStatus;
}
I have installed and Gcloud SDK on linux machine and i am trying to run gsutil command from a Jar File and my jar is executed from some outside program over ssh . But it just not working.
If i am running same command manually it works fine. May be because .bashrc is loaded when i am running command.
How can i do same thing from java.

You should use a String[] instead of a simple String as a parameter in the call to Runtime.
Runtime.getRuntime().exec(new String[]{"gsutil", "-m", "rsync", "-d", "-r", "gs://"+ storeCredentials.getStoreAccount(), "/sure/metadata /sure/replication/metadata'"});

Related

How can I start a .jar in xterm with args?

if (args.length == 0&&runningFromIntelliJ()==false) {
String OS = System.getProperty("os.name", "generic").toLowerCase(Locale.ENGLISH);
if (OS.indexOf("win") >= 0) {
String path = CODE.run.class.getProtectionDomain().getCodeSource().getLocation().getPath().substring(1);
String decodedPath = null;
try {
decodedPath = URLDecoder.decode(path, "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
try {
Runtime.getRuntime().exec("cmd"+" /c start java -jar \"" + decodedPath + "\" run");
} catch (IOException e) {
e.printStackTrace();
}
System.exit(0);
}
}
}
This Code is Starting a programm in cmd after i double clicked it. the problem is that it only works in windows And I want to run it on my raspberry pi. The problem now is that I habe no Idea how a can start a .jar with args in xterm.
runningFromIntelliJ() is just testing if I am running the programm in IntelliJ and skips that part if I do.
It seems like your app will do nothing once there's an argument passed to the jar.
if(args.length==0)
will be false hence the whole if. If you have other code to run with Arguments, try this:
java -jar yourJar.jar "arg 1" arg2#
Otherwise, review your code.
Here is one way to start a program with xterm.
xterm -hold -e '/bin/bash -c "ls -l"'
In this example, the program is simply the ls command, but it should be self-explanatory how to use it for java; just use the example found in another answer.
In your java code, what that looks like is:
Runtime.getRuntime().exec(String.format("xterm -hold -e '/bin/bash -c \"%s\"'", "java -jar '" + decodedPath + "' run"));
or without a shell:
Runtime.getRuntime().exec(String.format("xterm -hold -e 'java -jar \"%s\" run'", decodedPath));

How can I use either Runtime.exec() or ProcessBuilder to open google chrome through its pathname?

I am writing a java code that has the purpose of opening a URL on youtube using Google Chrome but I have been unsuccessful in understanding either method. Here is my current attempt at it.
import java.lang.ProcessBuilder;
import java.util.ArrayList;
public class processTest
{
public static void main(String[] args)
{
ArrayList<String> commands = new ArrayList<>();
commands.add("cd C:/Program Files/Google/Chrome/Application");
commands.add("chrome.exe youtube.com");
ProcessBuilder executeCommands = new ProcessBuilder( "C:/WINDOWS/System32/WindowsPowerShell/v1.0/powershell.exe", "cd C:/Program Files/Google/Chrome/Application", "chrome.exe youtube.com");
}
}
It compiles OK, but nothing happens when I run it. What is the deal?
As stated by Jim Garrison, ProcessBuilder's constructor only executes a single command. And you do not need to navigate through the directories to reach the executable.
Two possible solutions for your problem (Valid for my Windows 7, be sure to replace your Chrome path if neccesary)
With ProcessBuilder using constructor with two parameters: command, argument (to be passed to command)
try {
ProcessBuilder pb =
new ProcessBuilder(
"C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe",
"youtube.com");
pb.start();
System.out.println("Google Chrome launched!");
} catch (IOException e) {
e.printStackTrace();
}
With Runtime using method exec with one parameter, a String array. First element is the command, following elements are used as arguments for such command.
try {
Runtime.getRuntime().exec(
new String[]{"C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe",
"youtube.com"});
System.out.println("Google Chrome launched!");
} catch (Exception e) {
e.printStackTrace();
}
you shoule invoke start method to execute the operation, like this:
ProcessBuilder executeCommands = new ProcessBuilder( "C:/WINDOWS/System32/WindowsPowerShell/v1.0/powershell.exe", "cd C:/Program Files/Google/Chrome/Application", "chrome.exe youtube.com");
executeCommands.start();

how to execute the linux terminal custom command using java

I have binary of engine already developed with Hadoop(HDFS,HBASE,MAPREDUCE) and java which is use to generate CSV file. There are some operation performed by this engine like table creation in HBASE and generating the CSV File from this HBASE. But this engine is performed all operation through only command line , as input is given from Linux terminal in form of command. Now my requirement is to connect this Linux terminal Through java program and run the commands But I am not able to successfully run any of the command
There are two option I tried but none of them successfully worked. Please provide any suggestion or solution to solve this problem as I am just beginner of Linux and hadoop to figure out the problem
1st-way
public class EngineTest {
public static void main(String[] args) {
try {
Process process = Runtime
.getRuntime()
.exec("/home/cloudera/PVGproto/Base/ anloss -i ${TOOL_INPUT}/census_10000_col5.csv -d ${TOOL_DEF}/attr_all_def.txt -q k=14,dage=2 -g ${TOOL_RES}/census_100_col8_gen.csv");
process.waitFor();
BufferedReader bufferedReader = new BufferedReader(
new InputStreamReader(process.getInputStream()));
String line = "";
String output = "";
while ((line = bufferedReader.readLine()) != null) {
output += line + "\n";
}
System.out.println(output);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
2nd-way
I made one ex.sh file, in this file I put the required command for execution and call this . sh file from the same java program but the same thing happened its not running the command through java program
Process process = Runtime.getRuntime().exec("/home/cloudera/PVGproto/Base/ex.sh");
but if I run the same ex.sh from Linux terminal its running all the command successfully.
ex.sh
# !/bin/bash
exec /home/cloudera/PVGproto/Base/ anloss -i ${TOOL_INPUT}/census_10000_col5.csv -d ${TOOL_DEF}/attr_all_def.txt -q k=14,age=2 -g ${TOOL_RES}/census_100_col8_gen.csv
echo command run successfully

How to run sh script from jenkins

I need launch sh script from jenkins, it is simple, but my script change symlink for JAVA_HOME, in fact im switching between JDK versions using sh script. It works when Im launching job without jenkins(job writen on bash), but it does not working under jenkins... Jenkins remember JAVA_HOME after start and use this path... how can I change JAVA_HOME from sh script under jenkins ? may be from script invoke jenkins reload config if it's possible... thx for any help!
Just try as below ;
public static void execShellCmd(String cmd) {
try {
Runtime runtime = Runtime.getRuntime();
Process process = runtime.exec(new String[] { "/bin/bash", "-c", cmd });
int exitValue = process.waitFor();
System.out.println("exit value: " + exitValue);
BufferedReader buf = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line = "";
while ((line = buf.readLine()) != null) {
System.out.println("exec response: " + line);
}
} catch (Exception e) {
System.out.println(e);
}
}
For more details : Shell Script Running with java
Problem solved!!! soulution is simple, I have sh script that was launched in jenkins job like this:
./MY_SCRIPT.sh
And after that script launched under jenkins and I had problems with switching JAVA_HOME.
All is need to do launch script like this:
sh MY_SCRIPT.sh
and it will launched smt like from the system.

Firing command using java runtime class on a windows machine

I am trying to fire the following command on a windows(that came as part of a product we have bought):
start /wait setup /z"/sfC:\temp\input_file.txt" /s /f2"C:\temp\newlogfile.log"
Now the sad part is that I am failing to run the command using a java program that I wrote. (I have to run it as a part of something else, hence the need of running it through java)
Here is my code:
String[] cmd = new String [6];
cmd[0] = "start";
cmd[1] = "/wait";
cmd[2] = "setup";
cmd[3] = "/z\"/sfC:\\temp\\input_file.txt\"";
cmd[4] = "/s";
cmd[5] = "/f2\"C:\\temp\\newlogfile.log\"";
try
{
Runtime.getRuntime().exec(cmd);
}
catch(IOException e)
{
e.printStackTrace();
}
Please tell me what I am doing wrong here.
This is the output I am getting:
java.io.IOException: CreateProcess: start /wait setup /z"/sfC:\temp\input_file.txt" /s /f2"C:\temp\newlogfile.log" error=2
at java.lang.ProcessImpl.create(Native Method)
at java.lang.ProcessImpl.<init>(ProcessImpl.java:108)
at java.lang.ProcessImpl.start(ProcessImpl.java:56)
at java.lang.ProcessBuilder.start(ProcessBuilder.java:466)
at java.lang.Runtime.exec(Runtime.java:607)
at java.lang.Runtime.exec(Runtime.java:480)
at SilentAgent.fireCommand(SilentAgent.java:316)
at mainClass.main(mainClass.java:15)
Try with this:
String[] cmd = {
"cmd.exe",
"/c",
"start",
"/wait",
"setup",
"/z\"/sfC:\\temp\\input_file.txt\"",
"/s",
"/f2\"C:\\temp\\newlogfile.log\""
};
Runtime.getRuntime().exec(cmd);
Reason: start is an internal command available only from inside a cmd shell.
Do this way:-
Runtime.getRuntime().exec(new String[] {
"start ",
"/wait ",
"setup ",
"/z\"/sfC:/temp/input_file.txt\" ",
"/s ",
"/f2\"C:/temp/newlogfile.log\""});
Are you sure that you java program is located in the same directory of the 'start' program?
If not, pass the command string as a whole string
try {
String command = "start /wait setup /z\"/sfC:\\temp\\input_file.txt\" /s /f2\"C:\\temp\\newlogfile.log\"";
// The third parameter is the current working directory
Process p = runtime.exec(c, null, new File());
} catch (Exception e) {
e.printStackTrace();
}

Categories

Resources