My Eclipse version is Photon and docker version is 18.06.0-ce-mac70.
I want to execute the Docker command when I issue shell script commands on Eclipse.
But when I use a shell script, the ls command works well, but not docker + command
Error Stack trace :
`Exception in thread "main" java.io.IOException: Cannot run program
"docker": error=2, No such file or directory
at java.base/java.lang.ProcessBuilder.start(ProcessBuilder.java:1128)
at java.base/java.lang.ProcessBuilder.start(ProcessBuilder.java:1071)
at java.base/java.lang.Runtime.exec(Runtime.java:635)
at java.base/java.lang.Runtime.exec(Runtime.java:459)
at java.base/java.lang.Runtime.exec(Runtime.java:356)
at dbUpdate.ShellCommander.shellCmd1(ShellCommander.java:36)
at dbUpdate.ShellCommander.main(ShellCommander.java:29)
Caused by: java.io.IOException: error=2, No such file or directory
at java.base/java.lang.ProcessImpl.forkAndExec(Native Method)
at java.base/java.lang.ProcessImpl.<init>(ProcessImpl.java:339)
at java.base/java.lang.ProcessImpl.start(ProcessImpl.java:270)
at java.base/java.lang.ProcessBuilder.start(ProcessBuilder.java:1107)
... 6 more
And the code:
`package dbUpdate;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Scanner;`
public class ShellCommander {
static Scanner sc = new Scanner(System.in);
static String carSSID;
static String target;
static String IPAddress;
public static void main(String[] args) throws Exception {
String command = "docker ps";
shellCmd1(command);
}
public static void shellCmd1(String command) throws Exception {
Runtime runtime = Runtime.getRuntime();
Process process = runtime.exec(command);
InputStream is = process.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String line;
while((line = br.readLine()) != null) {
System.out.println(line);
}
}
}
Java doesn't search your PATH for commands. On my mac docker is in /usr/local/bin; I also would prefer a ProcessBuilder over Runtime.exec. Like
public static void main(String[] args) throws Exception {
String command = "/usr/local/bin/docker ps";
shellCmd1(command);
}
public static void shellCmd1(String command) throws Exception {
ProcessBuilder pb = new ProcessBuilder(command.split("\\s+"));
pb.inheritIO();
Process p = pb.start();
p.waitFor();
}
Related
In my idea IDE, I can see the compile error with red font in the console.But when I deploy the jar in the linux server.I can not see the compile log.How to print the compile error log?
public static void main(String[] args) throws Exception {
String compliePath="D:\\testFole";
String filename="D:\\test.java";
String[] arg = new String[] { "-d", compliePath, filename };
System.out.println(com.sun.tools.javac.Main.compile(arg));
}
Well if I got your question right, here is an approach to the outcome.
I think this will be platform-independent.
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
public class Main {
private static Process process;
public static void main(String[] args) {
runCommand();
getErrorMessage();
}
/**
* This method executes/runs the commands
*/
private static void runCommand()
{
File file = new File("D:\\\\test.java");
String changeDirectory = "cmd start cmd.exe /c cd D:\\";
String compile = " && javac D:\\test.java";
String run = " && java "+file.getName().replace(".java","");
String command = changeDirectory + compile + run;
try {
process = Runtime.getRuntime().exec(command);
}catch (IOException e){}
}
/**
* This method will get the errorStream from process
* and output it on the console.
*/
private static void getErrorMessage()
{
try (BufferedReader errorReader = new BufferedReader(new InputStreamReader(process.getErrorStream())))
{
String line;
if(errorReader.readLine() != null)
while ((line = errorReader.readLine()) != null)
System.out.println(line); //display error message
}catch (IOException e){}
}
}
I'm trying to write my first program in java. It's purpose is to root and unroot my Nexus 6P which I can do all in terminal with adb and fastboot, but I want to make a program that I can run and have menus of sorts. I found a way to execute commands weather it be batch, or bash (I use both Windows and Linux). My main class is
class main{
public static void main(String[] args){
String version = "0.0.1";
String commandIn = "adb";
int OSType = OSValidator.sys();
ExecuteShellCommand.main(commandIn);
System.out.println("Welcome to Nexus Tools: " + version);
System.out.println("This program will help you Root and UnRoot your Google Nexus 6P");
It does not make it past the ExecuteShellCommand it just stops.
Here is the ExecuteShellCommand class I found online and slightly changed
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class ExecuteShellCommand {
public static void main(String inputCommand) {
ExecuteShellCommand obj = new ExecuteShellCommand();
String command = inputCommand;
String output = obj.executeCommand(command);
System.out.println(output);
}
private String executeCommand(String command) {
StringBuffer output = new StringBuffer();
Process p;
try {
p = Runtime.getRuntime().exec(command);
p.waitFor();
BufferedReader reader =
new BufferedReader(new InputStreamReader(p.getInputStream()));
String line = "";
while ((line = reader.readLine())!= null) {
output.append(line + "\n");
}
} catch (Exception e) {
e.printStackTrace();
}
return output.toString();
}
}
the program just stops and I dont know whats going wrong.
For example, I've test.pptx open in Microsoft PowerPoint 2013 on Windows 10. I want to close it without closing Microsoft PowerPoint itself. How can I do that using Java 1.8?
Because it's external program, you need to kill your PC running power point task.
You can achieve it by using below Java code:
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class ClosePowerPoint {
private static final String TASKLIST = "tasklist";
private static final String KILL = "taskkill /IM ";
public static void main(String args[]) throws Exception {
System.out.print(isProcessRunging("POWERPNT.EXE"));
if (isProcessRunging(processName)) {
killProcess(processName);
}
}
public static boolean isProcessRunging(String serviceName) throws Exception {
Process p = Runtime.getRuntime().exec(TASKLIST);
BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
if (line.contains(serviceName)) {
return true;
}
}
return false;
}
public static void killProcess(String serviceName) throws Exception {
Runtime.getRuntime().exec(KILL + serviceName);
}
}
TestClass.java
package test;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class TestClass {
public static void main(String[] args) throws IOException {
System.out.println("inside");
ProcessBuilder pb = new ProcessBuilder("java", "-cp", "", "test.OtherClass");
Process p = pb.start();
BufferedReader reader = new BufferedReader(new InputStreamReader(p.getErrorStream()));
StringBuilder builder = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
builder.append(line);
builder.append(System.getProperty("line.separator"));
}
String result = builder.toString();
System.out.println(result);
}
}
OtherClass.java
package test;
public class OtherClass {
public static void main(String ar[]) {
System.out.println("Hello Amit!");
}
}
I am trying to run OtherClass from TestClass, but I am not able to do it. Running TestClass just prints "inside". I am not getting any exception and I am clueless right now.
I am implementing ProcessBuilder for the first time.
NOTE: I was able to run simple program using ProcessBuilder.
Also Can you tell what is meaning of -cp; I googled a lot but could not find its meaning.
EDIT:
I have updated code and now I am getting
inside
Error: Could not find or load main class test.OtherClass
Thanks!
Its likely to be the classpath.
Assuming you have a directory called test, Have you tried something like:
ProcessBuilder pb = new ProcessBuilder("java", "-cp", ".", "test.OtherClass");
I have a shell script like this.
#!/bin/sh
/home/hduser/Downloads/hadoop/bin/stop-all.sh
echo "RUNNING HADOOP PROGRAM"
cd /home/hduser/Downloads/hadoop
sudo rm -R /tmp/*
sudo rm -R /app/*
cd
sudo mkdir -p /app/hadoop/tmp
sudo chown hduser:hadoop /app/hadoop/tmp
sudo chmod 750 /app/hadoop/tmp
hadoop namenode -format
/home/hduser/Downloads/hadoop/bin/start-all.sh
jps
hadoop dfs -mkdir -p ~/Downloads/hadoop/input
hadoop dfs -copyFromLocal /home/hduser/Desktop/iris.arff ~/Downloads/hadoop/input
hadoop jar ~/Desktop/try.jar 2 weka.classifiers.trees.J48 ~/Downloads/hadoop/input ~/Downloads/hadoop/output
/home/hduser/Downloads/hadoop/bin/stop-all.sh
I am invoking this script in my java program like this
public class UIinput
{
public static void main(String[] args) throws IOException
{
// Runtime.getRuntime().exec("/home/hduser/Desktop/initial.sh");
new ProcessBuilder("/home/hduser/Desktop/initial.sh");
ProcessBuilder pb = new ProcessBuilder("/home/hduser/Desktop/initial.sh");
Process process=pb.start();
InputStream is = process.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String line;
System.out.printf("Output of running %s is:",
Arrays.toString(args));
while ((line = br.readLine()) != null)
{
System.out.println(line);
}
}
}
My start-all.sh,stop-all.sh and echo commands That are getting executed present in the script are getting executed but other commands are not.My output is like
Output of running [] is:no jobtracker to stop
localhost: no tasktracker to stop
no namenode to stop
localhost: no datanode to stop
localhost: no secondarynamenode to stop
RUNNING HADOOP PROGRAM
starting namenode, logging to /home/hduser/Downloads/hadoop/libexec/../logs/hadoop-hduser-namenode-ubuntu.out
localhost: starting datanode, logging to /home/hduser/Downloads/hadoop/libexec/../logs/hadoop-hduser-datanode-ubuntu.out
localhost: starting secondarynamenode, logging to /home/hduser/Downloads/hadoop/libexec/../logs/hadoop-hduser-secondarynamenode-ubuntu.out
starting jobtracker, logging to /home/hduser/Downloads/hadoop/libexec/../logs/hadoop-hduser-jobtracker-ubuntu.out
localhost: starting tasktracker, logging to /home/hduser/Downloads/hadoop/libexec/../logs/hadoop-hduser-tasktracker-ubuntu.out
stopping jobtracker
localhost: stopping tasktracker
no namenode to stop
Can anyone help me?I when I run my java code i want all of the commands to be executed in the shell script.
Thank you
Run your script with below code and see the problem details in system out
package test;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
public class CommandLineExecutor {
public final int EXEC_OK = 0;
public final int EXEC_FAILED = 1;
public static void main(String[] args) {
CommandLineExecutor cmd = new CommandLineExecutor();
String[] script = new String[]{ "/home/hduser/Desktop/initial.sh"};
boolean joinToProcess = true; //Main threads waits process finished.
int result = cmd.execute(script, joinToProcess);
System.out.println( result == 0 ? "Script succesfully run" : "Script failed" );
}
public int execute(String[] cmd, boolean joinToProcess) {
Runtime runtime = Runtime.getRuntime();
Process proc = null;
try {
System.out.println("executing cmd: "+concat(cmd));
proc = runtime.exec(cmd);
StreamProcessor errorStreamProcessor = new StreamProcessor(proc.getErrorStream());
StreamProcessor outputStreamProcessor = new StreamProcessor(proc.getInputStream());
errorStreamProcessor.start();
outputStreamProcessor.start();
} catch (Exception e) {
e.printStackTrace(System.out);
return EXEC_FAILED;
}
try {
int result = EXEC_OK;
if(joinToProcess)
result = proc.waitFor();
return result;
} catch (InterruptedException e) {
System.out.println("Error at executing command: " + concat(cmd) );
e.printStackTrace(System.out);
}
return EXEC_FAILED;
}
public static String concat(String[] array) {
StringBuffer buffer = new StringBuffer();
for (int i = 0; i < array.length; i++) {
if (i > 0)
buffer.append(' ');
buffer.append(array[i]);
}
return buffer.toString();
}
class StreamProcessor extends Thread {
private InputStream inputStream;
public StreamProcessor(InputStream is) {
this.inputStream = is;
}
public void run() {
try {
InputStreamReader isr = new InputStreamReader(inputStream);
BufferedReader br = new BufferedReader(isr);
while (true) {
String s = br.readLine();
if (s == null)
break;
System.out.println(s);
}
} catch (IOException e) {
e.printStackTrace(System.out);
}
}
}
}