KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > apache > cactus > integration > ant > container > AbstractContainer


1 /*
2  * ========================================================================
3  *
4  * Copyright 2003-2004 The Apache Software Foundation.
5  *
6  * Licensed under the Apache License, Version 2.0 (the "License");
7  * you may not use this file except in compliance with the License.
8  * You may obtain a copy of the License at
9  *
10  * http://www.apache.org/licenses/LICENSE-2.0
11  *
12  * Unless required by applicable law or agreed to in writing, software
13  * distributed under the License is distributed on an "AS IS" BASIS,
14  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15  * See the License for the specific language governing permissions and
16  * limitations under the License.
17  *
18  * ========================================================================
19  */

20 package org.apache.cactus.integration.ant.container;
21
22 import java.io.File JavaDoc;
23 import java.io.IOException JavaDoc;
24
25 import org.apache.cactus.integration.ant.deployment.DeployableFile;
26 import org.apache.cactus.integration.ant.util.AntLog;
27 import org.apache.cactus.integration.ant.util.AntTaskFactory;
28 import org.apache.commons.logging.Log;
29 import org.apache.tools.ant.BuildException;
30 import org.apache.tools.ant.ProjectComponent;
31 import org.apache.tools.ant.Task;
32 import org.apache.tools.ant.filters.ReplaceTokens;
33 import org.apache.tools.ant.taskdefs.Delete;
34 import org.apache.tools.ant.types.FileSet;
35 import org.apache.tools.ant.types.FilterChain;
36 import org.apache.tools.ant.types.Path;
37 import org.apache.tools.ant.types.PatternSet;
38 import org.apache.tools.ant.types.Environment.Variable;
39 import org.apache.tools.ant.types.selectors.SelectorUtils;
40
41 /**
42  * Abstract base class for supporting specific containers as nested elements in
43  * the {@link org.apache.cactus.integration.ant.CactusTask}.
44  *
45  * @version $Id: AbstractContainer.java,v 1.18 2004/05/31 20:05:22 vmassol Exp $
46  */

