KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > objectweb > util > browser > core > xmlparser > BrowserXMLParser


1 /*===========================================================================
2
3 ObjectWeb Browser Framework
4 Copyright (C) 2004 INRIA - USTL - LIFL - GOAL
5 Contact: openccm@objectweb.org
6
7 This library is free software; you can redistribute it and/or
8 modify it under the terms of the GNU Lesser General Public
9 License as published by the Free Software Foundation; either
10 version 2.1 of the License, or any later version.
11
12 This library is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 Lesser General Public License for more details.
16
17 You should have received a copy of the GNU Lesser General Public
18 License along with this library; if not, write to the Free Software
19 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
20 USA
21
22 Initial developer(s): Philippe Merle, Jerome Moroy.
23 Contributor(s): ______________________________________.
24
25 ===========================================================================*/

26
27 package org.objectweb.util.browser.core.xmlparser;
28
29 /** To use the generated class */
30 import org.objectweb.util.browser.browserConfig.Browser;
31 import org.objectweb.util.browser.browserConfig.beans.BrowserBeanImpl;
32 import org.objectweb.util.browser.browserConfig.beans.BrowserBean;
33 import org.objectweb.util.browser.browserConfig.Code;
34 import org.objectweb.util.browser.browserConfig.CodeImpl;
35 import org.objectweb.util.browser.browserConfig.DropAction;
36 import org.objectweb.util.browser.browserConfig.IconImpl;
37 import org.objectweb.util.browser.browserConfig.Include;
38 import org.objectweb.util.browser.browserConfig.Info;
39 import org.objectweb.util.browser.browserConfig.Mnemonic;
40 import org.objectweb.util.browser.browserConfig.Node;
41 import org.objectweb.util.browser.browserConfig.Icon;
42 import org.objectweb.util.browser.browserConfig.NodeImpl;
43 import org.objectweb.util.browser.browserConfig.Table;
44 import org.objectweb.util.browser.browserConfig.TypeSystem;
45 import org.objectweb.util.browser.browserConfig.Wrapper;
46 import org.objectweb.util.browser.browserConfig.beans.PanelBean;
47 import org.objectweb.util.browser.browserConfig.Panel;
48 import org.objectweb.util.browser.browserConfig.Menu;
49 import org.objectweb.util.browser.browserConfig.Item;
50 import org.objectweb.util.browser.browserConfig.Jar;
51 import org.objectweb.util.browser.browserConfig.Zip;
52 import org.objectweb.util.browser.browserConfig.Root;
53 import org.objectweb.util.browser.browserConfig.Accelerator;
54
55 /** The console's imports */
56 import org.objectweb.util.browser.core.naming.DefaultEntry;
57 import org.objectweb.util.browser.core.naming.DefaultName;
58 import org.objectweb.util.browser.core.naming.DefaultContextContainer;
59 import org.objectweb.util.browser.core.naming.DefaultContextFactory;
60 import org.objectweb.util.browser.api.Context;
61 import org.objectweb.util.browser.api.Entry;
62 import org.objectweb.util.browser.api.IconProvider;
63 import org.objectweb.util.browser.core.api.BrowserProperty;
64 import org.objectweb.util.browser.core.api.ContextContainer;
65 import org.objectweb.util.browser.core.api.ContextProperty;
66 import org.objectweb.util.browser.core.api.Decoder;
67 import org.objectweb.util.browser.core.api.DropActionFactory;
68 import org.objectweb.util.browser.core.api.FileIconProvider;
69 import org.objectweb.util.browser.core.api.InfoFactory;
70 import org.objectweb.util.browser.core.api.MenuFactoryConfiguration;
71 import org.objectweb.util.browser.core.api.PanelFactory;
72 import org.objectweb.util.browser.core.api.Role;
73 import org.objectweb.util.browser.core.api.RoleManagement;
74 import org.objectweb.util.browser.core.api.SpecificContextFactory;
75 import org.objectweb.util.browser.core.api.TableFactory;
76 import org.objectweb.util.browser.core.api.TypeSystemHandler;
77 import org.objectweb.util.browser.core.api.ViewFactory;
78 import org.objectweb.util.browser.core.api.RootFactory;
79 import org.objectweb.util.browser.core.common.ClassResolver;
80 import org.objectweb.util.browser.core.common.DefaultRole;
81 import org.objectweb.util.browser.core.common.DefaultTypeSystemHandler;
82 import org.objectweb.util.browser.core.common.DynamicTree;
83 import org.objectweb.util.browser.core.common.ExtendedBoolean;
84 import org.objectweb.util.browser.core.common.JavaTypeSystem;
85 import org.objectweb.util.browser.core.common.DefaultRootFactory;
86 import org.objectweb.util.browser.core.dnd.DefaultDropActionFactory;
87 import org.objectweb.util.browser.core.icon.DefaultFileIconProvider;
88 import org.objectweb.util.browser.core.info.DefaultInfoFactory;
89 import org.objectweb.util.browser.core.panel.DefaultCompositePanelFactory;
90 import org.objectweb.util.browser.core.panel.DefaultPanelFactory;
91 import org.objectweb.util.browser.core.panel.DefaultTableFactory;
92 import org.objectweb.util.browser.core.popup.DefaultMenuFactory;
93 import org.objectweb.util.browser.core.popup.ItemProperty;
94
95 /** The java API's imports */
96 import java.awt.dnd.DnDConstants JavaDoc;
97 import java.io.File JavaDoc;
98 import java.io.FileOutputStream JavaDoc;
99 import java.io.IOException JavaDoc;
100 import java.io.InputStream JavaDoc;
101 import java.io.FileInputStream JavaDoc;
102 import java.io.InputStreamReader JavaDoc;
103 import java.io.OutputStream JavaDoc;
104 import java.util.Enumeration JavaDoc;
105 import java.util.HashMap JavaDoc;
106 import java.util.List JavaDoc;
107 import java.util.Iterator JavaDoc;
108 import java.util.Map JavaDoc;
109 import java.util.StringTokenizer JavaDoc;
110 import java.util.Vector JavaDoc;
111 import java.util.zip.ZipEntry JavaDoc;
112 import java.util.zip.ZipException JavaDoc;
113 import java.util.zip.ZipFile JavaDoc;
114 import java.net.MalformedURLException JavaDoc;
115 import java.net.URL JavaDoc;
116
117 import javax.swing.KeyStroke JavaDoc;
118
119 /**
120  * Parses a Java object which represents an XML Configuration.
121  * A configuration for a node is firstly defined for a role and then for a kind of object.
122  *
123  * @author <a HREF="mailto:Jerome.Moroy@lifl.fr">Jerome Moroy</a>
124  * @version 0.1
125  */

