KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > de > gulden > framework > amoda > generic > core > GenericApplication


1 /*
2  * Project: AMODA - Abstract Modeled Application
3  * Class: de.gulden.framework.amoda.generic.core.GenericApplication
4  * Version: snapshot-beautyj-1.1
5  *
6  * Date: 2004-09-29
7  *
8  * This is a snapshot version of the AMODA 0.2 development branch,
9  * it is not released as a seperate version.
10  * For AMODA, see http://amoda.berlios.de/.
11  *
12  * This is licensed under the GNU Lesser General Public License (LGPL)
13  * and comes with NO WARRANTY.
14  *
15  * Author: Jens Gulden
16  * Email: amoda@jensgulden.de
17  */

18
19 package de.gulden.framework.amoda.generic.core;
20
21 import de.gulden.framework.amoda.generic.core.GenericApplicationEnvironmentFactory;
22 import de.gulden.framework.amoda.generic.metadata.*;
23 import de.gulden.framework.amoda.generic.option.*;
24 import de.gulden.framework.amoda.model.behaviour.Command;
25 import de.gulden.framework.amoda.model.behaviour.event.*;
26 import de.gulden.framework.amoda.model.core.*;
27 import de.gulden.framework.amoda.model.core.Application;
28 import de.gulden.framework.amoda.model.data.*;
29 import de.gulden.framework.amoda.model.document.*;
30 import de.gulden.framework.amoda.model.interaction.*;
31 import de.gulden.framework.amoda.model.option.*;
32 import de.gulden.framework.amoda.model.option.Option;
33 import de.gulden.util.*;
34 import java.lang.*;
35 import java.net.*;
36 import java.util.*;
37 import javax.swing.*;
38 import org.w3c.dom.*;
39 import org.w3c.dom.Document JavaDoc;
40
41 /**
42  * Class GenericApplication.
43  *
44  * @author Jens Gulden
45  * @version snapshot-beautyj-1.1
46  */

