Statistics
| Revision:

root / trunk / frameworks / _fwAndami / src / com / iver / andami / Launcher.java @ 665

History | View | Annotate | Download (35.4 KB)

1
package com.iver.andami;
2

    
3
import com.iver.andami.config.generate.Andami;
4
import com.iver.andami.config.generate.AndamiConfig;
5
import com.iver.andami.config.generate.Plugin;
6
import com.iver.andami.messages.Messages;
7
import com.iver.andami.plugins.PluginClassLoader;
8
import com.iver.andami.plugins.config.generate.ActionTool;
9
import com.iver.andami.plugins.config.generate.Depends;
10
import com.iver.andami.plugins.config.generate.Extension;
11
import com.iver.andami.plugins.config.generate.LabelSet;
12
import com.iver.andami.plugins.config.generate.Library;
13
import com.iver.andami.plugins.config.generate.Menu;
14
import com.iver.andami.plugins.config.generate.PluginConfig;
15
import com.iver.andami.plugins.config.generate.PopupMenu;
16
import com.iver.andami.plugins.config.generate.PopupMenus;
17
import com.iver.andami.plugins.config.generate.SelectableTool;
18
import com.iver.andami.plugins.config.generate.SkinExtension;
19
import com.iver.andami.plugins.config.generate.SkinExtensionType;
20
import com.iver.andami.plugins.config.generate.ToolBar;
21
import com.iver.andami.ui.MDIManagerLoadException;
22
import com.iver.andami.ui.SplashWindow;
23
import com.iver.andami.ui.WaitCursorEventQueue;
24
import com.iver.andami.ui.mdiFrame.MDIFrame;
25
import com.iver.andami.ui.mdiManager.MDIManagerFactory;
26

    
27
import com.iver.utiles.XMLEntity;
28
import com.iver.utiles.xmlEntity.generate.XmlTag;
29

    
30
import org.apache.log4j.Logger;
31
import org.apache.log4j.PropertyConfigurator;
32

    
33
import org.exolab.castor.xml.MarshalException;
34
import org.exolab.castor.xml.ValidationException;
35

    
36
import java.awt.EventQueue;
37
import java.awt.Toolkit;
38

    
39
import java.io.File;
40
import java.io.FileNotFoundException;
41
import java.io.FileReader;
42
import java.io.FileWriter;
43
import java.io.FilenameFilter;
44
import java.io.IOException;
45

    
46
import java.lang.reflect.InvocationTargetException;
47

    
48
import java.net.MalformedURLException;
49
import java.net.URL;
50

    
51
import java.util.ArrayList;
52
import java.util.Comparator;
53
import java.util.HashMap;
54
import java.util.HashSet;
55
import java.util.Iterator;
56
import java.util.Locale;
57
import java.util.TreeMap;
58

    
59
import javax.swing.ImageIcon;
60
import javax.swing.JComponent;
61
import javax.swing.SwingUtilities;
62
import javax.swing.UIManager;
63

    
64

    
65
/**
66
 * DOCUMENT ME!
67
 *
68
 * @author $author$
69
 * @version $Revision: 665 $
70
 */