126 public class BrowserXMLParser
127     implements XMLParser, BrowserProperty, RoleManagement {
128     
129     // ==================================================================
130
//
131
// Internal state.
132
//
133
// ==================================================================
134

135     /** The context which contains the XML properties.
136      * The roleConfig_ context contains the inherited role of a role and
137      */

138     protected ContextContainer role_context_, roleConfig_, inheritedRolesMap_;
139
140     /** The roleMap_ context stores the Role for a given role id. */
141     protected Map JavaDoc roleMap_;
142
143     /** The rootMap_ contains the definition of the root context. */
144     protected Map JavaDoc rootMap_;
145
146     /** The context property to use */
147     protected ContextProperty contextProperty_;
148
149     /** The decoder to use */
150     protected Decoder decoder_;
151
152     /** The TypeSystemHandler */
153     protected TypeSystemHandler typeSystemHandler_;
154
155     /** A reference to the tree */
156     protected DynamicTree tree_;
157     
158     /** The current role */
159     protected Role default_role_;
160     
161     /** The list of current roles */
162     protected Role[] current_roles_, current_roles_inheritance_;
163     
164     protected boolean sameRoleList_ = false;
165
166     /** The directory in which the zip file will be extracted. */
167     protected File JavaDoc extractedFolder_ = null;
168     
169     // ==================================================================
170
//
171
// Constructors.
172
//
173
// ==================================================================
174

175     /**
176      * Default constructor
177      */

178     public BrowserXMLParser(DynamicTree tree) {
179         role_context_ = new DefaultContextContainer();
180         roleConfig_ = new DefaultContextContainer();
181         roleMap_ = new HashMap JavaDoc();
182         rootMap_ = new HashMap JavaDoc();
183         inheritedRolesMap_ = new DefaultContextContainer();
184         typeSystemHandler_ = new DefaultTypeSystemHandler();
185         tree_ = tree;
186         default_role_ = new DefaultRole(RoleManagement.DEFAULT_ROLE);
187         current_roles_ = new Role[]{default_role_};
188         
189         // In order to remove the temporary folder before stopping the program
190
System.runFinalizersOnExit(true);
191                
192     }
193
194     // ==================================================================
195
//
196
// Internal methods.
197
//
198
// ==================================================================
199

200     /**
201      * Creates a node entry for java.lang.Object for the given role.
202      * @param role The role
203      */

204     protected Node getDefaultObjectConfig(){
205         // Default config for java.lang.Object
206
Node objectNode = new NodeImpl();
207         objectNode.setTypeName("java.lang.Object");
208         Icon objectIcon = new IconImpl();
209         Code iconCode = new CodeImpl();
210         iconCode.setValue("org.objectweb.util.browser.core.icon.ObjectIconFactory");
211         objectIcon.setCode(iconCode);
212         objectNode.setIcon(objectIcon);
213         //mergeConfig(objectNode.getTypeSystem() + "." + objectNode.getTypeName(), objectNode, role);
214
return objectNode;
215     }
216     
217     /**
218      * Add an Include element into the context
219      *
220      * @param include The Include element to interpret
221      */

222     protected void addInclude(Include include) {
223         InputStream JavaDoc inputStream = null;
224         // Tries to load the ressource from the ClassLoader
225
inputStream = ClassResolver.getResourceAsStream(include.getUrl());
226         if(inputStream==null){
227             System.err.println(include.getUrl() + ": resource not found in the ClassLoader");
228             try {
229                 URL JavaDoc url = new URL JavaDoc(include.getUrl());
230                 buildBrowser(url.openStream());
231             } catch (java.net.MalformedURLException JavaDoc e) {
232                 if (include.getUrl() != null && !include.getUrl().equals(""))
233                     System.err.println(include.getUrl() + ": Malformed URL !");
234                 else
235                     System.err.println("null URL exists in the XML file !");
236             } catch (java.io.FileNotFoundException JavaDoc e) {
237                 System.err.println(include.getUrl() + " : File not found !");
238             } catch (java.io.IOException JavaDoc e) {
239                 System.err.println(e.getMessage());
240             }
241         } else {
242             buildBrowser(inputStream);
243         }
244     }
245
246     /**
247      * Provide the class corresponding to the code element
248      * @param code The code element
249      * @return The corresponding class
250      */

251     protected Class JavaDoc getClass(Code code) {
252         // only Java is supported for the moment !!!
253
if(code!=null){
254             String JavaDoc className = code.getValue();
255             try{
256                 return ClassResolver.resolve(className);
257             }catch(ClassNotFoundException JavaDoc e){
258                 System.err.println("[BrowserXMLParser.getClass()] " + e + ": ClassNotFoundException");
259                 return null;
260             }
261         }
262         return null;
263     }
264
265     /**
266      * Add a TypeSystem element into the TypeSystemHandler
267      *
268      * @param typeSystem The TypeSystem to add
269      */

270     protected void addTypeSystem(TypeSystem typeSystem) {
271         if(typeSystem!=null){
272             Class JavaDoc c = getClass(typeSystem.getCode());
273             if(org.objectweb.util.browser.core.api.TypeSystem.class.isAssignableFrom(c)){
274                 try {
275                     typeSystemHandler_.addTypeSystem((org.objectweb.util.browser.core.api.TypeSystem)c.newInstance());
276                 } catch (InstantiationException JavaDoc e) {
277                     System.err.println("[BrowserXMLParser.addTypeSystem()]");
278                     e.printStackTrace();
279                 } catch (IllegalAccessException JavaDoc e) {
280                     System.err.println("[BrowserXMLParser.addTypeSystem()]");
281                     e.printStackTrace();
282                 }
283             }
284         }
285     }
286
287     /**
288      * Creates an Entry.
289      *
290      * @param value The value of the entry to create.
291      * @param id The id of the name of the entry to create.
292      *
293      * @return A new Entry.
294      */

295     protected Entry createEntry(String JavaDoc id, Object JavaDoc value) {
296         return new DefaultEntry(value, new DefaultName(id), null);
297     }
298
299     /**
300      * Loads the URL of the jar into the class loader
301      * @param jarURL The URL to load.
302      */

303     protected void loadJarURL(URL JavaDoc[] jarURL){
304         if(jarURL!=null)
305             ClassResolver.addContext(jarURL);
306     }
307
308     /**
309      * Loads the jar into the Browser CLassLoader
310      * @param jarList A list of jar to load
311      */

312     protected void loadJar(List JavaDoc jarList){
313         List JavaDoc urlList = new Vector JavaDoc();
314         for (Iterator JavaDoc i = jarList.iterator(); i.hasNext();) {
315             Object JavaDoc object = i.next();
316             if(object!=null && Jar.class.isAssignableFrom(object.getClass())){
317                 Jar jar = (Jar)object;
318                 String JavaDoc jarFile = jar.getUrl();
319                 try {
320                     urlList.add(new URL JavaDoc(jarFile));
321                 } catch (java.net.MalformedURLException JavaDoc e) {
322                     System.err.println(jarFile + " : Malformed URL !");
323                 }
324             }
325         }
326         if (!urlList.isEmpty()) {
327             loadJarURL((URL JavaDoc[]) urlList.toArray(new URL JavaDoc[0]));
328         }
329     }
330
331     /**
332      * Removes the given file and recursively removes if the target file is a directory.
333      */

334     public void remove(File JavaDoc file){
335         if(file!=null) {
336             if(file.isDirectory()){
337                 File JavaDoc[] children = file.listFiles();
338                 for(int i = 0 ; i < children.length ; i++)
339                     remove(children[i]);
340             }
341             file.delete();
342         }
343     }
344
345     /**
346      * Writes a file on the given input stream.
347      * Note that the stream are closed when leaving the this method.
348      */

349     protected void writeFile(InputStream JavaDoc input, OutputStream JavaDoc output) throws IOException JavaDoc {
350         int bufferSize = 1024;
351         byte[] buffer = new byte[bufferSize];
352         int length=0;
353         while((length = input.read(buffer))>0){
354             output.write(buffer, 0, length);
355         }
356         output.close();
357         input.close();
358     }
359
360     /**
361      * Extracts a ZipEntry into the tmp dir.
362      * @param file The zip file.
363      * @param entry The entry to extract.
364      * @throws IOException Throws when an IOException occured.
365      */

366     protected void extractEntry(ZipFile JavaDoc file, ZipEntry JavaDoc entry, String JavaDoc fileName) throws IOException JavaDoc {
367         writeFile(file.getInputStream(entry), new FileOutputStream JavaDoc(fileName));
368     }
369
370     /*
371      * It seems there is a problem with the methods "mkdirs()" and "deleteOnExit()" when they are working together.
372      * Indeed, the mkdirs method recursively creates the directory contained in this File definition and the deleteOnExit method
373      * removes those files when the virtual machine terminates, but when more than one directory is defined in the File, the first one
374      * is not removed by the deleteOnExit calling.
375      * It is the only problem that prevents this class to remove the "finalize()" method.
376      */

377     /**
378      * Creates the given directory.
379      * @param path The path of the disrectory to create
380      */

381     protected void createDirectory(String JavaDoc path){
382         File JavaDoc directory = new File JavaDoc(path);
383         if(!directory.exists()){
384             // the mkdirs method (used with deleteOnExit) doesn't remove the first directory of a directories path.
385
directory.deleteOnExit();
386             directory.mkdirs();
387         }
388     }
389
390     /**
391      * Extracts a Zip archive
392      */

393     protected void extractFile(File JavaDoc file, Vector JavaDoc javaArchives) throws IOException JavaDoc {
394         ZipFile JavaDoc zipFile = null;
395         try {
396             zipFile = new ZipFile JavaDoc(file.toString());
397         } catch (ZipException JavaDoc e) {
398             // Nothing to do
399
} finally {
400             file.deleteOnExit();
401         }
402         if(zipFile!=null){
403             for(Enumeration JavaDoc entries = zipFile.entries();entries.hasMoreElements();){
404                 ZipEntry JavaDoc zipEntry = (ZipEntry JavaDoc)entries.nextElement();
405                 if(zipEntry.isDirectory()){
406                     createDirectory(extractedFolder_.getCanonicalPath() + "/" + zipEntry.getName());
407                 } else {
408                     // Creates the directories
409
int indice = zipEntry.getName().lastIndexOf('/');
410                     if(indice!=-1){
411                         createDirectory(extractedFolder_.getCanonicalPath() + "/" + zipEntry.getName().substring(0,indice));
412                     }
413                     // Computes the name of the file
414
String JavaDoc fileName = extractedFolder_.getCanonicalPath() + "/" + zipEntry.getName();
415                     // Extracts the entry
416
try {
417                         extractEntry(zipFile, zipEntry, fileName);
418                     } catch (IOException JavaDoc e) {
419                         System.err.println("IOException: " + e.getMessage());
420                         e.printStackTrace();
421                     }
422                     if(zipEntry.getName().toLowerCase().endsWith(".jar")) {
423                         // Adds the java archive into the vector containing the Java archive to load
424
File JavaDoc jarFile = new File JavaDoc(fileName);
425                         jarFile.deleteOnExit();
426                         try {
427                             javaArchives.add(jarFile.toURL());
428                         } catch (IOException JavaDoc e) {
429                             System.err.println("IOException: " + e.getMessage());
430                             e.printStackTrace();
431                         }
432                     } else {
433                         extractFile(new File JavaDoc(fileName), javaArchives);
434                     }
435                 }
436             }
437         }
438     }
439
440     /**
441      * Loads the contained jar archives of the given zip element.
442      * @param zip A zip archive containing the jar archives to load.
443      */

444     protected void loadZip(URL JavaDoc zipURL) throws IOException JavaDoc {
445         if(zipURL!=null){
446             Vector JavaDoc javaArchives = new Vector JavaDoc();
447
448             // Copies the zip file into the java temp directory
449
String JavaDoc fileName = extractedFolder_.getCanonicalPath() + "/temp.zip";
450             writeFile(zipURL.openStream(), new FileOutputStream JavaDoc(fileName));
451
452             // Extracts the zip file
453
File JavaDoc zipFile = new File JavaDoc(fileName);
454             zipFile.deleteOnExit();
455             extractFile(zipFile, javaArchives);
456             
457             // Loads the jar contained in the given zip file
458
loadJarURL((URL JavaDoc[])javaArchives.toArray(new URL JavaDoc[0]));
459         }
460     }
461
462     /**
463      * Unzips all the zip archives of the given list and for each archive, loads the contained jar archives.
464      * @param zipList A list of zip archives containing the jar archives to load.
465      */

466     protected void loadZips(List JavaDoc zipList){
467         if(zipList!=null && zipList.size() > 0){
468             if(extractedFolder_== null){
469                 // Ceates a temp directory
470
String JavaDoc tmpDir = System.getProperty("java.io.tmpdir");
471                 if ((!tmpDir.endsWith("/")) && (!tmpDir.endsWith("\\")))
472                     tmpDir = tmpDir + "/";
473                 extractedFolder_ = new File JavaDoc(tmpDir + "browser" + System.currentTimeMillis());
474                 extractedFolder_.mkdir();
475                 extractedFolder_.deleteOnExit();
476             }
477             for(Iterator JavaDoc i = zipList.iterator() ; i.hasNext() ; ){
478                 Zip zip = (Zip)i.next();
479                 try {
480                     loadZip(new URL JavaDoc(zip.getUrl()));
481                 } catch (MalformedURLException JavaDoc e) {
482                     System.err.println("MalformedURLException: " + e.getMessage());
483                 } catch (IOException JavaDoc e) {
484                     System.err.println("IOException: " + e.getMessage());
485                 }
486             }
487         }
488     }
489
490     /**
491      * Looks for a role config for the given role.
492      * @param role The key of the search.
493      * @return The associated role config (or null)
494      */

495     protected ContextContainer getRoleContext(Role role){
496         if(role!=null)
497             return (ContextContainer)role_context_.getLocalValue(role.getId());
498         return null;
499     }
500     
501     /**
502      * Looks for the node with the given id for the given role.
503      * If no node is found for the given role and if a node exists for the default_role, this one is returned
504      * @param id The target of the node.
505      * @param role The role
506      * @param lookForInDefaultRole If no node is found for the given role and if a node exists for the default_role, this one is returned
507      * @return The associated node (or null)
508      */

509     protected Node getNode(String JavaDoc id, Role role, boolean lookForInDefaultRole) {
510         // The lookForInDefaultRole allows us to load a configuration for different roles.
511
ContextContainer roleContext = getRoleContext(role);
512         if(roleContext!=null) {
513             Node node = (Node) roleContext.getLocalValue(id);
514             if(node==null && !role.getId().equals(default_role_.getId()) && lookForInDefaultRole)
515                 return getNode(id,default_role_,lookForInDefaultRole);
516             return node;
517         } else if (!role.getId().equals(default_role_.getId()) && lookForInDefaultRole){
518             return getNode(id,default_role_,lookForInDefaultRole);
519         }
520         return null;
521     }
522
523     /**
524      * Merges two similar nodes if a node exists in the property context.Else adds the node into the property config
525      * If an element of the node is already define in the property context's node, this one is replaced by this which is contained in the given node.
526      * @param id Id of the node to merge.
527      * @param nodeToMerge The node to merge with the one contains in the property context.
528      * @param role The role for which the node is defined.
529      */

530     protected void mergeConfig(String JavaDoc id, Node nodeToMerge, Role role){
531         ContextContainer roleContext = getRoleContext(role);
532         if(roleContext != null) {
533             Node node = getNode(id,role,false);
534             if(node!=null){
535                 // Merge the wrapper config
536
Wrapper wrapper = nodeToMerge.getWrapper();
537                 if (wrapper != null)
538                     node.setWrapper(wrapper);
539                 // Merge the icon config
540
Icon icon = nodeToMerge.getIcon();
541                 if (icon != null)
542                     node.setIcon(icon);
543                 // Merge the panel config
544
Panel panel = nodeToMerge.getPanel();
545                 if (panel != null)
546                     node.setPanel(panel);
547                 // Merge the info config
548
Info info = nodeToMerge.getInfo();
549                 if (info != null)
550                     node.setInfo(info);
551                 // Merge the menu config
552
Menu menuToMerge = nodeToMerge.getMenu();
553                 if (menuToMerge != null) {
554                     Menu menu = node.getMenu();
555                     if(menu==null)
556                         node.setMenu(menuToMerge);
557                     else{
558                         if (menuToMerge.getInheritTreeMenu().equals("false"))
559                             menu.setInheritTreeMenu("false");
560                         if (menuToMerge.getInheritTypeMenu().equals("false"))
561                             menu.setInheritTypeMenu("false");
562                         List JavaDoc itemsToMerge = menuToMerge.getItemList();
563                         if (itemsToMerge!=null && itemsToMerge.size()>0){
564                             Iterator JavaDoc it = itemsToMerge.iterator();
565                             while (it.hasNext()) {
566                                 Item item = (Item) it.next();
567                                 menu.addItem(item);
568                             }
569                         }
570                     }
571                 }
572                 // Merge the drag&drop action config
573
List JavaDoc dropActionList = nodeToMerge.getDropActionList();
574                 if (dropActionList != null && !dropActionList.isEmpty()){
575                     Iterator JavaDoc it = dropActionList.iterator();
576                     while (it.hasNext()) {
577                         node.addDropAction((DropAction) it.next());
578                     }
579                 }
580             } else {
581                 // Adds the node into the role context
582
roleContext.addEntry(id, nodeToMerge);
583             }
584         } else {
585             // Saves the role map and the node into the context
586
ContextContainer newRoleContext = new DefaultContextContainer();
587             // Adding a default configuration for a node
588
Node objectNode = getDefaultObjectConfig();
589             newRoleContext.addEntry(objectNode.getTypeSystem() + "." + objectNode.getTypeName(), objectNode);
590             // Adding the entry
591
newRoleContext.addEntry(id, nodeToMerge);
592             role_context_.addEntry(role.getId(),newRoleContext);
593         }
594     }
595
596     /**
597      * Loads a given node for the given role into the property context.
598      * @param node The node to load.
599      * @param role The role for which the node is defined.
600      */

601     protected void loadNode(Node node, Role role) {
602         if(node!=null){
603             loadJar(node.getJarList());
604             String JavaDoc typeSystem = node.getTypeSystem();
605             String JavaDoc typeName = node.getTypeName();
606             if(typeSystem != null && !typeSystem.equals("") && typeName != null && !typeName.equals("")){
607                 mergeConfig(node.getTypeSystem() + "." + node.getTypeName(),node, role);
608             }
609         }
610     }
611
612     /**
613      * Loads a given root context for the given role into the property context.
614      * @param root The root to load.
615      * @param role The role for which the node is defined.
616      */

617     protected void loadRoot(Root root, Role role) {
618         if(root!=null){
619             rootMap_.put(role.getId(),root);
620         }
621     }
622     
623     /**
624      * Parses the XML file and builds the appropriate context
625      */

626     protected void buildContext(Browser browser) {
627         if (browser != null) {
628             // Loads zip elements
629
loadZips(browser.getZipList());
630             // Loads jar elements
631
loadJar(browser.getJarList());
632             // Loads root elements
633
loadRoot(browser.getRoot(), default_role_);
634             // Loads type-system elements
635
List JavaDoc typeSystemList = browser.getTypeSystemList();
636             for (Iterator JavaDoc i = typeSystemList.iterator(); i.hasNext();) {
637                 TypeSystem typeSystem = (TypeSystem) i.next();
638                 addTypeSystem(typeSystem);
639             }
640             typeSystemHandler_.addTypeSystem(new JavaTypeSystem());
641             // Loads include elements
642
List JavaDoc includeList = browser.getIncludeList();
643             for (Iterator JavaDoc i = includeList.iterator(); i.hasNext();) {
644                 Include include = (Include) i.next();
645                 addInclude(include);
646             }
647             // Loads node elements
648
List JavaDoc nodeList = browser.getNodeList();
649             for (Iterator JavaDoc i = nodeList.iterator(); i.hasNext();) {
650                 loadNode((Node) i.next(), default_role_);
651             }
652             // Loads role elements
653
List JavaDoc roleList = browser.getRoleList();
654             for (Iterator JavaDoc i = roleList.iterator(); i.hasNext();) {
655                 org.objectweb.util.browser.browserConfig.Role role =
656                     (org.objectweb.util.browser.browserConfig.Role)i.next();
657                 // Stores the inherited role and the role.
658
String JavaDoc roleId = role.getId().trim();
659                 if(role.getXmlextends()!=null && !role.getXmlextends().equals(""))
660                     roleConfig_.addEntry(roleId,role.getXmlextends());
661                 Role theRole = new DefaultRole(roleId);
662                 if(role.getKind().equals("abstract"))
663                     theRole.setConcrete(false);
664                 if(roleMap_.containsKey(roleId)){
665                     if(role.getKind().equals("abstract"))
666                         ((Role)roleMap_.get(roleId)).setConcrete(false);
667                 }else{
668                     roleMap_.put(roleId,theRole);
669                 }
670                 // Loads root elements
671
loadRoot(role.getRoot(), theRole);
672                 // Loads the nodes defined for this role
673
List JavaDoc roleNodeList = role.getNodeList();
674                 for(Iterator JavaDoc j = roleNodeList.iterator(); j.hasNext();) {
675                     loadNode((Node)j.next(), theRole);
676                 }
677             }
678         }
679     }
680
681     /**
682      * Builds the Browser object and builds the context if the created Browser is not null.
683      * @param stream A stream opened on the file containing the data defining the Browser
684      */

685     protected void buildBrowser(InputStream JavaDoc stream) {
686         try {
687             // We can't validate with DTD at this time (no way to fix the DTD file)
688
BrowserBean browser = BrowserBeanImpl.unmarshalBean(new InputStreamReader JavaDoc(stream),false);
689             //Browser browser = BrowserUnmarshaller.unmarshal(stream);
690
if (browser != null)
691                 buildContext(browser);
692         } catch (java.io.IOException JavaDoc e) {
693             System.err.println(e.getMessage());
694         }
695     }
696
697     /**
698      * Builds the Browser object and builds the context if the created Browser is not null.
699      * @param file The file containing the data defining the Browser
700      */

701     protected void buildBrowser(File JavaDoc file) {
702         try {
703             buildBrowser(new FileInputStream JavaDoc(file));
704         } catch (java.io.FileNotFoundException JavaDoc e) {
705             System.err.println("Error : " + file + " : File not found !");
706         }
707     }
708
709     protected PanelFactory getPanelFactory(Panel panel){
710         if(panel.getCode()!=null){
711         Class JavaDoc panelClass = getClass(panel.getCode());
712         if(panelClass!=null) {
713             if (org.objectweb.util.browser.api.Panel.class.isAssignableFrom(panelClass)) {
714                 PanelFactory panelFactory = new DefaultPanelFactory();
715                 panelFactory.setClassName(panelClass);
716                 panelFactory.setInheritTypePanel(panel.getInheritTypePanel().equals("false")?false:true);
717                 return panelFactory;
718             } else
719                 System.err.println(panel.getCode().getValue() + " is not a Panel instance !");
720             }
721         } else {
722             List JavaDoc childList = ((PanelBean)panel).getChildrenList();
723             DefaultCompositePanelFactory compositePanelFactory = new DefaultCompositePanelFactory();
724             compositePanelFactory.setInheritTypePanel(panel.getInheritTypePanel().equals("false")?false:true);
725             Iterator JavaDoc iterator = childList.iterator();
726             while (iterator.hasNext()) {
727                 Object JavaDoc element = iterator.next();
728                 if(Panel.class.isAssignableFrom(element.getClass())){
729                     Panel currentPanel = (Panel)element;
730                     compositePanelFactory.add(getPanelFactory(currentPanel));
731                 } else if (Table.class.isAssignableFrom(element.getClass())){
732                     Table currentTable = (Table)element;
733                     Class JavaDoc actionClass = getClass(currentTable.getCode());
734                     if (actionClass!=null){
735                         if (org.objectweb.util.browser.api.Table.class.isAssignableFrom(actionClass)) {
736                             TableFactory tableFactory = new DefaultTableFactory(tree_);
737                             tableFactory.setClassName(actionClass);
738                             compositePanelFactory.add((ViewFactory)tableFactory);
739                         } else
740                             System.err.println(currentTable.getCode().getValue() + " is not an Table instance !");
741                     }
742                 }
743             }
744             return compositePanelFactory;
745         }
746         return null;
747     }
748
749     /**
750      * Added the inherited role of the given roles in a list.
751      * @param roles An arrayt of roles.
752      * @param roleList The vector in which the inherited roles have to be added.
753      */

754     protected void buildRole(Role[] roles, Vector JavaDoc roleList){
755         // Adds the roles into the list
756
for(int i=0;i<roles.length;i++){
757             if(!roleList.contains(roles[i])){
758                 roleList.add(roles[i]);
759             }
760         }
761         // Creates a list containing all the role extended by the given roles array.
762
Vector JavaDoc allExtendedRoles = new Vector JavaDoc();
763         for(int i=0;i<roles.length;i++){
764             String JavaDoc theRoles = (String JavaDoc)roleConfig_.getLocalValue(roles[i].getId());
765             if(theRoles!=null){
766                 StringTokenizer JavaDoc st = new StringTokenizer JavaDoc(theRoles,",");
767                 while (st.hasMoreTokens()) {
768                     Role theRole = (Role)roleMap_.get(st.nextToken().trim());
769                     if(theRole!=null && !roleList.contains(theRole))
770                         allExtendedRoles.add(theRole);
771                 }
772             }
773         }
774         // Recursive call
775
if(allExtendedRoles.size()!=0)
776             buildRole((Role[])allExtendedRoles.toArray(new Role[0]),roleList);
777     }
778
779
780     /**
781      * Provides the inherited roles of the given role. If no inherited node is defined, an empty array is return.
782      * @param role The role.
783      * @return An array containing the inherited roles for the given role.
784      */

785     protected Role[] getInheritedRoles(Role[] roles){
786         Role[] returnRoleList = null;
787         if(sameRoleList_)
788             //object = inheritedRolesMap_.getLocalValue(role.getId());
789
returnRoleList = current_roles_inheritance_;
790         if(returnRoleList==null){
791             Vector JavaDoc roleList = new Vector JavaDoc();
792             buildRole(roles, roleList);
793             roleList.add(default_role_);
794             returnRoleList = (Role[])roleList.toArray(new Role[0]);
795             current_roles_inheritance_ = returnRoleList;
796             sameRoleList_ = true;
797             //inheritedRolesMap_.addEntry(role.getId(),object);
798
}
799         return returnRoleList;
800     }
801     
802     /**
803      * Provides the IconProvider associated to the given icon.
804      * @param icon The icon. It can be an icon file or a class able to provide an icon.
805      * @return The associated IconProvider
806      */

807     protected IconProvider getIconProvider(Icon icon){
808         if (icon != null) {
809             if(icon.getIconFile()!=null) {
810                 FileIconProvider iconFactory = new DefaultFileIconProvider();
811                 iconFactory.setUrl(icon.getIconFile().getUrl());
812                 return iconFactory;
813             } else if (icon.getCode()!=null) {
814                 try {
815                     Class JavaDoc factory = getClass(icon.getCode());
816                     if (factory!=null) {
817                         if (IconProvider.class.isAssignableFrom(factory))
818                             return (IconProvider)factory.newInstance();
819                         else
820                             System.err.println(icon.getCode().getValue() + " is not an IconProvider instance !");
821                     }
822                 } catch (InstantiationException JavaDoc e) {
823                     e.printStackTrace();
824                 } catch (IllegalAccessException JavaDoc e) {
825                     e.printStackTrace();
826                 }
827 // } else {
828
// System.err.println("An element \"icon-file\" or \"code\" is mandatory in an icon element definition !");
829
}
830         }
831         return null;
832     }
833     
834     /**
835      * Provides the KeyStroke associates to the given Mnemonic.
836      * @param mnemonic The object containing the definition of the keyStroke
837      * @return The associated KeyStroke.
838      */

839     protected KeyStroke JavaDoc getKeyStroke(Accelerator accelerator){
840         if(accelerator!=null){
841             String JavaDoc car = accelerator.getXmlchar();
842             if(car!=null && car.length()>0){
843                 Character JavaDoc character = new Character JavaDoc(car.charAt(0));
844                 int modifier = 0;
845                 modifier = (accelerator.getAlt().equals("true")?java.awt.Event.ALT_MASK:0)
846                     |(accelerator.getCtrl().equals("true")?java.awt.Event.CTRL_MASK:0)
847                     |(accelerator.getShift().equals("true")?java.awt.Event.SHIFT_MASK:0)
848                     |(accelerator.getMeta().equals("true")?java.awt.Event.META_MASK:0);
849                 if(modifier==0)
850                     return KeyStroke.getKeyStroke(character.charValue());
851                 else
852                     return KeyStroke.getKeyStroke(Character.toUpperCase(character.charValue()), modifier);
853             }
854         }
855         return null;
856     }
857
858     /**
859      * Provides the character for the given mnemonic.
860      * @param mnemonic The given mnemonic.
861      * @return The associated character.
862      */

863     protected Character JavaDoc getMnemonic(Mnemonic mnemonic) {
864         if(mnemonic!=null){
865             String JavaDoc car = mnemonic.getXmlchar();
866             if(car!=null && car.length()>0)
867                 return new Character JavaDoc(car.charAt(0));
868         }
869         return null;
870     }
871     
872     /**
873      * Provides the dropAction code corresponding to the given type.
874      * @param type The type of the drop action (copy/move/link)
875      * @return The associated dropAction code
876      */

877     protected int getDropAction(String JavaDoc type) {
878         if ("copy".equals(type))
879             return DnDConstants.ACTION_COPY;
880         else if ("move".equals(type))
881             return DnDConstants.ACTION_MOVE;
882         else if ("link".equals(type))
883             return DnDConstants.ACTION_LINK;
884         return -1;
885     }
886     
887     // ==================================================================
888
//
889
// Public methods of XMLDecoder interface.
890
//
891
// ==================================================================
892

893     /**
894      * Fixes the file which contains the properties.
895      * @param path The path containing the XML file(s) containing the configuration
896      * we want to abtain under a Context view (It can be a single file or a directory)
897      */

898     public void setPropertyFile(String JavaDoc path) {
899         InputStream JavaDoc inputStream = null;
900         if (path != null) {
901             // Tries to load the resource from the ClassLoader
902
inputStream = ClassResolver.getResourceAsStream(path);
903             if(inputStream==null){
904                 // Tries to load the resource from the file system
905
File JavaDoc file = new File JavaDoc(path);
906                 if (file.exists()) {
907                     if (file.isDirectory()) {
908                         File JavaDoc[] files = file.listFiles(new XMLFileFilter());
909                         for (int i = 0; i < files.length; i++) {
910                             buildBrowser(files[i]);
911                         }
912                     } else {
913                         buildBrowser(file);
914                     }
915                 } else {
916                     // Tries to load the resource via an URL
917
try {
918                         URL JavaDoc urlFile = new URL JavaDoc(path);
919                         inputStream = urlFile.openStream();
920                     } catch (MalformedURLException JavaDoc e) {
921                         System.err.println("Error: " + path + ": resource not found! ");
922                     } catch (IOException JavaDoc e) {
923                         System.err.println("Error: " + path + ": IOException! ");
924                     }
925                 }
926             }
927             if(inputStream!=null) {
928                 buildBrowser(inputStream);
929             }
930         } else
931             System.err.println("The path param is null ! ");
932     }
933
934     /**
935      * Fixes an array of files (or directories) which contains the properties
936      * @param files The path containing the XML file(s) containing the configuration
937      * we want to abtain under a Context view (Each value of the array can be a single file or a directory)
938      */

939     public void setPropertyFile(String JavaDoc[] files) {
940         for (int i = 0; i < files.length; i++)
941             setPropertyFile(files[i]);
942     }
943
944     // ==================================================================
945
//
946
// Public methods of BrowserProperty interface.
947
//
948
// ==================================================================
949

950     /**
951      * Fixes the context property to use to constructs the wrappers
952      * @param properties The context property to use
953      */

954     public void setContextProperty(ContextProperty properties) {
955         contextProperty_ = properties;
956         if (contextProperty_ != null)
957             decoder_ = contextProperty_.getDecoder();
958     }
959
960     /**
961      * Provides the TypeSystem to use in order to find appropriate key.
962      * @return The TypeSystem to use.
963      */

964     public org.objectweb.util.browser.core.api.TypeSystem getTypeSystem(){
965         return (org.objectweb.util.browser.core.api.TypeSystem)typeSystemHandler_;
966     }
967
968     /**
969      * Provides the entry to add into the icon property context or null.
970      * @param id The research key
971      * @return The entry to add or null
972      */

973     public Entry getIcon(String JavaDoc id, Role role, ExtendedBoolean nodeFound) {
974         Node node = getNode(id,role,false);
975         if (node != null) {
976             Icon icon = node.getIcon();
977             if (icon != null) {
978                 nodeFound.setValue(true);
979                 IconProvider iconProvider = getIconProvider(icon);
980                 if(iconProvider != null)
981                     return createEntry(id, iconProvider);
982             }
983         }
984         return null;
985     }
986
987     /**
988      * Provides the entry to add into the panel property context or null.
989      * @param id The research key
990      * @return The entry to add or null
991      */

992     public Entry getPanel(String JavaDoc id, Role role, ExtendedBoolean nodeFound) {
993         Node node = getNode(id,role,false);
994         if (node != null) {
995             Panel panel = node.getPanel();
996             if (panel != null) {
997                 nodeFound.setValue(true);
998                 PanelFactory panelFactory = getPanelFactory(panel);
999                 if (panelFactory != null)
1000                    return createEntry(id, panelFactory);
1001            }
1002        }
1003        return null;
1004    }
1005
1006    /**
1007     * Provides the entry to add into the menu property context or null.
1008     * @param id The research key (a class name)
1009     * @param role The associated role
1010     * @param nodeFound Indicates if a node has been found or not.
1011     * @return The entry to add or null
1012     */

1013    public Entry getMenu(String JavaDoc id, Role role, ExtendedBoolean nodeFound) {
1014        Node node = getNode(id,role,false);
1015        if (node != null) {
1016            Menu menu = node.getMenu();
1017            if (menu != null) {
1018                nodeFound.setValue(true);
1019                ContextContainer items = new DefaultContextContainer();
1020                ContextContainer childItems = new DefaultContextContainer();
1021                List JavaDoc itemList = menu.getItemList();
1022                int cpt = 0;
1023                for (Iterator JavaDoc i = itemList.iterator(); i.hasNext();) {
1024                    Item item = (Item) i.next();
1025                    ItemProperty ip = new ItemProperty(item.getLabel(),item.getCode().getValue(),item.getTreeChildVisible().equals("false") ? false : true,item.getTypeChildVisible().equals("true") ? true : false, getIconProvider(item.getIcon()),getKeyStroke(item.getAccelerator()),getMnemonic(item.getMnemonic()));
1026                    String JavaDoc label = item.getLabel();
1027                    if (label!=null && label.equals("-separator-")){
1028                        label = label + cpt;
1029                        cpt++;
1030                    }
1031                    if (item.getTreeChildVisible().equals("false"))
1032                        items.addEntry(label, ip);
1033                    else
1034                        childItems.addEntry(label, ip);
1035                }
1036                MenuFactoryConfiguration menuFactory = new DefaultMenuFactory();
1037                menuFactory.setInheritTreeMenu(menu.getInheritTreeMenu().equals("false") ? false : true);
1038                menuFactory.setInheritTypeMenu(menu.getInheritTypeMenu().equals("false") ? false : true);
1039                menuFactory.setItems(items);
1040                menuFactory.setChildItems(childItems);
1041                return createEntry(id, menuFactory);
1042            }
1043        }
1044        return null;
1045    }
1046
1047    /**
1048     * Provides the entry to add into the wrapper property context or null.
1049     * @param id The research key
1050     * @return The entry to add or null
1051     */

1052    public Entry getWrapper(String JavaDoc id, Role role, ExtendedBoolean nodeFound) {
1053        Node node = getNode(id,role,false);
1054        if (node != null) {
1055            Wrapper wrapper = node.getWrapper();
1056            if (wrapper != null) {
1057                nodeFound.setValue(true);
1058                Class JavaDoc wrapperClass = getClass(wrapper.getCode());
1059                if(wrapperClass != null) {
1060                    if (org.objectweb.util.browser.api.Wrapper.class.isAssignableFrom(wrapperClass) && Context.class.isAssignableFrom(wrapperClass)) {
1061                        SpecificContextFactory cf = new DefaultContextFactory(decoder_);
1062                        cf.setClassName(wrapperClass);
1063                        return createEntry(id, cf);
1064                    } else
1065                        System.err.println(wrapper.getCode().getValue() + " is not a Wrapper and a Context instance !");
1066                }
1067            }
1068        }
1069        return null;
1070    }
1071
1072    protected class XMLFileFilter implements java.io.FileFilter JavaDoc {
1073        public boolean accept(File JavaDoc pathname) {
1074            String JavaDoc extension = pathname.getName().substring(pathname.getName().lastIndexOf('.') + 1);
1075            return extension.equalsIgnoreCase("xml") && !pathname.isDirectory();
1076
1077        }
1078    }
1079
1080    /**
1081     * Provides the entry to add into the dropaction property context or null.
1082     * @param id The research key
1083     * @return The entry to add or null
1084     */

1085    public Entry getDropAction(String JavaDoc id, Role role, ExtendedBoolean nodeFound) {
1086        Node node = getNode(id,role,false);
1087        if (node != null) {
1088            List JavaDoc dropActionList = node.getDropActionList();
1089            if (dropActionList != null && !dropActionList.isEmpty()) {
1090                nodeFound.setValue(true);
1091                DropActionFactory dropActionFactory = null;
1092                Iterator JavaDoc it = dropActionList.iterator();
1093                while(it.hasNext()) {
1094                    DropAction dropAction = (DropAction)it.next();
1095                    Class JavaDoc actionClass = getClass(dropAction.getCode());
1096                    if(actionClass != null) {
1097                        if (org.objectweb.util.browser.api.DropAction.class.isAssignableFrom(actionClass)) {
1098                            if(dropActionFactory == null)
1099                                dropActionFactory = new DefaultDropActionFactory();
1100                            int dropActionType = getDropAction(dropAction.getType());
1101                            dropActionFactory.setLabel(dropAction.getLabel(), dropActionType);
1102                            dropActionFactory.setClassName(actionClass, dropActionType);
1103                        } else
1104                            System.err.println(dropAction.getCode().getValue() + " is not a DropAction instance !");
1105                    }
1106                }
1107                return createEntry(id, dropActionFactory);
1108            }
1109        }
1110        return null;
1111    }
1112
1113    /**
1114     * Provides the entry to add into the info property context or null.
1115     * @param id The research key
1116     * @return The associated entry or null
1117     */

1118    public Entry getInfo(String JavaDoc id, Role role, ExtendedBoolean nodeFound){
1119        Node node = getNode(id,role,false);
1120        if (node != null) {
1121            Info info = node.getInfo();
1122            if (info != null) {
1123                nodeFound.setValue(true);
1124                Class JavaDoc actionClass = getClass(info.getCode());
1125                if(actionClass !=null) {
1126                    if (org.objectweb.util.browser.api.Info.class.isAssignableFrom(actionClass)) {
1127                        InfoFactory infoFactory = new DefaultInfoFactory();
1128                        infoFactory.setClassName(actionClass);
1129                        return createEntry(id, infoFactory);
1130                    } else
1131                        System.err.println(info.getCode().getValue() + " is not an Info instance !");
1132                }
1133            }
1134        }
1135        return null;
1136    }
1137
1138    /**
1139     * Provides the initial context factory for the given role.
1140     */

1141    public RootFactory getRoot(Role role){
1142        if(rootMap_.containsKey(role.getId())){
1143            Root root = (Root)rootMap_.get(role.getId());
1144            Class JavaDoc actionClass = getClass(root.getCode());
1145            if(actionClass !=null) {
1146                if (org.objectweb.util.browser.api.Context.class.isAssignableFrom(actionClass)) {
1147                    RootFactory rootFactory = new DefaultRootFactory();
1148                    rootFactory.setClassName(actionClass);
1149                    return rootFactory;
1150                } else
1151                    System.err.println(root.getCode().getValue() + " is not a Context instance !");
1152            }
1153        }
1154        return null;
1155    }
1156
1157    /**
1158     * Provides the inherited roles of the current role. If no inherited node is defined, an empty array is return.
1159     * @param role The role.
1160     * @return An array containing the inherited roles for the current role.
1161     */

1162    public Role[] getInheritedRoles(){
1163        return getInheritedRoles(current_roles_);
1164    }
1165    
1166    // ==================================================================
1167
//
1168
// Public methods of RoleManagement interface.
1169
//
1170
// ==================================================================
1171

1172    /**
1173     * Provides the current role.
1174     *
1175     * @return The current role.
1176     */

1177    public Role[] getCurrentRoles(){
1178        return current_roles_;
1179    }
1180    
1181    /**
1182     * Fixes the current role.
1183     *
1184     * @param role_id The id of the role.
1185     */

1186    public void setCurrentRole(String JavaDoc[] roles_id){
1187        if(roles_id!=null){
1188            Role[] roles = new Role[roles_id.length];
1189            for(int i=0;i<roles_id.length;i++)
1190                roles[i] = new DefaultRole(roles_id[i].trim());
1191            setCurrentRole(roles);
1192        }
1193        //current_roles_ = new DefaultRole(role_id);
1194
}
1195
1196    /**
1197     * Fixes the current role.
1198     *
1199     * @param role The role to define as current role.
1200     */

1201    public void setCurrentRole(Role[] roles){
1202        sameRoleList_ = false;
1203        current_roles_ = roles;
1204    }
1205
1206    /**
1207     * Provides the list of all define roles.
1208     *
1209     * @return The list of roles.
1210     */

1211    public Role[] getRoleList(){
1212        return (Role[])roleMap_.values().toArray(new Role[0]);
1213    }
1214
1215    // ==================================================================
1216
//
1217
// Public method surcharging java.lang.Object methods.
1218
//
1219
// ==================================================================
1220

1221    /**
1222     * Removes the temporary folder containing the extracting files.
1223     * Overriding methods
1224     * @see java.lang.Object#finalize()
1225     */

1226    public void finalize() throws Throwable JavaDoc {
1227        if(extractedFolder_!=null && extractedFolder_.exists()){
1228            remove(extractedFolder_);
1229        }
1230    }
1231    
1232 }
1233
Popular Tags