47 public abstract class GenericApplication extends GenericApplicationModule implements Application, Command, LogPerformer {
48
49     // ------------------------------------------------------------------------
50
// --- fields ---
51
// ------------------------------------------------------------------------
52

53     public static String JavaDoc DEFAULT_CONFIGURATION_RESOURCE = System.getProperty("application.config" ,"res:application.xml");
54
55     public static final int YES = 0;
56
57     public static final int NO = 2;
58
59     public static final int CANCEL = 4;
60
61     public boolean verbose;
62
63     public boolean quiet;
64
65     protected Option[] simpleAnswerOptions;
66
67     protected Queue commandQueue;
68
69     protected Stack commandUndoStack;
70
71     protected Document JavaDoc configuration;
72
73     protected DocumentHandler documentHandler;
74
75     protected RecentFilesList recentFilesList;
76
77     public static final String JavaDoc OPTIONS_DIALOG_TITLE = "Options";
78
79     protected GenericApplicationEnvironment genericApplicationEnvironment;
80
81     public UndoStack undoStack;
82
83     public Collection applicationListener = new ArrayList();
84
85
86     // ------------------------------------------------------------------------
87
// --- constructor ---
88
// ------------------------------------------------------------------------
89

90     public GenericApplication() {
91         super();
92         setDocumentHandler(createDocumentHandler()); // default impl.
93
setRecentFilesList(createRecentFilesList());
94     }
95
96
97     // ------------------------------------------------------------------------
98
// --- methods ---
99
// ------------------------------------------------------------------------
100

101     public GenericApplicationEnvironment getGenericApplicationEnvironment() {
102         return genericApplicationEnvironment;
103     }
104
105     public void setGenericApplicationEnvironment(GenericApplicationEnvironment genericApplicationEnvironment) {
106         if (this.genericApplicationEnvironment != genericApplicationEnvironment) {
107             this.genericApplicationEnvironment = genericApplicationEnvironment;
108             if (genericApplicationEnvironment != null) genericApplicationEnvironment.setGenericApplication(this);
109         }
110     }
111
112     public UndoStack getUndoStack() {
113         return undoStack;
114     }
115
116     public void setUndoStack(UndoStack undoStack) {
117         this.undoStack = undoStack;
118     }
119
120     public Collection getApplicationListeners() {
121         return applicationListener;
122     }
123
124     public void addApplicationListener(ApplicationListener applicationListener) {
125         if (! this.applicationListener.contains(applicationListener)) this.applicationListener.add(applicationListener);
126     }
127
128     public void removeApplicationListener(ApplicationListener applicationListener) {
129         this.applicationListener.remove(applicationListener);
130     }
131
132     public void log(String JavaDoc text, Object JavaDoc source) {
133         de.gulden.framework.amoda.model.interaction.LogMessage m=getGenericApplicationEnvironment().createDefaultLogMessage(text,source,Message.INFORMATION_MESSAGE,null);
134         m.perform();
135     }
136
137     public void init(ApplicationEnvironment environment) {
138         GenericApplicationEnvironment env=(GenericApplicationEnvironment)environment; // throws ClastCastException if invalid environment
139
setGenericApplicationEnvironment(env);
140         simpleAnswerOptions=new de.gulden.framework.amoda.model.option.Option[3];
141         simpleAnswerOptions[0]=env.createDefaultOption("YES",Boolean.FALSE,env.createDefaultMetadata("Yes"));
142         simpleAnswerOptions[1]=env.createDefaultOption("NO",Boolean.FALSE,env.createDefaultMetadata("No"));
143         simpleAnswerOptions[2]=env.createDefaultOption("CANCEL",Boolean.FALSE,env.createDefaultMetadata("Cancel"));
144         undoStack=new UndoStack();
145         this.initModule(this);
146     }
147
148     public void start() {
149         super.start();
150         // to be extended or overwritten by subclass
151
if (getOptions().getBoolean(GenericApplicationEnvironment.CONFIGURATION_BATCH_MODE)) {
152             Collection batchCommands=((GenericApplicationEnvironment)getEnvironment()).getBatchCommands();
153             // do batch commands before starting interaction
154
for (Iterator it=batchCommands.iterator();it.hasNext();) {
155                 de.gulden.framework.amoda.model.behaviour.Command c=(de.gulden.framework.amoda.model.behaviour.Command)it.next();
156                 c.perform();
157             }
158         }
159         if (getOptions().getBoolean(GenericApplicationEnvironment.CONFIGURATION_INTERACTION_MODE)) {
160             startInteraction();
161         }
162     }
163
164     public void message(String JavaDoc title, String JavaDoc text) {
165         de.gulden.framework.amoda.model.interaction.Message m=getGenericApplicationEnvironment().createDefaultMessage(title,text,Message.INFORMATION_MESSAGE,null);
166         m.perform();
167     }
168
169     public void message(String JavaDoc text) {
170         message("Message",text);
171     }
172
173     public void log(String JavaDoc text) {
174         log(text,this);
175     }
176
177     public void error(String JavaDoc text, Throwable JavaDoc throwable, boolean exitApplication) {
178         de.gulden.framework.amoda.model.interaction.ErrorMessage m=getGenericApplicationEnvironment().createDefaultErrorMessage(text,throwable,exitApplication,null);
179         m.perform();
180     }
181
182     public String JavaDoc question(String JavaDoc title, String JavaDoc text, String JavaDoc answers) {
183         de.gulden.framework.amoda.model.interaction.Question q=getGenericApplicationEnvironment().createDefaultQuestion(title,text,answers,null);
184         getGenericApplicationEnvironment().doQuestion(q);
185         return q.getAnswer();
186     }
187
188     public String JavaDoc question(String JavaDoc text, String JavaDoc answers) {
189         return question("",text,answers);
190     }
191
192     public boolean confirm(String JavaDoc title, String JavaDoc text) {
193         return question(title,text,"yes,no").equals("yes");
194     }
195
196     public boolean confirm(String JavaDoc text) {
197         return confirm("",text);
198     }
199
200     public void run() {
201         ApplicationEnvironment env=createApplicationEnvironment();
202         env.launch(this);
203     }
204
205     public void startInteraction() {
206         // your code here
207
}
208
209     public void about() {
210         ((GenericApplicationEnvironment)getEnvironment()).doAbout();
211     }
212
213     public void welcome() {
214         // your code here
215
}
216
217     public void usage(boolean exitApplication) {
218         ((GenericApplicationEnvironment)getEnvironment()).doUsage(exitApplication);
219     }
220
221     public void usage(String JavaDoc errorText) {
222         message("Error: "+errorText);
223         usage(true);
224     }
225
226     public void error(Throwable JavaDoc throwable, boolean exit) {
227         error("",throwable,exit);
228     }
229
230     public Application getApplication() {
231         return this;
232     }
233
234     public ApplicationEnvironment getEnvironment() {
235         return getGenericApplicationEnvironment();
236     }
237
238     public void error(String JavaDoc text, Throwable JavaDoc cause) {
239         error(text,cause,isBatchMode());
240     }
241
242     public void error(String JavaDoc text) {
243         error(text,null);
244     }
245
246     public void fatalError(String JavaDoc text, Throwable JavaDoc cause) {
247         error(text,cause,true);
248     }
249
250     public void fatalError(String JavaDoc text) {
251         fatalError(text,null);
252     }
253
254     public void error(Throwable JavaDoc cause) {
255         error("",cause);
256     }
257
258     public void fatalError(Throwable JavaDoc cause) {
259         String JavaDoc msg = cause.getMessage();
260         if (msg == null) {
261             msg = "-" + cause.getClass().getName() + "-";
262         }
263         fatalError(msg, cause);
264     }
265
266     public URL getResource(String JavaDoc res) {
267         URL url;
268         if (res.startsWith("/")) { // absolute URL
269
url=this.getClass().getResource(res);
270         } else {
271             String JavaDoc resBase=getOptions().getString("resource-base");
272             if (!resBase.endsWith("/")) resBase+="/";
273             url=this.getClass().getResource(resBase+res);
274             if (url==null) { // not yet found, try in system-resources
275
resBase=getOptions().getString("environment-resource-base");
276                 if (!resBase.endsWith("/")) resBase+="/";
277                 url=this.getClass().getResource(resBase+res);
278                 // is still not found, url==null
279
}
280         }
281         return url;
282     }
283
284     public ImageIcon getImage(String JavaDoc res) {
285         return new ImageIcon(getResource(res));
286     }
287
288     public Workspace getWorkspace() {
289         return getGenericApplicationEnvironment().getWorkspace();
290     }
291
292     public ArgsParser createArgsParser() {
293         // your code here
294
return null;
295     }
296
297     public Workspace createWorkspace() {
298         return getGenericApplicationEnvironment().createDefaultWorkspace();
299     }
300
301     public void status(String JavaDoc text) {
302         Message m=getGenericApplicationEnvironment().createDefaultMessage(null,text,Message.STATUS_MESSAGE,null);
303         m.perform();
304     }
305
306     public DocumentHandler getDocumentHandler() {
307         return documentHandler;
308     }
309
310     public void setDocumentHandler(DocumentHandler _documentHandler) {
311         documentHandler = _documentHandler;
312     }
313
314     public RecentFilesList getRecentFilesList() {
315         return recentFilesList;
316     }
317
318     public void setRecentFilesList(RecentFilesList _recentFilesList) {
319         recentFilesList = _recentFilesList;
320     }
321
322     public boolean isVerbose() {
323         try {
324             return verbose || getOptions().getBoolean("verbose");
325         } catch (IllegalOptionError ioe) {
326             return verbose;
327         }
328     }
329
330     public void setVerbose(boolean _verbose) {
331         verbose = _verbose;
332     }
333
334     public boolean isQuiet() {
335         return quiet || getOptions().getBoolean("quiet");
336     }
337
338     public void setQuiet(boolean _quiet) {
339         quiet = _quiet;
340     }
341
342     public void exit() {
343         exit(0);
344     }
345
346     public void exit(int code) {
347         getGenericApplicationEnvironment().doExit(this, code);
348     }
349
350     public boolean isBatchMode() {
351         return getOptions().getBoolean("batch-mode");
352     }
353
354     public Value[] getInputValues() {
355         return getGenericApplicationEnvironment().getInputValues();
356     }
357
358     public void optionsDialog() {
359         de.gulden.framework.amoda.generic.interaction.GenericDialog d=new de.gulden.framework.amoda.generic.interaction.GenericDialog();
360         d.setTitle(OPTIONS_DIALOG_TITLE);
361         d.setParent(this);
362         d.setOptionsDirectly(getOptions()); // ..._Directly_ to avoid setting back-reference as parent member of options
363
d.perform();
364         if (d.getAnswer()==d.OK) {
365             ((de.gulden.framework.amoda.generic.option.GenericOptions)getOptions()).saveGlobalProperties();
366         }
367     }
368
369     public void perform() {
370         // your code here
371
}
372
373     public void help() {
374         ((GenericApplicationEnvironment)getEnvironment()).doHelp();
375     }
376
377     public Collection getAvailableFeatures() {
378         ArrayList features = new ArrayList();
379         for (Iterator it = getFeatures().iterator(); it.hasNext(); ) {
380             GenericFeature f = (GenericFeature)it.next();
381             if (!f.isSystem()) {
382                 features.add(f);
383             }
384         }
385         return features;
386     }
387
388     public synchronized boolean isInInitializing() {
389         return true;
390     }
391
392     public synchronized boolean isInRunning() {
393         return true;
394     }
395
396     public synchronized boolean isInWaitingForCommand() {
397         return true;
398     }
399
400     public synchronized boolean isInExecutingCommand() {
401         return true;
402     }
403
404     public synchronized boolean isInDestroying() {
405         return true;
406     }
407
408     protected abstract ApplicationEnvironment createApplicationEnvironment();
409
410     protected Message createAboutMessage() {
411         String JavaDoc name=getMetadata().get("title");
412         if (Toolbox.empty(name)) {
413             name=getMetadata().get("name");
414             if (Toolbox.empty(name)) {
415                 name="";
416             }
417         }
418         String JavaDoc version=getMetadata().get("version");
419         if (!Toolbox.empty(version)) {
420             version=" "+version;
421         } else {
422             version="";
423         }
424         String JavaDoc author=getMetadata().get("author");
425         if (!Toolbox.empty(author)) {
426             author=" by "+author;
427             String JavaDoc email=getMetadata().get("email");
428             if (!Toolbox.empty(email)) {
429                 email=", "+email;
430                 author=author+email;
431             }
432         } else {
433             author="";
434         }
435         String JavaDoc license=getMetadata().get("license-message"); // metadata description by default
436
if (!Toolbox.empty(license)) {
437             license=NL+license;
438         } else {
439             license="";
440         }
441         Message m = getGenericApplicationEnvironment().createDefaultMessage("about", name + version + author + license ,0,null);
442         return m;
443     }
444
445     protected Message createUsageMessage() {
446         StringBuffer JavaDoc sb=new StringBuffer JavaDoc();
447         String JavaDoc description = getMetadata().get("description").trim();
448         if (description.length()!=0) {
449             sb.append(description+NL+NL);
450         }
451         String JavaDoc usageLine = getUsageLine();
452         if (usageLine!=null) {
453             sb.append("Usage: "+usageLine+NL);
454         }
455         return getGenericApplicationEnvironment().createDefaultMessage("Usage",sb.toString(),0,null);
456     }
457
458     protected DocumentHandler createDocumentHandler() {
459         // your code here
460
return null;
461     }
462
463     protected ClipboardHandler createClipboardHandler() {
464         // your code here
465
return null;
466     }
467
468     protected RecentFilesList createRecentFilesList() {
469         return new GenericRecentFilesList();
470     }
471
472     protected URL getDefaultConfigurationDocumentResource() {
473         URL res;
474         try {
475             res = Toolbox.getResourceURL(DEFAULT_CONFIGURATION_RESOURCE);
476         } catch (java.net.MalformedURLException JavaDoc mue) {
477             res = null;
478         }
479         if (res != null) {
480             return res;
481         } else {
482             return super.getDefaultConfigurationDocumentResource();
483         }
484     }
485
486     protected Message createHelpMessage() {
487         StringBuffer JavaDoc sb=new StringBuffer JavaDoc();
488         Collection allOptions = getOptions().getAll(de.gulden.framework.amoda.model.option.OptionEntry.class, true).values();
489         if (!allOptions.isEmpty()) {
490             sb.append("options are: "+NL);
491             double[] weights={ 0.0, 0.0, 1.0 };
492             de.gulden.util.text.TextTable table=new de.gulden.util.text.TextTable( 3, 79, weights, ' ' );
493             for (Iterator it=allOptions.iterator();it.hasNext();) {
494                 de.gulden.framework.amoda.generic.option.GenericOptionEntry o=(de.gulden.framework.amoda.generic.option.GenericOptionEntry)it.next();
495                 if (!(o.isSystem())) {
496                     String JavaDoc name = "-" + o.getId();
497                     String JavaDoc shortcut = o.getShortcut();
498                     if (shortcut != null) {
499                         name = "-" + shortcut + " or\n" + name;
500                     }
501                     String JavaDoc description=de.gulden.util.Toolbox.noNull(o.getMetadata().get("description"));
502                     String JavaDoc type="<"+de.gulden.util.Toolbox.unqualify(o.getType().getName()).toLowerCase()+">";
503                     String JavaDoc defaultValue=o.getValue(o.STATE_DEFAULT).getString();
504                     if (defaultValue!=null) {
505                         description+=" (default: "+defaultValue+")";
506                     }
507                     String JavaDoc[] row = { name, type, description };
508                     table.addRow(row);
509                 }
510             }
511             sb.append(table.toString());
512         }
513         Message usage = createUsageMessage();
514         return getGenericApplicationEnvironment().createDefaultMessage("Help", usage.getText()+NL+sb.toString(), 0, null);
515     }
516
517     protected String JavaDoc getUsageLine() {
518         String JavaDoc u = getMetadata().get("usage").trim();
519         if (u.length()==0) {
520             u = getDefaulUsageLine();
521         }
522         return u;
523     }
524
525     protected String JavaDoc getDefaulUsageLine() {
526         if (getOptions().getBoolean(GenericApplicationEnvironment.CONFIGURATION_PERSISTENT_OPTIONS)) {
527             return "[java-and-classpath] "+findTitle().toLowerCase()+" -properties [properties-file]";
528         } else {
529             ArrayList relevantFeatures = new ArrayList();
530             for (Iterator it = getAvailableFeatures().iterator(); it.hasNext(); ) {
531                 Feature f = (Feature)it.next();
532                 if (
533                     (! (f.getId().equals("default") || f.getId().equals("exit")))
534                     && (! ( (f instanceof de.gulden.framework.amoda.model.core.FeatureGroup) || (f instanceof de.gulden.framework.amoda.model.interaction.InteractionMember ) ) )
535                    ) {
536                     relevantFeatures.add(f);
537                 }
538             }
539             return "[java-and-classpath] "+findTitle().toLowerCase()+" "+((relevantFeatures.size()>0)?"[commands] ":"")+"[options] [input]";
540         }
541     }
542
543     void initModule(GenericApplicationModule module) {
544         // load configuration from XML
545
org.w3c.dom.Element JavaDoc tag=module.getConfigurationDocument().getDocumentElement();
546         try {
547             de.gulden.util.xml.serializer.XMLSerializerFactory factory=getGenericApplicationEnvironment().getFactory().getXMLSerializerFactory();
548             de.gulden.util.xml.serializer.XMLSerializer ser=factory.createXMLSerializer();
549             ser.xmlDeserialize(module, tag);
550             if (this != module) { // also deserialize on this to get new options and features
551
de.gulden.framework.amoda.model.metadata.Metadata rememberMetadata = this.getMetadata();
552                 this.setMetadata(null); // DIRTY!
553
ser.xmlDeserialize(this, tag); // !!! to get options etc. of module into application, EXPERIMENTAL
554
this.setMetadata(rememberMetadata); // DIRTY!
555
}
556         } catch (de.gulden.util.xml.XMLException e) {
557             fatalError("can't parse configuration XML",e);
558         }
559         // re-init options
560
getGenericApplicationEnvironment().initApplicationOptions(this);
561         // init modules itself
562
module.init();
563         // inform listeners
564
Toolbox.fireEvent(getApplicationListeners(), "moduleLoaded", new de.gulden.framework.amoda.model.behaviour.event.ApplicationEvent(module));
565     }
566
567 } // end GenericApplication
568
Popular Tags