71
public class Launcher {
72
    private static Logger logger = Logger.getLogger(Launcher.class.getName());
73
    private static AndamiConfig andamiConfig;
74
    private static SplashWindow splashWindow;
75
    private static String userHome = System.getProperty("user.home");
76
    private static String appName;
77
    private static Locale locale;
78
    private static HashMap pluginsConfig = new HashMap();
79
    private static HashMap pluginsServices = new HashMap();
80
    private static MDIFrame frame;
81
    private static HashMap classesExtensions = new HashMap();
82
    private static String andamiConfigPath;
83
    private static String pluginsPersistencePath;
84

    
85
    /**
86
     * DOCUMENT ME!
87
     *
88
     * @param args DOCUMENT ME!
89
     *
90
     * @throws InterruptedException
91
     * @throws InvocationTargetException
92
     * @throws ConfigurationException
93
     * @throws MDIManagerLoadException
94
     */
95
    public static void main(String[] args)
96
        throws InterruptedException, InvocationTargetException, 
97
            ConfigurationException, MDIManagerLoadException {
98
        if (args.length != 1) {
99
            System.err.println("Uso: Launcher appName");
100
        }
101

    
102
        appName = args[0];
103

    
104
        andamiConfigPath = userHome + File.separator + appName +
105
            File.separator + "andami-config.xml";
106
        pluginsPersistencePath = userHome + File.separator + appName +
107
            File.separator + "plugins-persistence.xml";
108

    
109
        // Configurar el log4j
110
        PropertyConfigurator.configure(Launcher.class.getClassLoader()
111
                                                     .getResource("log4j.properties"));
112

    
113
        // Leer el fichero de configuraci?n de andami (andami-config.xsd)
114
        // locale
115
        // Buscar actualizaci?nes al comenzar
116
        //  Andami
117
        //  Plugins
118
        // Directorio de las extensiones
119
        andamiConfigFromXML(andamiConfigPath);
120

    
121
        // Configurar el locale
122
        locale = getLocale(andamiConfig.getLocaleLanguage(),
123
                andamiConfig.getLocaleCountry(), andamiConfig.getLocaleVariant());
124
        Locale.setDefault(locale);
125
        JComponent.setDefaultLocale(locale);
126
        Messages.init(locale);
127
        try {
128
                        UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
129
                        // UIManager.setLookAndFeel("com.iver.WindowsLookAndFeel.WindowsLookAndFeel");
130
        } catch (Exception e) {
131
            logger.warn("No se pudo poner el look and feel", e);
132
        }
133

    
134
        // Mostrar la ventana de inicio
135
        splashWindow = new SplashWindow(null);
136

    
137
        // TODO Buscar actualizaciones de Andami
138
        // TODO Buscar actualizaciones de los plugins
139
        // Se leen los config.xml de los plugins -----++++
140
        loadPlugins(andamiConfig.getPluginsDirectory());
141

    
142
        // Se configura el classloader del plugin
143
        pluginsClassLoaders();
144

    
145
        // Se carga un Skin si alguno de los plugins trae informaci?n para ello
146
        skinPlugin();
147

    
148
        //Se configura la cola de eventos
149
        EventQueue waitQueue = new WaitCursorEventQueue(MDIManagerFactory.createManager(),
150
                100);
151
        Toolkit.getDefaultToolkit().getSystemEventQueue().push(waitQueue);
152

    
153
        // Se configura la mensajer?a del plugin
154
        pluginsMessages();
155

    
156
        // Se modifica el andami-config con los plugins nuevos
157
        updateAndamiConfig();
158

    
159
        // Se prepara el MainFrame para albergar las extensiones
160
        frame = new MDIFrame();
161

    
162
        // Se configura el nombre e icono de la aplicaci?n
163
        frameIcon();
164

    
165
        SwingUtilities.invokeAndWait(new Runnable() {
166
                public void run() {
167
                    frame.init();
168
                }
169
            });
170

    
171
        // Se instalan los controles de las extensiones de los plugins
172
        SwingUtilities.invokeAndWait(new Runnable() {
173
                public void run() {
174
                    installPluginsControls();
175
                    installPluginsMenus();
176
                    installPluginsLabels();
177
                }
178
            });
179

    
180
        // Leer el fichero de persistencia
181
        //  info de los plugins
182
        //  bookmarks de los plugins
183
        loadPluginsPersistence();
184

    
185
        // Se instalan los controles del skin
186
        // Se inicializan todas las extensiones de todos los plugins
187
        SwingUtilities.invokeAndWait(new Runnable() {
188
                        public void run() {
189
                        initializeExtensions();
190
                        }
191
                });
192
        frame.setClassesExtensions(classesExtensions);
193

    
194
        // Se instalan los bookmarks de los plugins
195
        splashWindow.close();
196

    
197
        //Se muestra el frame principal
198
        frame.show();
199
        
200
        SwingUtilities.invokeAndWait(new Runnable() {
201
                        public void run() {
202
                                frame.enableControls();
203
                        }
204
                });
205
    }
206

    
207
    /**
208
     * DOCUMENT ME!
209
     *
210
     * @throws ConfigurationException
211
     */
212
    private static void loadPluginsPersistence() throws ConfigurationException {
213
        XMLEntity entity = persistenceFromXML();
214

    
215
        for (int i = 0; i < entity.getNumChild(); i++) {
216
            XMLEntity plugin = entity.getChild(i);
217
            String pName = plugin.getStringProperty(
218
                    "com.iver.andami.pluginName");
219
            ((PluginServices) pluginsServices.get(pName)).setPresistentXML(plugin);
220
        }
221
    }
222

    
223
    /**
224
     * DOCUMENT ME!
225
     */
226
    private static void installPluginsLabels() {
227
        Iterator i = pluginsConfig.keySet().iterator();
228

    
229
        while (i.hasNext()) {
230
            String name = (String) i.next();
231
            PluginConfig pc = (PluginConfig) pluginsConfig.get(name);
232
            PluginServices ps = (PluginServices) pluginsServices.get(name);
233

    
234
            LabelSet[] ls = pc.getLabelSet();
235

    
236
            for (int j = 0; j < ls.length; j++) {
237
                PluginClassLoader loader = ps.getClassLoader();
238

    
239
                try {
240
                    Class clase = loader.loadClass(ls[j].getClassName());
241
                    frame.setLabels(clase, ls[j].getLabel());
242
                } catch (ClassNotFoundException e) {
243
                    logger.error("No se pudo encontrar la clase de la labelset",
244
                        e);
245
                }
246
            }
247
        }
248
    }
249

    
250
    /**
251
     * DOCUMENT ME!
252
     *
253
     * @throws MDIManagerLoadException
254
     */
255
    private static void skinPlugin() throws MDIManagerLoadException {
256
        Iterator i = pluginsConfig.keySet().iterator();
257

    
258
        while (i.hasNext()) {
259
            String name = (String) i.next();
260
            PluginConfig pc = (PluginConfig) pluginsConfig.get(name);
261
            PluginServices ps = (PluginServices) pluginsServices.get(name);
262

    
263
            if (pc.getExtensions().getSkinExtension() != null) {
264
                if (MDIManagerFactory.getSkinExtension() != null) {
265
                    logger.error("Dos skin-extension. Usamos el ?ltimo");
266
                }
267

    
268
                SkinExtension se = pc.getExtensions().getSkinExtension();
269

    
270
                MDIManagerFactory.setSkinExtension(se, ps.getClassLoader());
271

    
272
                Class skinClass;
273

    
274
                try {
275
                    skinClass = ps.getClassLoader().loadClass(se.getClassName());
276

    
277
                    com.iver.andami.plugins.Extension skinInstance = (com.iver.andami.plugins.Extension) skinClass.newInstance();
278
                    classesExtensions.put(skinClass, skinInstance);
279
                } catch (ClassNotFoundException e) {
280
                    logger.error("No se pudo instanciar la clase mdi manager", e);
281
                    throw new MDIManagerLoadException(e);
282
                } catch (InstantiationException e) {
283
                    logger.error("No se pudo instanciar la clase mdi manager", e);
284
                    throw new MDIManagerLoadException(e);
285
                } catch (IllegalAccessException e) {
286
                    logger.error("No se pudo instanciar la clase mdi manager", e);
287
                    throw new MDIManagerLoadException(e);
288
                }
289
            }
290
        }
291
    }
292

    
293
    /**
294
     *
295
     */
296
    private static void frameIcon() {
297
        Iterator i = pluginsConfig.keySet().iterator();
298

    
299
        while (i.hasNext()) {
300
            String pName = (String) i.next();
301
            PluginConfig pc = (PluginConfig) pluginsConfig.get(pName);
302
            PluginServices ps = (PluginServices) pluginsServices.get(pName);
303

    
304
            if (pc.getIcon() != null) {
305
                ImageIcon icon = new ImageIcon(ps.getClassLoader().getResource(pc.getIcon()
306
                                                                                 .getSrc()));
307
                frame.setIconImage(icon.getImage());
308
                frame.setTitle(pc.getIcon().getText());
309
            }
310
        }
311
    }
312

    
313
    /**
314
     *
315
     */
316
    private static void initializeExtensions() {
317
        Iterator i = pluginsConfig.keySet().iterator();
318

    
319
        while (i.hasNext()) {
320
            String pName = (String) i.next();
321
            PluginConfig pc = (PluginConfig) pluginsConfig.get(pName);
322
            PluginServices ps = (PluginServices) pluginsServices.get(pName);
323

    
324
            Extension[] exts = pc.getExtensions().getExtension();
325

    
326
            TreeMap orderedExtensions = new TreeMap(new ExtensionComparator());
327

    
328
            for (int j = 0; j < exts.length; j++) {
329
                if (orderedExtensions.containsKey(exts[j])) {
330
                    logger.error(
331
                        "Two extensions with the same priority. Only will load one. " +
332
                        exts[j].getClassName());
333
                }
334

    
335
                orderedExtensions.put(exts[j], null);
336
            }
337

    
338
            Iterator e = orderedExtensions.keySet().iterator();
339

    
340
            while (e.hasNext()) {
341
                Extension extension = (Extension) e.next();
342
                com.iver.andami.plugins.Extension extensionInstance;
343

    
344
                try {
345
                    Class extensionClass = ps.getClassLoader().loadClass(extension.getClassName());
346
                    extensionInstance = (com.iver.andami.plugins.Extension) extensionClass.newInstance();
347
                    classesExtensions.put(extensionClass, extensionInstance);
348

    
349
                    extensionInstance.inicializar();
350
                } catch (InstantiationException e1) {
351
                    logger.error("Error instanciando la extension " +
352
                        extension.getClassName(), e1);
353
                } catch (IllegalAccessException e1) {
354
                    logger.error("Error instanciando la extension " +
355
                        extension.getClassName(), e1);
356
                } catch (ClassNotFoundException e1) {
357
                    logger.error("Error instanciando la extension " +
358
                        extension.getClassName(), e1);
359
                } catch (NoClassDefFoundError e1) {
360
                    logger.error("Error localizando la clase de la extension " +
361
                        extension.getClassName(), e1);
362
                }
363
            }
364
        }
365
    }
366

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

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

    
379
                TreeMap orderedMenus = new TreeMap(new MenuComparator());
380

    
381
                Extension[] exts = pc.getExtensions().getExtension();
382

    
383
                for (int j = 0; j < exts.length; j++) {
384
                    Menu[] menu = exts[j].getMenu();
385

    
386
                    for (int k = 0; k < menu.length; k++) {
387
                        SortableMenu sm = new SortableMenu(exts[j], menu[k]);
388

    
389
                        if (orderedMenus.containsKey(sm)) {
390
                            logger.error(
391
                                "Two menus with the same position. Only will load one. " +
392
                                exts[j].getClassName());
393
                        }
394

    
395
                        orderedMenus.put(sm, null);
396
                    }
397
                }
398

    
399
                // Se instalan las extensiones de MDI
400
                SkinExtension skinExt = pc.getExtensions().getSkinExtension();
401

    
402
                if (skinExt != null) {
403
                    Menu[] menu = skinExt.getMenu();
404

    
405
                    for (int k = 0; k < menu.length; k++) {
406
                        SortableMenu sm = new SortableMenu(skinExt, menu[k]);
407

    
408
                        if (orderedMenus.containsKey(sm)) {
409
                            logger.error(
410
                                "Two menus with the same position. Only will load one. " +
411
                                skinExt.getClassName());
412
                        }
413

    
414
                        orderedMenus.put(sm, null);
415
                    }
416
                }
417

    
418
                //Se itera por los menus ordenados
419
                Iterator e = orderedMenus.keySet().iterator();
420

    
421
                // Se ordenan los menues
422
                while (e.hasNext()) {
423
                    SortableMenu sm = (SortableMenu) e.next();
424

    
425
                    frame.addMenu(ps.getClassLoader(), sm.extension, sm.menu);
426
                }
427
            } catch (ClassNotFoundException e) {
428
                logger.error("No se pudo encontrar la clase de la extension", e);
429
            }
