• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 1091
  • Last Modified:

Run ant command

Please let me know how I can run an ant command through Java. Somthring like:
"ant run"
The important thing is that the program must figure out the current directory. (The build.xml file is present here).

Thanks!
0
dshrenik
Asked:
dshrenik
  • 49
  • 45
  • 7
2 Solutions
 
for_yanCommented:
you usually name the target iin the build.xml
like in this example in
http://ant.apache.org/manual/tutorial-HelloWorldWithAnt.html

<project>

    <target name="clean">
        <delete dir="build"/>
    </target>

    <target name="compile">
        <mkdir dir="build/classes"/>
        <javac srcdir="src" destdir="build/classes"/>
    </target>

    <target name="jar">
        <mkdir dir="build/jar"/>
        <jar destfile="build/jar/HelloWorld.jar" basedir="build/classes">
            <manifest>
                <attribute name="Main-Class" value="oata.HelloWorld"/>
            </manifest>
        </jar>
    </target>

    <target name="run">
        <java jar="build/jar/HelloWorld.jar" fork="true"/>
    </target>

</project>

Now you can compile, package and run the application via

ant compile
ant jar
ant run

Or shorter with

ant compile jar run

Open in new window

0
 
dshrenikAuthor Commented:
Sorry for not being clear.
I want to execute the command "ant run-xyz" from my java code.

Running this command does a specific task. The build.xml file is ready. I can do "ant run-xyz" from the command prompt and achieve what I want to do.

But, I now want to do this from java code.
0
 
for_yanCommented:

this has two examples - one going out to the system (Runtime.getRuntim())
another form within java - but that one is not tested here:
http://stackoverflow.com/questions/6663696/running-build-xml-from-java-program
0
Cloud Class® Course: Microsoft Windows 7 Basic

This introductory course to Windows 7 environment will teach you about working with the Windows operating system. You will learn about basic functions including start menu; the desktop; managing files, folders, and libraries.

 
for_yanCommented:
0
 
dshrenikAuthor Commented:
Can you tell me how I can do it for my requirement? I want to execute "ant run-xyz" and say my build file is at "C:/Dummy".

Thanks!
0
 
for_yanCommented:
I think you should try this way:
(if you have ant in your PATH fior your user)
Process proc = Runtime.getRuntime().exec("ant -buildfile  C:\\Dummy\\build.xml run-xyz");

Open in new window

0
 
dshrenikAuthor Commented:
That did not work.
0
 
for_yanCommented:
What did it write?
0
 
for_yanCommented:
Are you running your java app from command line?
0
 
dshrenikAuthor Commented:
I get this:

java.io.IOException: Cannot run program "ant": CreateProcess error=2, The system cannot find the file specified
0
 
for_yanCommented:
Yes, I believe that means that you don't have ant in your PATH

So how do you start your java?
0
 
dshrenikAuthor Commented:
But, when I run the command on the command prompt, it works fine.
0
 
dshrenikAuthor Commented:
I do have ant on my PATH, otherwise it would not work from command line.
0
 
for_yanCommented:
are you starting your java from the sasame command prompt?
0
 
dshrenikAuthor Commented:
I am running it as a Java application from Eclipse.
0
 
for_yanCommented:
And when you are ruunning form command prompt - you are sitting in some default folder wher youy have ant.bat ?

where is your ant.bat?

put it this way:


Process proc = Runtime.getRuntime().exec("C:\\myantbat_folder\\ant -buildfile  C:\\Dummy\\build.xml run-xyz");

Open in new window

0
 
dshrenikAuthor Commented:
When I am doing it from command prompt, it is working from any folder - not necessarily from the folder that has ant installed.
0
 
for_yanCommented:
try to run from any folder from command line this:


ant -buildfile  C:\Dummy\build.xml run-xyz
0
 
dshrenikAuthor Commented:
That is working!
From any folder in any drive.
0
 
for_yanCommented:
try this way:
Runtime.getRuntime().exec("cmd /c start ant.bat -buildfile  C:\\Dummy\\build.xml run-xyz")

Open in new window

0
 
dshrenikAuthor Commented:
Even that is not working, but I don't want to do it that way, since I want to do it an OS-independent manner.

Sorry for the trouble!
0
 
for_yanCommented:

Try this way, though it should be the same
String [] cmnd = {"ant.bat", "-buildfile","C:\\Dummy\\build.xml","run-xyz"};
Runtime.getRuntime().exec(cmnd);

Open in new window


and stioll try to opput the whole path before ant.bat
0
 
for_yanCommented:

add the full path before ant.bat

0
 
