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
.ListableBeanFactory
;
32 import org
.springframework
.beans
.factory
.config
.PropertyPlaceholderConfigurer
;
33 import org
.springframework
.beans
.factory
.xml
.XmlBeanDefinitionReader
;
34 import org
.springframework
.context
.ApplicationContext
;
35 import org
.springframework
.context
.ConfigurableApplicationContext
;
36 import org
.springframework
.context
.support
.GenericApplicationContext
;
37 import org
.springframework
.core
.io
.DefaultResourceLoader
;
38 import org
.springframework
.core
.io
.Resource
;
39 import org
.springframework
.core
.io
.ResourceLoader
;
40 import org
.springframework
.util
.SystemPropertyUtils
;
42 public class AntSlcApplication
{
43 private final static String DEFAULT_APP_LOG4J_PROPERTIES
= "org/argeo/slc/ant/defaultAppLog4j.properties";
45 private final static Log log
= LogFactory
.getLog(AntSlcApplication
.class);
47 private Resource contextLocation
;
48 private ApplicationContext parentContext
;
50 private Resource rootDir
;
51 private Resource confDir
;
54 public void execute(SlcExecution slcExecution
, Properties properties
,
55 Map
<String
, Object
> references
,
56 SlcExecutionOutput
<AntExecutionContext
> executionOutput
) {
58 // Properties and application logging initialization
59 initSystemProperties(properties
);
60 Log4jUtils
.initLog4j("classpath:" + DEFAULT_APP_LOG4J_PROPERTIES
);
62 log
.info("\n###\n### Start SLC execution " + slcExecution
.getUuid()
64 if (log
.isDebugEnabled()) {
65 log
.debug("rootDir=" + rootDir
);
66 log
.debug("confDir=" + confDir
);
67 log
.debug("workDir=" + workDir
);
70 // Spring initialization
71 ConfigurableApplicationContext ctx
= createExecutionContext(slcExecution
);
74 String scriptRelativePath
= findAntScript(slcExecution
);
75 List
<String
> targets
= findAntTargets(slcExecution
);
77 // Ant project initialization
78 Project project
= new Project();
79 AntExecutionContext executionContext
= new AntExecutionContext(project
);
80 project
.addReference(AntConstants
.REF_ROOT_CONTEXT
, ctx
);
81 project
.addReference(AntConstants
.REF_SLC_EXECUTION
, slcExecution
);
82 initProject(project
, properties
, references
);
83 parseProject(project
, scriptRelativePath
);
86 initStructure(project
, scriptRelativePath
);
87 runProject(project
, targets
);
89 if (executionOutput
!= null)
90 executionOutput
.postExecution(executionContext
);
95 protected void initSystemProperties(Properties userProperties
) {
96 // Set user properties as system properties so that Spring can access
98 if (userProperties
!= null) {
99 for (Object key
: userProperties
.keySet()) {
100 System
.setProperty(key
.toString(), userProperties
101 .getProperty(key
.toString()));
105 if (System
.getProperty(AntConstants
.DEFAULT_TEST_RUN_PROPERTY
) == null) {
106 System
.setProperty(AntConstants
.DEFAULT_TEST_RUN_PROPERTY
,
112 System
.setProperty(AntConstants
.ROOT_DIR_PROPERTY
, rootDir
113 .getURL().toString());
115 System
.setProperty(AntConstants
.CONF_DIR_PROPERTY
, confDir
116 .getURL().toString());
118 System
.setProperty(AntConstants
.WORK_DIR_PROPERTY
, workDir
119 .getCanonicalPath());
121 // Additional properties in slc.properties file. Already set sytem
122 // properties (such as the various directories) can be resolved in
124 if (confDir
!= null) {
125 Resource slcPropertiesRes
= confDir
126 .createRelative("slc.properties");
127 if (slcPropertiesRes
.exists()) {
128 Properties slcProperties
= new Properties();
129 InputStream in
= slcPropertiesRes
.getInputStream();
131 slcProperties
.load(in
);
133 IOUtils
.closeQuietly(in
);
136 for (String key
: slcProperties
.stringPropertyNames()) {
137 if (!System
.getProperties().containsKey(key
)) {
138 String value
= SystemPropertyUtils
139 .resolvePlaceholders(slcProperties
141 System
.setProperty(key
, value
);
146 } catch (Exception e
) {
147 throw new SlcException("Cannot init system properties.", e
);
151 protected ConfigurableApplicationContext
createExecutionContext(
152 SlcExecution slcExecution
) {
155 // Find runtime definition
156 Resource runtimeRes
= null;
157 String runtimeStr
= slcExecution
.getAttributes().get(
158 AntConstants
.EXECATTR_RUNTIME
);
159 if (runtimeStr
== null)
160 runtimeStr
= "default";
162 ResourceLoader rl
= new DefaultResourceLoader(getClass()
164 try {// tries absolute reference
165 runtimeRes
= rl
.getResource(runtimeStr
);
166 } catch (Exception e
) {
169 if (runtimeRes
== null || !runtimeRes
.exists()) {
171 runtimeRes
= confDir
.createRelative("runtime/" + runtimeStr
175 // Find runtime independent application context definition
176 if (confDir
!= null && contextLocation
== null) {
177 contextLocation
= confDir
178 .createRelative("applicationContext.xml");
181 GenericApplicationContext ctx
= new GenericApplicationContext(
183 ctx
.setDisplayName("SLC Execution #" + slcExecution
.getUuid());
185 XmlBeanDefinitionReader xmlReader
= new XmlBeanDefinitionReader(ctx
);
186 if (runtimeRes
!= null && runtimeRes
.exists())
187 xmlReader
.loadBeanDefinitions(runtimeRes
);
189 log
.warn("No runtime context defined");
191 if (contextLocation
!= null && contextLocation
.exists())
192 xmlReader
.loadBeanDefinitions(contextLocation
);
194 log
.warn("No runtime independent application context defined");
196 // Add property place holder
197 PropertyPlaceholderConfigurer ppc
= new PropertyPlaceholderConfigurer();
198 ppc
.setIgnoreUnresolvablePlaceholders(true);
199 ctx
.addBeanFactoryPostProcessor(ppc
);
203 } catch (Exception e
) {
204 throw new SlcException(
205 "Cannot create SLC execution application context.", e
);
209 protected String
findAntScript(SlcExecution slcExecution
) {
210 String scriptStr
= slcExecution
.getAttributes().get(
211 AntConstants
.EXECATTR_ANT_FILE
);
212 if (scriptStr
== null)
213 throw new SlcException("No Ant script provided");
218 protected List
<String
> findAntTargets(SlcExecution slcExecution
) {
219 String targetList
= slcExecution
.getAttributes().get(
220 AntConstants
.EXECATTR_ANT_TARGETS
);
221 List
<String
> targets
= new Vector
<String
>();
222 if (targetList
!= null) {
223 StringTokenizer stTargets
= new StringTokenizer(targetList
, ",");
224 while (stTargets
.hasMoreTokens()) {
225 targets
.add(stTargets
.nextToken());
231 protected void initProject(Project project
, Properties properties
,
232 Map
<String
, Object
> references
) {
233 if (properties
!= null) {
234 for (Map
.Entry
<Object
, Object
> entry
: properties
.entrySet()) {
235 project
.setUserProperty(entry
.getKey().toString(), entry
236 .getValue().toString());
240 if (references
!= null) {
241 for (Map
.Entry
<String
, Object
> entry
: references
.entrySet()) {
242 project
.addReference(entry
.getKey(), entry
.getValue());
246 project
.addBuildListener(new CommonsLoggingListener());
248 ListableBeanFactory context
= (ListableBeanFactory
) project
249 .getReference(AntConstants
.REF_ROOT_CONTEXT
);
250 // Register build listeners
251 Map
<String
, BuildListener
> listeners
= context
.getBeansOfType(
252 BuildListener
.class, false, true);
253 for (BuildListener listener
: listeners
.values()) {
254 project
.addBuildListener(listener
);
257 // Register log4j appenders from context
258 MDC
.put(AntConstants
.MDC_ANT_PROJECT
, project
);
259 Map
<String
, Appender
> appenders
= context
.getBeansOfType(
260 Appender
.class, false, true);
261 for (Appender appender
: appenders
.values()) {
262 LogManager
.getRootLogger().addAppender(appender
);
266 addCustomTaskAndTypes(project
);
269 /** Loads the SLC specific Ant tasks. */
270 protected void addCustomTaskAndTypes(Project project
) {
271 Properties taskdefs
= getDefs(project
,
272 AntConstants
.SLC_TASKDEFS_RESOURCE_PATH
);
273 for (Object o
: taskdefs
.keySet()) {
274 String name
= o
.toString();
276 project
.addTaskDefinition(name
, Class
.forName(taskdefs
277 .getProperty(name
)));
278 } catch (ClassNotFoundException e
) {
279 log
.error("Unknown class for task " + name
, e
);
282 Properties typedefs
= getDefs(project
,
283 AntConstants
.SLC_TYPEDEFS_RESOURCE_PATH
);
284 for (Object o
: typedefs
.keySet()) {
285 String name
= o
.toString();
287 project
.addDataTypeDefinition(name
, Class
.forName(typedefs
288 .getProperty(name
)));
289 } catch (ClassNotFoundException e
) {
290 log
.error("Unknown class for type " + name
, e
);
295 private Properties
getDefs(Project project
, String path
) {
296 Properties defs
= new Properties();
298 InputStream in
= project
.getClass().getResourceAsStream(path
);
301 } catch (IOException e
) {
302 throw new SlcException("Cannot load task definitions", e
);
307 protected void initStructure(Project project
, String scriptRelativePath
) {
308 // Init structure registry
309 StructureRegistry
<TreeSPath
> registry
= new TreeSRegistry();
310 project
.addReference(AntConstants
.REF_STRUCTURE_REGISTRY
, registry
);
313 StringTokenizer st
= new StringTokenizer(scriptRelativePath
, "/");
314 TreeSPath currPath
= null;
315 while (st
.hasMoreTokens()) {
316 String name
= st
.nextToken();
317 if (currPath
== null) {
318 currPath
= TreeSPath
.createRootPath(name
);
320 if (st
.hasMoreTokens())// don't register project file
321 currPath
= currPath
.createChild(name
);
323 registry
.register(currPath
, new SimpleSElement(name
));
327 String projectName
= project
.getName() != null
328 && !project
.getName().equals("") ? project
.getName()
330 TreeSPath projectPath
= currPath
.createChild(projectName
);
332 String projectDesc
= project
.getDescription() != null
333 && !project
.getDescription().equals("") ? project
334 .getDescription() : projectPath
.getName();
336 registry
.register(projectPath
, new SimpleSElement(projectDesc
));
337 project
.addReference(AntConstants
.REF_PROJECT_PATH
, projectPath
);
339 if (log
.isDebugEnabled())
340 log
.debug("Project path: " + projectPath
);
343 protected void parseProject(Project project
, String scriptRelativePath
) {
345 Resource script
= rootDir
.createRelative(scriptRelativePath
);
348 File scriptFile
= script
.getFile();
349 baseDir
= scriptFile
.getParentFile();
350 } catch (IOException e
) {// resource is not a file
351 baseDir
= new File(System
.getProperty("user.dir"));
353 project
.setBaseDir(baseDir
);
354 // Reset basedir property, in order to avoid base dir override when
356 project
.setProperty("basedir", baseDir
.getAbsolutePath());
358 ProjectHelper2 projectHelper
= new ProjectHelper2();
359 project
.addReference(ProjectHelper
.PROJECTHELPER_REFERENCE
,
361 projectHelper
.parse(project
, script
.getURL());
362 } catch (Exception e
) {
363 throw new SlcException("Could not parse project for script "
364 + scriptRelativePath
, e
);
369 protected void runProject(Project p
, List
<String
> targets
) {
370 p
.fireBuildStarted();
371 Throwable exception
= null;
373 if (targets
.size() == 0) {// no target defined
374 p
.executeTarget(p
.getDefaultTarget());
376 p
.executeTargets(new Vector
<String
>(targets
));
378 } catch (Throwable e
) {
380 throw new SlcException("SLC Ant execution failed", exception
);
382 p
.fireBuildFinished(exception
);
386 public void setContextLocation(Resource contextLocation
) {
387 this.contextLocation
= contextLocation
;
390 public void setRootDir(Resource rootDir
) {
391 this.rootDir
= rootDir
;
394 public void setConfDir(Resource confDir
) {
395 this.confDir
= confDir
;
398 public void setWorkDir(File workDir
) {
399 this.workDir
= workDir
;
402 public void setParentContext(ApplicationContext runtimeContext
) {
403 this.parentContext
= runtimeContext
;