KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > de > webman > generator > GenNode


1 package de.webman.generator;
2
3 import com.teamkonzept.lib.*;
4
5 import java.io.*;
6 import java.util.*;
7 import org.apache.log4j.Category;
8
9 /**
10  * @author $Author: gregor $
11  * @version $Revision: 1.6 $
12 */

13 public class GenNode
14 {
15     /**
16         Verweis zurueck auf den aktuellen statischen Kontext des laufenden Threads
17     */

18     private GeneratorContext context;
19
20     /** Log4J Category */
21     private static Category cat = Category.getInstance(GenNode.class.getName());
22     
23     /** ... */
24     private String JavaDoc nodeName;
25     private String JavaDoc description;
26     
27     /** alle Kinder - GenNodes */
28     private TKVector subNodes;
29     
30     /** alle Dokumente key:shortName Value: GenDocument */
31     private TKHashtable documents;
32     
33     private GenNode parent;
34     private int parentNodePos;
35     private SiteNode siteNode;
36     private SiteContent primContent;
37         
38     public GenNode( GeneratorContext context, SiteNode siteNode,
39         GenNode parent, String JavaDoc nodeName, String JavaDoc _description, TKVector documents,
40         SiteContent primContent, int parentNodePos )
41     {
42         this.context = context != null ? context : GeneratorContext.setup ();
43         
44         this.parent = parent;
45         this.nodeName = nodeName;
46         description = _description;
47         this.subNodes = this.context.genNodes.isRecursiveBuild() ? siteNode.getSubGenNodes( this ) : new TKVector();
48         this.documents = new TKHashtable();
49         this.siteNode = siteNode;
50         this.parentNodePos = parentNodePos;
51         this.primContent = primContent;
52         if (!this.context.genNodes.isRecursiveBuild()) return;
53         
54         Enumeration e = documents.elements();
55         while( e.hasMoreElements() )
56         {
57             SiteDocument doc = (SiteDocument) e.nextElement();
58             if( doc != null ) {
59                 if( doc.isRefered() ) {
60                     this.documents.put( doc.getShortName(), doc.getGenDocument( primContent, this ) );
61                 }
62             }
63             else {
64                 cat.warn("got hole in document-list");
65             }
66         }
67     }
68
69     public SiteContent getPrimaryContent()
70     {
71         return primContent;
72     }
73     
74     public TKHashtable getDocuments()
75     {
76         return documents;
77     }
78     
79     public TKVector getSubNodes()
80     {
81         return subNodes;
82     }
83     
84     /**
85         Returns the path-string of this site node.
86         The root-node's name is omitted.
87         Example: "/PressReleases/".
88     */

89     public String JavaDoc getPath()
90     {
91         return ( parent == null ? "/" : parent.getPath() + nodeName + "/" ) ;
92     }
93     
94     /**
95         Returns the relative path from the root node to this node.
96         The returned string does not include starting and trailing File.separator.
97         In contrast to the aboves getPath-method, the root's node name is NOT omitted!
98         Examples: "root" or "root/PressPreleases" etc.
99     */

100     public String JavaDoc getSubPathDir()
101     {
102         /*
103         return ( parent == null ? nodeName : parent.getSubPathDir() + File.separator + nodeName ) ;
104         */

105         return ( parent == null ? "" :
106             ( parent.parent == null ? nodeName : parent.getSubPathDir() + File.separator + nodeName )) ;
107     }
108     
109     public SiteNode getSiteNode()
110     {
111         return siteNode;
112     }
113     
114     public String JavaDoc getDescription()
115     {
116         return description;
117     }
118     
119     public GenNode getParent()
120     {
121         return parent;
122     }
123     
124     public String JavaDoc getNodeName()
125     {
126         return nodeName;
127     }
128     
129     public int depth ()
130     {
131         return ( parent == null ? 1 : parent.depth() + 1 );
132     }
133         
134     public String JavaDoc makePathRelativeTo (GenNode other)
135     {
136         int thisDepth = depth(); int otherDepth = other.depth();
137         StringBuffer JavaDoc up = new StringBuffer JavaDoc(thisDepth * 10);
138         StringBuffer JavaDoc down = new StringBuffer JavaDoc(otherDepth * 10);
139         GenNode thisNode = this; GenNode otherNode = other;
140         
141         while (thisDepth > otherDepth)
142         {
143             if (up.length() > 0) up.append('/'); up.append("..");
144             thisNode = thisNode.parent;
145             thisDepth--;
146         }
147             
148         while (thisDepth < otherDepth)
149         {
150             if (down.length() > 0) down.insert(0,'/');
151             down.insert(0,otherNode.nodeName);
152             otherNode = otherNode.parent;
153             otherDepth--;
154         }
155
156         GenNode thisUp = thisNode; GenNode otherUp = otherNode;
157         int shared = 0;
158
159         while (thisUp != null)
160         {
161             if (thisUp.nodeName.compareTo (otherUp.nodeName) == 0) shared++;
162             else shared = 0;
163             thisUp = thisUp.parent; otherUp = otherUp.parent;
164         }
165         
166         while (thisDepth > shared)
167         {
168             if (up.length() > 0) up.append('/'); up.append("..");
169             thisNode = thisNode.parent;
170             if (down.length() > 0) down.insert(0,'/');
171             down.insert(0,otherNode.nodeName);
172             otherNode = otherNode.parent;
173             thisDepth--;
174         }
175
176         if ((up.length() > 0) && (down.length() > 0))
177             return up.append('/').append(down.toString()).append('/').toString();
178         else if (up.length() > 0)
179             return up.append('/').toString();
180         else if (down.length() > 0)
181             return down.append('/').toString();
182         else return "";
183     }
184     
185     public void prepareGeneration()
186     {
187         Enumeration e = documents.elements();
188         while( e.hasMoreElements() )
189         {
190             ((GenDocument) e.nextElement()).prepareGeneration();
191         }
192         
193         e = subNodes.elements();
194         while( e.hasMoreElements() )
195         {
196             ((GenNode) e.nextElement()).prepareGeneration();
197         }
198     }
199     
200     /**
201         Generates the node by creating a directory with name
202         <code>nodeName</code> in the directory <code>baseDir</code>.
203         It also recursively generates all sub documents and sub nodes,
204         if this node isn't excluded by subtree generation (as specified by
205         a <code>refs</code> command line option).
206         @param baseDir the parent directory path of this node
207         @param rootDir the path to the document root
208         @param tmplBase the absoulte path to the template directory
209         @param genFileLogStream a logstream to which the generated files are written
210         @param cleanup: if true certain files will be removed from the directory
211     */

212     public void generate( File baseDir, String JavaDoc rootDir, String JavaDoc tmplBase, PrintStream genFileLogStream, boolean cleanup )
213         throws Exception JavaDoc
214     {
215         cat.debug("generate " + nodeName + " in " + baseDir.getAbsolutePath() );
216         File sourceDir = baseDir;
217         if( parent != null )
218         {
219             /*This condition assures that the document root coincides with the
220             the site root node. Removed by frank because output should be
221             generated in its proper 'root' directory below the document root
222             re-removed by alex */

223             sourceDir = new File( baseDir, nodeName );
224         }
225
226         String JavaDoc siteNodePath = siteNode.getPath();
227         if (context.siteNodes.getIncludeSubtreePath() != null &&
228             !context.siteNodes.getIncludeSubtreePath().startsWith(siteNodePath) &&
229             !siteNodePath.startsWith(context.siteNodes.getIncludeSubtreePath()))
230         {
231             cat.info(new Date().toString() + ": start subtree generation of node "+sourceDir.getAbsolutePath()+
232                     " stopped due to constraint" );
233                 return;
234         }
235         if( sourceDir.exists() ) {
236             if( !sourceDir.isDirectory() ) {
237                 throw new Error JavaDoc( "existing file "+sourceDir.getAbsolutePath()
238                     +" prevents creation of new directory" );
239             }
240         }
241         else {
242             if( !sourceDir.mkdirs() ) {
243                 throw new Error JavaDoc( "could not create file "+sourceDir.getAbsolutePath() );
244             }
245         }
246         
247         DirectoryFileListing genList = createGenList(sourceDir.getAbsolutePath());
248         Enumeration e = documents.elements();
249         while( e.hasMoreElements() )
250         {
251             GenDocument nextDoc = (GenDocument) e.nextElement();
252             try
253             {
254                 nextDoc.generate( sourceDir, rootDir, tmplBase, genFileLogStream );
255                 if (genList != null)
256                 {
257                     genList.generatedFile(nextDoc.getDocumentName());
258                 }
259             }
260             catch( Exception JavaDoc ex )
261             {
262                 cat.error( "generation of document "+nextDoc.getDocumentName()
263                     +" in " +sourceDir.getAbsolutePath()+" failed: " + ex.getMessage(), ex);
264                 // ex.printStackTrace(System.out);
265
}
266         }
267         e = subNodes.elements();
268         while( e.hasMoreElements() )
269         {
270             GenNode nextNode = (GenNode) e.nextElement();
271             try
272             {
273                 nextNode.generate( sourceDir, rootDir, tmplBase, genFileLogStream, cleanup );
274                 if (genList != null)
275                 {
276                     genList.generatedDirectory(nextNode.nodeName);
277                 }
278             }
279             catch( Exception JavaDoc ex )
280             {
281                 cat.error( "generation of node "+nextNode.nodeName
282                     +" in " +sourceDir.getAbsolutePath()+" failed: ", ex );
283             }
284         }
285         if (genList != null && cleanup)
286         {
287             deleteFiles(sourceDir.getAbsolutePath(), genList.getFilesToDelete());
288             deleteFiles(sourceDir.getAbsolutePath(), genList.getDirectoriesToDelete());
289         }
290         saveGenList(genList, false);
291     }
292     
293     public GenDocument getDocument( String JavaDoc name )
294     {
295         return (GenDocument) documents.get( name );
296     }
297
298     /**
299         Deletes a list of files and directories.
300         @param path the directory, where the files an directories are located
301         @param filesToDelete the list of files to delete (relative names
302         with respect to 'path').
303     */

304     private static boolean deleteFiles(String JavaDoc path, Enumeration filesToDelete)
305     {
306         boolean successful = true;
307         while (filesToDelete.hasMoreElements())
308         {
309             String JavaDoc name = (String JavaDoc) filesToDelete.nextElement();
310             File f = new File(path, name);
311             if (f.isDirectory())
312             {
313                 if (f.delete() == false && tryRecursiveDelete(f) == false) {
314                     successful = false;
315                 }
316             }
317             else
318             {
319                 if (f.delete() == false) {
320                     successful = false;
321                 }
322             }
323         }
324         return successful;
325     }
326     
327     /**
328         Tries to delete the directory <code>dir</code> by
329         deleting recursively all sub directores and sub files listed in
330         the generated-files list of this directory.
331         After this, the directory is deleted <code>dir</code> if it is empty.
332     */

333     private static boolean tryRecursiveDelete(File dir)
334     {
335         DirectoryFileListing genList = createGenList(dir.getAbsolutePath());
336         if (genList == null)
337         {
338             return false;
339         }
340             
341         boolean successful = true;
342         
343         Enumeration subdirs = genList.getDirectoryEntries();
344         while(subdirs.hasMoreElements())
345         {
346             File file = new File(dir.getAbsolutePath(), (String JavaDoc) subdirs.nextElement());
347             if (tryRecursiveDelete(file) == false) {
348                 successful = false;
349             }
350         }
351         
352         Enumeration files = genList.getFileEntries();
353         while(files.hasMoreElements())
354         {
355             File file = new File(dir.getAbsolutePath(), (String JavaDoc) files.nextElement());
356             if (file.delete() == false) {
357                 successful = false;
358             }
359         }
360         
361         //this deletes the "generated_files.list":
362
saveGenList(genList, false);
363         
364         if (!successful)
365         {
366             return false;
367         }
368         File file = new File(dir.getAbsolutePath());
369         return file.delete();
370     }
371
372     /**
373         Creates the <code>DirectoryFileListing</code> of the given
374         directory <code>dir</code>.
375         @return the DirectoryFileListing instance or null in case of error
376     */

377     private static DirectoryFileListing createGenList(String JavaDoc dir)
378     {
379         DirectoryFileListing genList = null;
380         try
381         {
382             genList = new DirectoryFileListing(dir);
383         } catch (IOException e)
384         {
385             cat.warn("Unable to open log file of generated files in directory " + dir);
386             return null;
387         }
388         return genList;
389     }
390     
391     /**
392         Saves the DirectoryFileListing <code>genNode</code>.
393         IOExceptions during save are catched and ignored.
394         @param addonly if set to false, the new listing will consist
395         of all file and directory names added through
396         <code>generatedFile(String)</code> or <code>generatedDirectory(String)</code>
397         if set to true, the new listing will consist of all old and new entries
398     */

399     private static void saveGenList(DirectoryFileListing genList, boolean addOnly)
400     {
401         try {
402             genList.save(addOnly);
403         }
404         catch (IOException e)
405         {
406             cat.warn("Unable to save log file of generated files", e);
407         }
408     }
409 }
410
411
Popular Tags