]> git.argeo.org Git - gpl/argeo-slc.git/blob - org.argeo.slc.agent/src/main/java/org/argeo/slc/ant/AntRunner.java
Improve Spring/Ant bridge
[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.springframework.context.ApplicationContext;
13
14 public class AntRunner {
15 private ApplicationContext context;
16 private ProjectHelper projectHelper;
17 private URL buildFile;
18 private String[] targets;
19 private Properties properties;
20
21 public AntRunner() {
22
23 }
24
25 public AntRunner(ApplicationContext context, ProjectHelper projectHelper,
26 URL buildFile, String[] targets) {
27 super();
28 this.context = context;
29 this.projectHelper = projectHelper;
30 this.buildFile = buildFile;
31 this.targets = targets;
32 }
33
34 public AntRunner(ApplicationContext context, URL buildFile, String target) {
35 super();
36 this.context = context;
37
38 BasicSlcProjectHelper basicSlcProjectHelper = new BasicSlcProjectHelper();
39 this.projectHelper = basicSlcProjectHelper;
40 basicSlcProjectHelper.setContext(context);
41
42 this.buildFile = buildFile;
43 this.targets = new String[] { target };
44 }
45
46 public void run() {
47 Project p = new Project();
48
49 String path = buildFile.getFile();
50 p.setUserProperty("ant.file", path);
51 p.setBaseDir(extractBaseDir(path));
52
53 p.init();
54 p.addReference(ProjectHelper.PROJECTHELPER_REFERENCE, projectHelper);
55 projectHelper.parse(p, buildFile);
56
57 if (properties != null) {
58 for (Map.Entry<Object, Object> entry : properties.entrySet()) {
59 p.setUserProperty(entry.getKey().toString(), entry.getValue()
60 .toString());
61 }
62 }
63
64 p.fireBuildStarted();
65 Throwable exception = null;
66 try {
67 if (targets == null) {
68 p.executeTarget(p.getDefaultTarget());
69 } else {
70 p.executeTargets(new Vector<String>(Arrays.asList(targets)));
71 }
72 } catch (Throwable e) {
73 exception = e;
74 throw new SlcAntException("Could not run Ant script " + buildFile,
75 e);
76 } finally {
77 p.fireBuildFinished(exception);
78 }
79
80 }
81
82 private File extractBaseDir(String path) {
83 String baseDir = null;
84 if (path.length() > 1) {
85 int indx = path.lastIndexOf('/', path.length() - 1);
86 if (indx == -1 || indx == 0) {
87 baseDir = "/";
88 } else {
89 baseDir = path.substring(0, indx) + "/";
90 }
91 } else {
92 baseDir = "/";
93 }
94 File file = new File(baseDir);
95 if (file.exists()) {
96 return file;
97 } else {
98 return new File(System.getProperty("user.dir"));
99 }
100 }
101
102 public static void main(String[] args) {
103 // TODO Auto-generated method stub
104
105 }
106
107 }