]> git.argeo.org Git - gpl/argeo-slc.git/blob - org.argeo.slc.agent/src/main/java/org/argeo/slc/ant/AntRunner.java
Improve packaging
[gpl/argeo-slc.git] / org.argeo.slc.agent / src / main / java / org / argeo / slc / ant / AntRunner.java
1 package org.argeo.slc.ant;
2
3 import java.io.File;
4 import java.net.URL;
5 import java.util.Arrays;
6 import java.util.Map;
7 import java.util.Properties;
8 import java.util.Vector;
9
10 import org.apache.tools.ant.Project;
11 import org.apache.tools.ant.ProjectHelper;
12 import org.apache.tools.ant.helper.ProjectHelper2;
13 import org.argeo.slc.core.SlcException;
14
15 /** Run regular Ant script (that is, not SLC instrumented) */
16 public class AntRunner {
17 private URL buildFile;
18 private String[] targets;
19 private Properties properties;
20
21 public AntRunner() {
22
23 }
24
25 public AntRunner(URL buildFile, String target, Properties properties) {
26 this(buildFile, new String[] { target }, properties);
27 }
28
29 public AntRunner(URL buildFile, String[] targets, Properties properties) {
30 this.buildFile = buildFile;
31 this.targets = targets;
32 this.properties = properties;
33 }
34
35 public void run() {
36 Project p = new Project();
37
38 String path = buildFile.getFile();
39 p.setUserProperty("ant.file", path);
40 p.setBaseDir(extractBaseDir(path));
41
42 p.init();
43 ProjectHelper projectHelper = new ProjectHelper2();
44 p.addReference(ProjectHelper.PROJECTHELPER_REFERENCE, projectHelper);
45 projectHelper.parse(p, buildFile);
46
47 if (properties != null) {
48 for (Map.Entry<Object, Object> entry : properties.entrySet()) {
49 p.setUserProperty(entry.getKey().toString(), entry.getValue()
50 .toString());
51 }
52 }
53
54 p.fireBuildStarted();
55 Throwable exception = null;
56 try {
57 if (targets == null) {
58 p.executeTarget(p.getDefaultTarget());
59 } else {
60 p.executeTargets(new Vector<String>(Arrays.asList(targets)));
61 }
62 } catch (Throwable e) {
63 exception = e;
64 throw new SlcException("Could not run Ant script " + buildFile, e);
65 } finally {
66 p.fireBuildFinished(exception);
67 }
68
69 }
70
71 private File extractBaseDir(String path) {
72 String baseDir = null;
73 if (path.length() > 1) {
74 int indx = path.lastIndexOf('/', path.length() - 1);
75 if (indx == -1 || indx == 0) {
76 baseDir = "/";
77 } else {
78 baseDir = path.substring(0, indx) + "/";
79 }
80 } else {
81 baseDir = "/";
82 }
83 File file = new File(baseDir);
84 if (file.exists()) {
85 return file;
86 } else {
87 return new File(System.getProperty("user.dir"));
88 }
89 }
90
91 }