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();
Related
How does java run a batch file in the background?
I have a batch file with the following content
#echo off
:start
start /b cmd /c example.exe -c config >nul 2>&1
goto :eof
In fact, I run this code under the command line, it can run in the background, but it seems that the "execution" of the java call will hang on the console on the idea, I am a java novice and I don't know the principle.
java code:
package com.example;
import org.apache.commons.exec.CommandLine;
import org.apache.commons.exec.DefaultExecutor;
public class Example {
public static void main(String[] args) throws Exception{
System.out.println("Hello World");
System.out.println("Started.");
String script_path = "";
boolean isWindows = System.getProperty("os.name").toLowerCase().startsWith("windows");
System.out.println(isWindows);
if (isWindows) {
System.out.println("it's Windows");
script_path = "c:/users/test-running/desktop/example.bat";
CommandLine cmdLine = new CommandLine("cmd");
cmdLine.addArgument(script_path);
cmdLine.addArgument("start").addArgument("server");
DefaultExecutor executor = new DefaultExecutor();
executor.execute(cmdLine);
System.out.println("Finished.");
} else {
System.out.println("it's Linux");
script_path = "/Users/seth/Downloads/example.sh";
CommandLine cmdLine = new CommandLine("/bin/bash");
cmdLine.addArgument(script_path);
cmdLine.addArgument("start").addArgument("server");
DefaultExecutor executor = new DefaultExecutor();
executor.execute(cmdLine);
System.out.println("Finished.");
}
}
}
So does anyone know what java is doing? Or is the syntax of the batch file wrong?
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
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 am passing parameters to hadoop jar as below:
hadoop jar C:\Pointerfile.jar main.com.asos.recommendations.Pointerfile -D Signal=Signaltest -D ProductData=ProductData -D CustomerSegment=CustomerSegment -D CustomerCategory=CustomerCategory -D P2PSimilarity=P2PSimilarity -D ProductCategory=ProductCategory/test -D ProductSegment=ProductSegment/test -D Customer=Customer -D ProductDataCN=ProductDatab -D CustomerSegmentCN=CustomerSegmentb -D CustomerCategoryCN=CustomerCategoryb -D P2PSimilarityCN=P2PSimilarityb -D ProductCategoryCN=ProductCategoryb -D ProductSegmentCN=ProductSegmentb -D SignalCN=Signalb -D CustomerCN=Customerb -D SAN=SAN -D version=v0.1
In java code I am trying to access those parameters:
Configuration conf = new Configuration();
System.out.println("parameters are" + conf.get("Signal"));
but it returns null.
I have also tried by removing space:
-DSignal=Signal and "-DSignal=Signal"
Use this kind of class :
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.util.Tool;
import org.apache.hadoop.util.ToolRunner;
public class MyClass extends Configured implements Tool {
#Override
public int run(String[] args) throws Exception {
Configuration conf = getConf();
System.out.println("parameters are" + conf.get("Signal"));
// Some code ...
return 0;
}
public static void main(String[] args) throws Exception {
int exitCode = ToolRunner.run(new MyClass(), args);
System.exit(exitCode);
}
}
In this class, getConf() will be filled with the parameters.
For call, don't use spaces nor quotes :
hadoop jar C:\Pointerfile.jar main.com.asos.recommendations.Pointerfile -DSignal=Signaltest -DProductData=ProductData -DCustomerSegment=CustomerSegment -DCustomerCategory=CustomerCategory -DP2PSimilarity=P2PSimilarity -DProductCategory=ProductCategory/test -DProductSegment=ProductSegment/test -DCustomer=Customer -DProductDataCN=ProductDatab -DCustomerSegmentCN=CustomerSegmentb -DCustomerCategoryCN=CustomerCategoryb -DP2PSimilarityCN=P2PSimilarityb -DProductCategoryCN=ProductCategoryb -DProductSegmentCN=ProductSegmentb -DSignalCN=Signalb -DCustomerCN=Customerb -DSAN=SAN -Dversion=v0.1
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