I run a command from terminal and it work, the command is:
docker exec mysql-container /bin/sh -c "./build/update-time.sh 1559652300000"
I want to be able to do this in JAVA, so i have tried the following but failed. Any ideas how to make it work?
public class DockerUtils {
public static DockerComposeRule docker;
public static DockerComposeExecOption option = DockerComposeExecOption.noOptions();
public static void updateTime() {
//also tried "bin/sh", "-c"
DockerComposeExecArgument args = DockerComposeExecArgument.arguments("bash", "-c", "./build/update-time.sh 1559652300000");
//this fails
docker.exec(option, "mysql-container", args);
}
}
Throws java.lang.NullPointerException
$> docker ps
(I had to cut the output below, but there is a container with the name!)
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
ce1e1d33dcef xx xx xx xx xx mysql-container
Related
I am trying to pull an alpine image using docker-java library. Image got pulled successfully but I am not seeing any docker output on console. How to enable logging in docker-java library.
public class DockerPull {
public static void main(String[] args) throws InterruptedException {
DockerClientConfig standard = DefaultDockerClientConfig.createDefaultConfigBuilder().build();
DockerClient dockerClient = DockerClientBuilder.getInstance(standard).build();
dockerClient.pullImageCmd("alpine:latest").exec(new PullImageResultCallback()).awaitCompletion(3600, TimeUnit.SECONDS);
}
}
Output:
Process finished with exit code 0
The following command works well in command line
shp2pgsql -s 4326 /Users/abc.shp | psql -U user1 -h localhost -p 5432 -d postgis
However when I run the following command in Java using ProcessBuilder it says command not found. Here is the code:
public static void main(String arg[]) throws Exception {
ProcessBuilder pb =
new ProcessBuilder("/bin/sh -c shp2pgsql /Users/abc.shp | psql -U user1 -h localhost -p 5432 -d postgis");
Process p = pb.start();
showOutput(p.getInputStream(), System.out);
showOutput(p.getErrorStream(), System.err);
}
private static void showOutput(final InputStream src, final PrintStream dest) {
new Thread(new Runnable() {
public void run() {
Scanner sc = new Scanner(src);
while (sc.hasNextLine()) {
dest.println(sc.nextLine());
}
}
}).start();
}
It seems that Java does not understand where the path of your environment (psql or shp2pgsql ..) is
You need to specify the path so that it can execute. It is usually in /usr/local/bin or usr/bin. Also, note the argument for "/bin/sh and "-c" (this you specify the command your going to execute is in string format)is separate. Just modify the following snippet. It should work!!
String env = "/usr/local/bin/";
ProcessBuilder pb =
new ProcessBuilder("/bin/sh", "-c", env +"shp2pgsql /Users/abc.shp | "+env+"psql -U user1 -h localhost -p 5432 -d postgis");
Process p = pb.start();
I tried to run this Java app:
public class Run_Process {
public static void main(String[] args) {
String myCommandIp = "netsh interface ip set address name=\"Ethernet\" static 192.168.0.4 255.255.255.0 192.168.0.1 1";
String myCommand2Dns = "netsh interface ipv4 add dnsserver \"Ethernet\" address=192.168.0.1 index=1";
runCommand(myCommandIp);
runCommand(myCommand2Dns);
}
static void runCommand(String command) {
try {
new ProcessBuilder(command.split(" ")).redirectError(ProcessBuilder.Redirect.INHERIT)
.redirectOutput(ProcessBuilder.Redirect.INHERIT).start();
} catch (Exception e) {
e.printStackTrace();
}
}
}
but I get:
The requested operation requires elevation(Run as administrator)
How to launch my app again, requesting elevation with the 'run as' verb? This is how I did it in Python. However, I need help to do it in Java.
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import ctypes, sys, subprocess
def is_admin():
try:
return ctypes.windll.shell32.IsUserAnAdmin()
except:
return False
if is_admin():
subprocess.call(['wmic', '/output:usracc.txt', 'useraccount', 'list', 'full', '/format:csv'])
else:
# Re-run the program with admin rights
ctypes.windll.shell32.ShellExecuteW(None, "runas", sys.executable, __file__, None, 1)
This has been asked so many times, but I need a concrete example for my case because I'm noob.
I will explain why this is not a duplicate of linked question. Using a shortcut is not an option. I have to assume that the user doesn't know how to create a shortcut. JNA and wizmo solutions are not explained. Here it says that:
So, in the Java world, you just have to do exactly what everyone else
has to do: launch your app again, requesting elevation. There are
several ways to launch elevated, the 'run as' verb probably being the
easiest.
So, I ask for help how to use a solution with 'run as' verb and ShellExecute in Java.
Ok, this is an answer to my question. I will leave this here for future reference. Firstly, I downloaded JNA from here. Run them with java -jar jna.jar and imported in my Eclipse project.
This will open cmd as admin if you answer yes in UAC and then it will run netsh command. It's the runas which starts UAC. You can use open to start cmd as normal user.
This SO answer helped me a lot with jna, a this one too with passing arguments in ShellExecute. Here you can read what /S and /C do.
import com.sun.jna.*;
import com.sun.jna.platform.win32.ShellAPI;
import com.sun.jna.platform.win32.WinDef;
import com.sun.jna.win32.*;
public class Main {
public interface Shell32 extends ShellAPI, StdCallLibrary {
Shell32 INSTANCE = (Shell32)Native.loadLibrary("shell32", Shell32.class);
WinDef.HINSTANCE ShellExecuteA(WinDef.HWND hwnd,
String lpOperation,
String lpFile,
String lpParameters,
String lpDirectory,
int nShowCmd);
}
public static void main(String[] args) {
WinDef.HWND h = null;
Shell32.INSTANCE.ShellExecuteA(h, "runas", "cmd.exe", "/S /C \"netsh interface ip set address name=\"Wi-Fi\" static 192.168.88.189 255.255.255.0 192.168.88.1 1\"", null, 1);
How to start chrome using Java?
For Windows the code is just as simple as below.
Runtime.getRuntime().exec(new String[]{"cmd", "/c", "start chrome http://localhost:8080"});
Is there something like above?
In Linux you can use like this:
Runtime.getRuntime().exec(new String[]{"bash", "-c", "/path/to/chrome http://yourwebsite.com"});
Replace the /path/to/chrome with the path in your system. Generally Google Chrome is installed at /opt/google/chrome/chrome
Or you can use google-chrome like this:
Runtime.getRuntime().exec(new String[]{"bash", "-c", "google-chrome http://yourwebsite.com"});
If you want to open up in chromium browser in Linux use it like this:
Runtime.getRuntime().exec(new String[]{"bash", "-c", "chromium-browser http://yourwebsite.com"});
For MAC OS try like this:
Runtime.getRuntime().exec(new String[]{"/usr/bin/open", "-a", "/Applications/Google Chrome.app", "http://yourwebsite.com/"});
You can use Selenium.
import org.openqa.selenium.chrome.ChromeDriver;
public class App
{
public static void main(String[] args) throws Throwable
{
ChromeDriver driver = new ChromeDriver();
System.setProperty("webdriver.chrome.driver", "/usr/bin/google-chrome");
// And now use this to visit Google
driver.get("http://www.google.com");
}
this should work fine for ubuntu 15.10 or higher
String[] cmd = {"bash","-c","google-chrome www.yourUrl.com"};
Process p = Runtime.getRuntime().exec(cmd);
Hope it helps.
>>> Check here (Note: Java File is Compiled and run by commands on Terminal)
File name: Test.java
public class Test {
public static void main(String[] args) {
try {
System.out.println("Executing command to open a chrome tab with terminal command!");
Runtime.getRuntime().exec(new String[]{"bash", "-c", "google-chrome https://stackoverflow.com/"});
System.out.println("A New tab or window should get opened in your Chrome Browser with Stack Overflow website!");
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
/**here
google-chrome https://stackoverflow.com/ -> terminal command to open a new chrome tab or window with the stack-overflow website.
**/
I know that I can run non GUI jar files from the command line. Is there any way that can do so by clicking or something and not writing the commands again and again.? Is there any software to do so. ( I am talking about a compiled jar and don't want to run from any ide)
public static final String TITLE = "CONSOLE title";
public static final String FILENAME = "myjar.jar";
public static void main(String[] args) throws InterruptedException, IOException {
if(args.length==0 || !args[args.length-1].equals("terminal")) {
String[] command;
if(System.getProperty("os.name").toLowerCase().contains("win")) {
command = new String[]{"cmd", "/c", "start \"title \\\""+TITLE+"\\\" & java -jar \\\""+new File(FILENAME).getAbsolutePath()+"\\\" terminal\""};
} else {
command =new String[]{"sh", "-c", "gnome-terminal -t \""+TITLE+"\" -x sh -c \"java -jar \\\""+new File(FILENAME).getAbsolutePath()+"\\\" terminal\""};
}
try {
Process p = Runtime.getRuntime().exec(command);
p.waitFor();
} catch(Throwable t){
t.printStackTrace();
}
} else {
//THERE IS YOUR CONSOLE PROGRAM:
System.out.println("Hey! What's your name?");
String read = new BufferedReader(new InputStreamReader(System.in)).readLine();
System.out.println("Hey, "+read+"!");
Thread.sleep(10000);
}
}
You can run it with double clicking on .jar file. Don't forget about MANIFEST.MF! :) (working on linux, also!)
Example (I only double clicked on jar file):
The way intended by Java is that you call java -jar XXXX.jar on the jars you need. Drawback is that you can't specify a classpath so all classes should be there.
A cooler way to package an application is by using Java WebStart. With that the user installs the application jut by clicking on a web browser. Check here http://docs.oracle.com/javase/8/docs/technotes/guides/javaws/developersguide/contents.html