dshrenikAuthor Commented:
Again, I don't want to do that since I want to be OS-independent and also for difffenrent users who have installed ant at different locations.
0
 
for_yanCommented:
Forget about os indpenednet - try to have it working at least someway - at least to undesrtand something - try with the full path
0
 
dshrenikAuthor Commented:
Even after that, it is not working.
0
 
for_yanCommented:
Do not know how it can be.

Go to your project folder - create in there file test.bat
and type say dir inside that file
and put in you main() method at the very beginning this piece:

          try{
       Runtime.getRuntime().exec("test.bat");
               } catch (Exception ex){
                   ex.printStackTrace();
               }
and check if it executes
0
 
dshrenikAuthor Commented:
Sorry, I did not get what you're trying to say...
0
 
for_yanCommented:
I want to test that you can execute any .bat file form your java in eclipse - so create simplest  test.bat
in your project root folder and try to exceute it through Runtime.getRuntime().exec() - it works for me
and shoudll work for everyone
0
 
dshrenikAuthor Commented:
It says:

java.io.IOException: Cannot run program "a.bat": CreateProcess error=2, The system cannot find the file specified

I created the .bat file in my project root folder.
0
 
dshrenikAuthor Commented:
Sorry, I placed it in the wrong project. It says:

java.io.IOException: Cannot run program "a.bat": CreateProcess error=193, %1 is not a valid Win32 application
0
 
dshrenikAuthor Commented:
But, this shows that it able to locate the .bat
0
 
for_yanCommented:
BUt it is still strange.
It executes for me withourt problem
0
 
dshrenikAuthor Commented:
Well, my .bat file has no contents in it.
0
 
for_yanCommented:
Do you have any spaces in your path to ant ?
0
 
for_yanCommented:
put "dir" command in it
0
 
dshrenikAuthor Commented:
After putting "dir", I do not get any errors, but I do not get any output as well.
0
 
for_yanCommented:
You should not get any output - but you have printStacktrace() and it would have printed if there would be an error
0
 
for_yanCommented:
Do you have spaces in the path to your ant.bat ?
0
 
dshrenikAuthor Commented:
I dont
0
 
dshrenikAuthor Commented:
@CEHJ:
I wasnt clear about the implementation. If possible, can you provide sample code as to how I can do what I said in ID: 36971068. Thanks!
0
 
for_yanCommented:
replace "test.bat" with "ant.bat" in the same place of the code and try  
0
 
dshrenikAuthor Commented:
@for_yan:
I do not get any errors. No output.
0
 
for_yanCommented:
OK, then add the whole line in the same place of code

ant.bat -buildfile  C:\\Dummy\\build.xml run-xyz")

Open in new window

0
 
dshrenikAuthor Commented:
Still doesn't work!
0
 
for_yanCommented:
So again writes error that it cannot find it?

But without argumnets it was not writing this error ?
0
 
for_yanCommented:
Do you have
C:\\Dummy\\build.xml
don't you have sapces in the real path to that ?
0
 
dshrenikAuthor Commented:
I dont get any error.
0
 
for_yanCommented:
So why do you say it doesn't work ?
0
 
dshrenikAuthor Commented:
I dont have spaces.
The funny thing is when I try:

ant.bat -buildfile  C:\\Dummy\\build.xml run-xyz

On the command line, it works, but not through java.
0
 
dshrenikAuthor Commented:
Because it is supposed to start the rabbitmq server, which does not happen.
0
 
for_yanCommented:
well that's another story - can you run say compilation stage and check if it compiles
If it does not write error it should be excuting - do you have printStackTrace() still in there in the code?
0
 
for_yanCommented:
why do we see now different picture than vbefore when it was writing errior with the same situation - when we started ?
0
 
dshrenikAuthor Commented:
I'm not sure!

But, the ant script is not running right? Otherwise, it should work!
0
 
for_yanCommented:
I think it is running - otherwise it would write an error - change "ant" in the first word to "ant1" - and see if you have an exception
0
 
dshrenikAuthor Commented:
It is not. I check Services to see if it is running or not.
Rabbitmq runs when I do it from command prompt, but not from java.
0
 
for_yanCommented:
change "ant" in the first word to "ant1" - and see if you have an exception  
0
 
for_yanCommented:
are yous tarting a service from java ?
0
 
dshrenikAuthor Commented:
Cannot run program "ant1": CreateProcess error=2, The system cannot find the file specified
0
 
for_yanCommented:
are you starting the  real winsdows service from java ?
or just java application?
0
 
dshrenikAuthor Commented:
I am starting the service through build.xml
0
 
for_yanCommented:
It means that it is runnng when you have "ant" there
0
 
