Statistics
| Revision:

svn-gvsig-desktop / trunk / frameworks / _fwAndami / src / com / iver / andami / Launcher.java @ 1119

History | View | Annotate | Download (37.9 KB)

1
/* gvSIG. Sistema de Informaci?n Geogr?fica de la Generalitat Valenciana
2
 *
3
 * Copyright (C) 2004 IVER T.I. and Generalitat Valenciana.
4
 *
5
 * This program is free software; you can redistribute it and/or
6
 * modify it under the terms of the GNU General Public License
7
 * as published by the Free Software Foundation; either version 2
8
 * of the License, or (at your option) any later version.
9
 *
10
 * This program is distributed in the hope that it will be useful,
11
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13
 * GNU General Public License for more details.
14
 *
15
 * You should have received a copy of the GNU General Public License
16
 * along with this program; if not, write to the Free Software
17
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307,USA.
18
 *
19
 * For more information, contact:
20
 *
21
 *  Generalitat Valenciana
22
 *   Conselleria d'Infraestructures i Transport
23
 *   Av. Blasco Ib??ez, 50
24
 *   46010 VALENCIA
25
 *   SPAIN
26
 *
27
 *      +34 963862235
28
 *   gvsig@gva.es
29
 *      www.gvsig.gva.es
30
 *
31
 *    or
32
 *
33
 *   IVER T.I. S.A
34
 *   Salamanca 50
35
 *   46005 Valencia
36
 *   Spain
37
 *
38
 *   +34 963163400
39
 *   dac@iver.es
40
 */
41
package com.iver.andami;
42

    
43
import java.awt.EventQueue;
44
import java.awt.Toolkit;
45
import java.io.BufferedInputStream;
46
import java.io.BufferedOutputStream;
47
import java.io.File;
48
import java.io.FileFilter;
49
import java.io.FileInputStream;
50
import java.io.FileNotFoundException;
51
import java.io.FileOutputStream;
52
import java.io.FileReader;
53
import java.io.FileWriter;
54
import java.io.FilenameFilter;
55
import java.io.IOException;
56
import java.io.InputStream;
57
import java.lang.reflect.InvocationTargetException;
58
import java.net.MalformedURLException;
59
import java.net.URL;
60
import java.net.URLConnection;
61
import java.util.ArrayList;
62
import java.util.Comparator;
63
import java.util.Date;
64
import java.util.HashMap;
65
import java.util.HashSet;
66
import java.util.Iterator;
67
import java.util.Locale;
68
import java.util.Properties;
69
import java.util.TreeMap;
70

    
71
import javax.jnlp.BasicService;
72
import javax.jnlp.ServiceManager;
73
import javax.jnlp.UnavailableServiceException;
74
import javax.swing.ImageIcon;
75
import javax.swing.JComponent;
76
import javax.swing.SwingUtilities;
77
import javax.swing.UIManager;
78

    
79
import org.apache.log4j.Logger;
80
import org.apache.log4j.PatternLayout;
81
import org.apache.log4j.PropertyConfigurator;
82
import org.apache.log4j.RollingFileAppender;
83
import org.exolab.castor.xml.MarshalException;
84
import org.exolab.castor.xml.ValidationException;
85

    
86
import com.iver.andami.config.generate.Andami;
87
import com.iver.andami.config.generate.AndamiConfig;
88
import com.iver.andami.config.generate.Plugin;
89
import com.iver.andami.messages.Messages;
90
import com.iver.andami.messages.NotificationManager;
91
import com.iver.andami.plugins.PluginClassLoader;
92
import com.iver.andami.plugins.config.generate.ActionTool;
93
import com.iver.andami.plugins.config.generate.Depends;
94
import com.iver.andami.plugins.config.generate.Extension;
95
import com.iver.andami.plugins.config.generate.Extensions;
96
import com.iver.andami.plugins.config.generate.LabelSet;
97
import com.iver.andami.plugins.config.generate.Menu;
98
import com.iver.andami.plugins.config.generate.PluginConfig;
99
import com.iver.andami.plugins.config.generate.PopupMenu;
100
import com.iver.andami.plugins.config.generate.PopupMenus;
101
import com.iver.andami.plugins.config.generate.SelectableTool;
102
import com.iver.andami.plugins.config.generate.SkinExtension;
103
import com.iver.andami.plugins.config.generate.SkinExtensionType;
104
import com.iver.andami.plugins.config.generate.ToolBar;
105
import com.iver.andami.ui.MDIManagerLoadException;
106
import com.iver.andami.ui.SplashWindow;
107
import com.iver.andami.ui.WaitCursorEventQueue;
108
import com.iver.andami.ui.mdiFrame.MDIFrame;
109
import com.iver.andami.ui.mdiManager.MDIManagerFactory;
110
import com.iver.utiles.XMLEntity;
111
import com.iver.utiles.xmlEntity.generate.XmlTag;
112

    
113

    
114
/**
115
 * DOCUMENT ME!
116
 *
117
 * @author $author$
118
 * @version $Revision: 1119 $
119
 */
