KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > enhydra > kelp > common > importer > ImportTool


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

23 package org.enhydra.kelp.common.importer;
24
25 // ToolBox
26
import org.enhydra.tool.ToolBoxInfo;
27 import org.enhydra.tool.common.FileUtil;
28 import org.enhydra.tool.common.PathHandle;
29 import org.enhydra.tool.common.ToolException;
30 import org.enhydra.tool.common.ExtensionFilter;
31 import org.enhydra.tool.common.TemplateTool;
32 import org.enhydra.tool.common.Template;
33 import org.enhydra.tool.common.Replacement;
34 import org.enhydra.tool.common.event.ProgressEvent;
35 import org.enhydra.tool.common.event.ProgressListener;
36
37 // AddinCore
38
import org.enhydra.kelp.common.Constants;
39 import org.enhydra.kelp.common.ProgressBuilder;
40 import org.enhydra.kelp.common.PathUtil;
41 import org.enhydra.kelp.common.ValidationException;
42 import org.enhydra.kelp.common.ValidationUtil;
43 import org.enhydra.kelp.common.deployer.DeployBuilder;
44 import org.enhydra.kelp.common.map.Mapper;
45 import org.enhydra.kelp.common.node.OtterTemplateNode;
46 import org.enhydra.kelp.common.node.OtterNode;
47 import org.enhydra.kelp.common.node.OtterNodeFactory;
48 import org.enhydra.kelp.common.node.OtterDocumentNode;
49
50
51 // Standard imports
52
import java.io.BufferedReader JavaDoc;
53 import java.io.IOException JavaDoc;
54 import java.io.File JavaDoc;
55 import java.io.FileFilter JavaDoc;
56 import java.io.FileInputStream JavaDoc;
57 import java.io.FilenameFilter JavaDoc;
58 import java.io.FileReader JavaDoc;
59 import java.util.Enumeration JavaDoc;
60 import java.util.Properties JavaDoc;
61 import java.util.Vector JavaDoc;
62 import java.util.ResourceBundle JavaDoc;
63
64 /**
65  * Class declaration
66  *
67  * @author Paul Mahar
68  */