for_yanCommented:
Can you execute some other stage from ant, so that we could check
0
 
for_yanCommented:
How are you starting the service?
0
 
for_yanCommented:

add output to that line - maybe we'll see some output in the out.txt file in your project root
ant.bat -buildfile  C:\\Dummy\\build.xml run-xyz  >  out.txt

Open in new window

0
 
dshrenikAuthor Commented:
Doesnt work through java. Works from command line.
0
 
for_yanCommented:

>Doesnt work through java. Works from command line.

It is doing something - otherwise it would write an error as you saw

try to do output and also explai how are you strating service - services may be specioal things
0
 
dshrenikAuthor Commented:
SORRY!!!

Other ant commands work. But the one that starts RabbitMQ does not work.
0
 
for_yanCommented:
Yes, I'm afraid starting service may be problemastic
but waht is the actual command which starts the service?
0
 
for_yanCommented:
Still try to make output to the file - maybe you'll sees something there
normamly when it starts from comman line - do you see some output to command line?
0
 
dshrenikAuthor Commented:
From the command line, I get"
Buildfile: ... \build.xml

start-rabbit-server:
     [exec] C:\Program Files (x86)\erl5.8.4\erts-5.8.4\bin\erlsrv: Failed to start service RabbitMQ.
     [exec] Error: An instance of the service is already running.

BUILD SUCCESSFUL
Total time: 1 second

From java, the output file has this:
Buildfile: .... \build.xml

start-rabbit-server:

"
0
 
for_yanCommented:

>  [exec] Error: An instance of the service is already running.

So why is that?

I think weee need to print also error stream
0
 
dshrenikAuthor Commented:
Thats not something to worry about actually. Its just that I tried to run ant when the serer was already running.
0
 
dshrenikAuthor Commented:
Its just that when I try to do it through Java, it stops midway... (as you can see from the output)
0
 
for_yanCommented:
change this way:
ant.bat -buildfile  C:\\Dummy\\build.xml run-xyz  2>  out.txt

Open in new window

0
 
dshrenikAuthor Commented:
I get this:


BUILD FAILED
C:\Users\ABC\build.xml:170: Execute failed: java.io.IOException: Cannot run program "rabbitmq-service.bat" (in directory "C:\Users\ABC"): CreateProcess error=2, The system cannot find the file specified
	at java.lang.ProcessBuilder.start(ProcessBuilder.java:460)
	at java.lang.Runtime.exec(Runtime.java:593)
	at org.apache.tools.ant.taskdefs.Execute$Java13CommandLauncher.exec(Execute.java:862)
	at org.apache.tools.ant.taskdefs.Execute.launch(Execute.java:481)
	at org.apache.tools.ant.taskdefs.Execute.execute(Execute.java:495)
	at org.apache.tools.ant.taskdefs.ExecTask.runExecute(ExecTask.java:631)
	at org.apache.tools.ant.taskdefs.ExecTask.runExec(ExecTask.java:672)
	at org.apache.tools.ant.taskdefs.ExecTask.execute(ExecTask.java:498)
	at org.apache.tools.ant.UnknownElement.execute(UnknownElement.java:291)
	at sun.reflect.GeneratedMethodAccessor4.invoke(Unknown Source)
	at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
	at java.lang.reflect.Method.invoke(Method.java:597)
	at org.apache.tools.ant.dispatch.DispatchUtils.execute(DispatchUtils.java:106)
	at org.apache.tools.ant.Task.perform(Task.java:348)
	at org.apache.tools.ant.Target.execute(Target.java:390)
	at org.apache.tools.ant.Target.performTasks(Target.java:411)
	at org.apache.tools.ant.Project.executeSortedTargets(Project.java:1399)
	at org.apache.tools.ant.Project.executeTarget(Project.java:1368)
	at org.apache.tools.ant.helper.DefaultExecutor.executeTargets(DefaultExecutor.java:41)
	at org.apache.tools.ant.Project.executeTargets(Project.java:1251)
	at org.apache.tools.ant.Main.runBuild(Main.java:809)
	at org.apache.tools.ant.Main.startAnt(Main.java:217)
	at org.apache.tools.ant.launch.Launcher.run(Launcher.java:280)
	at org.apache.tools.ant.launch.Launcher.main(Launcher.java:109)
Caused by: java.io.IOException: CreateProcess error=2, The system cannot find the file specified
	at java.lang.ProcessImpl.create(Native Method)
	at java.lang.ProcessImpl.<init>(ProcessImpl.java:81)
	at java.lang.ProcessImpl.start(ProcessImpl.java:30)
	at java.lang.ProcessBuilder.start(ProcessBuilder.java:453)
	... 23 more

