KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > enhydra > tool > common > TemplateTool


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.common;
25
26 // ToolBox imports
27
import org.enhydra.tool.ToolBoxInfo;
28 import org.enhydra.tool.common.event.TemplateEvent;
29 import org.enhydra.tool.common.event.TemplateListener;
30
31 // Standard imports
32
import java.awt.Component JavaDoc;
33 import java.awt.event.ActionEvent JavaDoc;
34 import java.awt.event.ActionListener JavaDoc;
35 import java.io.BufferedReader JavaDoc;
36 import java.io.IOException JavaDoc;
37 import java.io.InputStreamReader JavaDoc;
38 import java.io.File JavaDoc;
39 import java.io.FileFilter JavaDoc;
40 import java.io.FileReader JavaDoc;
41 import java.io.FileWriter JavaDoc;
42 import java.io.PrintWriter JavaDoc;
43 import java.net.URL JavaDoc;
44 import java.util.ArrayList JavaDoc;
45 import java.util.Arrays JavaDoc;
46 import java.util.ResourceBundle JavaDoc;
47 import javax.swing.JOptionPane JavaDoc;
48 import javax.swing.JFrame JavaDoc;
49 import javax.swing.JButton JavaDoc;
50 import javax.swing.JDialog JavaDoc;
51
52 //
53
public class TemplateTool {
54
55     //
56
static ResourceBundle JavaDoc res =
57         ResourceBundle.getBundle("org.enhydra.tool.common.Res"); // nores
58

59     //
60
private boolean echo = true;
61     private boolean overwrite = false;
62     private Component JavaDoc owner = null;
63     private Template[] templates = new Template[0];
64     private Replacement[] replacements = new Replacement[0];
65     private ArrayList JavaDoc templateList = new ArrayList JavaDoc();
66     private String JavaDoc[] initExtensions = new String JavaDoc[0];
67     private String JavaDoc initPathKey = new String JavaDoc();
68     private String JavaDoc initDestPath = new String JavaDoc();
69     private FileFilter JavaDoc filter = new TemplateFilter();
70     private TemplateListener[] listeners = new TemplateListener[0];
71     private PrintWriter JavaDoc echoWriter = new PrintWriter JavaDoc(System.out);
72
73     //
74
public TemplateTool() {}
75
76     public boolean isOverwrite() {
77         return overwrite;
78     }
79
80     public void setOverwrite(boolean o) {
81         overwrite = o;
82     }
83
84     public boolean isSwing() {
85         return (owner != null);
86     }
87
88     public Component JavaDoc getOwner() {
89         return owner;
90     }
91
92     public void setOwner(Component JavaDoc c) {
93         owner = c;
94     }
95
96     public Template[] getTemplates() {
97         return templates;
98     }
99
100     public void setTemplates(Template[] t) {
101         templates = t;
102     }
103
104     public TemplateListener[] getTemplateListeners() {
105         return listeners;
106     }
107
108     public void addTemplateListener(TemplateListener l) {
109         ArrayList JavaDoc list = null;
110
111         list = new ArrayList JavaDoc(Arrays.asList(listeners));
112         if (!list.contains(l)) {
113             list.add(l);
114             list.trimToSize();
115             listeners = new TemplateListener[list.size()];
116             listeners = (TemplateListener[]) list.toArray(listeners);
117         }
118         list.clear();
119     }
120
121     public void removeTemplateListener(TemplateListener l) {
122         ArrayList JavaDoc list = null;
123
124         list = new ArrayList JavaDoc(Arrays.asList(listeners));
125         if (list.contains(l)) {
126             list.remove(l);
127             list.trimToSize();
128             listeners = new TemplateListener[list.size()];
129             listeners = (TemplateListener[]) list.toArray(listeners);
130         }
131         list.clear();
132     }
133
134     //
135
//
136
public void initTemplates(File JavaDoc source, File JavaDoc dest, String JavaDoc[] exts) {
137         setInitExtensions(exts);
138         setInitDestination(dest.getAbsolutePath());
139         templateList.clear();
140         initPathKey = source.getAbsolutePath();
141         fillTemplateList(source);
142         templateList.trimToSize();
143         templates = new Template[templateList.size()];
144         templates = (Template[]) templateList.toArray(templates);
145         templateList.clear();
146     }
147
148     public void initTemplates(Template[] in, File JavaDoc dest, String JavaDoc[] exts) {
149         setInitExtensions(exts);
150         setInitDestination(dest.getAbsolutePath());
151         for (int i = 0; i < in.length; i++) {
152             initOutput(in[i]);
153         }
154         setTemplates(in);
155     }
156
157     public Replacement[] getReplacements() {
158         return replacements;
159     }
160
161     public void setReplacements(Replacement[] r) {
162         replacements = r;
163     }
164
165     public PrintWriter JavaDoc getEchoWriter() {
166         return echoWriter;
167     }
168
169     public void setEchoWriter(PrintWriter JavaDoc w) {
170         if (w == null) {
171             setEcho(false);
172         } else {
173             echoWriter = w;
174         }
175     }
176
177     public boolean isEcho() {
178         if (getEchoWriter() == null) {
179             echo = false;
180         }
181         return echo;
182     }
183
184     public void setEcho(boolean e) {
185         echo = e;
186     }
187
188     public File JavaDoc[] createOutput() throws ToolException {
189         ArrayList JavaDoc outList = new ArrayList JavaDoc();
190         File JavaDoc[] outFiles = new File JavaDoc[0];
191
192         for (int i = 0; i < templates.length; i++) {
193             File JavaDoc out = null;
194
195             out = templates[i].getOutput();
196             if (templates[i].isDirectory()) {
197                 out.mkdirs();
198             } else {
199                 if (isFileAvailable(out)) {
200                     fileSearchAndReplace(templates[i]);
201                     outList.add(templates[i].getOutput());
202                 }
203             }
204         }
205         outList.trimToSize();
206         outFiles = new File JavaDoc[outList.size()];
207         outFiles = (File JavaDoc[]) outList.toArray(outFiles);
208         outList.clear();
209         return outFiles;
210     }
211
212     public String JavaDoc lineSearchAndReplace(String JavaDoc in) {
213         String JavaDoc text = in;
214         String JavaDoc prefix = new String JavaDoc();
215         String JavaDoc suffix = new String JavaDoc();
216
217         for (int i = 0; i < replacements.length; i++) {
218             int indexOf = text.indexOf(replacements[i].getFind());
219             int lastIndex = -1;
220             int count = 0;
221
222             while (indexOf != -1 && indexOf > lastIndex && count < 1000) {
223
224                 // Catch recursive replacements by maxing out at
225
// after the 1000 replacement or break after one try
226
// if imediate recursion.
227
count++;
228                 prefix = text.substring(0, indexOf);
229                 suffix = text.substring(indexOf
230                                         + replacements[i].getFind().length());
231                 StringBuffer JavaDoc buf = new StringBuffer JavaDoc();
232
233                 buf.append(prefix);
234                 for (int j = 0; j < replacements[i].getReplaceWith().length;
235                         j++) {
236                     String JavaDoc rep = replacements[i].getReplaceWith()[j];
237
238                     if (j > 0) {
239                         if (File.separatorChar == '\\') { // Windows
240
buf.append((char) 13); // CR
241
}
242                         buf.append((char) 10); // LF
243
}
244                     buf.append(rep);
245                 }
246                 buf.append(suffix);
247                 text = buf.toString();
248                 indexOf = text.indexOf(replacements[i].getFind());
249                 if ((indexOf > -1)
250                         && (replacements[i].getReplaceWith().length > 1)) {
251                     break;
252                 }
253             }
254         }
255         return text;
256     }
257
258     //
259
//
260
protected void echoWrite(String JavaDoc out) {
261         if (isEcho()) {
262             getEchoWriter().println(out);
263             getEchoWriter().flush();
264         }
265     }
266
267     protected void echoWrite(Exception JavaDoc e) {
268         if (isEcho()) {
269             getEchoWriter().println(e.getMessage());
270         }
271         e.printStackTrace();
272     }
273
274     //
275
//
276
public void setInitDestination(String JavaDoc path) {
277         initDestPath = PathHandle.createPathString(path);
278     }
279
280     public String JavaDoc getInitDestination() {
281         return initDestPath;
282     }
283
284     public void setInitExtensions(String JavaDoc[] exts) {
285         ArrayList JavaDoc list = new ArrayList JavaDoc();
286
287         if (exts == null) {
288             initExtensions = new String JavaDoc[0];
289         } else {
290             for (int i = 0; i < exts.length; i++) {
291                 if (exts[i].length() > 0) {
292                     if ((exts[i].charAt(0) == '.')
293                             && (exts[i].length() > 1)) {
294                         list.add(exts[i].trim().substring(1));
295                     } else {
296                         list.add(exts[i].trim());
297                     }
298                 }
299             }
300             list.trimToSize();
301             initExtensions = new String JavaDoc[list.size()];
302             initExtensions = (String JavaDoc[]) list.toArray(initExtensions);
303         }
304     }
305
306     public String JavaDoc[] getInitExtensions() {
307         return initExtensions;
308     }
309
310     private void notify(Template in) {
311         TemplateListener[] templateListeners = getTemplateListeners();
312
313         if (templateListeners.length == 0) {
314
315             // done
316
} else {
317             TemplateEvent event = null;
318
319             event = new TemplateEvent(this, in);
320             for (int i = 0; i < templateListeners.length; i++) {
321                 templateListeners[i].onTemplate(event);
322             }
323         }
324     }
325
326     private void fileSearchAndReplace(Template in) throws ToolException {
327         BufferedReader JavaDoc reader = null;
328         PrintWriter JavaDoc writer = null;
329         File JavaDoc parent = null;
330         PathHandle ph = null;
331
332         notify(in);
333         ph = PathHandle.createPathHandle(in.getOutput());
334         parent = ph.getParent().getFile();
335         if ((parent != null) && (!parent.exists())) {
336             parent.mkdirs();
337         }
338         try {
339             reader =
340                 new BufferedReader JavaDoc(new InputStreamReader JavaDoc(in.getInputStream()));
341             writer = new PrintWriter JavaDoc(new FileWriter JavaDoc(ph.getFile()));
342             String JavaDoc line = reader.readLine();
343
344             while (line != null) {
345                 line = lineSearchAndReplace(line);
346                 writer.println(line);
347                 line = reader.readLine();
348             }
349             reader.close();
350             writer.close();
351             echoWrite(ResUtil.format(res.getString("Creating_file_0_"), ph));
352         } catch (IOException JavaDoc e) {
353             throw (new ToolException(e,
354                                      ResUtil.format(res.getString("Unable_to_create_0_"),
355                                                     ph)));
356         }
357     }
358
359     private void fillTemplateList(File JavaDoc root) {
360         if (root.isDirectory()) {
361             File JavaDoc[] children = new File JavaDoc[0];
362             Template template = null;
363             File JavaDoc out = null;
364
365             if (filter == null) {
366                 children = root.listFiles();
367             } else {
368                 children = root.listFiles(filter);
369             }
370             int count = 0;
371
372             for (int i = 0; i < children.length; i++) {
373                 if (children[i].isDirectory()) {
374                     fillTemplateList(children[i]);
375                 } else if (children[i].isFile()) {
376                     count++;
377                     template = new Template(children[i], initPathKey);
378                     initOutput(template);
379                     templateList.add(template);
380                 }
381             }
382             echoWrite(ResUtil.format(res.getString("_0_contains_1"), root,
383                                      count));
384         }
385     }
386
387     public void initOutput(Template template) {
388         String JavaDoc suffix = new String JavaDoc();
389         String JavaDoc ext = new String JavaDoc();
390         StringBuffer JavaDoc pathBuf = new StringBuffer JavaDoc();
391         File JavaDoc out = null;
392         int index = -1;
393
394         suffix = template.getRelativePath();
395         ext = template.getExtension().toLowerCase();
396         for (int i = 0; i < getInitExtensions().length; i++) {
397             if (ext.startsWith(getInitExtensions()[i].toLowerCase())) {
398                 index = i;
399                 break;
400             }
401         }
402         if (index > -1) {
403             suffix = suffix.substring(0,
404                                       suffix.length() - (ext.length() + 1));
405         }
406         pathBuf.append(initDestPath);
407         if (!pathBuf.toString().endsWith("/")) {
408             pathBuf.append('/');
409         }
410         pathBuf.append(suffix);
411         out = new File JavaDoc(lineSearchAndReplace(pathBuf.toString()));
412         template.setOutput(out);
413     }
414
415     /**
416      * Method declaration
417      *
418      *
419      * @param file
420      *
421      * @return
422      */

423     private boolean isFileAvailable(File JavaDoc file) throws ToolException {
424         boolean available = true;
425
426         if (file.exists() && (!file.isDirectory())) {
427             if (isOverwrite()) {
428                 file.delete();
429             } else {
430                 if (isSwing()) {
431                     available = askForOverwrite(file);
432                 } else {
433
434                     // command line
435
throw new ToolException(ResUtil.format(res.getString("File_already_exists_0"),
436                                                            file));
437                 }
438             }
439         }
440         return available;
441     }
442
443     /**
444      * Method declaration
445      *
446      */

447     private boolean askForOverwrite(File JavaDoc file) throws ToolException {
448         final String JavaDoc YES = res.getString("Yes");
449         final String JavaDoc ALL = res.getString("Yes_to_All");
450         final String JavaDoc NO = res.getString("No");
451         final String JavaDoc CANCEL = res.getString("Cancel");
452         final JOptionPane JavaDoc optionPane = new JOptionPane JavaDoc();
453         String JavaDoc mess = new String JavaDoc();
454
455         mess = ResUtil.format(res.getString("File_already_exists_n"), file);
456         optionPane.setMessage(mess);
457         final JDialog JavaDoc dialog = optionPane.createDialog(new JFrame JavaDoc(),
458                 res.getString("Confirm_Overwrite"));
459         JButton JavaDoc[] buttons = new JButton JavaDoc[4];
460         JButton JavaDoc selection = null;
461         boolean overwriteThis = false;
462         boolean cancel = false;
463
464         for (int i = 0; i < buttons.length; i++) {
465             buttons[i] = new JButton JavaDoc();
466             buttons[i].setActionCommand(new String JavaDoc() + i);
467             buttons[i].addActionListener(new ActionListener JavaDoc() {
468                 public void actionPerformed(ActionEvent JavaDoc event) {
469                     optionPane.setValue(event.getSource());
470                     dialog.setVisible(false);
471                 }
472
473             });
474         }
475         buttons[0].setText(YES);
476         buttons[1].setText(ALL);
477         buttons[2].setText(NO);
478         buttons[3].setText(CANCEL);
479         optionPane.setOptions(buttons);
480         dialog.pack();
481         dialog.show();
482         if (optionPane.getValue() instanceof JButton JavaDoc) {
483             selection = (JButton JavaDoc) optionPane.getValue();
484             if (selection.getText().equals(CANCEL)) {
485                 cancel = true;
486             } else if (selection.getText().equals(YES)) {
487                 overwriteThis = true;
488                 file.delete();
489             } else if (selection.getText().equals(ALL)) {
490                 overwriteThis = true;
491                 setOverwrite(true);
492                 file.delete();
493             }
494         }
495         optionPane.removeAll();
496         dialog.removeAll();
497         dialog.dispose();
498         if (cancel) {
499             throw new ToolException(res.getString("Template_processing"));
500         }
501         return overwriteThis;
502     }
503
504     private class TemplateFilter implements FileFilter JavaDoc {
505         public boolean accept(File JavaDoc file) {
506             boolean include = false;
507             PathHandle path = null;
508
509             if (file.isDirectory()) {
510                 include = true;
511             } else if (getInitExtensions().length > 0) {
512                 path = PathHandle.createPathHandle(file);
513                 include = path.hasExtension(getInitExtensions());
514             } else {
515                 include = true;
516             }
517             return include;
518         }
519
520     }
521 }
522
Popular Tags