Here is my code for junit test case
public class HelptextValidation {
#Test
public void test() {
CLIReaderTest cli=new CLIReaderTest();
String Output="Test Execution";
assertEquals(cli.readCommandLineParameters(new String[]{"-h"}) , Output);
}
}
And is the class method for which test case is prepared
public class CLIReaderTest {
private String user = "";
private String password = "";
private String serverUrl = "";
private boolean spit_everythingtoLog = false;
public boolean readCommandLineParameters(String[] args) {
Logger log = Logger.getLogger(CLIReader.class);
Options options = new Options();
Option helpOpt = Option.builder("h").longOpt("help").desc("Usage Help").build();
options.addOption(helpOpt);
Option serverurl = Option.builder("url").longOpt("server url").desc("Server url").required().hasArg().argName("url").build();
options.addOption(serverurl);
Option userOpt = Option.builder("u").longOpt("user").desc("User Name").hasArg().argName("user").required().build();
options.addOption(userOpt);
Option pwdOpt = Option.builder("p").longOpt("password").desc("user password").hasArg().argName("password").required().build();
options.addOption(pwdOpt);
try {
CommandLineParser parser = new DefaultParser();
CommandLine cmd = parser.parse(options, args, true);
if(cmd.hasOption("v")) {
spit_everythingtoLog = true;
}
serverUrl = cmd.getOptionValue("url");
user = cmd.getOptionValue("u");
password = cmd.getOptionValue("p");
streamName = cmd.getOptionValue("s");
compList = cmd.getOptionValue("c");
}
catch (Exception e) {
String temp1="--help";
String temp2="[--help]";
String temp3="[-h]";
String temp4="-h";
if(temp1.equals(args[0]) || temp2.equals(args[0]))
{
System.out.println("Test Execution");
System.exit(1);
}
}
Here when user passes java -jar abc.jar -h in command line the output is "Test Execution"
The same i want to do with my test case but i am unable to pass the cmd argument and compare it with string. Can anyone please help me out in this?
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
I want to launch a browser and load a web page using Java's Runtime exec by passing parameters.Here i am trying to pass parameters to the Runtime exec from a JAVA APPLET to launch exe.
In my case, the path "C:\SW\Dr. Joanna Schöpf-Grey213982\IVLS_VS25YWTL1\ActivityLog_2014_07.xml" contains the character "ö".But, the applets passing the path as "C:\SW\Dr. Joanna Sch�pf-Grey213982\IVLS_VS25YWTL1\ActivityLog_2014_07.xml" (by replacing the "ö" german character with �) to the Runtime exec.
The applet looks like this:
public class LaunchSSCPApplet extends JApplet {
private static final long serialVersionUID = -9024284603221319628L;
StringBuffer buffer;
Process p = null;
int inException = -1;
String filesList = null;
String filePath = null;
String sapNumber = null;
List<String> cmdList = new ArrayList<String>();
private JTextPane textArea;
public void init() {
try {
setupTextPanel();
buffer = new StringBuffer();
filePath = getParameter("exePath");
filesList = getParameter("filesList");
sapNumber = getParameter("sapNumber");
buffer.append("SSCP Executable Path : "+filePath);
if(filePath != null && !(filePath.trim().equals(""))){
cmdList.add(filePath);
}
if (sapNumber != null && !(sapNumber.trim().equals(""))) {
cmdList.add("--sap");
cmdList.add(sapNumber);
}
StringTokenizer tokenizer = new StringTokenizer(filesList, "|");
while(tokenizer.hasMoreTokens()){
String f = tokenizer.nextToken();
if (filePath.endsWith(".bat")) {
cmdList.add(f);
} else {
cmdList.add("--logfile");
cmdList.add("C:/SW/Dr.JoannaSchöpf-Grey213982/IVLS_VS25YWTL1/ActivityLog_2014_07.xml");
}
buffer.append("<br>");
buffer.append("FILE PATH: "+f);
}
String [] cmdArray = cmdList.toArray(new String[cmdList.size()]);
p = Runtime.getRuntime().exec(cmdArray);
if(filePath.contentEquals(".bat")) {
p.waitFor();
}
/*
* UnCommenting this as the Applet window has to be closed after launching SSCP
* Defect: 235626 : Observe the applet does not close after tool is launched
*/
JSObject win = JSObject.getWindow(this);
win.eval("window.close()");
} catch (IOException io) {
buffer.append("<br>");
buffer.append("An error occured while loading SSCP " +getStackTraceAsString(io));
} catch (Exception e) {
buffer.append("<br>");
buffer.append("Please contact administrator there is some problem loading application : "+getStackTraceAsString(e));
}
Please help me to fix the above problem.
I have this ruby class :
require 'stringio'
require 'hirb'
class Engine
def initialize()
#binding = Kernel.binding
end
def run(code)
# run something
stdout_id = $stdout.to_i
$stdout = StringIO.new
cmd = <<-EOF
$SAFE = 3
$stdout = StringIO.new
begin
#{code}
end
EOF
begin
result = Thread.new { Kernel.eval(cmd, #binding) }.value
rescue SecurityError
return "illegal"
rescue Exception => e
return e
ensure
output = get_stdout
$stdout = IO.new(stdout_id)
end
return output
end
private
def get_stdout
raise TypeError, "$stdout is a #{$stdout.class}" unless $stdout.is_a? StringIO
$stdout.rewind
$stdout.read
end
end
The "run" method should call an IRB's function and to capture the output (string format).
I want to call this function from a Java class but it can't find the IRB methods, even they are loaded (require 'hirb').
My java class looks like this :
public class MyClass {
private final static String jrubyhome = "/usr/lib/jruby/";
private String rubySources;
private String hirbSource;
private String myEngine;
private boolean loaded = false;
private void loadPaths() {
String userDir;
userDir = System.getProperty("user.dir");
rubySources = userDir + "/../ruby";
hirbSource = userDir + "/hirb.rb";
myEngine = rubySources + "/engine.rb";
System.setProperty("jruby.home", jrubyhome);
System.setProperty("org.jruby.embed.class.path", rubySources+":"+hirbSource);
System.setProperty("hbase.ruby.sources", rubySources+":"+hirbSource);
}
private String commandResponse(String command)
throws FileNotFoundException
{
String response;
loadPaths();
ScriptEngineManager manager = new ScriptEngineManager();
ScriptEngine engine = manager.getEngineByName("jruby");
ScriptingContainer container = new ScriptingContainer();
Reader reader = new FileReader(myEngine);
try {
Object receiver = engine.eval(reader);
String method = "run";
Object ob = container.callMethod(receiver,method,command);
response = ob.getClass().toString();
return response;
} catch (ScriptException e) {
System.out.println("exception");
}
return "FAILED";
}
public static void main(String args[])
throws IOException {
MyClass my = new MyClass();
System.out.println(my.commandResponse(args[0]));
}
}
Do you know what could be the problem?
[EDITED] After I extended the Kernel module and added the commands it worked.
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");
}
}
}