430
        }
431
    }
432

    
433
    /**
434
     *
435
     */
436
    private static void installPluginsControls() {
437
        Iterator i = pluginsConfig.keySet().iterator();
438

    
439
        while (i.hasNext()) {
440
            try {
441
                String pName = (String) i.next();
442
                PluginConfig pc = (PluginConfig) pluginsConfig.get(pName);
443
                PluginServices ps = (PluginServices) pluginsServices.get(pName);
444

    
445
                Extension[] exts = pc.getExtensions().getExtension();
446

    
447
                TreeMap orderedExtensions = new TreeMap(new ExtensionComparator());
448

    
449
                for (int j = 0; j < exts.length; j++) {
450
                    if (orderedExtensions.containsKey(exts[j])) {
451
                        logger.error(
452
                            "Two extensions with the same priority. Only will load one. " +
453
                            exts[j].getClassName());
454
                    }
455

    
456
                    orderedExtensions.put(exts[j], null);
457
                }
458

    
459
                Iterator e = orderedExtensions.keySet().iterator();
460

    
461
                // Se instalan las extensiones
462
                while (e.hasNext()) {
463
                    Extension ext = (Extension) e.next();
464

    
465
                    ToolBar[] toolbars = ext.getToolBar();
466

    
467
                    for (int k = 0; k < toolbars.length; k++) {
468
                        ActionTool[] tools = toolbars[k].getActionTool();
469

    
470
                        for (int t = 0; t < tools.length; t++) {
471
                            frame.addTool(ps.getClassLoader(), ext,
472
                                toolbars[k], tools[t]);
473
                        }
474

    
475
                        SelectableTool[] sTools = toolbars[k].getSelectableTool();
476

    
477
                        for (int t = 0; t < sTools.length; t++) {
478
                            frame.addTool(ps.getClassLoader(), ext,
479
                                toolbars[k], sTools[t]);
480
                        }
481
                    }
482

    
483
                    /*
484
                       Menu[] menu = ext.getMenu();
485
                       for (int k = 0; k < menu.length; k++) {
486
                           frame.addMenu(ps.getClassLoader(), ext, menu[k]);
487
                       }
488
                     */
489
                }
490

    
491
                // Se instalan las extensiones de MDI
492
                SkinExtension skinExt = pc.getExtensions().getSkinExtension();
493

    
494
                if (skinExt != null) {
495
                    ToolBar[] toolbars = skinExt.getToolBar();
496

    
497
                    for (int k = 0; k < toolbars.length; k++) {
498
                        ActionTool[] tools = toolbars[k].getActionTool();
499

    
500
                        for (int t = 0; t < tools.length; t++) {
501
                            frame.addTool(ps.getClassLoader(), skinExt,
502
                                toolbars[k], tools[t]);
503
                        }
504

    
505
                        SelectableTool[] sTools = toolbars[k].getSelectableTool();
506

    
507
                        for (int t = 0; t < sTools.length; t++) {
508
                            frame.addTool(ps.getClassLoader(), skinExt,
509
                                toolbars[k], sTools[t]);
510
                        }
511
                    }
512

    
513
                    /*
514
                       Menu[] menu = skinExt.getMenu();
515
                       for (int k = 0; k < menu.length; k++) {
516
                           frame.addMenu(ps.getClassLoader(), skinExt, menu[k]);
517
                       }
518
                     */
519
                }
520

    
521
                //Se instalan los popup menus
522
                PopupMenus pus = pc.getPopupMenus();
523

    
524
                if (pus != null) {
525
                    PopupMenu[] menus = pus.getPopupMenu();
526

    
527
                    for (int j = 0; j < menus.length; j++) {
528
                        frame.addPopupMenu(ps.getClassLoader(), menus[j]);
529
                    }
530
                }
531
            } catch (ClassNotFoundException e) {
532
                logger.error("No se pudo encontrar la clase de la extension", e);
533
            }
534
        }
535
    }