120
public class Launcher {
121
        private static Logger logger = Logger.getLogger(Launcher.class.getName());
122
        private static AndamiConfig andamiConfig;
123
        private static SplashWindow splashWindow;
124
        private static String userHome = System.getProperty("user.home");
125
        private static String appName;
126
        private static Locale locale;
127
        private static HashMap pluginsConfig = new HashMap();
128
        private static HashMap pluginsServices = new HashMap();
129
        private static MDIFrame frame;
130
        private static HashMap classesExtensions = new HashMap();
131
        private static String andamiConfigPath;
132
        private static String pluginsPersistencePath;
133

    
134
        /**
135
         * DOCUMENT ME!
136
         *
137
         * @param args DOCUMENT ME!
138
         *
139
         * @throws InterruptedException
140
         * @throws InvocationTargetException
141
         * @throws ConfigurationException
142
         * @throws MDIManagerLoadException
143
         * @throws IOException
144
         */
145
        public static void main(String[] args)
146
                throws InterruptedException, InvocationTargetException, 
147
                        ConfigurationException, MDIManagerLoadException, IOException {
148
                if ((args.length < 1) || (args.length > 2)) {
149
                        System.err.println("Uso: Launcher appName [locale]");
150
                }
151

    
152
                appName = args[0];
153
                
154
                //Se crea el directorio de configuraci?n de la aplicaci?n
155
                File parent = new File(System.getProperty("user.home") + File.separator + args[0] +
156
                                File.separator);
157
                parent.mkdirs();
158

    
159
                andamiConfigPath = System.getProperty("user.home") + File.separator +
160
                        appName + File.separator + "andami-config.xml";
161
                pluginsPersistencePath = System.getProperty("user.home") +
162
                        File.separator + appName + File.separator +
163
                        "plugins-persistence.xml";
164

    
165
                // Configurar el log4j
166
                PropertyConfigurator.configure(Launcher.class.getClassLoader()
167
                                                                                                         .getResource("log4j.properties"));
168

    
169
                PatternLayout l = new PatternLayout("%p %t %c - %m%n");
170
                RollingFileAppender fa = new RollingFileAppender(l,
171
                                System.getProperty("user.home") + File.separator + args[0] +
172
                                File.separator + args[0] + ".log", true);
173
                fa.setMaxFileSize("512KB");
174
                fa.setMaxBackupIndex(3);
175
                Logger.getRootLogger().addAppender(fa);
176

    
177
                // Leer el fichero de configuraci?n de andami (andami-config.xsd)
178
                // locale
179
                // Buscar actualizaci?nes al comenzar
180
                //  Andami
181
                //  Plugins
182
                // Directorio de las extensiones
183
                andamiConfigFromXML(andamiConfigPath);
184

    
185
                // Configurar el locale
186
                if (args.length == 2) {
187
                        locale = new Locale(args[1]);
188
                } else {
189
                        locale = getLocale(andamiConfig.getLocaleLanguage(),
190
                                        andamiConfig.getLocaleCountry(),
191
                                        andamiConfig.getLocaleVariant());
192
                }
193

    
194
                Locale.setDefault(locale);
195
                JComponent.setDefaultLocale(locale);
196
                Messages.init(locale);
197

    
198
                try {
199
                        UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
200

    
201
                        // UIManager.setLookAndFeel("com.iver.WindowsLookAndFeel.WindowsLookAndFeel");
202
                } catch (Exception e) {
203
                        logger.warn("No se pudo poner el look and feel", e);
204
                }
205

    
206
                // Mostrar la ventana de inicio
207
                splashWindow = new SplashWindow(null);
208

    
209
                // TODO Buscar actualizaciones de Andami
210
                // TODO Buscar actualizaciones de los plugins
211
                downloadExtensions(andamiConfig.getPluginsDirectory());
212

    
213
                // Se leen los config.xml de los plugins -----++++
214
                loadPlugins(andamiConfig.getPluginsDirectory());
215

    
216
                // Se configura el classloader del plugin
217
                pluginsClassLoaders();
218

    
219
                // Se carga un Skin si alguno de los plugins trae informaci?n para ello
220
                skinPlugin();
221

    
222
                //Se configura la cola de eventos
223
                EventQueue waitQueue = new WaitCursorEventQueue(MDIManagerFactory.createManager(),
224
                                100);
225
                Toolkit.getDefaultToolkit().getSystemEventQueue().push(waitQueue);
226

    
227
                // Se configura la mensajer?a del plugin
228
                pluginsMessages();
229

    
230
                // Se modifica el andami-config con los plugins nuevos
231
                updateAndamiConfig();
232

    
233
                // Se prepara el MainFrame para albergar las extensiones
234
                frame = new MDIFrame();
235

    
236
                // Se configura el nombre e icono de la aplicaci?n
237
                frameIcon();
238

    
239
                SwingUtilities.invokeAndWait(new Runnable() {
240
                                public void run() {
241
                                        frame.init();
242
                                }
243
                        });
244

    
245
                // Se instalan los controles de las extensiones de los plugins
246
                SwingUtilities.invokeAndWait(new Runnable() {
247
                                public void run() {
248
                                        installPluginsControls();
249
                                        installPluginsMenus();
250
                                        installPluginsLabels();
251
                                }
252
                        });
253

    
254
                // Leer el fichero de persistencia
255
                //  info de los plugins
256
                //  bookmarks de los plugins
257
                loadPluginsPersistence();
258

    
259
                // Se instalan los controles del skin
260
                // Se inicializan todas las extensiones de todos los plugins
261
                SwingUtilities.invokeAndWait(new Runnable() {
262
                                public void run() {
263
                                        initializeExtensions();
264
                                }
265
                        });
266
                frame.setClassesExtensions(classesExtensions);
267

    
268
                // Se instalan los bookmarks de los plugins
269
                splashWindow.close();
270

    
271
                //Se muestra el frame principal
272
                frame.show();
273

    
274
                SwingUtilities.invokeAndWait(new Runnable() {
275
                                public void run() {
276
                                        frame.enableControls();
277
                                }
278
                        });
279
        }
280

    
281
        /**
282
         * DOCUMENT ME!
283
         *
284
         * @throws ConfigurationException
285
         */
286
        private static void loadPluginsPersistence() throws ConfigurationException {
287
                XMLEntity entity = persistenceFromXML();
288

    
289
                for (int i = 0; i < entity.getNumChild(); i++) {
290
                        XMLEntity plugin = entity.getChild(i);
291
                        String pName = plugin.getStringProperty(
292
                                        "com.iver.andami.pluginName");
293
                        ((PluginServices) pluginsServices.get(pName)).setPresistentXML(plugin);
294
                }
295
        }
296

    
297
        /**
298
         * DOCUMENT ME!
299
         */
300
        private static void installPluginsLabels() {
301
                Iterator i = pluginsConfig.keySet().iterator();
302

    
303
                while (i.hasNext()) {
304
                        String name = (String) i.next();
305
                        PluginConfig pc = (PluginConfig) pluginsConfig.get(name);
306
                        PluginServices ps = (PluginServices) pluginsServices.get(name);
307

    
308
                        LabelSet[] ls = pc.getLabelSet();
309

    
310
                        for (int j = 0; j < ls.length; j++) {
311
                                PluginClassLoader loader = ps.getClassLoader();
312

    
313
                                try {
314
                                        Class clase = loader.loadClass(ls[j].getClassName());
315
                                        frame.setLabels(clase, ls[j].getLabel());
316
                                } catch (ClassNotFoundException e) {
317
                                        logger.error("No se pudo encontrar la clase de la labelset",
318
                                                e);
319
                                }
320
                        }
321
                }
322
        }
323

    
324
        /**
325
         * DOCUMENT ME!
326
         *
327
         * @throws MDIManagerLoadException
328
         */
329
        private static void skinPlugin() throws MDIManagerLoadException {
330
                Iterator i = pluginsConfig.keySet().iterator();
331

    
332
                while (i.hasNext()) {
333
                        String name = (String) i.next();
334
                        PluginConfig pc = (PluginConfig) pluginsConfig.get(name);
335
                        PluginServices ps = (PluginServices) pluginsServices.get(name);
336

    
337
                        if (pc.getExtensions().getSkinExtension() != null) {
338
                                if (MDIManagerFactory.getSkinExtension() != null) {
339
                                        logger.error("Dos skin-extension. Usamos el ?ltimo");
340
                                }
341

    
342
                                SkinExtension se = pc.getExtensions().getSkinExtension();
343

    
344
                                MDIManagerFactory.setSkinExtension(se, ps.getClassLoader());
345

    
346
                                Class skinClass;
347

    
348
                                try {
349
                                        skinClass = ps.getClassLoader().loadClass(se.getClassName());
350

    
351
                                        com.iver.andami.plugins.Extension skinInstance = (com.iver.andami.plugins.Extension) skinClass.newInstance();
352
                                        classesExtensions.put(skinClass, skinInstance);
353
                                } catch (ClassNotFoundException e) {
354
                                        logger.error("No se pudo instanciar la clase mdi manager", e);
355
                                        throw new MDIManagerLoadException(e);
356
                                } catch (InstantiationException e) {
357
                                        logger.error("No se pudo instanciar la clase mdi manager", e);
358
                                        throw new MDIManagerLoadException(e);
359
                                } catch (IllegalAccessException e) {
360
                                        logger.error("No se pudo instanciar la clase mdi manager", e);
361
                                        throw new MDIManagerLoadException(e);
362
                                }
363
                        }
364
                }
365
        }
366

    
367
        /**
368
         *
369
         */
370
        private static void frameIcon() {
371
                Iterator i = pluginsConfig.keySet().iterator();
372

    
373
                while (i.hasNext()) {
374
                        String pName = (String) i.next();
375
                        PluginConfig pc = (PluginConfig) pluginsConfig.get(pName);
376
                        PluginServices ps = (PluginServices) pluginsServices.get(pName);
377

    
378
                        if (pc.getIcon() != null) {
379
                                ImageIcon icon = new ImageIcon(ps.getClassLoader().getResource(pc.getIcon()
380
                                                                                                                                                                 .getSrc()));
381
                                frame.setIconImage(icon.getImage());
382
                                frame.setTitle(pc.getIcon().getText());
383
                        }
384
                }
385
        }
386

    
387
        /**
388
         *
389
         */
390
        private static void initializeExtensions() {
391
                Iterator i = pluginsConfig.keySet().iterator();
392

    
393
                while (i.hasNext()) {
394
                        String pName = (String) i.next();
395
                        PluginConfig pc = (PluginConfig) pluginsConfig.get(pName);
396
                        PluginServices ps = (PluginServices) pluginsServices.get(pName);
397

    
398
                        Extension[] exts = pc.getExtensions().getExtension();
399

    
400
                        TreeMap orderedExtensions = new TreeMap(new ExtensionComparator());
401

    
402
                        for (int j = 0; j < exts.length; j++) {
403
                                if (!exts[j].getActive()) {
404
                                        continue;
405
                                }
406

    
407
                                if (orderedExtensions.containsKey(exts[j])) {
408
                                        logger.error(
409
                                                "Two extensions with the same priority. Only will load one. " +
410
                                                exts[j].getClassName());
411
                                }
412

    
413
                                orderedExtensions.put(exts[j], null);
414
                        }
415

    
416
                        Iterator e = orderedExtensions.keySet().iterator();
417

    
418
                        while (e.hasNext()) {
419
                                Extension extension = (Extension) e.next();
420
                                com.iver.andami.plugins.Extension extensionInstance;
421

    
422
                                try {
423
                                        Class extensionClass = ps.getClassLoader().loadClass(extension.getClassName());
424
                                        extensionInstance = (com.iver.andami.plugins.Extension) extensionClass.newInstance();
425
                                        classesExtensions.put(extensionClass, extensionInstance);
426

    
427
                                        extensionInstance.inicializar();
428
                                } catch (InstantiationException e1) {
429
                                        logger.error("Error instanciando la extension " +
430
                                                extension.getClassName(), e1);
431
                                } catch (IllegalAccessException e1) {
432
                                        logger.error("Error instanciando la extension " +
433
                                                extension.getClassName(), e1);
434
                                } catch (ClassNotFoundException e1) {
435
                                        logger.error("Error instanciando la extension " +
436
                                                extension.getClassName(), e1);
437
                                } catch (NoClassDefFoundError e1) {
438
                                        logger.error("Error localizando la clase de la extension " +
439
                                                extension.getClassName(), e1);
440
                                }
441
                        }
442
                }
443
        }
444

    
445
        /**
446
         * DOCUMENT ME!
447
         */
448
        private static void installPluginsMenus() {
449
                TreeMap orderedMenus = new TreeMap(new MenuComparator());
450

    
451
                Iterator i = pluginsConfig.keySet().iterator();
452

    
453
                while (i.hasNext()) {
454
                        String pName = (String) i.next();
455
                        PluginServices ps = (PluginServices) pluginsServices.get(pName);
456
                        PluginConfig pc = (PluginConfig) pluginsConfig.get(pName);
457

    
458
                        Extension[] exts = pc.getExtensions().getExtension();
459

    
460
                        for (int j = 0; j < exts.length; j++) {
461
                                if (!exts[j].getActive()) {
462
                                        continue;
463
                                }
464

    
465
                                Menu[] menu = exts[j].getMenu();
466

    
467
                                for (int k = 0; k < menu.length; k++) {
468
                                        SortableMenu sm = new SortableMenu(ps.getClassLoader(),
469
                                                        exts[j], menu[k]);
470

    
471
                                        if (orderedMenus.containsKey(sm)) {
472
                                                logger.error(
473
                                                        "Two menus with the same position. Only will load one. " +
474
                                                        exts[j].getClassName());
475
                                        }
476

    
477
                                        orderedMenus.put(sm, null);
478
                                }
479
                        }
480

    
481
                        // Se instalan las extensiones de MDI
482
                        SkinExtension skinExt = pc.getExtensions().getSkinExtension();
483

    
484
                        if (skinExt != null) {
485
                                Menu[] menu = skinExt.getMenu();
486

    
487
                                for (int k = 0; k < menu.length; k++) {
488
                                        SortableMenu sm = new SortableMenu(ps.getClassLoader(),
489
                                                        skinExt, menu[k]);
490

    
491
                                        if (orderedMenus.containsKey(sm)) {
492
                                                logger.error(
493
                                                        "Two menus with the same position. Only will load one. " +
494
                                                        skinExt.getClassName());
495
                                        }
496

    
497
                                        orderedMenus.put(sm, null);
498
                                }
499
                        }
500
                }
501

    
502
                //Se itera por los menus ordenados
503
                Iterator e = orderedMenus.keySet().iterator();
504

    
505
                // Se ordenan los menues
506
                while (e.hasNext()) {
507
                        try {
508
                                SortableMenu sm = (SortableMenu) e.next();
509

    
510
                                frame.addMenu(sm.loader, sm.extension, sm.menu);
511
                        } catch (ClassNotFoundException ex) {
512
                                logger.error("No se pudo encontrar la clase de la extension", ex);
513
                        }
514
                }
515
        }
516

    
517
        /**
518
         *
519
         */
520
        private static void installPluginsControls() {
521
                Iterator i = pluginsConfig.keySet().iterator();
522

    
523
                while (i.hasNext()) {
524
                        try {
525
                                String pName = (String) i.next();
526
                                PluginConfig pc = (PluginConfig) pluginsConfig.get(pName);
527
                                PluginServices ps = (PluginServices) pluginsServices.get(pName);
528

    
529
                                Extension[] exts = pc.getExtensions().getExtension();
530

    
531
                                TreeMap orderedExtensions = new TreeMap(new ExtensionComparator());
532

    
533
                                for (int j = 0; j < exts.length; j++) {
534
                                        if (exts[j].getActive()) {
535
                                                if (orderedExtensions.containsKey(exts[j])) {
536
                                                        logger.error(
537
                                                                "Two extensions with the same priority. Only will load one. " +
538
                                                                exts[j].getClassName());
539
                                                }
540

    
541
                                                orderedExtensions.put(exts[j], null);
542
                                        }
543
                                }
544

    
545
                                Iterator e = orderedExtensions.keySet().iterator();
546

    
547
                                // Se instalan las extensiones
548
                                while (e.hasNext()) {
549
                                        Extension ext = (Extension) e.next();
550

    
551
                                        ToolBar[] toolbars = ext.getToolBar();
552

    
553
                                        for (int k = 0; k < toolbars.length; k++) {
554
                                                ActionTool[] tools = toolbars[k].getActionTool();
555

    
556
                                                for (int t = 0; t < tools.length; t++) {
557
                                                        frame.addTool(ps.getClassLoader(), ext,
558
                                                                toolbars[k], tools[t]);
559
                                                }
560

    
561
                                                SelectableTool[] sTools = toolbars[k].getSelectableTool();
562

    
563
                                                for (int t = 0; t < sTools.length; t++) {
564
                                                        frame.addTool(ps.getClassLoader(), ext,
565
                                                                toolbars[k], sTools[t]);
566
                                                }
567
                                        }
568

    
569
                                        /*
570
                                           Menu[] menu = ext.getMenu();
571
                                           for (int k = 0; k < menu.length; k++) {
572
                                               frame.addMenu(ps.getClassLoader(), ext, menu[k]);
573
                                           }
574
                                         */
575
                                }
576

    
577
                                // Se instalan las extensiones de MDI
578
                                SkinExtension skinExt = pc.getExtensions().getSkinExtension();
579

    
580
                                if (skinExt != null) {
581
                                        ToolBar[] toolbars = skinExt.getToolBar();
582

    
583
                                        for (int k = 0; k < toolbars.length; k++) {
584
                                                ActionTool[] tools = toolbars[k].getActionTool();
585

    
586
                                                for (int t = 0; t < tools.length; t++) {
587
                                                        frame.addTool(ps.getClassLoader(), skinExt,
588
                                                                toolbars[k], tools[t]);
589
                                                }
590

    
591
                                                SelectableTool[] sTools = toolbars[k].getSelectableTool();
592

    
593
                                                for (int t = 0; t < sTools.length; t++) {
594
                                                        frame.addTool(ps.getClassLoader(), skinExt,
595
                                                                toolbars[k], sTools[t]);
596
                                                }
597
                                        }
598

    
599
                                        /*
600
                                           Menu[] menu = skinExt.getMenu();
601
                                           for (int k = 0; k < menu.length; k++) {
602
                                               frame.addMenu(ps.getClassLoader(), skinExt, menu[k]);
603
                                           }
604
                                         */
605
                                }
606

    
607
                                //Se instalan los popup menus
608
                                PopupMenus pus = pc.getPopupMenus();
609

    
610
                                if (pus != null) {
611
                                        PopupMenu[] menus = pus.getPopupMenu();
612

    
613
                                        for (int j = 0; j < menus.length; j++) {
614
                                                frame.addPopupMenu(ps.getClassLoader(), menus[j]);
615
                                        }
616
                                }
617
                        } catch (ClassNotFoundException e) {
618
                                logger.error("No se pudo encontrar la clase de la extension", e);
619
                        }
620
                }
621
        }
622

    
623
        /**
624
         *
625
         */
626
        private static void updateAndamiConfig() {
627
                HashSet olds = new HashSet();
628

    
629
                Plugin[] plugins = andamiConfig.getPlugin();
630

    
631
                for (int i = 0; i < plugins.length; i++) {
632
                        olds.add(plugins[i].getName());
633
                }
634

    
635
                Iterator i = pluginsServices.values().iterator();
636

    
637
                while (i.hasNext()) {
638
                        PluginServices ps = (PluginServices) i.next();
639

    
640
                        if (!olds.contains(ps.getPluginName())) {
641
                                Plugin p = new Plugin();
642
                                p.setName(ps.getPluginName());
643
                                p.setUpdate(false);
644

    
645
                                andamiConfig.addPlugin(p);
646
                        }
647
                }
648
        }
649

    
650
        /**
651
         * DOCUMENT ME!
652
         */
653
        private static void pluginsClassLoaders() {
654
                HashSet instalados = new HashSet();
655

    
656
                // Se itera hasta que est?n todos instalados
657
                while (instalados.size() != pluginsConfig.size()) {
658
                        boolean circle = true;
659

    
660
                        //Hacemos una pasada por todos los plugins
661
                        Iterator i = pluginsConfig.keySet().iterator();
662

    
663
                        while (i.hasNext()) {
664
                                String pluginName = (String) i.next();
665
                                PluginConfig config = (PluginConfig) pluginsConfig.get(pluginName);
666

    
667
                                if (instalados.contains(pluginName)) {
668
                                        continue;
669
                                }
670

    
671
                                //Se obtienen las dependencias y sus class loaders
672
                                boolean ready = true;
673
                                Depends[] dependencies = config.getDepends();
674
                                PluginClassLoader[] loaders = new PluginClassLoader[dependencies.length];
675

    
676
                                for (int j = 0; j < dependencies.length; j++) {
677
                                        if (pluginsConfig.get(dependencies[j].getPluginName()) == null) {
678
                                                logger.error("Dependencia no resuelta en plugin " +
679
                                                        pluginName + ": " +
680
                                                        dependencies[j].getPluginName() +
681
                                                        ". Dependencia ignorada");
682

    
683
                                                continue;
684
                                        }
685

    
686
                                        if (!instalados.contains(dependencies[j].getPluginName())) {
687
                                                ready = false;
688
                                        } else {
689
                                                loaders[j] = ((PluginServices) pluginsServices.get(dependencies[j].getPluginName())).getClassLoader();
690
                                        }
691
                                }
692

    
693
                                //Si no est?n sus dependencias satisfechas se aborta la instalaci?n
694
                                if (!ready) {
695
                                        continue;
696
                                }
697

    
698
                                //Se genera el class loader
699
                                String jardir = config.getLibraries().getLibraryDir();
700
                                File jarDir = new File(andamiConfig.getPluginsDirectory() +
701
                                                File.separator + pluginName + File.separator + jardir);
702
                                File[] jarFiles = jarDir.listFiles(new FileFilter() {
703
                                        public boolean accept(File pathname) {
704
                                                return (pathname.getName().toUpperCase().endsWith(".JAR")) ||
705
                                                (pathname.getName().toUpperCase().endsWith(".ZIP"));
706
                                        }
707
                                });
708
                                
709
                                URL[] urls = new URL[jarFiles.length];
710
                                for (int j = 0; j < jarFiles.length; j++) {
711
                                        try {
712
                                                urls[j] = new URL("file:" + jarFiles[j]);
713
                                        } catch (MalformedURLException e) {
714
                                                logger.error("No se puede acceder a " +
715
                                                        jarFiles[j]);
716
                                        }
717
                                }
718

    
719
                                PluginClassLoader loader;
720

    
721
                                try {
722
                                        loader = new PluginClassLoader(urls,
723
                                                        andamiConfig.getPluginsDirectory() +
724
                                                        File.separator + pluginName,
725
                                                        Launcher.class.getClassLoader(), loaders);
726

    
727
                                        PluginServices ps = new PluginServices(loader);
728

    
729
                                        pluginsServices.put(ps.getPluginName(), ps);
730

    
731
                                        instalados.add(pluginName);
732

    
733
                                        circle = false;
734
                                } catch (IOException e) {
735
                                        logger.error("Error con las librer?as del plugin", e);
736
                                        pluginsConfig.remove(pluginName);
737
                                        i = pluginsConfig.keySet().iterator();
738
                                }
739
                        }
740

    
741
                        if (circle) {
742
                                logger.error("Hay dependencias circulares entre los plugins");
743

    
744
                                break;
745
                        }
746
                }
747

    
748
                //Se eliminan los plugins que no fueron instalados
749
                Iterator i = pluginsConfig.keySet().iterator();
750

    
751
                while (i.hasNext()) {
752
                        String pluginName = (String) i.next();
753
                        PluginConfig config = (PluginConfig) pluginsConfig.get(pluginName);
754
                        PluginServices ps = (PluginServices) pluginsServices.get(pluginName);
755

    
756
                        if (ps == null) {
757
                                pluginsConfig.remove(pluginName);
758
                                i = pluginsConfig.keySet().iterator();
759
                        }
760
                }
761
        }
762

    
763
        /**
764
         * DOCUMENT ME!
765
         */
766
        private static void pluginsMessages() {
767
                //Iteramos por todos los plugins
768
                Iterator i = pluginsConfig.keySet().iterator();
769

    
770
                while (i.hasNext()) {
771
                        String pluginName = (String) i.next();
772
                        PluginConfig config = (PluginConfig) pluginsConfig.get(pluginName);
773

    
774
                        PluginServices ps = (PluginServices) pluginsServices.get(pluginName);
775

    
776
                        if (config.getResourceBundle() != null) {
777
                                ps.setResourceBundle(config.getResourceBundle().getName(),
778
                                        locale);
779
                        }
780
                }
781
        }
782

    
783
        /**
784
         * DOCUMENT ME!
785
         *
786
         * @param name DOCUMENT ME!
787
         *
788
         * @return DOCUMENT ME!
789
         */
790
        static PluginServices getPluginServices(String name) {
791
                return (PluginServices) pluginsServices.get(name);
792
        }
793

    
794
        /**
795
         * DOCUMENT ME!
796
         *
797
         * @return DOCUMENT ME!
798
         */
799
        static String getPluginsDir() {
800
                return andamiConfig.getPluginsDirectory();
801
        }
802

    
803
        /**
804
         * DOCUMENT ME!
805
         *
806
         * @param s DOCUMENT ME!
807
         */
808
        static void setPluginsDir(String s) {
809
                andamiConfig.setPluginsDirectory(s);
810
        }
811

    
812
        /**
813
         * DOCUMENT ME!
814
         *
815
         * @return DOCUMENT ME!
816
         */
817
        static MDIFrame getMDIFrame() {
818
                return frame;
819
        }
820

    
821
        /**
822
         * DOCUMENT ME!
823
         *
824
         * @param pluginsDirectory
825
         */
826
        private static void loadPlugins(String pluginsDirectory) {
827
                File pDir = new File(pluginsDirectory);
828

    
829
                if (!pDir.exists()) {
830
                        return;
831
                }
832

    
833
                File[] pluginDirs = pDir.listFiles();
834

    
835
                for (int i = 0; i < pluginDirs.length; i++) {
836
                        if (pluginDirs[i].isDirectory()) {
837
                                File configXml = new File(pluginDirs[i].getAbsolutePath() +
838
                                                File.separator + "config.xml");
839

    
840
                                try {
841
                                        FileReader xml = new FileReader(configXml);
842
                                        PluginConfig pConfig = (PluginConfig) PluginConfig.unmarshal(xml);
843
                                        pluginsConfig.put(pluginDirs[i].getName(), pConfig);
844
                                } catch (FileNotFoundException e) {
845
                                        logger.info("Ignorando el directorio " +
846
                                                pluginDirs[i].getAbsolutePath() +
847
                                                " por no encontrar su fichero 'config.xml'");
848
                                } catch (MarshalException e) {
849
                                        logger.info("Ignorando el directorio " +
850
                                                pluginDirs[i].getAbsolutePath() +
851
                                                " por fichero 'config.xml' mal formado", e);
852
                                } catch (ValidationException e) {
853
                                        logger.info("Ignorando el directorio " +
854
                                                pluginDirs[i].getAbsolutePath() +
855
                                                " por fichero 'config.xml' mal formado", e);
856
                                }
857
                        }
858
                }
859
        }
860

    
861
        /**
862
         * DOCUMENT ME!
863
         *
864
         * @param language
865
         * @param country
866
         * @param variant
867
         *
868
         * @return DOCUMENT ME!
869
         */
870
        private static Locale getLocale(String language, String country,
871
                String variant) {
872
                if (variant != null) {
873
                        return new Locale(language, country, variant);
874
                } else if (country != null) {
875
                        return new Locale(language, country);
876
                } else if (language != null) {
877
                        return new Locale(language);
878
                } else {
879
                        return new Locale("es");
880
                }
881
        }
882

    
883
        /**
884
         * DOCUMENT ME!
885
         *
886
         * @param file DOCUMENT ME!
887
         *
888
         * @throws IOException DOCUMENT ME!
889
         * @throws MarshalException DOCUMENT ME!
890
         * @throws ValidationException DOCUMENT ME!
891
         */
892
        private static void andamiConfigToXML(String file)
893
                throws IOException, MarshalException, ValidationException {
894
                File xml = new File(file);
895
                File parent = xml.getParentFile();
896
                parent.mkdirs();
897

    
898
                FileWriter writer = new FileWriter(xml);
899
                andamiConfig.marshal(writer);
900
        }
901

    
902
        /**
903
         * DOCUMENT ME!
904
         *
905
         * @param file DOCUMENT ME!
906
         *
907
         * @throws ConfigurationException DOCUMENT ME!
908
         */
909
        private static void andamiConfigFromXML(String file)
910
                throws ConfigurationException {
911
                File xml = new File(file);
912

    
913
                //Si no existe se ponen los valores por defecto
914
                if (!xml.exists()) {
915
                        andamiConfig = new AndamiConfig();
916

    
917
                        Andami andami = new Andami();
918
                        andami.setUpdate(true);
919
                        andamiConfig.setAndami(andami);
920
                        andamiConfig.setLocaleCountry(Locale.getDefault().getCountry());
921
                        andamiConfig.setLocaleLanguage(Locale.getDefault().getLanguage());
922
                        andamiConfig.setLocaleVariant(Locale.getDefault().getVariant());
923

    
924
                        if (System.getProperty("javawebstart.version") != null) // Es java web start)
925
                         {
926
                                andamiConfig.setPluginsDirectory(new File(System.getProperty(
927
                                                        "user.home") + File.separator + appName +
928
                                                File.separator + "extensiones").getAbsolutePath());
929
                        } else {
930
                                andamiConfig.setPluginsDirectory(new File(appName +
931
                                                File.separator + "extensiones").getAbsolutePath());
932
                        }
933

    
934
                        andamiConfig.setPlugin(new Plugin[0]);
935
                } else {
936
                        //Se lee la configuraci?n
937
                        FileReader reader;
938

    
939
                        try {
940
                                reader = new FileReader(xml);
941
                                andamiConfig = (AndamiConfig) AndamiConfig.unmarshal(reader);
942
                        } catch (FileNotFoundException e) {
943
                                throw new ConfigurationException(e);
944
                        } catch (MarshalException e) {
945
                                throw new ConfigurationException(e);
946
                        } catch (ValidationException e) {
947
                                throw new ConfigurationException(e);
948
                        }
949
                }
950
        }
951

    
952
        /**
953
         * DOCUMENT ME!
954
         *
955
         * @return DOCUMENT ME!
956
         *
957
         * @throws ConfigurationException DOCUMENT ME!
958
         */
959
        private static XMLEntity persistenceFromXML() throws ConfigurationException {
960
                File xml = new File(pluginsPersistencePath);
961

    
962
                if (xml.exists()) {
963
                        FileReader reader;
964

    
965
                        try {
966
                                reader = new FileReader(xml);
967

    
968
                                XmlTag tag = (XmlTag) XmlTag.unmarshal(reader);
969

    
970
                                return new XMLEntity(tag);
971
                        } catch (FileNotFoundException e) {
972
                                throw new ConfigurationException(e);
973
                        } catch (MarshalException e) {
974
                                throw new ConfigurationException(e);
975
                        } catch (ValidationException e) {
976
                                throw new ConfigurationException(e);
977
                        }
978
                } else {
979
                        return new XMLEntity();
980
                }
981
        }
982

    
983
        /**
984
         * DOCUMENT ME!
985
         *
986
         * @param entity DOCUMENT ME!
987
         *
988
         * @throws ConfigurationException DOCUMENT ME!
989
         */
990
        private static void persistenceToXML(XMLEntity entity)
991
                throws ConfigurationException {
992
                File xml = new File(pluginsPersistencePath);
993

    
994
                FileWriter writer;
995

    
996
                try {
997
                        writer = new FileWriter(xml);
998
                        entity.getXmlTag().marshal(writer);
999
                } catch (FileNotFoundException e) {
1000
                        throw new ConfigurationException(e);
1001
                } catch (MarshalException e) {
1002
                        throw new ConfigurationException(e);
1003
                } catch (ValidationException e) {
1004
                        throw new ConfigurationException(e);
1005
                } catch (IOException e) {
1006
                        throw new ConfigurationException(e);
1007
                }
1008
        }
1009

    
1010
        /**
1011
         * Devuelve un array con los directorios de los plugins
1012
         *
1013
         * @param dirExt Directorio de las extensiones a partir del cual cuelgan
1014
         *                   todos los directorios de los plugins
1015
         *
1016
         * @return ArrayList con los directorios
1017
         */
1018
        private String[] getLocales(File dirExt) {
1019
                ArrayList types = new ArrayList();
1020
                File[] files = dirExt.listFiles();
1021

    
1022
                for (int i = 0; i < files.length; i++) {
1023
                        if (files[i].isDirectory()) {
1024
                                File[] textFile = files[i].listFiles(new FilenameFilter() {
1025
                                                        public boolean accept(File dir, String fileName) {
1026
                                                                return fileName.toLowerCase().startsWith("text_"); //$NON-NLS-1$
1027
                                                        }
1028
                                                });
1029

    
1030
                                for (int j = 0; j < textFile.length; j++) {
1031
                                        String s = (textFile[j]).getName().replaceAll("text_", "");
1032
                                        s = s.replaceAll(".properties", "");
1033
                                        s = s.trim();
1034

    
1035
                                        if (!types.contains(s)) {
1036
                                                types.add(s);
1037
                                        }
1038
                                }
1039
                        }
1040
                }
1041

    
1042
                return (String[]) types.toArray(new String[0]);
1043
        }
1044

    
1045
        /**
1046
         * DOCUMENT ME!
1047
         *
1048
         * @return Returns the frame.
1049
         */
1050
        static MDIFrame getFrame() {
1051
                return frame;
1052
        }
1053

    
1054
        /**
1055
         * Secuencia de cerrado de Andami
1056
         */
1057
        public static void closeApplication() {
1058
                //Configuraci?n de Andami
1059
                try {
1060
                        andamiConfigToXML(andamiConfigPath);
1061
                } catch (MarshalException e) {
1062
                        logger.error("No se pudo guardar la configuraci?n de Andami", e);
1063
                } catch (ValidationException e) {
1064
                        logger.error("No se pudo guardar la configuraci?n de Andami", e);
1065
                } catch (IOException e) {
1066
                        logger.error("No se pudo guardar la configuraci?n de Andami", e);
1067
                }
1068

    
1069
                //Persistencia de los plugins
1070
                Iterator i = pluginsConfig.keySet().iterator();
1071

    
1072
                XMLEntity entity = new XMLEntity();
1073

    
1074
                while (i.hasNext()) {
1075
                        String pName = (String) i.next();
1076
                        PluginServices ps = (PluginServices) pluginsServices.get(pName);
1077
                        XMLEntity ent = ps.getPersistentXML();
1078

    
1079
                        if (ent != null) {
1080
                                ent.putProperty("com.iver.andami.pluginName", pName);
1081
                                entity.addChild(ent);
1082
                        }
1083
                }
1084

    
1085
                try {
1086
                        persistenceToXML(entity);
1087
                } catch (ConfigurationException e1) {
1088
                        logger.error("Se produjo un error guardando la configuraci?n de los plugins",
1089
                                e1);
1090
                }
1091

    
1092
                System.exit(0);
1093
        }
1094

    
1095
        /**
1096
         * DOCUMENT ME!
1097
         *
1098
         * @return DOCUMENT ME!
1099
         */
1100
        static HashMap getClassesExtensions() {
1101
                return classesExtensions;
1102
        }
1103

    
1104
        /**
1105
         * DOCUMENT ME!
1106
         *
1107
         * @param extDir DOCUMENT ME!
1108
         */
1109
        private static void downloadExtensions(String extDir) {
1110
                java.util.Date fechaActual = null;
1111

    
1112
                try {
1113
                        if (System.getProperty("javawebstart.version") != null) {
1114
                                //Obtenemos la URL del servidor
1115
                                BasicService bs = (BasicService) ServiceManager.lookup(
1116
                                                "javax.jnlp.BasicService");
1117
                                URL baseURL = bs.getCodeBase();
1118

    
1119
                                //Se descargan las extensiones
1120
                                SplashWindow.process(5,
1121
                                        "Descargando las extensiones desde " + baseURL + " a " +
1122
                                        extDir);
1123

    
1124
                                URL url = new URL(baseURL + "extensiones.zip");
1125
                                URLConnection connection = url.openConnection();
1126

    
1127
                                System.out.println(url.toExternalForm() + ":");
1128
                                System.out.println("  Content Type: " +
1129
                                        connection.getContentType());
1130
                                System.out.println("  Content Length: " +
1131
                                        connection.getContentLength());
1132
                                System.out.println("  Last Modified: " +
1133
                                        new Date(connection.getLastModified()));
1134
                                System.out.println("  Expiration: " +
1135
                                        connection.getExpiration());
1136
                                System.out.println("  Content Encoding: " +
1137
                                        connection.getContentEncoding());
1138

    
1139
                                // Guardamos la fecha del fichero de extensiones que nos hemos bajado, y
1140
                                // comprobamos el ?ltimo que se ha bajado. Si no son
1141
                                // iguales, nos bajamos el nuevo. Si son iguales, no
1142
                                // nos bajamos nada.
1143
                                Long miliSecondsInWeb = new Long(connection.getLastModified());
1144

    
1145
                                // PluginServices ps = PluginServices.getPluginServices("com.iver.core");
1146
                                // if (ps.getPersistentXML().getStringProperty("timestamp") != null)
1147
                                File destDir = new File(extDir);
1148

    
1149
                                if (!destDir.exists()) {
1150
                                        // Creamos gvSIG
1151
                                        destDir.getParentFile().mkdir();
1152

    
1153
                                        if (!destDir.mkdir()) {
1154
                                                System.err.println("Imposible crear el directorio " +
1155
                                                        destDir.getAbsolutePath());
1156
                                        }
1157
                                }
1158

    
1159
                                File timeFile = new File(destDir.getParent() + File.separator +
1160
                                                "timeStamp.properties");
1161

    
1162
                                if (!timeFile.exists()) {
1163
                                        timeFile.createNewFile();
1164
                                }
1165

    
1166
                                FileInputStream inAux = new FileInputStream(timeFile);
1167
                                Properties prop = new Properties();
1168
                                prop.load(inAux);
1169
                                inAux.close();
1170

    
1171
                                if (prop.getProperty("timestamp") != null) {
1172
                                        Long lastMiliSeconds = (Long) new Long(prop.getProperty(
1173
                                                                "timestamp"));
1174

    
1175
                                        if (lastMiliSeconds.longValue() == miliSecondsInWeb.longValue()) {
1176
                                                System.out.println("No hay nueva actualizaci?n");
1177

    
1178
                                                return;
1179
                                        }
1180

    
1181
                                        System.out.println("timeStampWeb= " + miliSecondsInWeb);
1182
                                        System.out.println("timeStampLocal= " + lastMiliSeconds);
1183
                                } else {
1184
                                        System.out.println("El timeStamp no est? escrito en " +
1185
                                                timeFile.getAbsolutePath());
1186
                                }
1187

    
1188
                                InputStream stream = connection.getInputStream();
1189
                                File temp = File.createTempFile("gvsig", ".zip");
1190
                                temp.deleteOnExit();
1191

    
1192
                                FileOutputStream file = new FileOutputStream(temp);
1193
                                BufferedInputStream in = new BufferedInputStream(stream);
1194
                                BufferedOutputStream out = new BufferedOutputStream(file);
1195

    
1196
                                int i;
1197
                                int pct;
1198
                                int desde;
1199
                                int hasta;
1200

    
1201
                                hasta = connection.getContentLength() / 1024;
1202
                                desde = 0;
1203

    
1204
                                while ((i = in.read()) != -1) {
1205
                                        pct = ((desde / 1024) * 100) / hasta;
1206

    
1207
                                        if (((desde % 10240) == 0) && (pct > 10) &&
1208
                                                        ((pct % 10) == 0)) {
1209
                                                SplashWindow.process(pct,
1210
                                                        (desde / 1024) + "Kb de " + hasta +
1211
                                                        "Kb descargados...");
1212
                                        }
1213

    
1214
                                        out.write(i);
1215
                                        desde++;
1216
                                }
1217

    
1218
                                out.flush();
1219
                                out.close();
1220
                                in.close();
1221

    
1222
                                //Se extrae el zip
1223
                                SplashWindow.process(5, "Extensiones descargadas.");
1224

    
1225
                                System.out.println("Extrayendo a " + destDir.getAbsolutePath());
1226

    
1227
                                Date fechaDir = new Date(destDir.lastModified());
1228
                                System.out.println("Fecha del directorio " + extDir + " = " +
1229
                                        fechaDir.toString());
1230
                                Utilities.extractTo(temp, new File(extDir), splashWindow);
1231

    
1232
                                // Si todo ha ido bien, guardamos el timestamp.
1233
                                ///  App.instance.getPc().addProperties("timestamp", miliSecondsInWeb);
1234
                                // XMLEntity xml=ps.getPersistentXML();
1235
                                fechaActual = new java.util.Date();
1236

    
1237
                                FileOutputStream outAux = new FileOutputStream(timeFile);
1238
                                prop.setProperty("timestamp", miliSecondsInWeb.toString());
1239
                                prop.store(outAux, "last download");
1240
                                outAux.close();
1241
                                System.out.println("Fecha actual guardada: " +
1242
                                        fechaActual.toGMTString());
1243

    
1244
                                /* xml.putProperty("timestamp",fechaActual.toGMTString());
1245
                                   ps.setPresistentXML(xml); */
1246
                        }
1247
                } catch (IOException e) {
1248
                        NotificationManager.addError("", e);
1249
                } catch (UnavailableServiceException e) {
1250
                        NotificationManager.addError("", e);
1251
                } catch (SecurityException e) {
1252
                        System.err.println("No se puede escribir el timeStamp " +
1253
                                fechaActual.toGMTString());
1254
                        NotificationManager.addError("", e);
1255
                }
1256
        }
1257

    
1258
        /**
1259
         * DOCUMENT ME!
1260
         *
1261
         * @return DOCUMENT ME!
1262
         */
1263
        private static Extensions[] getExtensions() {
1264
                ArrayList array = new ArrayList();
1265
                Iterator iter = pluginsConfig.values().iterator();
1266

    
1267
                while (iter.hasNext()) {
1268
                        array.add(((PluginConfig) iter.next()).getExtensions());
1269
                }
1270

    
1271
                return (Extensions[]) array.toArray(new Extensions[0]);
1272
        }
1273

    
1274
        /**
1275
         * DOCUMENT ME!
1276
         *
1277
         * @return DOCUMENT ME!
1278
         */
1279
        public static HashMap getPluginConfig() {
1280
                return pluginsConfig;
1281
        }
1282

    
1283
        /**
1284
         * DOCUMENT ME!
1285
         *
1286
         * @param s DOCUMENT ME!
1287
         *
1288
         * @return DOCUMENT ME!
1289
         */
1290
        public static Extension getExtension(String s) {
1291
                Extensions[] exts = getExtensions();
1292

    
1293
                for (int i = 0; i < exts.length; i++) {
1294
                        for (int j = 0; j < exts[i].getExtensionCount(); j++) {
1295
                                if (exts[i].getExtension(j).getClassName().equals(s)) {
1296
                                        return exts[i].getExtension(j);
1297
                                }
1298
                        }
1299
                }
1300

    
1301
                return null;
1302
        }
1303

    
1304
        /**
1305
         * DOCUMENT ME!
1306
         *
1307
         * @return DOCUMENT ME!
1308
         */
1309
        public static AndamiConfig getAndamiConfig() {
1310
                return andamiConfig;
1311
        }
1312

    
1313
        /**
1314
         * DOCUMENT ME!
1315
         *
1316
         * @author $author$
1317
         * @version $Revision: 1119 $
1318
         */
1319
        public static class ExtensionComparator implements Comparator {
1320
                /**
1321
                 * DOCUMENT ME!
1322
                 *
1323
                 * @param o1 DOCUMENT ME!
1324
                 * @param o2 DOCUMENT ME!
1325
                 *
1326
                 * @return DOCUMENT ME!
1327
                 */
1328
                public int compare(Object o1, Object o2) {
1329
                        Extension e1 = (Extension) o1;
1330
                        Extension e2 = (Extension) o2;
1331

    
1332
                        if (!e1.hasPriority() && !e2.hasPriority()) {
1333
                                return -1;
1334
                        }
1335

    
1336
                        if (e1.hasPriority() && !e2.hasPriority()) {
1337
                                return -Integer.MAX_VALUE;
1338
                        }
1339

    
1340
                        if (e2.hasPriority() && !e1.hasPriority()) {
1341
                                return Integer.MAX_VALUE;
1342
                        }
1343

    
1344
                        return e1.getPriority() - e2.getPriority();
1345
                }
1346
        }
1347

    
1348
        /**
1349
         * DOCUMENT ME!
1350
         */
1351
        public static class MenuComparator implements Comparator {
1352
                private static ExtensionComparator extComp = new ExtensionComparator();
1353

    
1354
                /**
1355
                 * DOCUMENT ME!
1356
                 *
1357
                 * @param o1 DOCUMENT ME!
1358
                 * @param o2 DOCUMENT ME!
1359
                 *
1360
                 * @return DOCUMENT ME!
1361
                 */
1362
                public int compare(Object o1, Object o2) {
1363
                        SortableMenu e1 = (SortableMenu) o1;
1364
                        SortableMenu e2 = (SortableMenu) o2;
1365

    
1366
                        if (!e1.menu.hasPosition() && !e2.menu.hasPosition()) {
1367
                                if (e1.extension instanceof SkinExtensionType) {
1368
                                        return 1;
1369
                                } else if (e2.extension instanceof SkinExtensionType) {
1370
                                        return -1;
1371
                                } else {
1372
                                        return extComp.compare(e1.extension, e2.extension);
1373
                                }
1374
                        }
1375

    
1376
                        if (e1.menu.hasPosition() && !e2.menu.hasPosition()) {
1377
                                return -Integer.MAX_VALUE;
1378
                        }
1379

    
1380
                        if (e2.menu.hasPosition() && !e1.menu.hasPosition()) {
1381
                                return Integer.MAX_VALUE;
1382
                        }
1383

    
1384
                        return e1.menu.getPosition() - e2.menu.getPosition();
1385
                }
1386
        }
1387

    
1388
        /**
1389
         * DOCUMENT ME!
1390
         *
1391
         * @author $author$
1392
         * @version $Revision: 1119 $
1393
         */
1394
        public static class SortableMenu {
1395
                public PluginClassLoader loader;
1396
                public Menu menu;
1397
                public SkinExtensionType extension;
1398

    
1399
                /**
1400
                 * DOCUMENT ME!
1401
                 *
1402
                 * @param loader DOCUMENT ME!
1403
                 * @param skinExt
1404
                 * @param menu2
1405
                 */
1406
                public SortableMenu(PluginClassLoader loader,
1407
                        SkinExtensionType skinExt, Menu menu2) {
1408
                        extension = skinExt;
1409
                        menu = menu2;
1410
                        this.loader = loader;
1411
                }
1412
        }
1413

    
1414
        /*public static Extension getExtension(Class s) {
1415
           //String aux=s.getName().substring(s.getName().lastIndexOf("."),s.getName().length());
1416
           String aux1=s.getName().substring(0,s.getName().lastIndexOf("."));
1417
           PluginConfig p=(PluginConfig)pluginsConfig.get(aux1);
1418
           Extension ext=null;
1419
           if (p!=null){
1420
           Extensions exts=p.getExtensions();
1421
        
1422
           for (int i=0;i<exts.getExtensionCount();i++){
1423
                   if (exts.getExtension(i).getClassName().equals(s.getName())){
1424
                           ext=exts.getExtension(i);
1425
                   }
1426
           }
1427
           }
1428
           return ext;
1429
           }
1430
         */
1431
}