Reputation: 2313
I want to use one of Ant's task (scp) from inside my code. Is there any way to do it?
Should I simply reference one of Ant's library and call the API directly from my code?
Upvotes: 2
Views: 2319
Reputation: 22692
Yes, you can invoke Ant tasks quite easily from your code.
Here's an example of how to extend an Ant Task:
import org.apache.tools.ant.Project;
import org.apache.tools.ant.Target;
import org.apache.tools.ant.taskdefs.Copy;
public class MyCopyTask extends Copy {
public MyCopyTask() {
setProject(new Project());
getProject().init();
setTaskName("MyCopy");
setTaskType("MyCopy");
setOwningTarget(new Target());
}
}
Here's how to use it in your code:
MyCopyTask copier = new MyCopyTask();
copier.setFile(srcFile);
copier.setTofile(toFile);
copier.execute();
Here's some more info:
Upvotes: 5
Reputation: 354
I think Runtime.getRuntime().exec("ant deploy");
depends on your OS, if you just run it in one fixed OS, it is really a simpler and easy way to get what you want. :)
Upvotes: 0
Reputation: 31212
I think invoking a system call would be simpler:
try {
Runtime.getRuntime().exec("ant scpTask");
} catch (IOException e) {
e.printStackTrace();
}
Upvotes: 0
Reputation: 4676
This would certainly work to include the Ant task inside your Java code. We have done this before as a last resort. One gotcha is you will likely be setting some Ant specific properties (e.g. setProject) to get the task to actually work. This can make it a bit awkward to use. In addition, you will likely need, as you mention, the Ant runtime libraries to get this to run.
My first recommendation would be to see if there is a way to call the actual SCP code you want directly without the Ant overhead. The second alternative would be to look for a Java SCP library or find out what the Ant scp task is using. See scp via java for some more examples. The final recommendation would be to include the Ant task as described above.
Upvotes: 0