536

    
537
    /**
538
     *
539
     */
540
    private static void updateAndamiConfig() {
541
        HashSet olds = new HashSet();
542

    
543
        Plugin[] plugins = andamiConfig.getPlugin();
544

    
545
        for (int i = 0; i < plugins.length; i++) {
546
            olds.add(plugins[i].getName());
547
        }
548

    
549
        Iterator i = pluginsServices.values().iterator();
550

    
551
        while (i.hasNext()) {
552
            PluginServices ps = (PluginServices) i.next();
553

    
554
            if (!olds.contains(ps.getPluginName())) {
555
                Plugin p = new Plugin();
556
                p.setName(ps.getPluginName());
557
                p.setUpdate(false);
558

    
559
                andamiConfig.addPlugin(p);
560
            }
561
        }
562
    }
563

    
564
    /**
565
     * DOCUMENT ME!
566
     */
567
    private static void pluginsClassLoaders() {
568
        HashSet instalados = new HashSet();
569

    
570
        // Se itera hasta que est?n todos instalados
571
        while (instalados.size() != pluginsConfig.size()) {
572
            boolean circle = true;
573

    
574
            //Hacemos una pasada por todos los plugins
575
            Iterator i = pluginsConfig.keySet().iterator();
576

    
577
            while (i.hasNext()) {
578
                String pluginName = (String) i.next();
579
                PluginConfig config = (PluginConfig) pluginsConfig.get(pluginName);
580

    
581
                if (instalados.contains(pluginName)) {
582
                    continue;
583
                }
584

    
585
                //Se obtienen las dependencias y sus class loaders
586
                boolean ready = true;
587
                Depends[] dependencies = config.getDepends();
588
                PluginClassLoader[] loaders = new PluginClassLoader[dependencies.length];
589

    
590
                for (int j = 0; j < dependencies.length; j++) {
591
                    if (pluginsConfig.get(dependencies[j].getPluginName()) == null) {
592
                        logger.error("Dependencia no resuelta en plugin " +
593
                            pluginName + ": " +
594
                            dependencies[j].getPluginName() +
595
                            ". Dependencia ignorada");
596

    
597
                        continue;
598
                    }
599

    
600
                    if (!instalados.contains(dependencies[j].getPluginName())) {
601
                        ready = false;
602
                    } else {
603
                        loaders[j] = ((PluginServices) pluginsServices.get(dependencies[j].getPluginName())).getClassLoader();
604
                    }
605
                }
606

    
607
                //Si no est?n sus dependencias satisfechas se aborta la instalaci?n
608
                if (!ready) {
609
                    continue;
610
                }
611

    
612
                //Se genera el class loader
613
                Library[] jars = config.getLibraries().getLibrary();
614
                URL[] urls = new URL[jars.length];
615

    
616
                for (int j = 0; j < jars.length; j++) {
617
                    try {
618
                        urls[j] = new URL("file:" +
619
                                andamiConfig.getPluginsDirectory() +
620
                                File.separator + pluginName + File.separator +
621
                                jars[j].getFile());
622
                    } catch (MalformedURLException e) {
623
                        logger.error("No se puede acceder a " +
624
                            jars[j].getFile());
625
                    }
626
                }
627

    
628
                PluginClassLoader loader;
629

    
630
                try {
631
                    loader = new PluginClassLoader(urls,
632
                            andamiConfig.getPluginsDirectory() +
633
                            File.separator + pluginName,
634
                            Launcher.class.getClassLoader(), loaders);
635

    
636
                    PluginServices ps = new PluginServices(loader);
637

    
638
                    pluginsServices.put(ps.getPluginName(), ps);
639

    
640
                    instalados.add(pluginName);
641

    
642
                    circle = false;
643
                } catch (IOException e) {
644
                    logger.error("Error con las librer?as del plugin", e);
645
                    pluginsConfig.remove(pluginName);
646
                    i = pluginsConfig.keySet().iterator();
647
                }
648
            }
649

    
650
            if (circle) {
651
                logger.error("Hay dependencias circulares entre los plugins");
652

    
653
                break;
654
            }
655
        }
656

    
657
        //Se eliminan los plugins que no fueron instalados
658
        Iterator i = pluginsConfig.keySet().iterator();
659

    
660
        while (i.hasNext()) {
661
            String pluginName = (String) i.next();
662
            PluginConfig config = (PluginConfig) pluginsConfig.get(pluginName);
663
            PluginServices ps = (PluginServices) pluginsServices.get(pluginName);
664

    
665
            if (ps == null) {
666
                pluginsConfig.remove(pluginName);
667
                i = pluginsConfig.keySet().iterator();
668
            }
669
        }
670
    }