Total time: 0 seconds

Open in new window

0
 
dshrenikAuthor Commented:
But how come it works from command line?
0
 
for_yanCommented:
interestuing, why wouild it not find this file?
0
 
dshrenikAuthor Commented:
Exactly! The funny thing is it works perfectly from command line (from any folder!)
0
 
for_yanCommented:
still - try to put the whole path to it in the build.xml - is the fuill path already there?

0
 
dshrenikAuthor Commented:
You want me to change the contents of build.xml?
0
 
for_yanCommented:
well, I'd try (keep the copy of course)
make sure that path again has no spaces within
0
 
dshrenikAuthor Commented:
Sure. I'll try that.
Thanks so much for your help!!!
0
 
for_yanCommented:
OK. Try, there is still some hope. Good Luck!
0
 
dshrenikAuthor Commented:
Ghosh!
You won't believe what the mistake was!

I added RabbitMQ to the classpath after starting Eclipse. That's the reasdon why it could not locate rabbitmq.

Worked after restarting eclipse! :-/
0
 
dshrenikAuthor Commented:
Just a quick question:
Will ths work for Mac and Linus if I replace the Windows directory structure with the corresponding directory structure for Mac or Linux?
0
 
for_yanCommented:
well, that happens.
Good, it worked!
Will try to rememeber for the future.
0
 
for_yanCommented:
I think it should - you determine the OS:
System.getProperty("os.name") and depending on the response construct appropriate path and command
I think should work.
Myabe will require half a day more of debuiugging thhiugh :)
0
 
dshrenikAuthor Commented:
ROFL!
0
 
dshrenikAuthor Commented:
If possible, can you answer this question:
http://www.experts-exchange.com/Programming/Languages/Java/Q_27397951.html

Thanks!
0
 
CEHJCommented:
>>Please let me know how I can run an ant command through Java.

dshrenik, i'm confused. How does the accepted answer meet that criterion? Presumably you wanted to execute Ant in order to start RabbitMQ platform-independently, which the answer certainly isn't?
0
 
dshrenikAuthor Commented:
@CEHJ:
No, I wanted to know how to run an ant command. Though my ultimate goal was to be able to start RabbitMQ, I generalized the question to just running an ant command.
0
 
CEHJCommented:
>>No, I wanted to know how to run an ant command.

But that's not what the accepted answer tells you. What it tells you is how to start ant from a platform-dependent batch file.

From what i can tell of your goal, you should be starting Ant programmatically, i.e. platform-independently
0
 
dshrenikAuthor Commented:
@CEHJ:
I think you are right.

I will "request attention", so that points can be shared. Thanks!
0
 
CEHJCommented:
>>so that points can be shared.

Or ... so that the question can be answered ;)
0
 
CEHJCommented:
You need to do something like the following (use your own string for program)
import org.apache.tools.ant.taskdefs.ExecTask;
import org.apache.tools.ant.Project;

public class AntExec {
    public static void main(String[] args) {
	final String program = "/usr/bin/beep";
	Project proj = new Project();
	proj.init();
	ExecTask exec = new ExecTask();
	exec.setProject(proj);
	exec.setExecutable(program);
	exec.setSpawn(true);
	exec.perform();
    }
}

Open in new window

0
 
for_yanCommented:
This is another option



 File buildFile = new File("build.xml");
   Project p = new Project();
   p.setUserProperty("ant.file", buildFile.getAbsolutePath());
   p.init();
   ProjectHelper helper = ProjectHelper.getProjectHelper();
   p.addReference("ant.projectHelper", helper);
   helper.parse(p, buildFile);
   p.executeTarget(p.getDefaultTarget());

Open in new window

see this API:
http://www.jajakarta.org/ant/ant-1.6.1/docs/ja/manual/api/org/apache/tools/ant/ProjectHelper.html 


I mentioned this option twice in the very beinning of this trail, but you
chose to go other way.

0
 
for_yanCommented:
This is by the way where you want to download necessary jar to execute ant from inside your java
http://mirrors.ibiblio.org/pub/mirrors/maven2/org/apache/ant/ant/1.7.1/ant-1.7.1.jar
0
 
CEHJCommented:
>>This is by the way where you want to download necessary jar to execute ant from inside your java

You just need to install Ant and put the correct jars in your classpath
0
 
CEHJCommented:
:)
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Upgrade your Question Security!

Your question, your audience. Choose who sees your identity—and your question—with question security.

  • 49
  • 45
  • 7
Tackle projects and never again get stuck behind a technical roadblock.
Join Now