69 public class ImportTool extends ProgressBuilder {
70
71     // string not to be resourced
72
static ResourceBundle JavaDoc res =
73         ResourceBundle.getBundle("org.enhydra.kelp.common.Res"); // nores
74
private final static String JavaDoc KELP_PROPERTIES = "kelp.properties"; // nores
75
private final static String JavaDoc PACKAGE_KEY = "package "; // nores
76
private final String JavaDoc[] IMAGE_TYPES = {
77         "gif", "jpg"
78     }; // nores
79

80     //
81
private ExtensionFilter optionFilter = null;
82     private ImportPaths paths = null;
83     private File JavaDoc[] inFiles = new File JavaDoc[0];
84
85     /**
86      * Method declaration
87      *
88      *
89      * @param javaSource
90      *
91      * @return
92      */

93     protected static String JavaDoc readPackage(File JavaDoc javaSource) {
94         BufferedReader JavaDoc in = null;
95         String JavaDoc line = null;
96         String JavaDoc pack = null;
97
98         try {
99             in = new BufferedReader JavaDoc(new FileReader JavaDoc(javaSource));
100             line = in.readLine();
101             while (line != null) {
102                 line = line.trim();
103                 if (line.startsWith(PACKAGE_KEY)) {
104                     pack = line.substring(PACKAGE_KEY.length(),
105                                           line.indexOf(';'));
106                     pack = pack.trim();
107                     break;
108                 } else {
109                     line = in.readLine();
110                 }
111             }
112             in.close();
113         } catch (java.io.IOException JavaDoc e) {
114             line = null;
115         }
116         if (!ValidationUtil.isJavaPackage(pack)) {
117             pack = null;
118         }
119         return pack;
120     }
121
122     /**
123      * Constructor declaration
124      */

125     public ImportTool() {
126         super();
127         optionFilter = new ExtensionFilter();
128         optionFilter.setDirectoryValid(false);
129         optionFilter.addExtension(Constants.TYPE_XMLC);
130     }
131
132     public ImportPaths getPaths() {
133         return paths;
134     }
135
136     public void setPaths(ImportPaths p) {
137         paths = p;
138     }
139
140     /**
141      *
142      */

143     public void addFiles(File JavaDoc[] files) {
144         OtterNodeFactory nodeFactory = null;
145         OtterDocumentNode node = null;
146         Mapper mapper = new Mapper(paths.getProject());
147         Vector JavaDoc templateVector = new Vector JavaDoc();
148         PathHandle inputPath = null;
149         String JavaDoc[] docTypes = new String JavaDoc[0];
150
151         docTypes = ToolBoxInfo.getSupportedDocTypes();
152         inputPath =
153             PathHandle.createPathHandle(paths.getProject().getDeployInputPath());
154         nodeFactory = paths.getProject().getNodeFactory();
155         for (int i = 0; i < files.length; i++) {
156             OtterNode folder = null;
157             PathHandle path = null;
158
159             path = PathHandle.createPathHandle(files[i]);
160             if (isIgnored(path.getPath())) {
161
162                 // ignore it
163
} else {
164                 folder = getFolder(nodeFactory, inputPath, files[i]);
165                 if (path.hasExtension(Constants.TYPE_JAVA)) {
166                     nodeFactory.createJavaFileNode(folder, path.getPath());
167
168                     // Images
169
} else if (path.hasExtension(IMAGE_TYPES)) {
170                     nodeFactory.createImageFileNode(folder, path.getPath());
171
172                     // Document resources
173
} else if (path.hasExtension(docTypes)) {
174                     node = nodeFactory.createDocumentNode(folder,
175                                                           path.getPath());
176                     setupDocumentNode(mapper, node);
177
178                     // Templates
179
} else if (path.hasExtension(Constants.TYPE_IN)
180                            && inputPath.parentOf(path)) {
181                     OtterTemplateNode template = null;
182
183                     template = nodeFactory.createTemplateNode(folder,
184                                                               path.getPath());
185                     template.setSelected(true);
186
187                     // Other files xmlc, xml, makefile, rul, conf, etc.
188
} else {
189                     nodeFactory.createTextFileNode(folder, path.getPath());
190                 }
191             }
192         }
193     }
194
195     /**
196      * Method declaration
197      *
198      *
199      * @param project
200      */

201     public void importFilesFromRoot() {
202         importFiles(readFilesFromRoot());
203     }
204
205     /**
206      * Method declaration
207      *
208      *
209      * @param project
210      * @param files
211      */

212     public void importFiles(File JavaDoc[] files) {
213         setFresh(true);
214         inFiles = files;
215         if (getProgressListeners().length == 0) {
216             privateImport();
217         } else {
218             ImportRunner runner = new ImportRunner();
219             runner.start();
220         }
221     }
222
223     private void privateImport() {
224         File JavaDoc[] files = inFiles;
225
226         inFiles = new File JavaDoc[0];
227         if (isFresh()) {
228             refreshProgress(10, res.getString("Preparing_import"));
229             preAdd();
230         }
231         if (isFresh()) {
232             refreshProgress(15, res.getString("Searching_templates"));
233             files = processConfInSource(files);
234         }
235         if (isFresh()) {
236             refreshProgress(20, res.getString("Importing_files"));
237             paths.initPackageMap(true);
238         }
239         if (isFresh()) {
240             addFiles(files);
241         }
242         if (isFresh()) {
243             refreshProgress(75, res.getString("Reading_makefiles"));
244             paths.getMakefileReader().updateProject();
245         }
246         if (isFresh()) {
247             refreshProgress(85, res.getString("Processing_input"));
248             deployInput();
249         }
250         if (isFresh()) {
251             refreshProgress(95, res.getString("Processing_templates"));
252         }
253     }
254
255     // Handle E3 newapp generated .conf templates that should
256
// be .conf.in
257
private File JavaDoc[] processConfInSource(File JavaDoc[] files) {
258         TemplateTool tool = null;
259         Template[] temps = new Template[1];
260         File JavaDoc dest = null;
261         PathHandle filePath = null;
262         PathHandle searchPath = null;
263
264         searchPath = PathHandle.createPathHandle(paths.getSourcePath()
265                                                  + File.separator
266                                                  + paths.getPackagePath());
267         for (int i = 0; i < files.length; i++) {
268             if (files[i] == null) {
269
270                 // skip
271
} else {
272                 filePath = PathHandle.createPathHandle(files[i]);
273                 if (filePath.hasExtension(Constants.TYPE_CONF)
274                         && searchPath.parentOf(filePath)) {
275                     StringBuffer JavaDoc buf = new StringBuffer JavaDoc();
276
277                     buf.append(filePath);
278                     buf.append('.');
279                     buf.append(Constants.TYPE_IN);
280                     dest = new File JavaDoc(buf.toString());
281                     if (!dest.exists()) {
282                         try {
283                             tool = new TemplateTool();
284                             temps[0] = new Template(files[i], searchPath.getPath());
285                             temps[0].setOutput(dest);
286                             tool.setTemplates(temps);
287                             files[i] = tool.createOutput()[0];
288                         } catch (ToolException e) {
289                             e.printStackTrace();
290                         }
291                     }
292                 }
293             }
294         }
295         return files;
296     }
297
298     /**
299      *
300      */

301     private void preAdd() {
302         setupProjectSourcePath();
303         paths.initProject();
304         addKelpProperties();
305     }
306
307     /**
308      *
309      */

310     private void deployInput() {
311         DeployBuilder builder = null;
312         OtterTemplateNode[] nodes = new OtterTemplateNode[0];
313
314         nodes = PathUtil.getInputTemplates(paths.getProject());
315         builder = new DeployBuilder();
316         builder.setProject(paths.getProject());
317         builder.setInputNodes(nodes);
318         builder.setEcho(false);
319         builder.buildInput();
320         builder.buildContent();
321
322         // Handler for Enhydra 3 style startup
323
boolean servlet = false;
324         String JavaDoc multi = new String JavaDoc();
325         String JavaDoc path = new String JavaDoc();
326
327         for (int i = 0; i < nodes.length; i++) {
328             path = nodes[i].getOutputPath();
329             if (path.endsWith(Constants.FILE_SERVLET_CONF)) {
330                 servlet = true;
331             } else if (path.endsWith(Constants.FILE_MULTISERVER_CONF)) {
332                 multi = path;
333             }
334         }
335         if ((!servlet) && multi.length() > 0) {
336             paths.getProject().setDeployBootstrapPath(multi);
337             if (paths.getProject().isDeployStartupRun()) {
338                 paths.getProject().configureRunClass();
339             }
340         }
341     }
342
343     private boolean isIgnored(String JavaDoc in) {
344         boolean ignore = false;
345         String JavaDoc path = in.toLowerCase().trim();
346
347         // conditional strings not to be translated
348
if (path.endsWith(".bak")) { // nores
349
ignore = true;
350         } else if (path.endsWith(".class")) { // nores
351
ignore = true;
352         } else if (path.endsWith("~")) { // nores
353
ignore = true;
354         } else if (path.endsWith(".jpr")) { // nores
355
ignore = true;
356         } else if (path.endsWith(".jpx")) { // nores
357
ignore = true;
358         } else if (path.endsWith(".jrl")) { // nores
359
ignore = true;
360         } else if (path.endsWith(".local")) { // nores
361
ignore = true;
362         } else if (path.endsWith("tbl")) { // nores
363
ignore = true;
364         } else if (path.endsWith("tmp")) { // nores
365
ignore = true;
366         } else if (path.endsWith(ImportTool.KELP_PROPERTIES.toLowerCase())) {
367             ignore = true;
368         } else if (path.indexOf("/cvs/") > -1) { // nores
369
ignore = true;
370         } else if (path.indexOf("/classes/") > -1) { // nores
371
ignore = true;
372         }
373         return ignore;
374     }
375
376     /**
377      *
378      */

379     private void addKelpProperties() {
380         StringBuffer JavaDoc filePath = new StringBuffer JavaDoc();
381         Properties JavaDoc properties = new Properties JavaDoc();
382         File JavaDoc file;
383         FileInputStream JavaDoc inStream;
384         Enumeration JavaDoc names;
385         String JavaDoc name;
386         String JavaDoc value;
387
388         filePath.append(paths.getProject().getRootPath());
389         filePath.append(File.separator);
390         filePath.append(KELP_PROPERTIES);
391         file = new File JavaDoc(filePath.toString());
392         if (file.exists()) {
393             try {
394                 inStream = new FileInputStream JavaDoc(file);
395                 properties.load(inStream);
396                 names = properties.propertyNames();
397                 while (names.hasMoreElements()) {
398                     name = (String JavaDoc) names.nextElement();
399                     value = properties.getProperty(name);
400                     paths.getProject().setProperty(name, value);
401                 }
402                 inStream.close();
403                 properties.clear();
404                 file.delete();
405             } catch (Exception JavaDoc e) {
406
407                 // non-fatal, report and continue
408
e.printStackTrace();
409             }
410         }
411     }
412
413     private String JavaDoc lookupSymbolicName(File JavaDoc sourceFile) {
414         MakefileData[] syms = new MakefileData[0];
415         String JavaDoc symName = new String JavaDoc();
416
417         syms = paths.getMakefileReader().getSymbolicMakefiles();
418         for (int i = 0; i < syms.length; i++) {
419             if (syms[i].containSourceDoc(sourceFile.getAbsolutePath())) {
420                 File JavaDoc makeParent = new File JavaDoc(syms[i].getMakeParentPath());
421
422                 symName = '.' + makeParent.getName();
423                 break;
424             }
425         }
426         return symName;
427     }
428
429     /**
430      *
431      */

432     private OtterNode getFolder(OtterNodeFactory nodeFactory,
433                                 PathHandle inputPath,
434                                 File JavaDoc sourceFile) {
435
436         // Source path + app package + folder + java file name =
437
// java file absolute path.
438
OtterNode folderNode = paths.getProject();
439         String JavaDoc symName = new String JavaDoc();
440         String JavaDoc folderName = new String JavaDoc();
441         PathHandle projectRoot = null;
442         PathHandle sourceRoot = null;
443         PathHandle packagePath = null;
444         PathHandle outputPath = null;
445
446         folderName = PathHandle.createPathString(sourceFile.getParent());
447         projectRoot = PathHandle.createPathHandle(paths.getProject().getRootPath());
448         sourceRoot = PathHandle.createPathHandle(paths.getSourcePath());
449         outputPath = PathHandle.createPathHandle(paths.getDeployRootPath());
450         packagePath = PathHandle.createPathHandle(sourceRoot.getPath()
451                                                   + File.separator
452                                                   + paths.getPackagePath());
453
454         // check if source is in symbolic makefiles
455
symName = lookupSymbolicName(sourceFile);
456
457         //
458
if (sourceRoot.parentOf(folderName)) {
459             if (packagePath.parentOf(folderName)) {
460                 folderName =
461                     folderName.substring(packagePath.getPath().length() + 1);
462                 folderName = folderName.replace('/', '.');
463             } else {
464                 folderName =
465                     folderName.substring(sourceRoot.getPath().length() + 1);
466             }
467             folderNode = nodeFactory.createFolderNode(paths.getProject(),
468                                                       folderName + symName);
469         } else if (projectRoot.parentOf(folderName)) {
470             folderName = folderName.substring(projectRoot.getPath().length()
471                                               + 1);
472             folderNode = nodeFactory.createFolderNode(paths.getProject(),
473                                                       folderName + symName);
474         } else if (inputPath.parentOf(sourceFile)) {
475            folderName = Constants.DIR_INPUT;
476            folderNode = nodeFactory.createFolderNode(paths.getProject(),
477                                                      folderName + symName);
478         } else if (outputPath.parentOf(sourceFile)) {
479            folderName = Constants.DIR_OUTPUT;
480            folderNode = nodeFactory.createFolderNode(paths.getProject(),
481                                                      folderName + symName);
482
483         }
484         return folderNode;
485     }
486
487     /**
488      *
489      */

490     private void setupDocumentNode(Mapper mapper, OtterDocumentNode node) {
491         String JavaDoc sourcePath = node.getFilePath();
492         File JavaDoc sourceFile = null;
493         PathHandle parentPath = null;
494
495         parentPath = PathHandle.createPathHandle(paths.getSourcePath()
496                                                  + File.separator
497                                                  + paths.getPackagePath());
498         if ((sourcePath != null) && (parentPath.parentOf(sourcePath))) {
499             sourceFile = new File JavaDoc(sourcePath);
500             File JavaDoc file = null;
501             File JavaDoc[] list = new File JavaDoc[0];
502             String JavaDoc mappedPath = null;
503             String JavaDoc sourceName = null;
504             String JavaDoc javaName = null;
505
506             // if .xmlc options file found in mapped path,
507
// set xmlc file property
508
mappedPath = mapper.getMappedSourcePath(node);
509             file = new File JavaDoc(mappedPath);
510             file = file.getParentFile();
511             list = file.listFiles(optionFilter);
512             if ((list != null) && (list.length >= 1)) {
513                 node.setXMLCOptionFilePath(list[0].getAbsolutePath());
514             }
515             list = file.listFiles(paths.getJavaFilter());
516             if (list != null) {
517                 for (int i = 0; i < list.length; i++) {
518                     sourceName = sourceFile.getName().toLowerCase();
519                     sourceName =
520                         sourceName.substring(0, sourceName.lastIndexOf('.'));
521                     javaName = list[i].getName().toLowerCase();
522                     if (javaName.startsWith(sourceName)) {
523                         node.setSelected(true);
524                         break;
525                     }
526                 }
527             }
528             if (!node.isSelected()) {
529                 node.setStatic(true);
530             }
531
532             // if mapped package directory contains
533
// an xmlc file than set it as the
534
// String optionFilename = new String();
535
// node.setXMLCOptionFilename(optionFilename);
536
}
537     }
538
539     /**
540      *
541      */

542     private void setupProjectSourcePath() {
543         String JavaDoc[] path = paths.getProject().getSourcePathArray();
544         String JavaDoc[] newPath;
545         File JavaDoc current;
546         String JavaDoc[] javaList;
547         boolean javaFound = false;
548
549         for (int i = 0; i < path.length; i++) {
550             current = new File JavaDoc(path[i]);
551             javaList = current.list(new FilenameFilter JavaDoc() {
552
553                 /**
554                  * Method declaration
555                  *
556                  * @param dir
557                  * @param name
558                  *
559                  * @return
560                  */

561                 public boolean accept(File JavaDoc dir, String JavaDoc name) {
562                     return name.trim().toLowerCase().endsWith(Constants.TYPE_JAVA);
563                 }
564
565             });
566             if ((javaList != null) && (javaList.length >= 1)) {
567                 javaFound = true;
568             }
569         }
570         if (paths.getSourcePath().length() > 0) {
571             if (javaFound) {
572                 newPath = new String JavaDoc[path.length + 1];
573                 newPath[0] = paths.getSourcePath();
574                 for (int i = 1; i < (path.length + 1); i++) {
575                     newPath[i] = path[i - 1];
576                 }
577             } else {
578                 newPath = new String JavaDoc[1];
579                 newPath[0] = paths.getSourcePath();
580             }
581             paths.getProject().setSourcePathArray(newPath);
582         }
583     }
584
585     /**
586      *
587      */

588     private File JavaDoc[] readFilesFromRoot() {
589         File JavaDoc[] files = new File JavaDoc[0];
590
591         if (paths.getRootPath() != null) {
592             File JavaDoc root = new File JavaDoc(paths.getRootPath());
593
594             files = readFiles(root);
595         }
596         return files;
597     }
598
599     /**
600      *
601      */

602     private File JavaDoc[] readFiles(File JavaDoc dir) {
603         File JavaDoc[] files = new File JavaDoc[0];
604         Vector JavaDoc fileVector = new Vector JavaDoc();
605         PathHandle classes = null;
606         PathHandle output = null;
607
608         classes = PathHandle.createPathHandle(paths.getClassOutputPath());
609         output = PathHandle.createPathHandle(paths.getDeployRootPath());
610         if (dir.isDirectory()) {
611             File JavaDoc[] list = dir.listFiles();
612
613             for (int i = 0; i < list.length; i++) {
614                 if (list[i].isDirectory()) {
615                     PathHandle cursor = null;
616
617                     cursor = PathHandle.createPathHandle(list[i]);
618                     if (classes.parentOf(cursor) || output.parentOf(cursor)) {
619
620                         // skip over classes and output folders.
621
} else {
622                         File JavaDoc[] subList = readFiles(list[i]);
623
624                         for (int j = 0; j < subList.length; j++) {
625                             fileVector.addElement(subList[j]);
626                         }
627                     }
628                 } else if (list[i].isFile()) {
629                     fileVector.addElement(list[i]);
630                 }
631             }
632         }
633         if (fileVector.size() > 0) {
634             files = (File JavaDoc[]) fileVector.toArray(files);
635         }
636         return files;
637     }
638
639     private void buildImpl() {
640         setFresh(true);
641         refreshProgress(5, res.getString("Starting_import"));
642         privateImport();
643         if (isFresh()) {
644             refreshProgress(100, res.getString("Complete"));
645         }
646     }
647
648
649     private class ImportRunner extends Thread JavaDoc {
650        protected ImportRunner() {
651             setPriority((int) ((Thread.MIN_PRIORITY + Thread.NORM_PRIORITY) / 2));
652         }
653
654        public void run() {
655             buildImpl();
656         }
657
658     }
659
660
661 }
662
Popular Tags