671

    
672
    /**
673
     * DOCUMENT ME!
674
     */
675
    private static void pluginsMessages() {
676
        //Iteramos por todos los plugins
677
        Iterator i = pluginsConfig.keySet().iterator();
678

    
679
        while (i.hasNext()) {
680
            String pluginName = (String) i.next();
681
            PluginConfig config = (PluginConfig) pluginsConfig.get(pluginName);
682

    
683
            PluginServices ps = (PluginServices) pluginsServices.get(pluginName);
684

    
685
            if (config.getResourceBundle() != null) {
686
                ps.setResourceBundle(config.getResourceBundle().getName(),
687
                    locale);
688
            }
689
        }
690
    }
691

    
692
    /**
693
     * DOCUMENT ME!
694
     *
695
     * @param name DOCUMENT ME!
696
     *
697
     * @return DOCUMENT ME!
698
     */
699
    static PluginServices getPluginServices(String name) {
700
        return (PluginServices) pluginsServices.get(name);
701
    }
702

    
703
    /**
704
     * DOCUMENT ME!
705
     *
706
     * @return DOCUMENT ME!
707
     */
708
    static MDIFrame getMDIFrame() {
709
        return frame;
710
    }
711

    
712
    /**
713
     * DOCUMENT ME!
714
     *
715
     * @param pluginsDirectory
716
     */
