KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > enhydra > tool > codegen > ProjectGenerator


1
2 /*
3  * Enhydra Java Application Server Project
4  *
5  * The contents of this file are subject to the Enhydra Public License
6  * Version 1.1 (the "License"); you may not use this file except in
7  * compliance with the License. You may obtain a copy of the License on
8  * the Enhydra web site ( http://www.enhydra.org/ ).
9  *
10  * Software distributed under the License is distributed on an "AS IS"
11  * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See
12  * the License for the specific terms governing rights and limitations
13  * under the License.
14  *
15  * The Initial Developer of the Enhydra Application Server is Lutris
16  * Technologies, Inc. The Enhydra Application Server and portions created
17  * by Lutris Technologies, Inc. are Copyright Lutris Technologies, Inc.
18  * All Rights Reserved.
19  *
20  * Contributor(s):
21  * Paul Mahar
22  *
23  */

24 package org.enhydra.tool.codegen;
25
26 // ToolBox imports
27
import org.enhydra.tool.ToolBoxInfo;
28 import org.enhydra.tool.codegen.wizard.CodeGenPanel;
29 import org.enhydra.tool.common.FileUtil;
30 import org.enhydra.tool.common.PathHandle;
31 import org.enhydra.tool.common.Replacement;
32 import org.enhydra.tool.common.ReplacementSet;
33 import org.enhydra.tool.common.ResUtil;
34 import org.enhydra.tool.common.Template;
35 import org.enhydra.tool.common.TemplateFilter;
36 import org.enhydra.tool.common.TemplateTool;
37 import org.enhydra.tool.common.ToolException;
38 import org.enhydra.tool.common.event.TemplateEvent;
39 import org.enhydra.tool.common.event.TemplateListener;
40 import org.enhydra.tool.configure.ConfigTool;
41
42 // Standard imports
43
import java.io.BufferedReader JavaDoc;
44 import java.io.IOException JavaDoc;
45 import java.io.File JavaDoc;
46 import java.io.FileNotFoundException JavaDoc;
47 import java.io.FileReader JavaDoc;
48 import java.io.FileWriter JavaDoc;
49 import java.io.PrintWriter JavaDoc;
50 import java.util.ArrayList JavaDoc;
51 import java.util.Arrays JavaDoc;
52 import java.util.Properties JavaDoc;
53 import java.util.ResourceBundle JavaDoc;
54 import java.util.StringTokenizer JavaDoc;
55 import java.util.Vector JavaDoc;
56
57 //
58
abstract public class ProjectGenerator extends TemplateDrivenGenerator
59     implements Constants {
60
61     //
62
private String JavaDoc javaPath = ToolBoxInfo.getJavaPath();
63     private String JavaDoc[] copyright = new String JavaDoc[0];
64     private String JavaDoc[] shellSteps = null;
65     private String JavaDoc[] addinSteps = null;
66     private boolean cli = true;
67
68     public String JavaDoc[] getOutputExcludes() {
69         ArrayList JavaDoc list = new ArrayList JavaDoc();
70         String JavaDoc[] ex = new String JavaDoc[0];
71
72         if (cli) {
73             if (ToolBoxInfo.isEnhydra3()) {
74 // for excluding makefiles and config.mk
75
list.add('.' + TYPE_MK);
76                 list.add(File.separator + FILE_MAKEFILE);
77 //include creating build.xml files
78
// list.add(File.separator + FILE_BUILD_XML);
79
} else {
80                 list.add('.' + TYPE_MK);
81                 list.add(File.separator + FILE_MAKEFILE);
82                 list.add(File.separator + FILE_BUILD_XML);
83             }
84         } else {
85             list.add('.' + TYPE_MK);
86             list.add(File.separator + FILE_MAKEFILE);
87             list.add(File.separator + FILE_RUN_IN);
88             list.add(File.separator + FILE_RUN_BAT_IN);
89             list.add(File.separator + FILE_BUILD_XML);
90         }
91         list.add(".bak");
92         list.trimToSize();
93         ex = new String JavaDoc[list.size()];
94         ex = (String JavaDoc[]) list.toArray(ex);
95         list.clear();
96         return ex;
97     }
98
99     //
100
public ProjectGenerator() {
101         super();
102     }
103
104     public File JavaDoc[] generate() throws GeneratorException {
105         File JavaDoc[] files = new File JavaDoc[0];
106         File JavaDoc readme = null;
107         ArrayList JavaDoc list = null;
108
109         setOverwrite(getOptionSet().lookup(ProjectOptionSet.OVERWRITE).isValue());
110         cli = (!getOptionSet().lookup(ProjectOptionSet.NOCLI).isValue());
111         files = super.generate();
112         list = new ArrayList JavaDoc(Arrays.asList(files));
113         readme = generateReadme(getDestination());
114         list.add(readme);
115         files = new File JavaDoc[list.size()];
116         files = (File JavaDoc[]) list.toArray(files);
117         list.clear();
118         return files;
119     }
120
121     public void storeProperties() {
122         try {
123             getOptionSet().lookup(ProjectOptionSet.OVERWRITE).setValue(isOverwrite());
124         } catch (GeneratorException e) {
125             e.printStackTrace();
126         }
127         super.storeProperties();
128     }
129
130     public void setProperties(Properties JavaDoc p) throws GeneratorException {
131         super.setProperties(p);
132
133         // Ignore persisted make and script flags
134
getOptionSet().lookup(ProjectOptionSet.NOCLI).setValue(false);
135
136         // ensure unique projectName
137
PathHandle handle = null;
138         File JavaDoc destDir = null;
139         String JavaDoc destPath = new String JavaDoc();
140         String JavaDoc projectName = new String JavaDoc();
141         String JavaDoc[] fileList = new String JavaDoc[0];
142         boolean newName = false;
143
144         handle =
145             PathHandle.createPathHandle(getOptionSet().lookup(ProjectOptionSet.ROOT).getValue());
146         destPath = handle.getPath();
147         projectName =
148             getOptionSet().lookup(ProjectOptionSet.PROJECT).getValue();
149         destDir = handle.getFile();
150         if (!destDir.exists()) {
151             destDir.mkdirs();
152         }
153         fileList = destDir.list();
154         for (int i = 0; i < fileList.length; i++) {
155             if (fileList[i].equalsIgnoreCase(projectName)) {
156                 newName = true;
157                 char lastChar = projectName.charAt(projectName.length()
158                                                      - 1);
159                 String JavaDoc digits = new String JavaDoc();
160
161                 while (Character.isDigit(lastChar)) {
162                     projectName = projectName.substring(0,
163                                                         projectName.length()
164                                                         - 1);
165                     digits = lastChar + digits;
166                     lastChar = projectName.charAt(projectName.length() - 1);
167                 }
168                 int next = 1;
169
170                 try {
171                     next = Integer.parseInt(digits);
172                 } catch (NumberFormatException JavaDoc e) {
173                     next = 1;
174                 }
175                 next++;
176                 projectName = projectName + next;
177                 i = 0; // start the search over again
178
}
179         }
180         if (newName) {
181             getOptionSet().lookup(ProjectOptionSet.PROJECT).setValue(projectName);
182         }
183     }
184
185     public TemplateFilter createCopyFilter(TemplateTool tool)
186             throws GeneratorException {
187         ProjectTemplateFilter copyFilter = null;
188
189         copyFilter = new ProjectTemplateFilter(tool, getDestination());
190         copyFilter.setIncludeTemplate(false);
191         copyFilter.setInputIncludes(getInputIncludes());
192         copyFilter.setOutputExcludes(getOutputExcludes());
193         return copyFilter;
194     }
195
196     public TemplateFilter createTemplateFilter(TemplateTool tool)
197             throws GeneratorException {
198         ProjectTemplateFilter templateFilter = null;
199
200         templateFilter = new ProjectTemplateFilter(tool, getDestination());
201         templateFilter.setIncludeTemplate(true);
202         templateFilter.setInputIncludes(getInputIncludes());
203         templateFilter.setOutputExcludes(getOutputExcludes());
204         return templateFilter;
205     }
206
207     public String JavaDoc getDestination() throws GeneratorException {
208         StringBuffer JavaDoc buf = new StringBuffer JavaDoc();
209         PathHandle path = null;
210
211         buf.append(getOptionSet().lookup(ProjectOptionSet.ROOT).getValue());
212         buf.append(File.separator);
213         buf.append(getOptionSet().lookup(ProjectOptionSet.PROJECT).getValue());
214         path = PathHandle.createPathHandle(buf.toString());
215         return path.getPath();
216     }
217
218     public void setJavaPath(String JavaDoc p) {
219         javaPath = PathHandle.createPathString(p);
220     }
221
222     public String JavaDoc getJavaPath() {
223         return javaPath;
224     }
225
226     /**
227      * Set the steps required to build the project from
228      * a unix shell.
229      *
230      * @param steps
231      * An array of strings, each string will be inserted into
232      * a readme.html file as numbered step for building the
233      * project from a unix shell.
234      */

235     public void setShellSteps(String JavaDoc[] steps) {
236         shellSteps = steps;
237     }
238
239     /**
240      * Get steps required to build the project from
241      * a unix shell.
242      *
243      * @return
244      * An array of strings, each string will be inserted into
245      * a readme.html file as numbered step for building the
246      * project using make files.
247      */

248     public String JavaDoc[] getShellSteps() {
249         String JavaDoc[] steps = shellSteps;
250
251         if (steps == null) {
252             steps = getDefaultShellSteps();
253         }
254         return steps;
255     }
256
257     /**
258      * Get steps required to build the project with the an IDE Addin.
259      *
260      * @return
261      * An array of strings, each string will be inserted into
262      * a readme.html file as numbered step for building the
263      * project within an IDE.
264      */

265     public String JavaDoc[] getAddinSteps() {
266         String JavaDoc[] steps = addinSteps;
267
268         if (steps == null) {
269             steps = getDefaultAddinSteps();
270         }
271         return steps;
272     }
273
274     /**
275      * Set the steps required to build the project from
276      * within an IDE.
277      *
278      * @param steps
279      * An array of strings, each string will be inserted into
280      * a readme.html file as numbered step for building the
281      * project within an IDE.
282      */

283     public void setAddinSteps(String JavaDoc[] steps) {
284         addinSteps = steps;
285     }
286
287     /**
288      * Get the path where Java source files were generated.
289      *
290      * @return
291      * The java source directory.
292      */

293     public String JavaDoc getProjectSourcePath() throws GeneratorException {
294         String JavaDoc path = new String JavaDoc();
295
296         path = findProjectSourcePath(getTemplateRoot());
297         if (path == null) {
298             throw new GeneratorException(res.getString("Project_source_not"));
299         }
300         return path;
301     }
302
303     /**
304      * Method declaration
305      *
306      *
307      * @exception GeneratorException
308      */

309     public void initReplacementSet() throws GeneratorException {
310         try {
311             String JavaDoc packageName = null;
312             String JavaDoc shellPackageDir = null;
313             String JavaDoc systemPackageDir = null;
314             String JavaDoc content = null;
315             int index = 0;
316
317             //
318
packageName =
319                 getOptionSet().lookup(ProjectOptionSet.PACKAGE).getValue();
320             shellPackageDir = packageName.replace('.', '/');
321             systemPackageDir = packageName.replace('.', File.separatorChar);
322
323             //
324
readCopyright();
325             getReplacementSet().lookup(ProjectReplacementSet.COPYRIGHT).setReplaceWith(copyright);
326             getReplacementSet().lookup(ProjectReplacementSet.at_PROJECT_at).setReplaceWith(getOptionSet().lookup(ProjectOptionSet.PROJECT).getValue());
327             getReplacementSet().lookup(ProjectReplacementSet.at_PACKAGE_DIR_at).setReplaceWith(systemPackageDir);
328             getReplacementSet().lookup(ProjectReplacementSet.SHELL_PACKAGE_DIR).setReplaceWith(shellPackageDir);
329             getReplacementSet().lookup(ProjectReplacementSet.JAVA_PACKAGE).setReplaceWith(packageName);
330         } catch (ToolException e) {
331             e.printStackTrace();
332             throw new GeneratorException(e,
333                                          res.getString("Unable_to_init_rep"));
334         }
335     }
336
337     public void onTemplate(TemplateEvent event) {
338         PathHandle phOut = null;
339         ReplacementSet eventSet = null;
340
341         phOut = PathHandle.createPathHandle(event.getTemplate().getOutput());
342         eventSet = new ReplacementSet(event.getTool().getReplacements());
343         try {
344             if (copyright.length >= 1) {
345                 int last = 0;
346                 String JavaDoc[] newCR = new String JavaDoc[0];
347
348                 newCR = new String JavaDoc[copyright.length + 2];
349                 newCR[0] = new String JavaDoc();
350                 if (newCR.length >= 1) {
351                     last = (newCR.length - 1);
352                 }
353                 if (phOut.endsWith('/' + FILE_MAKEFILE)
354                         || phOut.hasExtension(TYPE_MK)) {
355                     for (int i = 1; i < (newCR.length - 1); i++) {
356                         newCR[i] = "# " + copyright[i - 1]; // nores
357
}
358                     newCR[last] = "#"; // nores
359
} else if (phOut.hasExtension(TYPE_JAVA)) {
360                     for (int i = 1; i < (newCR.length - 1); i++) {
361                         newCR[i] = " * " + copyright[i - 1]; // nores
362
}
363                     newCR[last] = " *"; // nores
364
} else if (phOut.hasExtension(TYPE_XML)) {
365                     for (int i = 1; i < (newCR.length - 1); i++) {
366                         newCR[i] = " " + copyright[i - 1]; // nores
367
}
368                     newCR[last] = " "; // nores
369
} else {
370                     newCR = new String JavaDoc[1];
371                     newCR[0] = new String JavaDoc();
372                 }
373                 eventSet.lookup(ProjectReplacementSet.COPYRIGHT).setReplaceWith(newCR);
374             }
375
376             // Force class names to initial cap
377
if (phOut.hasExtension(TYPE_JAVA)) {
378                 File JavaDoc out = phOut.getFile();
379                 char c0 = out.getName().charAt(0);
380
381                 if (Character.isLowerCase(c0)) {
382                     StringBuffer JavaDoc buf = new StringBuffer JavaDoc();
383
384                     buf.append(out.getParent());
385                     buf.append(File.separator);
386                     buf.append(Character.toUpperCase(c0));
387                     if (out.getName().length() > 1) {
388                         buf.append(out.getName().substring(1));
389                     }
390                     event.getTemplate().setOutput(new File JavaDoc(buf.toString()));
391                     buf.setLength(0);
392                     buf.append(eventSet.lookup(ProjectReplacementSet.at_PROJECT_at).getReplaceWith()[0]);
393                     buf.setCharAt(0, Character.toUpperCase(c0));
394                     eventSet.lookup(ProjectReplacementSet.at_PROJECT_at).setReplaceWith(buf.toString());
395                 }
396                 event.getTool().setReplacements(eventSet.toArray());
397             }
398         } catch (ToolException e) {
399             e.printStackTrace();
400         }
401     }
402
403     abstract protected String JavaDoc[] getDefaultShellSteps();
404     abstract protected String JavaDoc[] getDefaultAddinSteps();
405
406     //
407
private void readCopyright() {
408         String JavaDoc copyText = new String JavaDoc();
409         String JavaDoc copyPath = new String JavaDoc();
410         StringTokenizer JavaDoc tokenizer = null;
411         File JavaDoc copyFile = null;
412         BufferedReader JavaDoc reader = null;
413         Vector JavaDoc readVector = new Vector JavaDoc();
414
415         try {
416             copyText =
417                 getOptionSet().lookup(ProjectOptionSet.COPYRIGHT).getValue();
418             if (copyText.trim().length() > 0) {
419                 final String JavaDoc NEWLINE = "\n"; // nores
420

421                 tokenizer = new StringTokenizer JavaDoc(copyText, NEWLINE);
422                 copyright = new String JavaDoc[tokenizer.countTokens()];
423                 for (int i = 0; i < copyright.length; i++) {
424                     copyright[i] = tokenizer.nextToken();
425                 }
426             }
427         } catch (GeneratorException e) {
428             e.printStackTrace();
429         }
430         if (copyright.length == 0) {
431             try {
432                 copyPath =
433                     getOptionSet().lookup(ProjectOptionSet.COPYRIGHTFILE).getValue();
434                 if (FileUtil.isFile(copyPath)) {
435                     copyFile = new File JavaDoc(copyPath);
436                     reader = new BufferedReader JavaDoc(new FileReader JavaDoc(copyFile));
437                     String JavaDoc line = reader.readLine();
438
439                     while (line != null) {
440                         readVector.addElement(new String JavaDoc(line));
441                         line = reader.readLine();
442                     }
443                     reader.close();
444                     copyright = new String JavaDoc[readVector.size()];
445                     copyright = (String JavaDoc[]) readVector.toArray(copyright);
446                     readVector.clear();
447                 }
448             } catch (GeneratorException e) {
449                 e.printStackTrace();
450                 copyright = new String JavaDoc[0];
451             } catch (FileNotFoundException JavaDoc e) {
452                 e.printStackTrace();
453                 copyright = new String JavaDoc[0];
454             } catch (IOException JavaDoc e) {
455                 e.printStackTrace();
456                 copyright = new String JavaDoc[0];
457             }
458         }
459     }
460
461     /**
462      * Method declaration
463      *
464      *
465      * @param target
466      *
467      * @exception GeneratorException
468      */

469     public Replacement[] createReplacementsForDirectory(PathHandle path)
470             throws GeneratorException {
471         Replacement[] pathReps = new Replacement[0];
472         StringBuffer JavaDoc rootPath = new StringBuffer JavaDoc();
473         PathHandle destHandle = null;
474         PathHandle target = null;
475         PathHandle cursor = null;
476
477         destHandle = PathHandle.createPathHandle(getDestination());
478         target = PathHandle.createPathHandle(path.getPath());
479         cursor = PathHandle.createPathHandle(path.getPath());
480         if (destHandle.parentOf(cursor)) {
481             rootPath.append('.');
482             rootPath.append('.');
483             cursor =
484                 PathHandle.createPathHandle(cursor.getFile().getParent());
485             while (destHandle.parentOf(cursor)) {
486                 rootPath.append('/');
487                 rootPath.append('.');
488                 rootPath.append('.');
489                 cursor =
490                     PathHandle.createPathHandle(cursor.getFile().getParent());
491             }
492         } else {
493             rootPath.append('.');
494         }
495         try {
496             getReplacementSet().lookup(ProjectReplacementSet.SHELL_ROOT_PATH).setReplaceWith(rootPath.toString());
497         } catch (ToolException e) {
498             throw new GeneratorException(e,
499                                          res.getString("Unable_to_init_root"));
500         }
501         pathReps = getReplacementSet().toArray();
502         StringBuffer JavaDoc inputBuf = new StringBuffer JavaDoc();
503         PathHandle inputPath = null;
504
505         inputBuf.append(getDestination().toLowerCase());
506         inputBuf.append(File.separator);
507         inputBuf.append(DIR_INPUT);
508         inputBuf.append(File.separator);
509         inputPath = PathHandle.createPathHandle(inputBuf.toString());
510         if (!inputPath.parentOf(target)) {
511             try {
512                 Replacement[] confReps = new Replacement[0];
513                 ArrayList JavaDoc newList = null;
514                 ReplacementSet pathSet = null;
515
516                 confReps = ConfigTool.createReplacements(getDestination()
517                                                          + File.separator
518                                                          + DIR_OUTPUT);
519                 newList = new ArrayList JavaDoc();
520                 newList.addAll(Arrays.asList(pathReps));
521                 newList.addAll(Arrays.asList(confReps));
522                 pathReps = (Replacement[]) newList.toArray(pathReps);
523                 newList.clear();
524                 pathSet = new ReplacementSet(pathReps);
525                 pathSet.lookup(ConfigTool.JAVA_PATH).setReplaceWith(getJavaPath());
526                 pathReps = pathSet.toArray();
527             } catch (ToolException e) {
528                 throw new GeneratorException(e,
529                                              res.getString("Unable_to_create_path"));
530             }
531         }
532         return pathReps;
533     }
534
535     // /
536
// /
537
private String JavaDoc findProjectSourcePath(Template source)
538             throws GeneratorException {
539         String JavaDoc found = null;
540         StringBuffer JavaDoc buf = new StringBuffer JavaDoc();
541         Template[] list = new Template[0];
542
543         list = source.listTemplates();
544         buf.append(ProjectReplacementSet.at_PACKAGE_DIR_at);
545         buf.append('/');
546         for (int i = 0; i < list.length; i++) {
547             if (list[i].isDirectory()) {
548                 if (list[i].getRelativePath().endsWith(buf.toString())) {
549                     String JavaDoc pack = new String JavaDoc();
550                     TemplateTool tool = null;
551
552                     tool = new TemplateTool();
553                     tool.setReplacements(getReplacementSet().toArray());
554                     tool.setInitDestination(getDestination());
555                     tool.initOutput(list[i]);
556                     found = list[i].getOutput().getAbsolutePath();
557                     pack =
558                         tool.lineSearchAndReplace(ProjectReplacementSet.at_PACKAGE_DIR_at);
559                     found = found.substring(0,
560                                             found.length() - pack.length());
561                     found = found.replace('\\', '/');
562                 } else {
563                     found = findProjectSourcePath(list[i]);
564                 }
565             }
566             if (found != null) {
567                 break;
568             }
569         }
570         return found;
571     }
572
573     /**
574      * Method declaration
575      *
576      *
577      * @param destDir
578      *
579      * @exception java.io.IOException
580      */

581     private File JavaDoc generateReadme(String JavaDoc destPath) throws GeneratorException {
582         File JavaDoc readme = null;
583         PrintWriter JavaDoc out = null;
584         Replacement rep = null;
585         String JavaDoc projName = new String JavaDoc();
586
587         readme = new File JavaDoc(destPath + File.separator + FILE_README_HTML);
588         readme.getParentFile().mkdirs();
589         try {
590             out = new PrintWriter JavaDoc(new FileWriter JavaDoc(readme));
591         } catch (IOException JavaDoc e) {
592             throw new GeneratorException(e,
593                                          res.getString("Unable_to_create_readme"));
594         }
595         try {
596             rep =
597                 getReplacementSet().lookup(ProjectReplacementSet.at_PROJECT_at);
598             projName = rep.getReplaceWith()[0];
599         } catch (ToolException e) {
600             projName = res.getString("The_project");
601         }
602         out.println("<html>"); // nores
603
out.println("<head>"); // nores
604
out.println(" "
605                     + ResUtil.format(res.getString("Title_readme"),
606                                      projName));
607         out.println("</head>"); // nores
608
out.println("<body>"); // nores
609
out.println("<br>"); // nors
610
if (getAddinSteps() != null && getAddinSteps().length >= 1) {
611             out.println("<h2>"
612                         + ResUtil.format(res.getString("To_build_with_kelp"), projName)
613                         + "</h2>");
614             out.println(getAddinSteps()[0]);
615             out.println("<ol>"); // nores
616
for (int i = 1; i < getAddinSteps().length; i++) {
617                 out.println(" <li>"); // nores
618
out.println(" " + getAddinSteps()[i]); // nores
619
out.println(" </li>"); // nores
620
}
621             out.println("</ol>"); // nores
622
}
623         if (!cli) {
624
625             // don't show shell build steps if not all required
626
// files are present.
627
} else if (getShellSteps() != null && getShellSteps().length >= 1) {
628             out.println("<h2>"
629                         + ResUtil.format(res.getString("To_build_with_shell"), projName)
630                         + "</h2>");
631             out.println("<ol>"); // nores
632
for (int i = 0; i < getShellSteps().length; i++) {
633                 out.println(" <li>"); // nores
634
out.println(" " + getShellSteps()[i]); // nores
635
out.println(" </li>"); // nores
636
}
637             out.println("</ol>"); // nores
638
}
639         out.println("</body>"); // nores
640
out.println("</html>"); // nores
641
out.flush();
642         out.close();
643         return readme;
644     }
645
646 }
647
Popular Tags