47 public abstract class AbstractContainer extends ProjectComponent
48     implements Container
49 {
50     // Constants ---------------------------------------------------------------
51

52     /**
53      * The path under which the container resources are stored in the JAR.
54      */

55     protected static final String JavaDoc RESOURCE_PATH =
56         "/org/apache/cactus/integration/ant/container/resources/";
57
58     // Instance Variables ------------------------------------------------------
59

60     /**
61      * The WAR or EAR that should be deployed to the container.
62      */

63     private DeployableFile deployableFile;
64
65     /**
66      * A pattern set which lists patterns for names of test cases that are to be
67      * excluded from a specific container.
68      */

69     private PatternSet patternSet = new PatternSet();
70
71     /**
72      * The directory to which the test reports should be written.
73      */

74     private File JavaDoc toDir;
75
76     /**
77      * Name of a property that must exist in the project if tests are to be run
78      * on the container.
79      */

80     private String JavaDoc ifCondition;
81
82     /**
83      * Name of a property that must not exist in the project if tests are to be
84      * run on the container.
85      */

86     private String JavaDoc unlessCondition;
87
88     /**
89      * The factory for creating ant tasks.
90      */

91     private AntTaskFactory antTaskFactory;
92
93     /**
94      * The log to use.
95      */

96     private Log log = AntLog.NULL;
97
98     /**
99      * List of system properties to set in the container JVM.
100      */

101     private Variable[] systemProperties;
102
103     /**
104      * The time to sleep after the container has started up.
105      */

106     private long startUpWait = 1000;
107
108     /**
109      * Additional classpath entries for the classpath that will be used to
110      * start the containers.
111      */

112     private Path containerClasspath;
113     
114     // Public Methods ----------------------------------------------------------
115

116     /**
117      * @see Container#getTestContext()
118      */

119     public String JavaDoc getTestContext()
120     {
121         return null;
122     }
123     
124     /**
125      * Sets the time to wait after the container has been started up.
126      *
127      * The default time is 1 second.
128      *
129      * Note: This is a hack while waiting for container specific solutions
130      * that tell exactly when the server is started or not. ATM, the only known
131      * issue is with JBoss, where the servlet engine is started before the full
132      * JBoss is started and thus it may happen that we try to shutdown JBoss
133      * before it has finished starting, leading to an exception.
134      *
135      * @param theStartUpWait The time to wait in milliseconds
136      */

137     public void setStartUpWait(long theStartUpWait)
138     {
139         this.startUpWait = theStartUpWait;
140     }
141
142     /**
143      * Creates a nested exclude element that is added to the pattern set.
144      *
145      * @return The created exclude element
146      */

147     public final PatternSet.NameEntry createExclude()
148     {
149         return this.patternSet.createExclude();
150     }
151
152     /**
153      * Returns the exclude patterns.
154      *
155      * @return The exclude patterns
156      */

157     public final String JavaDoc[] getExcludePatterns()
158     {
159         return this.patternSet.getExcludePatterns(getProject());
160     }
161
162     /**
163      * Sets the name of a property that must exist in the project if tests are
164      * to be run on the container.
165      *
166      * @param theIfCondition The property name to set
167      */

168     public final void setIf(String JavaDoc theIfCondition)
169     {
170         this.ifCondition = theIfCondition;
171     }
172
173     /**
174      * Sets the directory to which the test reports should be written.
175      *
176      * @param theToDir The output directory to set
177      */

178     public final void setToDir(File JavaDoc theToDir)
179     {
180         this.toDir = theToDir;
181     }
182
183     /**
184      * Sets the name of a property that must not exist in the project if tests
185      * are to be run on the container.
186      *
187      * @param theUnlessCondition The property name to set
188      */

189     public final void setUnless(String JavaDoc theUnlessCondition)
190     {
191         this.unlessCondition = theUnlessCondition;
192     }
193
194     // Container Implementation ------------------------------------------------
195

196     /**
197      * @see Container#getStartUpWait
198      */

199     public long getStartUpWait()
200     {
201         return this.startUpWait;
202     }
203
204     /**
205      * @see Container#getToDir
206      */

207     public final File JavaDoc getToDir()
208     {
209         return this.toDir;
210     }
211
212     /**
213      * The default implementation does nothing.
214      *
215      * @see Container#init
216      */

217     public void init()
218     {
219         // The default implementation doesn nothing
220
}
221
222     /**
223      * @see Container#isEnabled
224      */

225     public final boolean isEnabled()
226     {
227         return (testIfCondition() && testUnlessCondition());
228     }
229
230     /**
231      * @see Container#isExcluded
232      */

233     public final boolean isExcluded(String JavaDoc theTestName)
234     {
235         String JavaDoc[] excludePatterns =
236             this.patternSet.getExcludePatterns(getProject());
237         if (excludePatterns != null)
238         {
239             String JavaDoc testPath = theTestName.replace('.', '/');
240             for (int i = 0; i < excludePatterns.length; i++)
241             {
242                 String JavaDoc excludePattern = excludePatterns[i];
243                 if (excludePattern.endsWith(".java")
244                  || excludePattern.endsWith(".class"))
245                 {
246                     excludePattern = excludePattern.substring(
247                         0, excludePattern.lastIndexOf('.'));
248                 }
249                 if (SelectorUtils.matchPath(excludePattern, testPath))
250                 {
251                     return true;
252                 }
253             }
254         }
255         return false;
256     }
257
258     /**
259      * @see Container#setAntTaskFactory
260      */

261     public final void setAntTaskFactory(AntTaskFactory theFactory)
262     {
263         this.antTaskFactory = theFactory;
264     }
265
266     /**
267      * @see Container#setDeployableFile
268      */

269     public final void setDeployableFile(DeployableFile theDeployableFile)
270     {
271         this.deployableFile = theDeployableFile;
272     }
273
274     /**
275      * @see Container#setLog
276      */

277     public final void setLog(Log theLog)
278     {
279         this.log = theLog;
280     }
281
282     /**
283      * @see Container#setSystemProperties
284      */

285     public void setSystemProperties(Variable[] theProperties)
286     {
287         this.systemProperties = theProperties;
288     }
289
290     /**
291      * @see Container#getSystemProperties
292      */

293     public Variable[] getSystemProperties()
294     {
295         return this.systemProperties;
296     }
297
298     /**
299      * @see Container#setContainerClasspath(Path)
300      * @since Cactus 1.6
301      */

302     public void setContainerClasspath(Path theClasspath)
303     {
304         this.containerClasspath = theClasspath;
305     }
306
307     /**
308      * @see Container#getContainerClasspath()
309      * @since Cactus 1.6
310      */

311     public Path getContainerClasspath()
312     {
313         return this.containerClasspath;
314     }
315     
316     // Protected Methods -------------------------------------------------------
317

318     /**
319      * Creates and returns a new instance of the Ant task mapped to the
320      * specified logical name using the
321      * {@link org.apache.cactus.integration.ant.util.AntTaskFactory} set.
322      *
323      * @param theName The logical name of the task to create
324      * @return A new isntance of the task
325      * @see AntTaskFactory#createTask
326      */

327     protected final Task createAntTask(String JavaDoc theName)
328     {
329         return this.antTaskFactory.createTask(theName);
330     }
331
332     /**
333      * Convenience method for creating a new directory inside another one.
334      *
335      * @param theParentDir The directory in which the new directory should be
336      * created
337      * @param theName The name of the directory to create
338      * @return The new directory
339      * @throws IOException If the directory could not be created
340      */

341     protected final File JavaDoc createDirectory(File JavaDoc theParentDir, String JavaDoc theName)
342         throws IOException JavaDoc
343     {
344         File JavaDoc dir = new File JavaDoc(theParentDir, theName);
345         dir.mkdirs();
346         if (!dir.isDirectory())
347         {
348             throw new IOException JavaDoc(
349                 "Couldn't create directory " + dir.getAbsolutePath());
350         }
351         return dir;
352     }
353
354     /**
355      * Creates the default filter chain that should be applied while copying
356      * container configuration files to the temporary directory from which the
357      * container is started. The default filter chain replaces all occurences
358      * of @cactus.port@ with the TCP port of the container, and all occurences
359      * of @cactus.context@ with the web-application's context path (if the
360      * deployable file is a web-app).
361      *
362      * @return The default filter chain
363      */

364     protected final FilterChain createFilterChain()
365     {
366         ReplaceTokens.Token token = null;
367         FilterChain filterChain = new FilterChain();
368
369         // Token for the cactus port
370
ReplaceTokens replacePort = new ReplaceTokens();
371         token = new ReplaceTokens.Token();
372         token.setKey("cactus.port");
373         token.setValue(String.valueOf(getPort()));
374         replacePort.addConfiguredToken(token);
375         filterChain.addReplaceTokens(replacePort);
376
377         // Token for the cactus webapp context.
378
if (getDeployableFile() != null)
379         {
380             ReplaceTokens replaceContext = new ReplaceTokens();
381             token = new ReplaceTokens.Token();
382             token.setKey("cactus.context");
383             token.setValue(getDeployableFile().getTestContext());
384             replaceContext.addConfiguredToken(token);
385             filterChain.addReplaceTokens(replaceContext);
386         }
387         
388         return filterChain;
389     }
390
391     /**
392      * Clean the temporary directory.
393      *
394      * @param theTmpDir the temp directory to clean
395      */

396     protected void cleanTempDirectory(File JavaDoc theTmpDir)
397     {
398         // Clean up stuff previously put in the temporary directory
399
Delete delete = (Delete) createAntTask("delete");
400         FileSet fileSet = new FileSet();
401         fileSet.setDir(theTmpDir);
402         fileSet.createInclude().setName("**/*");
403         delete.addFileset(fileSet);
404         delete.setIncludeEmptyDirs(true);
405         delete.setFailOnError(false);
406         delete.execute();
407     }
408     
409     /**
410      * Convenience method that creates a temporary directory or
411      * prepares the one passed by the user.
412      *
413      * @return The temporary directory
414      * @param theCustomTmpDir The user specified custom dir or null if none has
415      * been specified (ie we'll create default one).
416      * @param theName The name of the directory relative to the system specific
417      * temporary directory
418      */

419     protected File JavaDoc setupTempDirectory(File JavaDoc theCustomTmpDir, String JavaDoc theName)
420     {
421         File JavaDoc tmpDir;
422         
423         if (theCustomTmpDir == null)
424         {
425             tmpDir = new File JavaDoc(System.getProperty("java.io.tmpdir"), theName);
426         }
427         else
428         {
429             tmpDir = theCustomTmpDir;
430         }
431         
432         if (!tmpDir.exists())
433         {
434             if (!tmpDir.mkdirs())
435             {
436                 throw new BuildException("Could not create temporary "
437                     + "directory [" + tmpDir + "]");
438             }
439         }
440
441         // make sure we're returning a directory
442
if (!tmpDir.isDirectory())
443         {
444             throw new BuildException("[" + tmpDir + "] is not a directory");
445         }
446
447         return tmpDir;
448     }
449     
450     /**
451      * Returns the log to use.
452      *
453      * @return The log
454      */

455     protected final Log getLog()
456     {
457         return this.log;
458     }
459
460     /**
461      * Returns the web-application archive that is to be deployed to the
462      * container.
463      *
464      * @return The WAR file
465      */

466     protected final DeployableFile getDeployableFile()
467     {
468         return this.deployableFile;
469     }
470
471     // Private Methods ---------------------------------------------------------
472

473     /**
474      * Tests whether the property necessary to run the tests in the container
475      * has been set.
476      *
477      * @return <code>true</code> if the tests should be run in the container,
478      * <code>false</code> otherwise
479      */

480     private boolean testIfCondition()
481     {
482         if (ifCondition == null || ifCondition.length() == 0)
483         {
484             return true;
485         }
486         
487         return (getProject().getProperty(ifCondition) != null);
488     }
489
490     /**
491      * Tests whether the property specified as the 'unless' condition has not
492      * been set.
493      *
494      * @return <code>true</code> if the tests should be run in the container,
495      * <code>false</code> otherwise
496      */

497     private boolean testUnlessCondition()
498     {
499         if (unlessCondition == null || unlessCondition.length() == 0)
500         {
501             return true;
502         }
503         return (getProject().getProperty(unlessCondition) == null);
504     }
505
506 }
507
Popular Tags