717
    private static void loadPlugins(String pluginsDirectory) {
718
        File pDir = new File(pluginsDirectory);
719

    
720
        if (!pDir.exists()) {
721
            return;
722
        }
723

    
724
        File[] pluginDirs = pDir.listFiles();
725

    
726
        for (int i = 0; i < pluginDirs.length; i++) {
727
            if (pluginDirs[i].isDirectory()) {
728
                File configXml = new File(pluginDirs[i].getAbsolutePath() +
729
                        File.separator + "config.xml");
730

    
731
                try {
732
                    FileReader xml = new FileReader(configXml);
733
                    PluginConfig pConfig = (PluginConfig) PluginConfig.unmarshal(xml);
734
                    pluginsConfig.put(pluginDirs[i].getName(), pConfig);
735
                } catch (FileNotFoundException e) {
736
                    logger.info("Ignorando el directorio " +
737
                        pluginDirs[i].getAbsolutePath() +
738
                        " por no encontrar su fichero 'config.xml'");
739
                } catch (MarshalException e) {
740
                    logger.info("Ignorando el directorio " +
741
                        pluginDirs[i].getAbsolutePath() +
742
                        " por fichero 'config.xml' mal formado", e);
743
                } catch (ValidationException e) {
744
                    logger.info("Ignorando el directorio " +
745
                        pluginDirs[i].getAbsolutePath() +
746
                        " por fichero 'config.xml' mal formado", e);
747
                }
748
            }
749
        }
750
    }
751

    
752
    /**
753
     * DOCUMENT ME!
754
     *
755
     * @param language
756
     * @param country
757
     * @param variant
758
     *
759
     * @return DOCUMENT ME!
760
     */
761
    private static Locale getLocale(String language, String country,
762
        String variant) {
763
        if (variant != null) {
764
            return new Locale(language, country, variant);
765
        } else if (country != null) {
766
            return new Locale(language, country);
767
        } else if (language != null) {
768
            return new Locale(language);
769
        } else {
770
            return new Locale("es");
771
        }
772
    }
773

    
774
    /**
775
     * DOCUMENT ME!
776
     *
777
     * @param file DOCUMENT ME!
778
     *
779
     * @throws IOException DOCUMENT ME!
780
     * @throws MarshalException DOCUMENT ME!
781
     * @throws ValidationException DOCUMENT ME!
782
     */
783
    private static void andamiConfigToXML(String file)
784
        throws IOException, MarshalException, ValidationException {
785
        File xml = new File(file);
786

    
787
        FileWriter writer = new FileWriter(xml);
788
        andamiConfig.marshal(writer);
789
    }
