1 package org
.argeo
.slc
.ant
;
4 import java
.io
.IOException
;
5 import java
.io
.InputStream
;
8 import java
.util
.Properties
;
9 import java
.util
.StringTokenizer
;
10 import java
.util
.Vector
;
12 import org
.apache
.commons
.io
.IOUtils
;
13 import org
.apache
.commons
.logging
.Log
;
14 import org
.apache
.commons
.logging
.LogFactory
;
15 import org
.apache
.log4j
.Appender
;
16 import org
.apache
.log4j
.LogManager
;
17 import org
.apache
.log4j
.MDC
;
18 import org
.apache
.tools
.ant
.BuildListener
;
19 import org
.apache
.tools
.ant
.Project
;
20 import org
.apache
.tools
.ant
.ProjectHelper
;
21 import org
.apache
.tools
.ant
.helper
.ProjectHelper2
;
22 import org
.apache
.tools
.ant
.listener
.CommonsLoggingListener
;
23 import org
.argeo
.slc
.core
.SlcException
;
24 import org
.argeo
.slc
.core
.process
.SlcExecution
;
25 import org
.argeo
.slc
.core
.structure
.SimpleSElement
;
26 import org
.argeo
.slc
.core
.structure
.StructureRegistry
;
27 import org
.argeo
.slc
.core
.structure
.tree
.TreeSPath
;
28 import org
.argeo
.slc
.core
.structure
.tree
.TreeSRegistry
;
29 import org
.argeo
.slc
.logging
.Log4jUtils
;
30 import org
.argeo
.slc
.runtime
.SlcExecutionOutput
;
31 import org
.springframework
.beans
.factory
.BeanFactoryUtils
;
32 import org
.springframework
.beans
.factory
.ListableBeanFactory
;
33 import org
.springframework
.beans
.factory
.config
.PropertyPlaceholderConfigurer
;
34 import org
.springframework
.beans
.factory
.xml
.XmlBeanDefinitionReader
;
35 import org
.springframework
.context
.ApplicationContext
;
36 import org
.springframework
.context
.ConfigurableApplicationContext
;
37 import org
.springframework
.context
.support
.GenericApplicationContext
;
38 import org
.springframework
.core
.io
.DefaultResourceLoader
;
39 import org
.springframework
.core
.io
.Resource
;
40 import org
.springframework
.core
.io
.ResourceLoader
;
41 import org
.springframework
.util
.SystemPropertyUtils
;
43 public class AntSlcApplication
{
44 private final static String DEFAULT_APP_LOG4J_PROPERTIES
= "org/argeo/slc/ant/defaultAppLog4j.properties";
46 private final static Log log
= LogFactory
.getLog(AntSlcApplication
.class);
48 private Resource contextLocation
;
49 private ConfigurableApplicationContext parentContext
;
51 private Resource rootDir
;
52 private Resource confDir
;
55 public void execute(SlcExecution slcExecution
, Properties properties
,
56 Map
<String
, Object
> references
,
57 SlcExecutionOutput
<AntExecutionContext
> executionOutput
) {
59 // Properties and application logging initialization
60 initSystemProperties(properties
);
61 Log4jUtils
.initLog4j("classpath:" + DEFAULT_APP_LOG4J_PROPERTIES
);
63 log
.info("\n###\n### Start SLC execution " + slcExecution
.getUuid()
65 if (log
.isDebugEnabled()) {
66 log
.debug("rootDir=" + rootDir
);
67 log
.debug("confDir=" + confDir
);
68 log
.debug("workDir=" + workDir
);
71 // Spring initialization
72 ConfigurableApplicationContext ctx
= createExecutionContext(slcExecution
);
75 String scriptRelativePath
= findAntScript(slcExecution
);
76 List
<String
> targets
= findAntTargets(slcExecution
);
78 // Ant project initialization
79 Project project
= new Project();
80 AntExecutionContext executionContext
= new AntExecutionContext(project
);
81 project
.addReference(AntConstants
.REF_ROOT_CONTEXT
, ctx
);
82 project
.addReference(AntConstants
.REF_SLC_EXECUTION
, slcExecution
);
83 initProject(project
, properties
, references
);
84 parseProject(project
, scriptRelativePath
);
87 initStructure(project
, scriptRelativePath
);
88 runProject(project
, targets
);
90 if (executionOutput
!= null)
91 executionOutput
.postExecution(executionContext
);
96 protected void initSystemProperties(Properties userProperties
) {
97 // Set user properties as system properties so that Spring can access
99 if (userProperties
!= null) {
100 for (Object key
: userProperties
.keySet()) {
101 System
.setProperty(key
.toString(), userProperties
102 .getProperty(key
.toString()));
106 if (System
.getProperty(AntConstants
.DEFAULT_TEST_RUN_PROPERTY
) == null) {
107 System
.setProperty(AntConstants
.DEFAULT_TEST_RUN_PROPERTY
,
113 System
.setProperty(AntConstants
.ROOT_DIR_PROPERTY
, rootDir
114 .getURL().toString());
116 System
.setProperty(AntConstants
.CONF_DIR_PROPERTY
, confDir
117 .getURL().toString());
119 System
.setProperty(AntConstants
.WORK_DIR_PROPERTY
, workDir
120 .getCanonicalPath());
122 // Additional properties in slc.properties file. Already set sytem
123 // properties (such as the various directories) can be resolved in
125 if (confDir
!= null) {
126 Resource slcPropertiesRes
= confDir
127 .createRelative("slc.properties");
128 if (slcPropertiesRes
.exists()) {
129 Properties slcProperties
= new Properties();
130 InputStream in
= slcPropertiesRes
.getInputStream();
132 slcProperties
.load(in
);
134 IOUtils
.closeQuietly(in
);
137 for (String key
: slcProperties
.stringPropertyNames()) {
138 if (!System
.getProperties().containsKey(key
)) {
139 String value
= SystemPropertyUtils
140 .resolvePlaceholders(slcProperties
142 System
.setProperty(key
, value
);
147 } catch (Exception e
) {
148 throw new SlcException("Cannot init system properties.", e
);
152 protected ConfigurableApplicationContext
createExecutionContext(
153 SlcExecution slcExecution
) {
156 // Find runtime definition
157 Resource runtimeRes
= null;
158 String runtimeStr
= slcExecution
.getAttributes().get(
159 AntConstants
.EXECATTR_RUNTIME
);
160 if (runtimeStr
== null)
161 runtimeStr
= "default";
163 ResourceLoader rl
= new DefaultResourceLoader(getClass()
165 try {// tries absolute reference
166 runtimeRes
= rl
.getResource(runtimeStr
);
167 } catch (Exception e
) {
170 if (runtimeRes
== null || !runtimeRes
.exists()) {
172 runtimeRes
= confDir
.createRelative("runtime/" + runtimeStr
176 // Find runtime independent application context definition
177 if (confDir
!= null && contextLocation
== null) {
178 contextLocation
= confDir
179 .createRelative("applicationContext.xml");
182 GenericApplicationContext ctx
= new GenericApplicationContext(
184 ctx
.setDisplayName("SLC Execution #" + slcExecution
.getUuid());
186 XmlBeanDefinitionReader xmlReader
= new XmlBeanDefinitionReader(ctx
);
187 if (runtimeRes
!= null && runtimeRes
.exists())
188 xmlReader
.loadBeanDefinitions(runtimeRes
);
190 log
.warn("No runtime context defined");
192 if (contextLocation
!= null && contextLocation
.exists())
193 xmlReader
.loadBeanDefinitions(contextLocation
);
195 log
.warn("No runtime independent application context defined");
197 // Add property place holder
198 PropertyPlaceholderConfigurer ppc
= new PropertyPlaceholderConfigurer();
199 ppc
.setIgnoreUnresolvablePlaceholders(true);
200 ctx
.addBeanFactoryPostProcessor(ppc
);
204 } catch (Exception e
) {
205 throw new SlcException(
206 "Cannot create SLC execution application context.", e
);
210 protected String
findAntScript(SlcExecution slcExecution
) {
211 String scriptStr
= slcExecution
.getAttributes().get(
212 AntConstants
.EXECATTR_ANT_FILE
);
213 if (scriptStr
== null)
214 throw new SlcException("No Ant script provided");
219 protected List
<String
> findAntTargets(SlcExecution slcExecution
) {
220 String targetList
= slcExecution
.getAttributes().get(
221 AntConstants
.EXECATTR_ANT_TARGETS
);
222 List
<String
> targets
= new Vector
<String
>();
223 if (targetList
!= null) {
224 StringTokenizer stTargets
= new StringTokenizer(targetList
, ",");
225 while (stTargets
.hasMoreTokens()) {
226 targets
.add(stTargets
.nextToken());
232 protected void initProject(Project project
, Properties properties
,
233 Map
<String
, Object
> references
) {
234 if (properties
!= null) {
235 for (Map
.Entry
<Object
, Object
> entry
: properties
.entrySet()) {
236 project
.setUserProperty(entry
.getKey().toString(), entry
237 .getValue().toString());
241 if (references
!= null) {
242 for (Map
.Entry
<String
, Object
> entry
: references
.entrySet()) {
243 project
.addReference(entry
.getKey(), entry
.getValue());
247 project
.addBuildListener(new CommonsLoggingListener());
249 ListableBeanFactory context
= (ListableBeanFactory
) project
250 .getReference(AntConstants
.REF_ROOT_CONTEXT
);
251 // Register build listeners
252 Map
<String
, BuildListener
> listeners
= BeanFactoryUtils
253 .beansOfTypeIncludingAncestors(context
, BuildListener
.class,
255 for (BuildListener listener
: listeners
.values()) {
256 project
.addBuildListener(listener
);
259 // Register log4j appenders from context
260 MDC
.put(AntConstants
.MDC_ANT_PROJECT
, project
);
261 Map
<String
, Appender
> appenders
= context
.getBeansOfType(
262 Appender
.class, false, true);
263 for (Appender appender
: appenders
.values()) {
264 LogManager
.getRootLogger().addAppender(appender
);
268 addCustomTaskAndTypes(project
);
271 /** Loads the SLC specific Ant tasks. */
272 protected void addCustomTaskAndTypes(Project project
) {
273 Properties taskdefs
= getDefs(project
,
274 AntConstants
.SLC_TASKDEFS_RESOURCE_PATH
);
275 for (Object o
: taskdefs
.keySet()) {
276 String name
= o
.toString();
278 project
.addTaskDefinition(name
, Class
.forName(taskdefs
279 .getProperty(name
)));
280 } catch (ClassNotFoundException e
) {
281 log
.error("Unknown class for task " + name
, e
);
284 Properties typedefs
= getDefs(project
,
285 AntConstants
.SLC_TYPEDEFS_RESOURCE_PATH
);
286 for (Object o
: typedefs
.keySet()) {
287 String name
= o
.toString();
289 project
.addDataTypeDefinition(name
, Class
.forName(typedefs
290 .getProperty(name
)));
291 } catch (ClassNotFoundException e
) {
292 log
.error("Unknown class for type " + name
, e
);
297 private Properties
getDefs(Project project
, String path
) {
298 Properties defs
= new Properties();
300 InputStream in
= project
.getClass().getResourceAsStream(path
);
303 } catch (IOException e
) {
304 throw new SlcException("Cannot load task definitions", e
);
309 protected void initStructure(Project project
, String scriptRelativePath
) {
310 // Init structure registry
311 StructureRegistry
<TreeSPath
> registry
= new TreeSRegistry();
312 project
.addReference(AntConstants
.REF_STRUCTURE_REGISTRY
, registry
);
315 StringTokenizer st
= new StringTokenizer(scriptRelativePath
, "/");
316 TreeSPath currPath
= null;
317 while (st
.hasMoreTokens()) {
318 String name
= st
.nextToken();
319 if (currPath
== null) {
320 currPath
= TreeSPath
.createRootPath(name
);
322 if (st
.hasMoreTokens())// don't register project file
323 currPath
= currPath
.createChild(name
);
325 registry
.register(currPath
, new SimpleSElement(name
));
329 String projectName
= project
.getName() != null
330 && !project
.getName().equals("") ? project
.getName()
332 TreeSPath projectPath
= currPath
.createChild(projectName
);
334 String projectDesc
= project
.getDescription() != null
335 && !project
.getDescription().equals("") ? project
336 .getDescription() : projectPath
.getName();
338 registry
.register(projectPath
, new SimpleSElement(projectDesc
));
339 project
.addReference(AntConstants
.REF_PROJECT_PATH
, projectPath
);
341 if (log
.isDebugEnabled())
342 log
.debug("Project path: " + projectPath
);
345 protected void parseProject(Project project
, String scriptRelativePath
) {
347 Resource script
= rootDir
.createRelative(scriptRelativePath
);
350 File scriptFile
= script
.getFile();
351 baseDir
= scriptFile
.getParentFile();
352 } catch (IOException e
) {// resource is not a file
353 baseDir
= new File(System
.getProperty("user.dir"));
355 project
.setBaseDir(baseDir
);
356 // Reset basedir property, in order to avoid base dir override when
358 project
.setProperty("basedir", baseDir
.getAbsolutePath());
360 ProjectHelper2 projectHelper
= new ProjectHelper2();
361 project
.addReference(ProjectHelper
.PROJECTHELPER_REFERENCE
,
363 projectHelper
.parse(project
, script
.getURL());
364 } catch (Exception e
) {
365 throw new SlcException("Could not parse project for script "
366 + scriptRelativePath
, e
);
371 protected void runProject(Project p
, List
<String
> targets
) {
372 p
.fireBuildStarted();
373 Throwable exception
= null;
375 if (targets
.size() == 0) {// no target defined
376 p
.executeTarget(p
.getDefaultTarget());
378 p
.executeTargets(new Vector
<String
>(targets
));
380 } catch (Throwable e
) {
382 throw new SlcException("SLC Ant execution failed", exception
);
384 p
.fireBuildFinished(exception
);
388 public void setContextLocation(Resource contextLocation
) {
389 this.contextLocation
= contextLocation
;
392 public void setRootDir(Resource rootDir
) {
393 this.rootDir
= rootDir
;
396 public void setConfDir(Resource confDir
) {
397 this.confDir
= confDir
;
400 public void setWorkDir(File workDir
) {
401 this.workDir
= workDir
;
404 public void setParentContext(ConfigurableApplicationContext runtimeContext
) {
405 this.parentContext
= runtimeContext
;