Statistics
| Revision:

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

History | View | Annotate | Download (33.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.File;
46
import java.io.FileFilter;
47
import java.io.FileNotFoundException;
48
import java.io.FileReader;
49
import java.io.FileWriter;
50
import java.io.FilenameFilter;
51
import java.io.IOException;
52
import java.lang.reflect.InvocationTargetException;
53
import java.net.MalformedURLException;
54
import java.net.URL;
55
import java.util.ArrayList;
56
import java.util.Comparator;
57
import java.util.HashMap;
58
import java.util.HashSet;
59
import java.util.Iterator;
60
import java.util.Locale;
61
import java.util.TreeMap;
62

    
63
import javax.swing.ImageIcon;
64
import javax.swing.JComponent;
65
import javax.swing.SwingUtilities;
66
import javax.swing.UIManager;
67

    
68
import org.apache.log4j.Logger;
69
import org.apache.log4j.PatternLayout;
70
import org.apache.log4j.PropertyConfigurator;
71
import org.apache.log4j.RollingFileAppender;
72
import org.exolab.castor.xml.MarshalException;
73
import org.exolab.castor.xml.ValidationException;
74

    
75
import com.iver.andami.config.generate.Andami;
76
import com.iver.andami.config.generate.AndamiConfig;
77
import com.iver.andami.config.generate.Plugin;
78
import com.iver.andami.messages.Messages;
79
import com.iver.andami.plugins.PluginClassLoader;
80
import com.iver.andami.plugins.config.generate.ActionTool;
81
import com.iver.andami.plugins.config.generate.Depends;
82
import com.iver.andami.plugins.config.generate.Extension;
83
import com.iver.andami.plugins.config.generate.Extensions;
84
import com.iver.andami.plugins.config.generate.LabelSet;
85
import com.iver.andami.plugins.config.generate.Menu;
86
import com.iver.andami.plugins.config.generate.PluginConfig;
87
import com.iver.andami.plugins.config.generate.PopupMenu;
88
import com.iver.andami.plugins.config.generate.PopupMenus;
89
import com.iver.andami.plugins.config.generate.SelectableTool;
90
import com.iver.andami.plugins.config.generate.SkinExtension;
91
import com.iver.andami.plugins.config.generate.SkinExtensionType;
92
import com.iver.andami.plugins.config.generate.ToolBar;
93
import com.iver.andami.ui.AndamiEventQueue;
94
import com.iver.andami.ui.MDIManagerLoadException;
95
import com.iver.andami.ui.SplashWindow;
96
import com.iver.andami.ui.mdiFrame.MDIFrame;
97
import com.iver.andami.ui.mdiManager.MDIManagerFactory;
98
import com.iver.utiles.XMLEntity;
99
import com.iver.utiles.xmlEntity.generate.XmlTag;
100

    
101

    
102
/**
103
 * DOCUMENT ME!
104
 *
105
 * @author $author$
106
 * @version $Revision: 2291 $
107
 */
108
public class Launcher {
109
        private static Logger logger = Logger.getLogger(Launcher.class.getName());
110
        private static AndamiConfig andamiConfig;
111
        private static SplashWindow splashWindow;
112
        private static String userHome = System.getProperty("user.home");
113
        private static String appName;
114
        private static Locale locale;
115
        private static HashMap pluginsConfig = new HashMap();
116
        private static HashMap pluginsServices = new HashMap();
117
        private static MDIFrame frame;
118
        private static HashMap classesExtensions = new HashMap();
119
        private static String andamiConfigPath;
120
        private static String pluginsPersistencePath;
121

    
122
        /**
123
         * DOCUMENT ME!
124
         *
125
         * @param args DOCUMENT ME!
126
         * @throws Exception
127
         *
128
         * @throws InterruptedException
129
         * @throws InvocationTargetException
130
         * @throws ConfigurationException
131
         * @throws MDIManagerLoadException
132
         * @throws IOException
133
         */
134
        public static void main(String[] args) throws Exception {
135
            try{
136

    
137
            if (!validJVM()){
138
                System.exit(-1);
139
            }
140
                
141
            if ((args.length < 1) || (args.length > 3)) {
142
                        System.err.println("Uso: Launcher appName plugins-directory [locale]");
143
                }
144

    
145
                appName = args[0];
146

    
147
                //Se crea el directorio de configuraci?n de la aplicaci?n
148
                File parent = new File(System.getProperty("user.home") +
149
                                File.separator + args[0] + File.separator);
150
                parent.mkdirs();
151

    
152
                andamiConfigPath = System.getProperty("user.home") + File.separator +
153
                        appName + File.separator + "andami-config.xml";
154
                pluginsPersistencePath = System.getProperty("user.home") +
155
                        File.separator + appName + File.separator +
156
                        "plugins-persistence.xml";
157

    
158
                // Configurar el log4j
159
                PropertyConfigurator.configure(Launcher.class.getClassLoader()
160
                                                                                                         .getResource("log4j.properties"));
161

    
162
                PatternLayout l = new PatternLayout("%p %t %C - %m%n");
163
                RollingFileAppender fa = new RollingFileAppender(l,
164
                                System.getProperty("user.home") + File.separator + args[0] +
165
                                File.separator + args[0] + ".log", false);
166
                fa.setMaxFileSize("512KB");
167
                fa.setMaxBackupIndex(3);
168
                Logger.getRootLogger().addAppender(fa);
169

    
170
                // Leer el fichero de configuraci?n de andami (andami-config.xsd)
171
                // locale
172
                // Buscar actualizaci?nes al comenzar
173
                //  Andami
174
                //  Plugins
175
                // Directorio de las extensiones
176
                andamiConfigFromXML(andamiConfigPath);
177
                andamiConfig.setPluginsDirectory(args[1]);
178

    
179
                // Configurar el locale
180
                if (args.length == 3) {
181
                        locale = new Locale(args[2]);
182
                } else {
183
                        locale = getLocale(andamiConfig.getLocaleLanguage(),
184
                                        andamiConfig.getLocaleCountry(),
185
                                        andamiConfig.getLocaleVariant());
186
                }
187

    
188
                Locale.setDefault(locale);
189
                JComponent.setDefaultLocale(locale);
190
                Messages.init(locale);
191

    
192
                //Se pone el lookAndFeel
193
                try {
194
                        UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
195
                } catch (Exception e) {
196
                        logger.warn(Messages.getString("Launcher.look_and_feel"), e);
197
                }
198

    
199
                // Mostrar la ventana de inicio
200
                splashWindow = new SplashWindow(null);
201

    
202
                // TODO Buscar actualizaciones de los plugins
203

    
204
                // Se leen los config.xml de los plugins -----++++
205
                loadPlugins(andamiConfig.getPluginsDirectory());
206

    
207
                // Se configura el classloader del plugin
208
                pluginsClassLoaders();
209

    
210
                // Se carga un Skin si alguno de los plugins trae informaci?n para ello
211
                skinPlugin();
212

    
213
                //Se configura la cola de eventos
214
                EventQueue waitQueue = new AndamiEventQueue();
215
                Toolkit.getDefaultToolkit().getSystemEventQueue().push(waitQueue);
216

    
217
                // Se configura la mensajer?a del plugin
218
                pluginsMessages();
219

    
220
                // Se modifica el andami-config con los plugins nuevos
221
                updateAndamiConfig();
222

    
223
                // Se prepara el MainFrame para albergar las extensiones
224
                frame = new MDIFrame();
225

    
226
                // Se configura el nombre e icono de la aplicaci?n
227
                frameIcon();
228

    
229
                SwingUtilities.invokeAndWait(new Runnable() {
230
                                public void run() {
231
                                        frame.init();
232
                                }
233
                        });
234

    
235
                // Se instalan los controles de las extensiones de los plugins
236
                SwingUtilities.invokeAndWait(new Runnable() {
237
                                public void run() {
238
                                        installPluginsControls();
239
                                        installPluginsMenus();
240
                                        installPluginsLabels();
241
                                }
242
                        });
243

    
244
                // Leer el fichero de persistencia
245
                //  info de los plugins
246
                //  bookmarks de los plugins
247
                loadPluginsPersistence();
248

    
249
                // Se instalan los controles del skin
250
                // Se inicializan todas las extensiones de todos los plugins
251
                SwingUtilities.invokeAndWait(new Runnable() {
252
                                public void run() {
253
                                        initializeExtensions();
254
                                }
255
                        });
256
                frame.setClassesExtensions(classesExtensions);
257

    
258
                // Se instalan los bookmarks de los plugins
259
                splashWindow.close();
260

    
261
                //Se muestra el frame principal
262
                frame.show();
263

    
264
                SwingUtilities.invokeAndWait(new Runnable() {
265
                                public void run() {
266
                                        frame.enableControls();
267
                                }
268
                        });
269
            }catch(Exception e){
270
                logger.error("excepci?n al arrancar", e);
271
                System.exit(-1);
272
            }
273
        }
274

    
275
        /**
276
     * @return
277
     */
278
    private static boolean validJVM() {
279
        char thirdCharacter = System.getProperty("java.version").charAt(2);
280
        if (thirdCharacter < '4'){
281
            return false;
282
            }else{
283
                return true;
284
            }
285
    }
286

    
287
    /**
288
         * DOCUMENT ME!
289
         *
290
         * @throws ConfigurationException
291
         */
292
        private static void loadPluginsPersistence() throws ConfigurationException {
293
                XMLEntity entity = persistenceFromXML();
294

    
295
                for (int i = 0; i < entity.getNumChild(); i++) {
296
                        XMLEntity plugin = entity.getChild(i);
297
                        String pName = plugin.getStringProperty(
298
                                        "com.iver.andami.pluginName");
299
                        if (pluginsServices.get(pName)!= null){
300
                                ((PluginServices) pluginsServices.get(pName)).setPersistentXML(plugin);
301
                        }
302
                }
303
        }
304

    
305
        /**
306
         * DOCUMENT ME!
307
         */
308
        private static void installPluginsLabels() {
309
                Iterator i = pluginsConfig.keySet().iterator();
310

    
311
                while (i.hasNext()) {
312
                        String name = (String) i.next();
313
                        PluginConfig pc = (PluginConfig) pluginsConfig.get(name);
314
                        PluginServices ps = (PluginServices) pluginsServices.get(name);
315

    
316
                        LabelSet[] ls = pc.getLabelSet();
317

    
318
                        for (int j = 0; j < ls.length; j++) {
319
                                PluginClassLoader loader = ps.getClassLoader();
320

    
321
                                try {
322
                                        Class clase = loader.loadClass(ls[j].getClassName());
323
                                        frame.setLabels(clase, ls[j].getLabel());
324
                                } catch (ClassNotFoundException e) {
325
                                        logger.error(Messages.getString("Launcher.labelset_class"),
326
                                                e);
327
                                }
328
                        }
329
                }
330
        }
331

    
332
        /**
333
         * DOCUMENT ME!
334
         *
335
         * @throws MDIManagerLoadException
336
         */
337
        private static void skinPlugin() throws MDIManagerLoadException {
338
                Iterator i = pluginsConfig.keySet().iterator();
339

    
340
                while (i.hasNext()) {
341
                        String name = (String) i.next();
342
                        PluginConfig pc = (PluginConfig) pluginsConfig.get(name);
343
                        PluginServices ps = (PluginServices) pluginsServices.get(name);
344

    
345
                        if (pc.getExtensions().getSkinExtension() != null) {
346
                                if (MDIManagerFactory.getSkinExtension() != null) {
347
                                        logger.warn(Messages.getString(
348
                                                        "Launcher.Dos_skin_extension"));
349
                                }
350

    
351
                                SkinExtension se = pc.getExtensions().getSkinExtension();
352

    
353
                                MDIManagerFactory.setSkinExtension(se, ps.getClassLoader());
354

    
355
                                Class skinClass;
356

    
357
                                try {
358
                                        skinClass = ps.getClassLoader().loadClass(se.getClassName());
359

    
360
                                        com.iver.andami.plugins.Extension skinInstance = (com.iver.andami.plugins.Extension) skinClass.newInstance();
361
                                        classesExtensions.put(skinClass, skinInstance);
362
                                } catch (ClassNotFoundException e) {
363
                                        logger.error(Messages.getString(
364
                                                        "Launcher.No_se_encontro_la_clase_mdi_manager"), e);
365
                                        throw new MDIManagerLoadException(e);
366
                                } catch (InstantiationException e) {
367
                                        logger.error(Messages.getString(
368
                                                        "Launcher.No_se_pudo_instanciar_la_clase_mdi_manager"),
369
                                                e);
370
                                        throw new MDIManagerLoadException(e);
371
                                } catch (IllegalAccessException e) {
372
                                        logger.error(Messages.getString(
373
                                                        "Launcher.No_se_pudo_acceder_a_la_clase_mdi_manager"),
374
                                                e);
375
                                        throw new MDIManagerLoadException(e);
376
                                }
377
                        }
378
                }
379
        }
380

    
381
        /**
382
         *
383
         */
384
        private static void frameIcon() {
385
                Iterator i = pluginsConfig.keySet().iterator();
386

    
387
                while (i.hasNext()) {
388
                        String pName = (String) i.next();
389
                        PluginConfig pc = (PluginConfig) pluginsConfig.get(pName);
390
                        PluginServices ps = (PluginServices) pluginsServices.get(pName);
391

    
392
                        if (pc.getIcon() != null) {
393
                                ImageIcon icon = new ImageIcon(ps.getClassLoader().getResource(pc.getIcon()
394
                                                                                                                                                                 .getSrc()));
395
                                frame.setIconImage(icon.getImage());
396
                                frame.setTitlePrefix(pc.getIcon().getText());
397
                        }
398
                }
399
        }
400

    
401
        /**
402
         *
403
         */
404
        private static void initializeExtensions() {
405
                Iterator i = pluginsConfig.keySet().iterator();
406

    
407
                while (i.hasNext()) {
408
                        String pName = (String) i.next();
409
                        PluginConfig pc = (PluginConfig) pluginsConfig.get(pName);
410
                        PluginServices ps = (PluginServices) pluginsServices.get(pName);
411

    
412
                        Extension[] exts = pc.getExtensions().getExtension();
413

    
414
                        TreeMap orderedExtensions = new TreeMap(new ExtensionComparator());
415

    
416
                        for (int j = 0; j < exts.length; j++) {
417
                                if (!exts[j].getActive()) {
418
                                        continue;
419
                                }
420

    
421
                                if (orderedExtensions.containsKey(exts[j])) {
422
                                        logger.warn(Messages.getString(
423
                                                        "Launcher.Two_extensions_with_the_same_priority") +
424
                                                exts[j].getClassName());
425
                                }
426

    
427
                                orderedExtensions.put(exts[j], null);
428
                        }
429

    
430
                        Iterator e = orderedExtensions.keySet().iterator();
431

    
432
                        while (e.hasNext()) {
433
                                Extension extension = (Extension) e.next();
434
                                com.iver.andami.plugins.Extension extensionInstance;
435

    
436
                                try {
437
                                        Class extensionClass = ps.getClassLoader().loadClass(extension.getClassName());
438
                                        extensionInstance = (com.iver.andami.plugins.Extension) extensionClass.newInstance();
439
                                        classesExtensions.put(extensionClass, extensionInstance);
440

    
441
                                        extensionInstance.inicializar();
442
                                } catch (InstantiationException e1) {
443
                                        logger.error(Messages.getString(
444
                                                        "Launcher.Error_instanciando_la_extension") +
445
                                                extension.getClassName(), e1);
446
                                } catch (IllegalAccessException e1) {
447
                                        logger.error(Messages.getString(
448
                                                        "Launcher.Error_instanciando_la_extension") +
449
                                                extension.getClassName(), e1);
450
                                } catch (ClassNotFoundException e1) {
451
                                        logger.error(Messages.getString(
452
                                                        "Launcher.No_se_encontro_la_clase_de_la_extension") +
453
                                                extension.getClassName(), e1);
454
                                } catch (NoClassDefFoundError e1) {
455
                                        logger.error(Messages.getString(
456
                                                        "Launcher.Error_localizando_la_clase_de_la_extension") +
457
                                                extension.getClassName(), e1);
458
                                }
459
                        }
460
                }
461
        }
462

    
463
        /**
464
         * DOCUMENT ME!
465
         */
466
        private static void installPluginsMenus() {
467
                TreeMap orderedMenus = new TreeMap(new MenuComparator());
468

    
469
                Iterator i = pluginsConfig.keySet().iterator();
470

    
471
                while (i.hasNext()) {
472
                        String pName = (String) i.next();
473
                        PluginServices ps = (PluginServices) pluginsServices.get(pName);
474
                        PluginConfig pc = (PluginConfig) pluginsConfig.get(pName);
475

    
476
                        Extension[] exts = pc.getExtensions().getExtension();
477

    
478
                        for (int j = 0; j < exts.length; j++) {
479
                                if (!exts[j].getActive()) {
480
                                        continue;
481
                                }
482

    
483
                                Menu[] menu = exts[j].getMenu();
484

    
485
                                for (int k = 0; k < menu.length; k++) {
486
                                        SortableMenu sm = new SortableMenu(ps.getClassLoader(),
487
                                                        exts[j], menu[k]);
488

    
489
                                        if (orderedMenus.containsKey(sm)) {
490
                                                logger.error(Messages.getString(
491
                                                                "Launcher.Two_menus_with_the_same_position") +
492
                                                        exts[j].getClassName());
493
                                        }
494

    
495
                                        orderedMenus.put(sm, null);
496
                                }
497
                        }
498

    
499
                        // Se instalan las extensiones de MDI
500
                        SkinExtension skinExt = pc.getExtensions().getSkinExtension();
501

    
502
                        if (skinExt != null) {
503
                                Menu[] menu = skinExt.getMenu();
504

    
505
                                for (int k = 0; k < menu.length; k++) {
506
                                        SortableMenu sm = new SortableMenu(ps.getClassLoader(),
507
                                                        skinExt, menu[k]);
508

    
509
                                        if (orderedMenus.containsKey(sm)) {
510
                                                logger.error(Messages.getString(
511
                                                                "Launcher.Two_menus_with_the_same_position") +
512
                                                        skinExt.getClassName());
513
                                        }
514

    
515
                                        orderedMenus.put(sm, null);
516
                                }
517
                        }
518
                }
519

    
520
                //Se itera por los menus ordenados
521
                Iterator e = orderedMenus.keySet().iterator();
522

    
523
                // Se ordenan los menues
524
                while (e.hasNext()) {
525
                        try {
526
                                SortableMenu sm = (SortableMenu) e.next();
527

    
528
                                frame.addMenu(sm.loader, sm.extension, sm.menu);
529
                        } catch (ClassNotFoundException ex) {
530
                                logger.error(Messages.getString(
531
                                                "Launcher.No_se_encontro_la_clase_de_la_extension"), ex);
532
                        }
533
                }
534
        }
535

    
536
        /**
537
         *
538
         */
539
        private static void installPluginsControls() {
540
                Iterator i = pluginsConfig.keySet().iterator();
541

    
542
                HashMap extensionPluginServices = new HashMap();
543
                HashMap extensionPluginConfig = new HashMap();
544
                TreeMap orderedExtensions = new TreeMap(new ExtensionComparator());
545
                while (i.hasNext()) {
546
                                String pName = (String) i.next();
547
                                PluginConfig pc = (PluginConfig) pluginsConfig.get(pName);
548
                                PluginServices ps = (PluginServices) pluginsServices.get(pName);
549

    
550
                                Extension[] exts = pc.getExtensions().getExtension();
551

    
552
                                for (int j = 0; j < exts.length; j++) {
553
                                        if (exts[j].getActive()) {
554
                                                if (orderedExtensions.containsKey(exts[j])) {
555
                                                        logger.error(Messages.getString(
556
                                                                        "Launcher.Two_extensions_with_the_same_priority") +
557
                                                                exts[j].getClassName());
558
                                                }
559

    
560
                                                orderedExtensions.put(exts[j], null);
561
                                                extensionPluginServices.put(exts[j], ps);
562
                                                extensionPluginConfig.put(exts[j], pc);
563
                                        }
564
                                }
565
                }
566

    
567
                try {
568
                        Iterator e = orderedExtensions.keySet().iterator();
569

    
570
                        // Se instalan las extensiones
571
                        while (e.hasNext()) {
572
                                Extension ext = (Extension) e.next();
573

    
574
                                ToolBar[] toolbars = ext.getToolBar();
575

    
576
                                for (int k = 0; k < toolbars.length; k++) {
577
                                        ActionTool[] tools = toolbars[k].getActionTool();
578

    
579
                                        for (int t = 0; t < tools.length; t++) {
580
                                                frame.addTool(((PluginServices)extensionPluginServices.get(ext)).getClassLoader(), ext,
581
                                                        toolbars[k], tools[t]);
582
                                        }
583

    
584
                                        SelectableTool[] sTools = toolbars[k].getSelectableTool();
585

    
586
                                        for (int t = 0; t < sTools.length; t++) {
587
                                                frame.addTool(((PluginServices)extensionPluginServices.get(ext)).getClassLoader(), ext,
588
                                                        toolbars[k], sTools[t]);
589
                                        }
590
                                }
591
                        }
592

    
593
                        i = pluginsConfig.keySet().iterator();
594
                        while (i.hasNext()) {
595
                                String pName = (String) i.next();
596
                                PluginConfig pc = (PluginConfig) pluginsConfig.get(pName);
597
                                PluginServices ps = (PluginServices) pluginsServices.get(pName);
598
                                // Se instalan las extensiones de MDI
599
                                SkinExtension skinExt = pc.getExtensions().getSkinExtension();
600
        
601
                                if (skinExt != null) {
602
                                        ToolBar[] toolbars = skinExt.getToolBar();
603
        
604
                                        for (int k = 0; k < toolbars.length; k++) {
605
                                                ActionTool[] tools = toolbars[k].getActionTool();
606
        
607
                                                for (int t = 0; t < tools.length; t++) {
608
                                                        frame.addTool(ps.getClassLoader(), skinExt,
609
                                                                toolbars[k], tools[t]);
610
                                                }
611
        
612
                                                SelectableTool[] sTools = toolbars[k].getSelectableTool();
613
        
614
                                                for (int t = 0; t < sTools.length; t++) {
615
                                                        frame.addTool(ps.getClassLoader(), skinExt,
616
                                                                toolbars[k], sTools[t]);
617
                                                }
618
                                        }
619
        
620
                                        /*
621
                                           Menu[] menu = skinExt.getMenu();
622
                                           for (int k = 0; k < menu.length; k++) {
623
                                               frame.addMenu(ps.getClassLoader(), skinExt, menu[k]);
624
                                           }
625
                                         */
626
                                }
627
                                //Se instalan los popup menus
628
                                PopupMenus pus = pc.getPopupMenus();
629

    
630
                                if (pus != null) {
631
                                        PopupMenu[] menus = pus.getPopupMenu();
632

    
633
                                        for (int j = 0; j < menus.length; j++) {
634
                                                frame.addPopupMenu(ps.getClassLoader(), menus[j]);
635
                                        }
636
                                }
637
                        }
638
                } catch (ClassNotFoundException e) {
639
                        logger.error(Messages.getString(
640
                                        "Launcher.No_se_encontro_la_clase_de_la_extension"), e);
641
                }
642
        }
643

    
644
        /**
645
         *
646
         */
647
        private static void updateAndamiConfig() {
648
                HashSet olds = new HashSet();
649

    
650
                Plugin[] plugins = andamiConfig.getPlugin();
651

    
652
                for (int i = 0; i < plugins.length; i++) {
653
                        olds.add(plugins[i].getName());
654
                }
655

    
656
                Iterator i = pluginsServices.values().iterator();
657

    
658
                while (i.hasNext()) {
659
                        PluginServices ps = (PluginServices) i.next();
660

    
661
                        if (!olds.contains(ps.getPluginName())) {
662
                                Plugin p = new Plugin();
663
                                p.setName(ps.getPluginName());
664
                                p.setUpdate(false);
665

    
666
                                andamiConfig.addPlugin(p);
667
                        }
668
                }
669
        }
670

    
671
        /**
672
         * DOCUMENT ME!
673
         */
674
        private static void pluginsClassLoaders() {
675
                HashSet instalados = new HashSet();
676

    
677
                // Se itera hasta que est?n todos instalados
678
                while (instalados.size() != pluginsConfig.size()) {
679
                        boolean circle = true;
680

    
681
                        //Hacemos una pasada por todos los plugins
682
                        Iterator i = pluginsConfig.keySet().iterator();
683

    
684
                        while (i.hasNext()) {
685
                                String pluginName = (String) i.next();
686
                                PluginConfig config = (PluginConfig) pluginsConfig.get(pluginName);
687

    
688
                                if (instalados.contains(pluginName)) {
689
                                        continue;
690
                                }
691

    
692
                                //Se obtienen las dependencias y sus class loaders
693
                                boolean ready = true;
694
                                Depends[] dependencies = config.getDepends();
695
                                PluginClassLoader[] loaders = new PluginClassLoader[dependencies.length];
696

    
697
                                for (int j = 0; j < dependencies.length; j++) {
698
                                        if (pluginsConfig.get(dependencies[j].getPluginName()) == null) {
699
                                                logger.error(Messages.getString(
700
                                                                "Launcher.Dependencia_no_resuelta_en_plugin") +
701
                                                        pluginName + ": " +
702
                                                        dependencies[j].getPluginName());
703

    
704
                                                continue;
705
                                        }
706

    
707
                                        if (!instalados.contains(dependencies[j].getPluginName())) {
708
                                                ready = false;
709
                                        } else {
710
                                                loaders[j] = ((PluginServices) pluginsServices.get(dependencies[j].getPluginName())).getClassLoader();
711
                                        }
712
                                }
713

    
714
                                //Si no est?n sus dependencias satisfechas se aborta la instalaci?n
715
                                if (!ready) {
716
                                        continue;
717
                                }
718

    
719
                                //Se genera el class loader
720
                                String jardir = config.getLibraries().getLibraryDir();
721
                                File jarDir = new File(andamiConfig.getPluginsDirectory() +
722
                                                File.separator + pluginName + File.separator + jardir);
723
                                File[] jarFiles = jarDir.listFiles(new FileFilter() {
724
                                                        public boolean accept(File pathname) {
725
                                                                return (pathname.getName().toUpperCase()
726
                                                                                                .endsWith(".JAR")) ||
727
                                                                (pathname.getName().toUpperCase().endsWith(".ZIP"));
728
                                                        }
729
                                                });
730

    
731
                                URL[] urls = new URL[jarFiles.length];
732

    
733
                                for (int j = 0; j < jarFiles.length; j++) {
734
                                        try {
735
                                                urls[j] = new URL("file:" + jarFiles[j]);
736
                                        } catch (MalformedURLException e) {
737
                                                logger.error(Messages.getString(
738
                                                                "Launcher.No_se_puede_acceder_a") +
739
                                                        jarFiles[j]);
740
                                        }
741
                                }
742

    
743
                                PluginClassLoader loader;
744

    
745
                                try {
746
                                        loader = new PluginClassLoader(urls,
747
                                                        andamiConfig.getPluginsDirectory() +
748
                                                        File.separator + pluginName,
749
                                                        Launcher.class.getClassLoader(), loaders);
750

    
751
                                        PluginServices ps = new PluginServices(loader);
752

    
753
                                        pluginsServices.put(ps.getPluginName(), ps);
754

    
755
                                        instalados.add(pluginName);
756

    
757
                                        circle = false;
758
                                } catch (IOException e) {
759
                                        logger.error(Messages.getString(
760
                                                        "Launcher.Error_con_las_librerias_del_plugin"), e);
761
                                        pluginsConfig.remove(pluginName);
762
                                        i = pluginsConfig.keySet().iterator();
763
                                }
764
                        }
765

    
766
                        if (circle) {
767
                                logger.error(Messages.getString(
768
                                                "Launcher.Hay_dependencias_circulares"));
769

    
770
                                break;
771
                        }
772
                }
773

    
774
                //Se eliminan los plugins que no fueron instalados
775
                Iterator i = pluginsConfig.keySet().iterator();
776

    
777
                while (i.hasNext()) {
778
                        String pluginName = (String) i.next();
779
                        PluginConfig config = (PluginConfig) pluginsConfig.get(pluginName);
780
                        PluginServices ps = (PluginServices) pluginsServices.get(pluginName);
781

    
782
                        if (ps == null) {
783
                                pluginsConfig.remove(pluginName);
784
                                i = pluginsConfig.keySet().iterator();
785
                        }
786
                }
787
        }
788

    
789
        /**
790
         * DOCUMENT ME!
791
         */
792
        private static void pluginsMessages() {
793
                //Iteramos por todos los plugins
794
                Iterator i = pluginsConfig.keySet().iterator();
795

    
796
                while (i.hasNext()) {
797
                        String pluginName = (String) i.next();
798
                        PluginConfig config = (PluginConfig) pluginsConfig.get(pluginName);
799

    
800
                        PluginServices ps = (PluginServices) pluginsServices.get(pluginName);
801

    
802
                        if (config.getResourceBundle() != null) {
803
                                ps.setResourceBundle(config.getResourceBundle().getName(),
804
                                        locale);
805
                        }
806
                }
807
        }
808

    
809
        /**
810
         * DOCUMENT ME!
811
         *
812
         * @param name DOCUMENT ME!
813
         *
814
         * @return DOCUMENT ME!
815
         */
816
        static PluginServices getPluginServices(String name) {
817
                return (PluginServices) pluginsServices.get(name);
818
        }
819

    
820
        /**
821
         * DOCUMENT ME!
822
         *
823
         * @return DOCUMENT ME!
824
         */
825
        static String getPluginsDir() {
826
                return andamiConfig.getPluginsDirectory();
827
        }
828

    
829
        /**
830
         * DOCUMENT ME!
831
         *
832
         * @param s DOCUMENT ME!
833
         */
834
        static void setPluginsDir(String s) {
835
                andamiConfig.setPluginsDirectory(s);
836
        }
837

    
838
        /**
839
         * DOCUMENT ME!
840
         *
841
         * @return DOCUMENT ME!
842
         */
843
        static MDIFrame getMDIFrame() {
844
                return frame;
845
        }
846

    
847
        /**
848
         * DOCUMENT ME!
849
         *
850
         * @param pluginsDirectory
851
         */
852
        private static void loadPlugins(String pluginsDirectory) {
853
                File pDir = new File(pluginsDirectory);
854

    
855
                if (!pDir.exists()) {
856
                        return;
857
                }
858

    
859
                File[] pluginDirs = pDir.listFiles();
860

    
861
                for (int i = 0; i < pluginDirs.length; i++) {
862
                        if (pluginDirs[i].isDirectory()) {
863
                                File configXml = new File(pluginDirs[i].getAbsolutePath() +
864
                                                File.separator + "config.xml");
865

    
866
                                try {
867
                                        FileReader xml = new FileReader(configXml);
868
                                        PluginConfig pConfig = (PluginConfig) PluginConfig.unmarshal(xml);
869
                                        pluginsConfig.put(pluginDirs[i].getName(), pConfig);
870
                                } catch (FileNotFoundException e) {
871
                                        logger.info(Messages.getString(
872
                                                        "Launcher.Ignorando_el_directorio") +
873
                                                pluginDirs[i].getAbsolutePath() +
874
                                                Messages.getString("Launcher.config_no_encontrado"));
875
                                } catch (MarshalException e) {
876
                                        logger.info(Messages.getString(
877
                                                        "Launcher.Ignorando_el_directorio") +
878
                                                pluginDirs[i].getAbsolutePath() +
879
                                                Messages.getString("Launcher.config_mal_formado"), e);
880
                                } catch (ValidationException e) {
881
                                        logger.info(Messages.getString(
882
                                                        "Launcher.Ignorando_el_directorio") +
883
                                                pluginDirs[i].getAbsolutePath() +
884
                                                Messages.getString("Launcher.config_mal_formado"), e);
885
                                }
886
                        }
887
                }
888
        }
889

    
890
        /**
891
         * DOCUMENT ME!
892
         *
893
         * @param language
894
         * @param country
895
         * @param variant
896
         *
897
         * @return DOCUMENT ME!
898
         */
899
        private static Locale getLocale(String language, String country,
900
                String variant) {
901
                if (variant != null) {
902
                        return new Locale(language, country, variant);
903
                } else if (country != null) {
904
                        return new Locale(language, country);
905
                } else if (language != null) {
906
                        return new Locale(language);
907
                } else {
908
                        return new Locale("es");
909
                }
910
        }
911

    
912
        /**
913
         * DOCUMENT ME!
914
         *
915
         * @param file DOCUMENT ME!
916
         *
917
         * @throws IOException DOCUMENT ME!
918
         * @throws MarshalException DOCUMENT ME!
919
         * @throws ValidationException DOCUMENT ME!
920
         */
921
        private static void andamiConfigToXML(String file)
922
                throws IOException, MarshalException, ValidationException {
923
                File xml = new File(file);
924
                File parent = xml.getParentFile();
925
                parent.mkdirs();
926

    
927
                FileWriter writer = new FileWriter(xml);
928
                andamiConfig.marshal(writer);
929
        }
930

    
931
        /**
932
         * DOCUMENT ME!
933
         *
934
         * @param file DOCUMENT ME!
935
         *
936
         * @throws ConfigurationException DOCUMENT ME!
937
         */
938
        private static void andamiConfigFromXML(String file)
939
                throws ConfigurationException {
940
                File xml = new File(file);
941

    
942
                //Si no existe se ponen los valores por defecto
943
                if (!xml.exists()) {
944
                        andamiConfig = new AndamiConfig();
945

    
946
                        Andami andami = new Andami();
947
                        andami.setUpdate(true);
948
                        andamiConfig.setAndami(andami);
949
                        andamiConfig.setLocaleCountry(Locale.getDefault().getCountry());
950
                        andamiConfig.setLocaleLanguage(Locale.getDefault().getLanguage());
951
                        andamiConfig.setLocaleVariant(Locale.getDefault().getVariant());
952

    
953
                        if (System.getProperty("javawebstart.version") != null) // Es java web start)
954
                         {
955
                                andamiConfig.setPluginsDirectory(new File(System.getProperty(
956
                                                        "user.home") + File.separator + appName +
957
                                                File.separator + "extensiones").getAbsolutePath());
958
                        } else {
959
                                andamiConfig.setPluginsDirectory(new File(appName +
960
                                                File.separator + "extensiones").getAbsolutePath());
961
                        }
962

    
963
                        andamiConfig.setPlugin(new Plugin[0]);
964
                } else {
965
                        //Se lee la configuraci?n
966
                        FileReader reader;
967

    
968
                        try {
969
                                reader = new FileReader(xml);
970
                                andamiConfig = (AndamiConfig) AndamiConfig.unmarshal(reader);
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
                }
979
        }
980

    
981
        /**
982
         * DOCUMENT ME!
983
         *
984
         * @return DOCUMENT ME!
985
         *
986
         * @throws ConfigurationException DOCUMENT ME!
987
         */
988
        private static XMLEntity persistenceFromXML() throws ConfigurationException {
989
                File xml = new File(pluginsPersistencePath);
990

    
991
                if (xml.exists()) {
992
                        FileReader reader;
993

    
994
                        try {
995
                                reader = new FileReader(xml);
996

    
997
                                XmlTag tag = (XmlTag) XmlTag.unmarshal(reader);
998

    
999
                                return new XMLEntity(tag);
1000
                        } catch (FileNotFoundException e) {
1001
                                throw new ConfigurationException(e);
1002
                        } catch (MarshalException e) {
1003
                                throw new ConfigurationException(e);
1004
                        } catch (ValidationException e) {
1005
                                throw new ConfigurationException(e);
1006
                        }
1007
                } else {
1008
                        return new XMLEntity();
1009
                }
1010
        }
1011

    
1012
        /**
1013
         * DOCUMENT ME!
1014
         *
1015
         * @param entity DOCUMENT ME!
1016
         *
1017
         * @throws ConfigurationException DOCUMENT ME!
1018
         */
1019
        private static void persistenceToXML(XMLEntity entity)
1020
                throws ConfigurationException {
1021
                File xml = new File(pluginsPersistencePath);
1022

    
1023
                FileWriter writer;
1024

    
1025
                try {
1026
                        writer = new FileWriter(xml);
1027
                        entity.getXmlTag().marshal(writer);
1028
                } catch (FileNotFoundException e) {
1029
                        throw new ConfigurationException(e);
1030
                } catch (MarshalException e) {
1031
                        throw new ConfigurationException(e);
1032
                } catch (ValidationException e) {
1033
                        throw new ConfigurationException(e);
1034
                } catch (IOException e) {
1035
                        throw new ConfigurationException(e);
1036
                }
1037
        }
1038

    
1039
        /**
1040
         * Devuelve un array con los directorios de los plugins
1041
         *
1042
         * @param dirExt Directorio de las extensiones a partir del cual cuelgan
1043
         *                   todos los directorios de los plugins
1044
         *
1045
         * @return ArrayList con los directorios
1046
         */
1047
        private String[] getLocales(File dirExt) {
1048
                ArrayList types = new ArrayList();
1049
                File[] files = dirExt.listFiles();
1050

    
1051
                for (int i = 0; i < files.length; i++) {
1052
                        if (files[i].isDirectory()) {
1053
                                File[] textFile = files[i].listFiles(new FilenameFilter() {
1054
                                                        public boolean accept(File dir, String fileName) {
1055
                                                                return fileName.toLowerCase().startsWith("text_"); //$NON-NLS-1$
1056
                                                        }
1057
                                                });
1058

    
1059
                                for (int j = 0; j < textFile.length; j++) {
1060
                                        String s = (textFile[j]).getName().replaceAll("text_", "");
1061
                                        s = s.replaceAll(".properties", "");
1062
                                        s = s.trim();
1063

    
1064
                                        if (!types.contains(s)) {
1065
                                                types.add(s);
1066
                                        }
1067
                                }
1068
                        }
1069
                }
1070

    
1071
                return (String[]) types.toArray(new String[0]);
1072
        }
1073

    
1074
        /**
1075
         * DOCUMENT ME!
1076
         *
1077
         * @return Returns the frame.
1078
         */
1079
        static MDIFrame getFrame() {
1080
                return frame;
1081
        }
1082

    
1083
        /**
1084
         * Secuencia de cerrado de Andami
1085
         */
1086
        public static void closeApplication() {
1087
                //Configuraci?n de Andami
1088
                try {
1089
                        andamiConfigToXML(andamiConfigPath);
1090
                } catch (MarshalException e) {
1091
                        logger.error(Messages.getString(
1092
                                        "Launcher.No_se_pudo_guardar_la_configuracion_de_andami"), e);
1093
                } catch (ValidationException e) {
1094
                        logger.error(Messages.getString(
1095
                                        "Launcher.No_se_pudo_guardar_la_configuracion_de_andami"), e);
1096
                } catch (IOException e) {
1097
                        logger.error(Messages.getString(
1098
                                        "Launcher.No_se_pudo_guardar_la_configuracion_de_andami"), e);
1099
                }
1100

    
1101
                //Persistencia de los plugins
1102
                Iterator i = pluginsConfig.keySet().iterator();
1103

    
1104
                XMLEntity entity = new XMLEntity();
1105

    
1106
                while (i.hasNext()) {
1107
                        String pName = (String) i.next();
1108
                        PluginServices ps = (PluginServices) pluginsServices.get(pName);
1109
                        XMLEntity ent = ps.getPersistentXML();
1110

    
1111
                        if (ent != null) {
1112
                                ent.putProperty("com.iver.andami.pluginName", pName);
1113
                                entity.addChild(ent);
1114
                        }
1115
                }
1116

    
1117
                try {
1118
                        persistenceToXML(entity);
1119
                } catch (ConfigurationException e1) {
1120
                        logger.error(Messages.getString(
1121
                                        "Launcher.Se_produjo_un_error_guardando_la_configuracion_de_los_plugins"),
1122
                                e1);
1123
                }
1124

    
1125
                //Para la depuraci?n de memory leaks
1126
                System.gc();
1127

    
1128
        System.exit(0);
1129
        }
1130

    
1131
        /**
1132
         * DOCUMENT ME!
1133
         *
1134
         * @return DOCUMENT ME!
1135
         */
1136
        static HashMap getClassesExtensions() {
1137
                return classesExtensions;
1138
        }
1139

    
1140
        /**
1141
         * DOCUMENT ME!
1142
         *
1143
         * @return DOCUMENT ME!
1144
         */
1145
        private static Extensions[] getExtensions() {
1146
                ArrayList array = new ArrayList();
1147
                Iterator iter = pluginsConfig.values().iterator();
1148

    
1149
                while (iter.hasNext()) {
1150
                        array.add(((PluginConfig) iter.next()).getExtensions());
1151
                }
1152

    
1153
                return (Extensions[]) array.toArray(new Extensions[0]);
1154
        }
1155

    
1156
        /**
1157
         * DOCUMENT ME!
1158
         *
1159
         * @return DOCUMENT ME!
1160
         */
1161
        public static HashMap getPluginConfig() {
1162
                return pluginsConfig;
1163
        }
1164

    
1165
        /**
1166
         * DOCUMENT ME!
1167
         *
1168
         * @param s DOCUMENT ME!
1169
         *
1170
         * @return DOCUMENT ME!
1171
         */
1172
        public static Extension getExtension(String s) {
1173
                Extensions[] exts = getExtensions();
1174

    
1175
                for (int i = 0; i < exts.length; i++) {
1176
                        for (int j = 0; j < exts[i].getExtensionCount(); j++) {
1177
                                if (exts[i].getExtension(j).getClassName().equals(s)) {
1178
                                        return exts[i].getExtension(j);
1179
                                }
1180
                        }
1181
                }
1182

    
1183
                return null;
1184
        }
1185

    
1186
        /**
1187
         * DOCUMENT ME!
1188
         *
1189
         * @return DOCUMENT ME!
1190
         */
1191
        public static AndamiConfig getAndamiConfig() {
1192
                return andamiConfig;
1193
        }
1194

    
1195
        /**
1196
         * DOCUMENT ME!
1197
         *
1198
         * @author $author$
1199
         * @version $Revision: 2291 $
1200
         */
1201
        private static class ExtensionComparator implements Comparator {
1202
                /**
1203
                 * DOCUMENT ME!
1204
                 *
1205
                 * @param o1 DOCUMENT ME!
1206
                 * @param o2 DOCUMENT ME!
1207
                 *
1208
                 * @return DOCUMENT ME!
1209
                 */
1210
                public int compare(Object o1, Object o2) {
1211
                        Extension e1 = (Extension) o1;
1212
                        Extension e2 = (Extension) o2;
1213

    
1214
                        if (!e1.hasPriority() && !e2.hasPriority()) {
1215
                                return -1;
1216
                        }
1217

    
1218
                        if (e1.hasPriority() && !e2.hasPriority()) {
1219
                                return -Integer.MAX_VALUE;
1220
                        }
1221

    
1222
                        if (e2.hasPriority() && !e1.hasPriority()) {
1223
                                return Integer.MAX_VALUE;
1224
                        }
1225

    
1226
                        if (e1.getPriority() != e2.getPriority()){
1227
                                return e2.getPriority() - e1.getPriority();
1228
                        }else{
1229
                                return (e2.toString().compareTo(e1.toString()));
1230
                        }
1231
                }
1232
        }
1233

    
1234
        /**
1235
         * DOCUMENT ME!
1236
         */
1237
        private static class MenuComparator implements Comparator {
1238
                private static ExtensionComparator extComp = new ExtensionComparator();
1239

    
1240
                /**
1241
                 * DOCUMENT ME!
1242
                 *
1243
                 * @param o1 DOCUMENT ME!
1244
                 * @param o2 DOCUMENT ME!
1245
                 *
1246
                 * @return DOCUMENT ME!
1247
                 */
1248
                public int compare(Object o1, Object o2) {
1249
                        SortableMenu e1 = (SortableMenu) o1;
1250
                        SortableMenu e2 = (SortableMenu) o2;
1251

    
1252
                        if (!e1.menu.hasPosition() && !e2.menu.hasPosition()) {
1253
                                if (e1.extension instanceof SkinExtensionType) {
1254
                                        return 1;
1255
                                } else if (e2.extension instanceof SkinExtensionType) {
1256
                                        return -1;
1257
                                } else {
1258
                                        return extComp.compare(e1.extension, e2.extension);
1259
                                }
1260
                        }
1261

    
1262
                        if (e1.menu.hasPosition() && !e2.menu.hasPosition()) {
1263
                                return -Integer.MAX_VALUE;
1264
                        }
1265

    
1266
                        if (e2.menu.hasPosition() && !e1.menu.hasPosition()) {
1267
                                return Integer.MAX_VALUE;
1268
                        }
1269

    
1270
                        return e1.menu.getPosition() - e2.menu.getPosition();
1271
                }
1272
        }
1273

    
1274
        /**
1275
         * DOCUMENT ME!
1276
         *
1277
         * @author $author$
1278
         * @version $Revision: 2291 $
1279
         */
1280
        private static class SortableMenu {
1281
                public PluginClassLoader loader;
1282
                public Menu menu;
1283
                public SkinExtensionType extension;
1284

    
1285
                /**
1286
                 * DOCUMENT ME!
1287
                 *
1288
                 * @param loader DOCUMENT ME!
1289
                 * @param skinExt
1290
                 * @param menu2
1291
                 */
1292
                public SortableMenu(PluginClassLoader loader,
1293
                        SkinExtensionType skinExt, Menu menu2) {
1294
                        extension = skinExt;
1295
                        menu = menu2;
1296
                        this.loader = loader;
1297
                }
1298
        }
1299
}