Not able to open Edge Browser by Runtime.exec method - java

We are facing an issue where the below code is not able to open Microsoft Edge by running the command.
import java.io.IOException;
import java.io.InputStream;
public class ProcessTest {
private static final String NO_FRAME_MERGING_CMD_EDGE = "cmd.exe /c start microsoft-edge:";
private static final Object DOUBLE_QUOTE = "\"";
public static void main(String[] args) throws IOException {
Runtime rt = Runtime.getRuntime();
String url = "http://google.com";
url = new StringBuilder().append(DOUBLE_QUOTE).append(url).append(DOUBLE_QUOTE).toString();
System.out.println(NO_FRAME_MERGING_CMD_EDGE+ url);
Process process = rt.exec(NO_FRAME_MERGING_CMD_EDGE+ url);
printErrorlog(process);
}
public static void printErrorlog(Process process) {
try {
if (process != null && isProcessTerminated(process)) {
StringBuffer string_error = new StringBuffer();
InputStream errorStream = process.getErrorStream();
if (errorStream != null) {
int c = 0;
while ((c = errorStream.read()) != -1) {
string_error.append((char) c);
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
private static boolean isProcessTerminated (Process process) {
try {
process.exitValue();
} catch (IllegalThreadStateException itse) {
itse.printStackTrace();
return false;
}
return true;
}
}
In the logs we see
cmd.exe /c start microsoft-edge:"http://google.com"
java.lang.IllegalThreadStateException: process has not exited
at java.lang.ProcessImpl.exitValue(Native Method)
at ProcessTest1.isProcessTerminated(ProcessTest1.java:40)
at ProcessTest1.printErrorlog(ProcessTest1.java:22)
at ProcessTest1.main(ProcessTest1.java:16)
But the browser does not open.
When we run the command below in a bash file or on the command line, the windows is able to opening Edge. So I am not able to understand why it is not opening by Java.
cmd.exe /c start microsoft-edge:"http://google.com"
We are using jdk 6 to run the programm.

Related

runtime.exec(batchCommand) - Issues with Space in folder

Below method return me below path
Output - "C:\ProgramData\MySQL\MySQL Server 5.5\bin\"
private String getPath() {
String mysqlpath = "";
try {
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection(dbUrl, user, password);
Statement stmt = con.createStatement();
ResultSet res = stmt.executeQuery("select ##datadir");
while (res.next()) {
mysqlpath = res.getString(1);
}
mysqlpath = mysqlpath.replace("\\Data", "\\bin").replace("\\", "\\\\");
System.out.println("Mysql path is :" + mysqlpath);
} catch (Exception ee) {
System.out.println(ee);
}
return mysqlpath;
}
Now i run below command to export mysql dump.
Runtime runtime = Runtime.getRuntime();
Process p = runtime.exec(batchCommand);
batchCommand - "C:\ProgramData\MySQL\MySQL Server 5.5\bin\mysqldump" -h localhost --port 3306 -u root --password=root123 --add-drop-database -B accountingbook -r "E:\softwares\Tomcat_accountingBook\webapps\accountingbookaccountingbook-localhost-(02-08-2017).sql"
Exception - java.io.IOException: Cannot run program ""C:\ProgramData\MySQL\MySQL": CreateProcess error=2, The system cannot find the file specified
I also tried below, but same issue:-
1.) Process p = runtime.exec(batchCommand.split(" "));
2.) Adding double quotes like "C:\ProgramData\MySQL\MySQL Server 5.5\bin\"
Problem is it breaks as soon as it encounters space.
From the Exception, it looks like JVM is not able to find MYSQL executable file at the location given.
This can be due to "\" file separator. Try using "\\" to separate your paths. Then your path would be : "C:\\ProgramData\\MySQL\\MySQL.
I'v written one class this might help you click here
public class RuntimeExample {
private final String commandCode = "cmd /c";
private final Scanner scanner = new Scanner(System.in);
private Process process;
private BufferedReader reader;
private String input = "";
private final String defaultCode = "help";
public RuntimeExample() {
UserInput();
}
private void UserInput() {
System.out.println("Enter command (ex: ipconfig)");
input = scanner.nextLine();
if (input.isEmpty()) {
System.out.println("You didn't give any command please take a look at these available Commands." + "\n");
sendCommand(defaultCode);
} else {
sendCommand(input);
}
}
private void sendCommand(String command) {
try {
process = Runtime.getRuntime().exec(commandCode + " " + command);
reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line;
while ((line = reader.readLine()) != null) {
showResult(line);
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
private void showResult(String result) {
System.out.println(result + "\n");
}
public static void main(String[] args) {
new RuntimeExample();
}
}

Java command error. Couldn't find or load main class

Today I meet a problem with "java" command.
I work in Intellij IDEA and think that I wrong classpath to "java" command.
Please, help me.
package ru.mch;
import ru.mch.RunTask;
public class Program {
public static void main(String[] args) {
String taskCode = "class UserProgram{ public static void main(String[] args) { int b = 3 + 1; System.out.println(b);}}";
String packageName = "package ru.mch; ";
String all = packageName + taskCode ;
RunTask runTask = new RunTask(all);
int result = runTask.run();
}
}
I want to get program code from String, create new java class, write code to the class and compile and run new java class.
package ru.mch;
import java.io.*;
public class RunTask {
private String answerFromPage;
private int programExitValue;
public RunTask(String answerFromPage) {
this.answerFromPage = answerFromPage;
this.programExitValue = 0;
}
private static void printLines(String name, InputStream ins) throws Exception {
String line = null;
BufferedReader in = new BufferedReader(
new InputStreamReader(ins));
while ((line = in.readLine()) != null) {
System.out.println(line);
}
}
private static int runProcess(String command) throws Exception {
Process pro = Runtime.getRuntime().exec(command);
printLines(/*command + */" stdout:", pro.getInputStream());
printLines(" stderr:", pro.getErrorStream());
pro.waitFor();
System.out.println(command + " exit value = " + pro.exitValue());
return pro.exitValue();
}
public int run(){
//String fileName = "src\\main\\java\\ru\\mch\\UserProgram.java";
String fileName = "src\\main\\java\\ru\\mch\\UserProgram.java";
File f = new File(fileName);
f.getParentFile().mkdirs();
try {
f.createNewFile();
} catch (IOException e) {
throw new IllegalArgumentException("File creating error");
}
try(FileWriter writer = new FileWriter(fileName, false))
{
writer.write(this.answerFromPage);
writer.flush();
}
catch(IOException ex){
System.out.println(ex.getMessage());
}
try {
System.out.println(runProcess("javac -sourcepath src src\\main\\java\\ru\\mch\\UserProgram.java"));
System.out.println("------------");
this.programExitValue = runProcess("java src\\main\\java\\ru.mch.UserProgram");
} catch (Exception e) {
e.printStackTrace();
}
return this.programExitValue;
}
}
This is IDEA log :
javac src\main\java\ru\mch\UserProgram.java exit value = 0
0
------------
Error: Could not find or load main class src\main\java\ru.mch.UserProgram
java src\main\java\ru.mch.UserProgram exit value = 1
New class was created and .class too.
I try to write full classpath, try to write '\' instead of '.' in package name, but all is wrong.
Sorry for my bad English.
Use the following command:
java -cp src\main\java ru.mch.UserProgram

Execute a sqoop command using processbuilder in java

I have a working sqoop command which imports data from oracle to hive.
When i am trying to run the sqoop command using the process builder API it is giving
java.io.IOException: error=2, No such file or directory
The same command works without any issues when executing it from the shell. Please let me know how to resolve this.
I also tried splitting the command into array of strings as well as list of strings. But, the two approaches did not work.
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
public class SqoopTest {
static ProcessBuilder processBuilder = null;
static Process spawnProcess = null;
static int exitValue;
static int pid;
static List<String> commands;
public static void main(String[] args) {
runSqoop();
}
/*
* Executes the shell script with a series of sqoop commands.
*
*
*
* sqoop import -D mapred.child.java.opts='\-Djava.security.egd=file:/dev/../dev/urandom'
* --connect 'jdbc:oracle:thin:#(DESCRIPTION=(ADDRESS_LIST=(LOAD_BALANCE=ON)(FAILOVER=ON)(ADDRESS=(PROTOCOL=TCP)(HOST=173.37)(PORT=1541))(ADDRESS=(PROTOCOL=TCP)(HOST=173.37)(PORT=1541)))(CONNECT_DATA=(SERVICE_NAME=CAFI2PRD)(SERVER=DEDICATED)))'
* --username XXCSS_O --password "c******3" --split-by LINE_ITEM_ID -m 10
* --query "select LINE_ITEM_ID,LIST_PRICE,SERVICE_VALUE from XXCSS_KTN_REQ_LINE_DETAIL where \$CONDITIONS AND lid_date > to_date('2016-10-13 03:04:18','MM/dd/yyyy hh24:mi:ss') and lid_date <= to_date('2016-10-13 03:04:18','MM/dd/yyyy hh24:mi:ss')"
* --map-column-hive LINE_ITEM_ID=BIGINT,LIST_PRICE=BIGINT,SERVICE_VALUE=BIGINT
* --null-string '\\\\N' --null-non-string '\\\\N' --hcatalog-home
* /opt/mapr/hive/hive-1.2/hcatalog --hcatalog-table XXCSS_KTN_REQ_LINE_DETAIL --hcatalog-database frameworks_dataingestion
*
*/
public static void runSqoop() {
commands = new ArrayList<String>();
commands.add("sqoop import -D mapred.child.java.opts=\'\\-Djava.security.egd=file:/dev/../dev/urandom\' --connect \'jdbc:oracle:thin:#(DESCRIPTION=(ADDRESS_LIST=(LOAD_BALANCE=ON)(FAILOVER=ON)(ADDRESS=(PROTOCOL=TCP)(HOST=173.37)(PORT=1541))(ADDRESS=(PROTOCOL=TCP)(HOST=173.37)(PORT=1541)))(CONNECT_DATA=(SERVICE_NAME=CAFI2PRD)(SERVER=DEDICATED)))\' --username XXCSS_O --password \"c*****3\" --split-by LINE_ITEM_ID -m 10 --query \"select LINE_ITEM_ID,LIST_PRICE,SERVICE_VALUE from XXCSS_KTN_REQ_LINE_DETAIL where \\$CONDITIONS AND lid_date > to_date(\'2016-10-13 00:00:00\',\'yyyy-MM-dd hh24:mi:ss\') and lid_date <= to_date(\'2016-10-13 03:04:18\',\'yyyy-MM-dd hh24:mi:ss\')\" --map-column-hive LINE_ITEM_ID=BIGINT,LIST_PRICE=BIGINT,SERVICE_VALUE=BIGINT --null-string '\\\\N' --null-non-string '\\\\N' --hcatalog-home /opt/mapr/hive/hive-1.2/hcatalog --hcatalog-table XXCSS_KTN_REQ_LINE_DETAIL --hcatalog-database frameworks_dataingestion");
processBuilder = new ProcessBuilder(commands);
try {
System.out.println("Executing " + commands.toString());
spawnProcess = processBuilder.start();
BufferedReader reader =
new BufferedReader(new InputStreamReader(spawnProcess.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);
try {
exitValue = spawnProcess.waitFor();
pid = getPID(spawnProcess);
System.out.println("The PID is " + pid);
} catch (InterruptedException e) {
System.out.println(e.getMessage());
} catch (Exception e) {
System.out.println(e.getMessage());
}
System.out.println("Process exited with the status :" + exitValue);
} catch (Exception e) {
e.printStackTrace();
}
}
/*
* Retrieves the process id of the executed command.
*
* #param process the executed process
*
* #return PID
*/
public static int getPID(Process process) {
try {
Class<?> processImplClass = process.getClass();
Field fpid = processImplClass.getDeclaredField("pid");
if (!fpid.isAccessible()) {
fpid.setAccessible(true);
}
return fpid.getInt(process);
} catch (Exception e) {
System.out.println(e.getMessage());
return -1;
}
}
/*
* Retrieves the current java process id
*
* #return java process ID
*/
// #SuppressWarnings("restriction")
// public static int getCurrentJavaPID() {
// int jvmpid = 0;
// java.lang.management.RuntimeMXBean runtime = java.lang.management.ManagementFactory.getRuntimeMXBean();
// try {
// java.lang.reflect.Field jvm = runtime.getClass().getDeclaredField("jvm");
// jvm.setAccessible(true);
// sun.management.VMManagement mgmt = (sun.management.VMManagement) jvm.get(runtime);
// java.lang.reflect.Method pid_method = mgmt.getClass().getDeclaredMethod("getProcessId");
// pid_method.setAccessible(true);
//
// jvmpid = (Integer) pid_method.invoke(mgmt);
// } catch (Exception e) {
// e.getMessage();
// }
// return jvmpid;
// }
}
Note: for security concerns i have replaced the ip addresses and passwords with dummy variables.
Tried passing the command as a string array. But, it doesnt recognize the JDBC Connection string
public static void runSqoop() {
String[] commands = {"sqoop","import","-D mapred.child.java.opts=\'\\-Djava.security.egd=file:/dev/../dev/urandom\'","--connect", "\'jdbc:oracle:thin:#(DESCRIPTION=(ADDRESS_LIST=(LOAD_BALANCE=ON)(FAILOVER=ON)(ADDRESS=(PROTOCOL=TCP)(HOST=173.37)(PORT=1541))(ADDRESS=(PROTOCOL=TCP)(HOST=173.370)(PORT=1541)))(CONNECT_DATA=(SERVICE_NAME=CAFI2PRD)(SERVER=DEDICATED)))\'","--username","XXCSS_O","--password","\"c***3\"", "--split-by","LINE_ITEM_ID","-m","10","--query","\"select LINE_ITEM_ID,LIST_PRICE,SERVICE_VALUE from XXCSS_KTN_REQ_LINE_DETAIL where \\$CONDITIONS AND lid_date > to_date(\'2016-10-13 00:00:00\',\'yyyy-MM-dd hh24:mi:ss\') and lid_date <= to_date(\'2016-10-13 03:04:18\',\'yyyy-MM-dd hh24:mi:ss\')\"","--null-string","'\\\\N'","--null-non-string","'\\\\N'","--hcatalog-home","/opt/mapr/hive/hive-1.2/hcatalog","--hcatalog-table","XXCSS_KTN_REQ_LINE_DETAIL","--hcatalog-database","frameworks_dataingestion"};
processBuilder = new ProcessBuilder(commands);
try {
System.out.println("Executing " + commands.toString());
spawnProcess = processBuilder.start();
BufferedReader reader =
new BufferedReader(new InputStreamReader(spawnProcess.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);
try {
exitValue = spawnProcess.waitFor();
pid = getPID(spawnProcess);
System.out.println("The PID is " + pid);
} catch (InterruptedException e) {
System.out.println(e.getMessage());
} catch (Exception e) {
System.out.println(e.getMessage());
}
System.out.println("Process exited with the status :" + exitValue);
} catch (Exception e) {
e.printStackTrace();
}
}
Stack trace:
cat: /opt/mapr/zookeeper/zookeeperversion: No such file or directory
16/10/25 07:41:12 INFO sqoop.Sqoop: Running Sqoop version:
1.4.6-mapr-1609 16/10/25 07:41:12 WARN tool.BaseSqoopTool: Setting your password on the command-line is insecure. Consider using -P
instead. 16/10/25 07:41:13 ERROR tool.BaseSqoopTool: Got error
creating database manager: java.io.IOException: No manager for connect
string:
'jdbc:oracle:thin:#(DESCRIPTION=(ADDRESS_LIST=(LOAD_BALANCE=ON)(FAILOVER=ON)(ADDRESS=(PROTOCOL=TCP)(HOST=173.37)(PORT=1541))(ADDRESS=(PROTOCOL=TCP)(HOST=173.37)(PORT=1541)))(CONNECT_DATA=(SERVICE_NAME=CAFI2PRD)(SERVER=DEDICATED)))'
at org.apache.sqoop.ConnFactory.getManager(ConnFactory.java:191)
at org.apache.sqoop.tool.BaseSqoopTool.init(BaseSqoopTool.java:256)
at org.apache.sqoop.tool.ImportTool.init(ImportTool.java:89)
at org.apache.sqoop.tool.ImportTool.run(ImportTool.java:593)
at org.apache.sqoop.Sqoop.run(Sqoop.java:143)
at org.apache.hadoop.util.ToolRunner.run(ToolRunner.java:70)
at org.apache.sqoop.Sqoop.runSqoop(Sqoop.java:179)
at org.apache.sqoop.Sqoop.runTool(Sqoop.java:218)
at org.apache.sqoop.Sqoop.runTool(Sqoop.java:227)
at org.apache.sqoop.Sqoop.main(Sqoop.java:236)
You have to provide commands and args separately as like below
Process p = new ProcessBuilder("myCommand", "myArg").start();
OR
ProcessBuilder pb =
new ProcessBuilder("myCommand", "myArg1", "myArg2");
pb.start();
Here is a example

How can I tell wheter a file is opened by an other application?

Is there a way to tell whether a file is opened by another application in PHP of Java?
Command fuser -v filename will tell you everything you need to know:
$ fuser -v test.php
USER PID ACCESS COMMAND
test.php: guest 17983 F.... cat
I'd say No. Please read these threads.
How to check if a file is already open by another process in C?
Java: Check if file is already open
How to check if a file has been opened by another application in C++
On windows you could download handle which is a command line tool to identify which windows file handles are owned by which processes.
Output looks like this:
Handle v3.46
Copyright (C) 1997-2011 Mark Russinovich
Sysinternals - www.sysinternals.com
------------------------------------------------------------------------------
System pid: 4 NT AUTHORITY\SYSTEM
84: File (R--) C:\System Volume Information\_restore{5D536487-92AI-5I25-9237-28AHSOU23728}\RP425\change.log
B4: File (RWD) C:\Documents and Settings\All Users\Application Data\avg9\Log\avgldr.log
728: File (-W-) C:\pagefile.sys
7A4: File (---) C:\WINDOWS\system32\config\SECURITY
(etc...)
Here an example application which uses handle.exe to determine if there is a handle on a file or directory (Windows only):
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
/**
* Application which determines which processes have a handle on a file or
* directory. Pass the file or directory to check as the first application
* parameter.
*
* This application uses handle.exe, which can be downloaded here:
* http://technet.microsoft.com/en-us/sysinternals/bb896655
*
* Copy handle.exe to C:/Program Files/handle/
*
* For the Runtime.exec() code I looked at:
* http://www.javaworld.com/javaworld/jw-12-2000/jw-1229-traps.html?page=2
*
* #author Adriaan
*/
public class Handle {
private static final String HANDLE_PATH = "C:/Program Files/handle/handle.exe";
private static final String DEFAULT_TARGET = "C:\\WINDOWS";
public static void main(String[] args) throws IOException,
InterruptedException {
checkOS();
String fileName = getFileName(args);
Process proc = executeCommand(fileName);
readResults(fileName, proc);
checkTermination(proc);
}
private static void checkOS() {
String osName = System.getProperty("os.name");
if (!osName.contains("Windows")) {
throw new IllegalStateException("Can only run under Windows");
}
}
private static String getFileName(String[] args) {
String fileName;
if (args != null && args.length > 0) {
fileName = args[0];
} else {
fileName = DEFAULT_TARGET;
}
return fileName;
}
private static Process executeCommand(String fileName) throws IOException {
String[] cmd = new String[] { HANDLE_PATH, fileName };
Runtime rt = Runtime.getRuntime();
Process proc = rt.exec(cmd);
return proc;
}
private static void readResults(final String fileName, final Process proc) {
Thread errorHandler = new Thread() {
public void run() {
try {
BufferedReader br = new BufferedReader(
new InputStreamReader(proc.getErrorStream()));
String line = null;
while ((line = br.readLine()) != null) {
System.err.println(line);
}
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
};
Thread outputHandler = new Thread() {
public void run() {
try {
BufferedReader br = new BufferedReader(
new InputStreamReader(proc.getInputStream()));
String line = null;
while ((line = br.readLine()) != null) {
if (line.endsWith(fileName)) {
System.out.println(line);
}
}
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
};
errorHandler.start();
outputHandler.start();
}
private static void checkTermination(final Process proc)
throws InterruptedException {
int exitVal = proc.waitFor();
if (exitVal != 0) {
throw new IllegalStateException("Exitvalue " + exitVal);
}
}
}
You probably want to use file locking.
http://tuxradar.com/practicalphp/8/11/0
Edit: This is presuming you mean programatically with PHP or Java.
On linux you can scan through all the /proc/{pid}/fd/nnn file descriptors to see if the file in question is already open.
Using files to share data between running programs is generally a bad idea and error prone.

Execute another jar in a Java program

I had written several simple java applications named as A.jar, B.jar.
Now i want to write a GUI java program so that user can press button A to execute A.jar and button B to execute B.jar.
Also i want to output the run-time process detail in my GUI program.
Any suggestion?
If I understand correctly it appears you want to run the jars in a separate process from inside your java GUI application.
To do this you can use:
// Run a java app in a separate system process
Process proc = Runtime.getRuntime().exec("java -jar A.jar");
// Then retreive the process output
InputStream in = proc.getInputStream();
InputStream err = proc.getErrorStream();
Its always good practice to buffer the output of the process.
.jar isn't executable. Instantiate classes or make call to any static method.
EDIT:
Add Main-Class entry while creating a JAR.
>p.mf (content of p.mf)
Main-Class: pk.Test
>Test.java
package pk;
public class Test{
public static void main(String []args){
System.out.println("Hello from Test");
}
}
Use Process class and it's methods,
public class Exec
{
public static void main(String []args) throws Exception
{
Process ps=Runtime.getRuntime().exec(new String[]{"java","-jar","A.jar"});
ps.waitFor();
java.io.InputStream is=ps.getInputStream();
byte b[]=new byte[is.available()];
is.read(b,0,b.length);
System.out.println(new String(b));
}
}
Hope this helps:
public class JarExecutor {
private BufferedReader error;
private BufferedReader op;
private int exitVal;
public void executeJar(String jarFilePath, List<String> args) throws JarExecutorException {
// Create run arguments for the
final List<String> actualArgs = new ArrayList<String>();
actualArgs.add(0, "java");
actualArgs.add(1, "-jar");
actualArgs.add(2, jarFilePath);
actualArgs.addAll(args);
try {
final Runtime re = Runtime.getRuntime();
//final Process command = re.exec(cmdString, args.toArray(new String[0]));
final Process command = re.exec(actualArgs.toArray(new String[0]));
this.error = new BufferedReader(new InputStreamReader(command.getErrorStream()));
this.op = new BufferedReader(new InputStreamReader(command.getInputStream()));
// Wait for the application to Finish
command.waitFor();
this.exitVal = command.exitValue();
if (this.exitVal != 0) {
throw new IOException("Failed to execure jar, " + this.getExecutionLog());
}
} catch (final IOException | InterruptedException e) {
throw new JarExecutorException(e);
}
}
public String getExecutionLog() {
String error = "";
String line;
try {
while((line = this.error.readLine()) != null) {
error = error + "\n" + line;
}
} catch (final IOException e) {
}
String output = "";
try {
while((line = this.op.readLine()) != null) {
output = output + "\n" + line;
}
} catch (final IOException e) {
}
try {
this.error.close();
this.op.close();
} catch (final IOException e) {
}
return "exitVal: " + this.exitVal + ", error: " + error + ", output: " + output;
}
}
The following works by starting the jar with a batch file, in case the program runs as a stand alone:
public static void startExtJarProgram(){
String extJar = Paths.get("C:\\absolute\\path\\to\\batchfile.bat").toString();
ProcessBuilder processBuilder = new ProcessBuilder(extJar);
processBuilder.redirectError(new File(Paths.get("C:\\path\\to\\JavaProcessOutput\\extJar_out_put.txt").toString()));
processBuilder.redirectInput();
try {
final Process process = processBuilder.start();
try {
final int exitStatus = process.waitFor();
if(exitStatus==0){
System.out.println("External Jar Started Successfully.");
System.exit(0); //or whatever suits
}else{
System.out.println("There was an error starting external Jar. Perhaps path issues. Use exit code "+exitStatus+" for details.");
System.out.println("Check also C:\\path\\to\\JavaProcessOutput\\extJar_out_put.txt file for additional details.");
System.exit(1);//whatever
}
} catch (InterruptedException ex) {
System.out.println("InterruptedException: "+ex.getMessage());
}
} catch (IOException ex) {
System.out.println("IOException. Faild to start process. Reason: "+ex.getMessage());
}
System.out.println("Process Terminated.");
System.exit(0);
}
In the batchfile.bat then we can say:
#echo off
start /min C:\path\to\jarprogram.jar
If the jar's in your classpath, and you know its Main class, you can just invoke the main class. Using DITA-OT as an example:
import org.dita.dost.invoker.CommandLineInvoker;
....
CommandLineInvoker.main('-f', 'html5', '-i', 'samples/sequence.ditamap', '-o', 'test')
Note this will make the subordinate jar share memory space and a classpath with your jar, with all the potential for interference that can cause. If you don't want that stuff polluted, you have other options, as mentioned above - namely:
create a new ClassLoader with the jar in it. This is more safe; you can at least isolate the new jar's knowledge to a core classloader if you architect things with the knowledge that you'll be making use of alien jars. It's what we do in my shop for our plugins system; the main application is a tiny shell with a ClassLoader factory, a copy of the API, and knowledge that the real application is the first plugin for which it should build a ClassLoader. Plugins are a pair of jars - interface and implementation - that are zipped up together. The ClassLoaders all share all the interfaces, while each ClassLoader only has knowledge of its own implementation. The stack's a little complex, but it passes all tests and works beautifully.
use Runtime.getRuntime.exec(...) (which wholly isolates the jar, but has the normal "find the application", "escape your strings right", "platform-specific WTF", and "OMG System Threads" pitfalls of running system commands.
First we cerate a class FirstFileOutput having a main method that outputs a line to stable output and a line to stable error. With all first procedure, we'll again create a class RuntimeExecCheck that will run our FirstFileOutput class in starting for process, and after that RuntimeExecCheck class will read the stable output and the stable error from FirstFileOutput and output comes.
package check;
public class FirstFileOutput{
public static void main(String[] args) {
System.out.println("This is output to stable output");
System.err.println("This is output to stable error");
}
}
package check;
import java.io.InputStream;
import java.io.IOException;
import java.io.InputStreamReader;
public class RuntimeExecCheck {
public static void main(String[] args) {
try {
Runtime runTime = Runtime.getRuntime();
Process process = runTime.exec("java -classpath C:\\projects\\workspace\\check\\bin check.FirstFileOutput");
InputStream inputStream = process.getInputStream();
InputStreamReader isr = new InputStreamReader(inputStream);
InputStream errorStream = process.getErrorStream();
InputStreamReader esr = new InputStreamReader(errorStream);
int n1;
char[] c1 = new char[1024];
StringBuffer stableOutput = new StringBuffer();
while ((n1 = isr.read(c1)) > 0) {
stableOutput.append(c1, 0, n1);
}
System.out.println("Stable Output: " + stableOutput.toString());
int n2;
char[] c2 = new char[1024];
StringBuffer stableError = new StringBuffer();
while ((n2 = esr.read(c2)) > 0) {
stableError.append(c2, 0, n2);
}
System.out.println("Stable Error: " + stableError.toString());
} catch (IOException e) {
e.printStackTrace();
}
}
}
If you are java 1.6 then the following can also be done:
import javax.tools.JavaCompiler;
import javax.tools.ToolProvider;
public class CompilerExample {
public static void main(String[] args) {
String fileToCompile = "/Users/rupas/VolatileExample.java";
JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
int compilationResult = compiler.run(null, null, null, fileToCompile);
if (compilationResult == 0) {
System.out.println("Compilation is successful");
} else {
System.out.println("Compilation Failed");
}
}
}

Categories

Resources