How to run a docker image from java Program? - java

I'm trying to run an Ubuntu image from a java program using a script; here is how:
my java code:
public static void main(String[] args) {
executeCommand("/home/abrahem/IdeaProjects/untitled3/src/createContainer.sh");
}
public static void executeCommand(String filePath) {
File file = new File(filePath);
if (!file.isFile()) {
throw new IllegalArgumentException("The file " + filePath + " does not exist");
}
try {
if (isLinux()) {
Process p = Runtime.getRuntime().exec("sh " + filePath);
p.waitFor(); // i tried to remove this but still not work for my me
} else if (isWindows()) {
Runtime.getRuntime().exec("cmd /c start " + filePath);
}
} catch (InterruptedException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
here is my createContainer.sh script file:
#!bin/sh
sudo docker run ubuntu
when I go to bin and type:
docker ps
or
docker ps -a
It should show the running Ubuntu container, but it doesn't.
Note: there is nothing wrong with the shell location; I try to create file in shell file and it works.

You do not capture any error messages or normal output from your process. Maybe it just works?
Use getErrorStream() and getOutputStream() methods of Process to capture the output from the process somewhat like described here. You may just see the expected output. If not, it should be the error message on the error stream.

Related

JAVA: Fail to launch batch file as as Adminstrator (File with Run as Adminstrator config)

I want launch a batch file with JAVA. So I create a shortcut to this file and config Run as Administrator. I tested the batch file and it run success. But when, I run it with java, the batch file don't run with Administrator and the request is denied.
In java source, I try to call a shortcut of cmd.exe with shortcut configed Run as Administrator. And java source open the commandline with Administrator success.
Please help me.
Here my code:
package testfp;
import java.io.*;
public class RunCommand {
String command,result;
public RunCommand(String command) {
this.command = command;
run();
System.out.println(this.result);
}
public void run() {
try
{
Process process = Runtime.getRuntime().exec("cmd /c start C:\\Users\\minhlc\\Desktop\\test\\CMD");
// Fail to open with Administrator
// Process process = Runtime.getRuntime().exec("cmd /c start C:\\Users\\minhlc\\Desktop\\test\\start_apache");
// process.destroy();
// Process process = Runtime.getRuntime().exec("cmd /c start");
// kill_process();
BufferedReader br = new BufferedReader(
new InputStreamReader(process.getInputStream()));
String line;
try {
while ((line = br.readLine()) != null) {
this.result = this.result + "\n" + line;
}
} finally {
// br.close();
};
} catch (IOException e)
{
e.printStackTrace();
}
}
public void kill_process()
{
try {
Runtime.getRuntime().exec("taskkill /f /im cmd.exe") ;
} catch (Exception e) {
e.printStackTrace();
}
}
public String get_result() {
return result;
}
}
Thank for reading.
You need to run the java process with an administration privilege.
Open command line with "Run as administrator" and then
java -jar you_app.jar

Could not load main class when compiled and executed with Runtime.exec()

I have the following code to run three executions :
public static void main(String[] args) throws InterruptedException, IOException
{
String filepath1 = "cmd /c gradlew jmhJar";
String filepath2 = "cmd /c java -jar path/to/the/file/filename.jar -rf csv -rff path/to/save/file1.csv -wi 3 -i 5 -f 2";
String filepath4 = "cmd /c javac path/to/the/file/ParserHash.java";/*Code to compile is parserHash.java*/
String filepath3 = "cmd /c java path/to/the/compiled/class/ParserHash "C:/Users/msek/Desktop/trial/result/file1.csv C:/Users/msek/Desktop/trial/result/file2.csv C:/Users/msek/Desktop/trial/result/file3.csv";
try
{
runProcess(filepath1);
runProcess(filepath2);
System.out.println("Sucessfully written into file1.csv");
runProcess(filepath4);
System.out.println("Compilation Over");
runProcess(filepath3);
System.out.println("Program Sucessfully Executed");
}
catch (Exception e)
{
e.printStackTrace();
}
}
public static void runProcess(String processString)
{
try
{
final Process p = Runtime.getRuntime().exec(processString);
new Thread(new Runnable() {
public void run() {
BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line = null;
try {
while ((line = input.readLine()) != null)
System.out.println(line);
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
p.waitFor();
}
catch (Exception x)
{
x.printStackTrace();
}
}
If I compile the java file going to that particular directory and compile its compiling successfully and on running it, it executes successfully. But if I pass it like "cmd /c path/to/java/file/file.java" its getting compiled but when I execute it, I get an error stating that could not find or load mainclass eventhough class file is present.
I have looked various links on this which suggested buid process, but that didn't work.
I just want to know where I'm going wrong and how to compile, execute a java file by passing multiple arguments using Runtime.exec()..
java path/to/the/compiled/class/ParserHash
If you're having trouble with an exec() you should:
Try the command from a command line yourself. It will fail the same way in this case.
Look up the syntax of the command. In this case you will learn that the argument to the java command is not a path but a class name, fully qualified, i.e. including the package name. With dots.

Running cmd command from java using process builder

I am trying to convert an HTML file to pdf and view it using my pdf viewer(vsmartpdf.exe).Its a cmd command which goes like "vmartpdf.exe -c 'path of html file' 'path of output folder' ". I am trying to execute this command using java program . Below is what i did.
import java.io.IOException;
public class LoadTesting implements Runnable {
#Override
public void run() {
try {
//String command = "C:\\Users\\vishalt\\Desktop\\New Source\\deliver\\vsmartpdf\\vsmartpdf.exe";
//Runtime.getRuntime().exec("cmd /c "+command);
//Process process = new ProcessBuilder("cmd.exe", "/c", "cd \"C:\\Users\\vishalt\\Vsmartfinal\" && dir").start();
Runtime rt = Runtime.getRuntime();
String[] cmd = { "C:\\Users\\Desktop\\Vsmartfinal\\vsmartpdf.exe", "-c", "C:\\Users\\vishalt\\Desktop\\output\\SCB_MOLPU.HTML", " C:\\Users\\vishalt\\Desktop\\output\\"};
Process p = rt.exec(cmd);
System.out.println("Called");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
then i am calling this thread . But i am getting error as
CreateProcess error=2, The system cannot find the file specified.
Can somebody please help me with it
The error message means that C:\Users\Desktop\Vsmartfinal\vsmartpdf.exe doesn't exist at the time when the code is executed.
A common source for this problem is that this executable exists in a developer machine but not on the production server.

Is it possible to execute a Java code string at runtime in Android?

I want to get a line of Java code from user and execute it in Android. For example:
String strExecutable = " int var; var = 4 + 3"
Object obj = aLibrary.eval(strExecutable);
It is not java script and I want to run a java code.
Is it possible? If yes how?
I have studied links like this. But they are questions about JVM not Android Dalvik.
You can try BeanShell! It's super easy and works also on android. Just build your app with jar library.
import bsh.Interpreter;
private void runString(String code){
Interpreter interpreter = new Interpreter();
try {
interpreter.set("context", this);//set any variable, you can refer to it directly from string
interpreter.eval(code);//execute code
}
catch (Exception e){//handle exception
e.printStackTrace();
}
}
But be careful! Using this in production app may be security risk,
especially if your app interacts with users data / files.
You can try something like this:
// Code Execute, Khaled A Khunaifer, 27 March 2013
class CodeExcute
{
public static void execute (String[] commands, String[] headers)
{
// build commands into new java file
try
{
FileWriter fstream = new FileWriter("Example.java");
BufferedWriter out = new BufferedWriter(fstream);
out.write("");
for (String header : headers) out.append(header);
out.append("class Example { public static void main(String args[]) { ");
for (String cmd : commands) out.append(cmd);
out.append(" } }");
out.close();
}
catch (Exception e)
{
System.err.println("Error: " + e.getMessage());
}
// set path, compile, & run
try
{
Process tr = Runtime.getRuntime().exec(
new String[]{ "java -cp .",
"javac Example.java",
"java Example" } );
}
catch (Exception e)
{
System.err.println("Error: " + e.getMessage());
}
}
}

How do I open an image in the default image viewer using Java on Windows?

I have a button to view an image attached to a log entry and when the user clicks that button I want it to open the image in the user's default image viewer on a Windows machine?
How do I know which viewer in the default image viewer?
Right now I'm doing something like this but it doesn't work:
String filename = "\""+(String)attachmentsComboBox.getSelectedItem()+"\"";
Runtime.getRuntime().exec("rundll32.exe C:\\WINDOWS\\System32\\shimgvw.dll,ImageView_Fullscreen "+filename);
And by doesn't work I mean it doesn't do anything. I tried to run the command just in the command line and nothing happened. No error, nothing.
Try with the CMD /C START
public class Test2 {
public static void main(String[] args) throws Exception {
String fileName = "c:\\temp\\test.bmp";
String [] commands = {
"cmd.exe" , "/c", "start" , "\"DummyTitle\"", "\"" + fileName + "\""
};
Process p = Runtime.getRuntime().exec(commands);
p.waitFor();
System.out.println("Done.");
}
}
This will start the default photo viewer associated with the file extension.
A better way is to use java.awt.Desktop.
import java.awt.Desktop;
import java.io.File;
public class Test2 {
public static void main(String[] args) throws Exception {
File f = new File("c:\\temp\\test.bmp");
Desktop dt = Desktop.getDesktop();
dt.open(f);
System.out.println("Done.");
}
}
See Launch the application associated with a file extension
You can use the Desktop class which does exactly what you need, to open system associated application.
File file = new File( fileName );
Desktop.getDesktop().open( file );
Another solution that works well on Windows XP/Vista/7 and can open any type of file (url, doc, xml, image, etc.)
Process p;
try {
String command = "rundll32 url.dll,FileProtocolHandler \""+ new File(filename).getAbsolutePath() +"\"";
p = Runtime.getRuntime().exec(command);
p.waitFor();
} catch (IOException e) {
// TODO Auto-generated catch block
} catch (InterruptedException e) {
// TODO Auto-generated catch block
}

Categories