790

    
791
    /**
792
     * DOCUMENT ME!
793
     *
794
     * @param file DOCUMENT ME!
795
     *
796
     * @throws ConfigurationException DOCUMENT ME!
797
     */
798
    private static void andamiConfigFromXML(String file)
799
        throws ConfigurationException {
800
        File xml = new File(file);
801

    
802
        //Si no existe se ponen los valores por defecto
803
        if (!xml.exists()) {
804
            andamiConfig = new AndamiConfig();
805

    
806
            Andami andami = new Andami();
807
            andami.setUpdate(true);
808
            andamiConfig.setAndami(andami);
809
            andamiConfig.setLocaleCountry(Locale.getDefault().getCountry());
810
            andamiConfig.setLocaleLanguage(Locale.getDefault().getLanguage());
811
            andamiConfig.setLocaleVariant(Locale.getDefault().getVariant());
812
            andamiConfig.setPluginsDirectory(appName + File.separator + "extensiones");
813
            andamiConfig.setPlugin(new Plugin[0]);
814
        } else {
815
            //Se lee la configuraci?n
816
            FileReader reader;
817

    
818
            try {
819
                reader = new FileReader(xml);
820
                andamiConfig = (AndamiConfig) AndamiConfig.unmarshal(reader);
821
            } catch (FileNotFoundException e) {
822
                throw new ConfigurationException(e);
823
            } catch (MarshalException e) {
824
                throw new ConfigurationException(e);
825
            } catch (ValidationException e) {
826
                throw new ConfigurationException(e);
827
            }
828
        }
829
    }
830

    
831
    /**
832
     * DOCUMENT ME!
833
     *
834
     * @return DOCUMENT ME!
835
     *
836
     * @throws ConfigurationException DOCUMENT ME!
837
     */
838
    private static XMLEntity persistenceFromXML() throws ConfigurationException {
839
        File xml = new File(pluginsPersistencePath);
840

    
841
        if (xml.exists()) {
842
            FileReader reader;
843

    
844
            try {
845
                reader = new FileReader(xml);
846

    
847
                XmlTag tag = (XmlTag) XmlTag.unmarshal(reader);
848

    
849
                return new XMLEntity(tag);
850
            } catch (FileNotFoundException e) {
851
                throw new ConfigurationException(e);
852
            } catch (MarshalException e) {
853
                throw new ConfigurationException(e);
854
            } catch (ValidationException e) {
855
                throw new ConfigurationException(e);
856
            }
857
        } else {
858
            return new XMLEntity();
859
        }
860
    }
861

    
862
    /**
863
     * DOCUMENT ME!
864
     *
865
     * @param entity DOCUMENT ME!
866
     *
867
     * @throws ConfigurationException DOCUMENT ME!
868
     */
869
    private static void persistenceToXML(XMLEntity entity)
870
        throws ConfigurationException {
871
        File xml = new File(pluginsPersistencePath);
872

    
873
        FileWriter writer;
874

    
875
        try {
876
            writer = new FileWriter(xml);
877
            entity.getXmlTag().marshal(writer);
878
        } catch (FileNotFoundException e) {
879
            throw new ConfigurationException(e);
880
        } catch (MarshalException e) {
881
            throw new ConfigurationException(e);
882
        } catch (ValidationException e) {
883
            throw new ConfigurationException(e);
884
        } catch (IOException e) {
885
            throw new ConfigurationException(e);
886
        }
887
    }
888

    
889
    /**
890
     * Devuelve un array con los directorios de los plugins
891
     *
892
     * @param dirExt Directorio de las extensiones a partir del cual cuelgan
893
     *        todos los directorios de los plugins
894
     *
895
     * @return ArrayList con los directorios
896
     */
897
    private String[] getLocales(File dirExt) {
898
        ArrayList types = new ArrayList();
899
        File[] files = dirExt.listFiles();
900

    
901
        for (int i = 0; i < files.length; i++) {
902
            if (files[i].isDirectory()) {
903
                File[] textFile = files[i].listFiles(new FilenameFilter() {
904
                            public boolean accept(File dir, String fileName) {
905
                                return fileName.toLowerCase().startsWith("text_"); //$NON-NLS-1$
906
                            }
907
                        });
908

    
909
                for (int j = 0; j < textFile.length; j++) {
910
                    String s = (textFile[j]).getName().replaceAll("text_", "");
911
                    s = s.replaceAll(".properties", "");
912
                    s = s.trim();
913

    
914
                    if (!types.contains(s)) {
915
                        types.add(s);
916
                    }
917
                }
918
            }
919
        }
920

    
921
        return (String[]) types.toArray(new String[0]);
922
    }
923

    
924
    /**
925
     * DOCUMENT ME!
926
     *
927
     * @return Returns the frame.
928
     */
929
    static MDIFrame getFrame() {
930
        return frame;
931
    }
932

    
933
    /**
934
     * Secuencia de cerrado de Andami
935
     */
936
    public static void closeApplication() {
937
        //Configuraci?n de Andami
938
        try {
939
            andamiConfigToXML(andamiConfigPath);
940
        } catch (MarshalException e) {
941
            logger.error("No se pudo guardar la configuraci?n de Andami", e);
942
        } catch (ValidationException e) {
943
            logger.error("No se pudo guardar la configuraci?n de Andami", e);
944
        } catch (IOException e) {
945
            logger.error("No se pudo guardar la configuraci?n de Andami", e);
946
        }
947

    
948
        //Persistencia de los plugins
949
        Iterator i = pluginsConfig.keySet().iterator();
950

    
951
        XMLEntity entity = new XMLEntity();
952

    
953
        while (i.hasNext()) {
954
            String pName = (String) i.next();
955
            PluginServices ps = (PluginServices) pluginsServices.get(pName);
956
            XMLEntity ent = ps.getPersistentXML();
957

    
958
            if (ent != null) {
959
                ent.putProperty("com.iver.andami.pluginName", pName);
960
                entity.addChild(ent);
961
            }
962
        }
963

    
964
        try {
965
            persistenceToXML(entity);
966
        } catch (ConfigurationException e1) {
967
            logger.error("Se produjo un error guardando la configuraci?n de los plugins",
968
                e1);
969
        }
970

    
971
        System.exit(0);
972
    }
973

    
974
    /**
975
     * DOCUMENT ME!
976
     *
977
     * @return DOCUMENT ME!
978
     */
979
    static HashMap getClassesExtensions() {
980
        return classesExtensions;
981
    }
982

    
983
    /**
984
     * DOCUMENT ME!
985
     *
986
     * @author $author$
987
     * @version $Revision: 665 $
988
     */
989
    public static class ExtensionComparator implements Comparator {
990
        /**
991
         * DOCUMENT ME!
992
         *
993
         * @param o1 DOCUMENT ME!
994
         * @param o2 DOCUMENT ME!
995
         *
996
         * @return DOCUMENT ME!
997
         */
998
        public int compare(Object o1, Object o2) {
999
            Extension e1 = (Extension) o1;
1000
            Extension e2 = (Extension) o2;
1001

    
1002
            if (!e1.hasPriority() && !e2.hasPriority()) {
1003
                return -1;
1004
            }
1005

    
1006
            if (e1.hasPriority() && !e2.hasPriority()) {
1007
                return -Integer.MAX_VALUE;
1008
            }
1009

    
1010
            if (e2.hasPriority() && !e1.hasPriority()) {
1011
                return Integer.MAX_VALUE;
1012
            }
1013

    
1014
            return e1.getPriority() - e2.getPriority();
1015
        }
1016
    }
1017

    
1018
    /**
1019
     * DOCUMENT ME!
1020
     */
1021
    public static class MenuComparator implements Comparator {
1022
        private static ExtensionComparator extComp = new ExtensionComparator();
1023

    
1024
        /**
1025
         * DOCUMENT ME!
1026
         *
1027
         * @param o1 DOCUMENT ME!
1028
         * @param o2 DOCUMENT ME!
1029
         *
1030
         * @return DOCUMENT ME!
1031
         */
1032
        public int compare(Object o1, Object o2) {
1033
            SortableMenu e1 = (SortableMenu) o1;
1034
            SortableMenu e2 = (SortableMenu) o2;
1035

    
1036
            if (!e1.menu.hasPosition() && !e2.menu.hasPosition()) {
1037
                if (e1.extension instanceof SkinExtensionType) {
1038
                    return 1;
1039
                } else if (e2.extension instanceof SkinExtensionType) {
1040
                    return -1;
1041
                } else {
1042
                    return extComp.compare(e1.extension, e2.extension);
1043
                }
1044
            }
1045

    
1046
            if (e1.menu.hasPosition() && !e2.menu.hasPosition()) {
1047
                return -Integer.MAX_VALUE;
1048
            }
1049

    
1050
            if (e2.menu.hasPosition() && !e1.menu.hasPosition()) {
1051
                return Integer.MAX_VALUE;
1052
            }
1053

    
1054
            return e1.menu.getPosition() - e2.menu.getPosition();
1055
        }
1056
    }
1057

    
1058
    /**
1059
     * DOCUMENT ME!
1060
     *
1061
     * @author $author$
1062
     * @version $Revision: 665 $
1063
     */
1064
    public static class SortableMenu {
1065
        public Menu menu;
1066
        public SkinExtensionType extension;
1067

    
1068
        /**
1069
         * DOCUMENT ME!
1070
         *
1071
         * @param skinExt
1072
         * @param menu2
1073
         */
1074
        public SortableMenu(SkinExtensionType skinExt, Menu menu2) {
1075
            extension = skinExt;
1076
            menu = menu2;
1077
        }
1078
    }
1079
}