Statistics
| Revision:

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

History | View | Annotate | Download (42.2 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.messages.NotificationManager;
8
import com.iver.andami.plugins.PluginClassLoader;
9
import com.iver.andami.plugins.config.generate.ActionTool;
10
import com.iver.andami.plugins.config.generate.Depends;
11
import com.iver.andami.plugins.config.generate.Extension;
12
import com.iver.andami.plugins.config.generate.Extensions;
13
import com.iver.andami.plugins.config.generate.LabelSet;
14
import com.iver.andami.plugins.config.generate.Library;
15
import com.iver.andami.plugins.config.generate.Menu;
16
import com.iver.andami.plugins.config.generate.PluginConfig;
17
import com.iver.andami.plugins.config.generate.PopupMenu;
18
import com.iver.andami.plugins.config.generate.PopupMenus;
19
import com.iver.andami.plugins.config.generate.SelectableTool;
20
import com.iver.andami.plugins.config.generate.SkinExtension;
21
import com.iver.andami.plugins.config.generate.SkinExtensionType;
22
import com.iver.andami.plugins.config.generate.ToolBar;
23
import com.iver.andami.ui.MDIManagerLoadException;
24
import com.iver.andami.ui.SplashWindow;
25
import com.iver.andami.ui.WaitCursorEventQueue;
26
import com.iver.andami.ui.mdiFrame.MDIFrame;
27
import com.iver.andami.ui.mdiManager.MDIManagerFactory;
28

    
29
import com.iver.utiles.XMLEntity;
30
import com.iver.utiles.xmlEntity.generate.XmlTag;
31

    
32
import org.apache.log4j.Logger;
33
import org.apache.log4j.PropertyConfigurator;
34

    
35
import org.exolab.castor.xml.MarshalException;
36
import org.exolab.castor.xml.ValidationException;
37

    
38
import java.awt.EventQueue;
39
import java.awt.Toolkit;
40

    
41
import java.io.BufferedInputStream;
42
import java.io.BufferedOutputStream;
43
import java.io.File;
44
import java.io.FileNotFoundException;
45
import java.io.FileOutputStream;
46
import java.io.FileReader;
47
import java.io.FileWriter;
48
import java.io.FilenameFilter;
49
import java.io.IOException;
50
import java.io.InputStream;
51

    
52
import java.lang.reflect.InvocationTargetException;
53

    
54
import java.net.MalformedURLException;
55
import java.net.URL;
56
import java.net.URLConnection;
57

    
58
import java.util.ArrayList;
59
import java.util.Comparator;
60
import java.util.Date;
61
import java.util.HashMap;
62
import java.util.HashSet;
63
import java.util.Iterator;
64
import java.util.Locale;
65
import java.util.TreeMap;
66

    
67
import javax.jnlp.BasicService;
68
import javax.jnlp.ServiceManager;
69
import javax.jnlp.UnavailableServiceException;
70
import javax.swing.ImageIcon;
71
import javax.swing.JComponent;
72
import javax.swing.SwingUtilities;
73
import javax.swing.UIManager;
74

    
75

    
76
/**
77
 * DOCUMENT ME!
78
 *
79
 * @author $author$
80
 * @version $Revision: 1013 $
81
 */
82
public class Launcher {
83
    private static Logger logger = Logger.getLogger(Launcher.class.getName());
84
    private static AndamiConfig andamiConfig;
85
    private static SplashWindow splashWindow;
86
    private static String userHome = System.getProperty("user.home");
87
    private static String appName;
88
    private static Locale locale;
89
    private static HashMap pluginsConfig = new HashMap();
90
    private static HashMap pluginsServices = new HashMap();
91
    private static MDIFrame frame;
92
    private static HashMap classesExtensions = new HashMap();
93
    private static String andamiConfigPath;
94
    private static String pluginsPersistencePath;
95

    
96
    
97
    /**
98
     * DOCUMENT ME!
99
     *
100
     * @param args DOCUMENT ME!
101
     *
102
     * @throws InterruptedException
103
     * @throws InvocationTargetException
104
     * @throws ConfigurationException
105
     * @throws MDIManagerLoadException
106
     */
107
    public static void main(String[] args)
108
        throws InterruptedException, InvocationTargetException, 
109
            ConfigurationException, MDIManagerLoadException {
110
        if (args.length != 1) {
111
            System.err.println("Uso: Launcher appName");
112
        }
113

    
114
        appName = args[0];
115

    
116
        andamiConfigPath = appName +
117
            File.separator + "andami-config.xml";
118
        pluginsPersistencePath = appName +
119
            File.separator + "plugins-persistence.xml";
120

    
121
        // Configurar el log4j
122
        PropertyConfigurator.configure(Launcher.class.getClassLoader()
123
                                                     .getResource("log4j.properties"));
124

    
125
        // Leer el fichero de configuraci?n de andami (andami-config.xsd)
126
        // locale
127
        // Buscar actualizaci?nes al comenzar
128
        //  Andami
129
        //  Plugins
130
        // Directorio de las extensiones
131
        andamiConfigFromXML(andamiConfigPath);
132

    
133
        // Configurar el locale
134
        locale = getLocale(andamiConfig.getLocaleLanguage(),
135
                andamiConfig.getLocaleCountry(), andamiConfig.getLocaleVariant());
136
        Locale.setDefault(locale);
137
        JComponent.setDefaultLocale(locale);
138
        Messages.init(locale);
139
        try {
140
                        UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
141
                        // UIManager.setLookAndFeel("com.iver.WindowsLookAndFeel.WindowsLookAndFeel");
142
        } catch (Exception e) {
143
            logger.warn("No se pudo poner el look and feel", e);
144
        }
145

    
146
        // Mostrar la ventana de inicio
147
        splashWindow = new SplashWindow(null);
148

    
149
        // TODO Buscar actualizaciones de Andami
150
        // TODO Buscar actualizaciones de los plugins
151
        downloadExtensions(andamiConfig.getPluginsDirectory());        
152
        // Se leen los config.xml de los plugins -----++++
153
        loadPlugins(andamiConfig.getPluginsDirectory());
154

    
155
        // Se configura el classloader del plugin
156
        pluginsClassLoaders();
157

    
158
        // Se carga un Skin si alguno de los plugins trae informaci?n para ello
159
        skinPlugin();
160

    
161
        //Se configura la cola de eventos
162
        EventQueue waitQueue = new WaitCursorEventQueue(MDIManagerFactory.createManager(),
163
                100);
164
        Toolkit.getDefaultToolkit().getSystemEventQueue().push(waitQueue);
165

    
166
        // Se configura la mensajer?a del plugin
167
        pluginsMessages();
168

    
169
        // Se modifica el andami-config con los plugins nuevos
170
        updateAndamiConfig();
171

    
172
        // Se prepara el MainFrame para albergar las extensiones
173
        frame = new MDIFrame();
174

    
175
        // Se configura el nombre e icono de la aplicaci?n
176
        frameIcon();
177

    
178
        SwingUtilities.invokeAndWait(new Runnable() {
179
                public void run() {
180
                    frame.init();
181
                }
182
            });
183

    
184
        // Se instalan los controles de las extensiones de los plugins
185
        SwingUtilities.invokeAndWait(new Runnable() {
186
                public void run() {
187
                    installPluginsControls();
188
                    installPluginsMenus();
189
                    installPluginsLabels();
190
                }
191
            });
192

    
193
        // Leer el fichero de persistencia
194
        //  info de los plugins
195
        //  bookmarks de los plugins
196
        loadPluginsPersistence();
197

    
198

    
199
        // Se instalan los controles del skin
200
        // Se inicializan todas las extensiones de todos los plugins
201
        SwingUtilities.invokeAndWait(new Runnable() {
202
                        public void run() {
203
                        initializeExtensions();
204
                        }
205
                });
206
        frame.setClassesExtensions(classesExtensions);
207

    
208
        // Se instalan los bookmarks de los plugins
209
        splashWindow.close();
210

    
211
        //Se muestra el frame principal
212
        frame.show();
213
        
214
        SwingUtilities.invokeAndWait(new Runnable() {
215
                        public void run() {
216
                                frame.enableControls();
217
                        }
218
                });
219
    }
220

    
221
    /**
222
     * DOCUMENT ME!
223
     *
224
     * @throws ConfigurationException
225
     */
226
    private static void loadPluginsPersistence() throws ConfigurationException {
227
        XMLEntity entity = persistenceFromXML();
228

    
229
        for (int i = 0; i < entity.getNumChild(); i++) {
230
            XMLEntity plugin = entity.getChild(i);
231
            String pName = plugin.getStringProperty(
232
                    "com.iver.andami.pluginName");
233
            ((PluginServices) pluginsServices.get(pName)).setPresistentXML(plugin);
234
        }
235
    }
236

    
237
    /**
238
     * DOCUMENT ME!
239
     */
240
    private static void installPluginsLabels() {
241
        Iterator i = pluginsConfig.keySet().iterator();
242

    
243
        while (i.hasNext()) {
244
            String name = (String) i.next();
245
            PluginConfig pc = (PluginConfig) pluginsConfig.get(name);
246
            PluginServices ps = (PluginServices) pluginsServices.get(name);
247

    
248
            LabelSet[] ls = pc.getLabelSet();
249

    
250
            for (int j = 0; j < ls.length; j++) {
251
                PluginClassLoader loader = ps.getClassLoader();
252

    
253
                try {
254
                    Class clase = loader.loadClass(ls[j].getClassName());
255
                    frame.setLabels(clase, ls[j].getLabel());
256
                } catch (ClassNotFoundException e) {
257
                    logger.error("No se pudo encontrar la clase de la labelset",
258
                        e);
259
                }
260
            }
261
        }
262
    }
263

    
264
    /**
265
     * DOCUMENT ME!
266
     *
267
     * @throws MDIManagerLoadException
268
     */
269
    private static void skinPlugin() throws MDIManagerLoadException {
270
        Iterator i = pluginsConfig.keySet().iterator();
271

    
272
        while (i.hasNext()) {
273
            String name = (String) i.next();
274
            PluginConfig pc = (PluginConfig) pluginsConfig.get(name);
275
            PluginServices ps = (PluginServices) pluginsServices.get(name);
276

    
277
            if (pc.getExtensions().getSkinExtension() != null) {
278
                if (MDIManagerFactory.getSkinExtension() != null) {
279
                    logger.error("Dos skin-extension. Usamos el ?ltimo");
280
                }
281

    
282
                SkinExtension se = pc.getExtensions().getSkinExtension();
283

    
284
                MDIManagerFactory.setSkinExtension(se, ps.getClassLoader());
285

    
286
                Class skinClass;
287

    
288
                try {
289
                    skinClass = ps.getClassLoader().loadClass(se.getClassName());
290

    
291
                    com.iver.andami.plugins.Extension skinInstance = (com.iver.andami.plugins.Extension) skinClass.newInstance();
292
                    classesExtensions.put(skinClass, skinInstance);
293
                } catch (ClassNotFoundException e) {
294
                    logger.error("No se pudo instanciar la clase mdi manager", e);
295
                    throw new MDIManagerLoadException(e);
296
                } catch (InstantiationException e) {
297
                    logger.error("No se pudo instanciar la clase mdi manager", e);
298
                    throw new MDIManagerLoadException(e);
299
                } catch (IllegalAccessException e) {
300
                    logger.error("No se pudo instanciar la clase mdi manager", e);
301
                    throw new MDIManagerLoadException(e);
302
                }
303
            }
304
        }
305
    }
306

    
307
    /**
308
     *
309
     */
310
    private static void frameIcon() {
311
        Iterator i = pluginsConfig.keySet().iterator();
312

    
313
        while (i.hasNext()) {
314
            String pName = (String) i.next();
315
            PluginConfig pc = (PluginConfig) pluginsConfig.get(pName);
316
            PluginServices ps = (PluginServices) pluginsServices.get(pName);
317

    
318
            if (pc.getIcon() != null) {
319
                ImageIcon icon = new ImageIcon(ps.getClassLoader().getResource(pc.getIcon()
320
                                                                                 .getSrc()));
321
                frame.setIconImage(icon.getImage());
322
                frame.setTitle(pc.getIcon().getText());
323
            }
324
        }
325
    }
326

    
327
    /**
328
     *
329
     */
330
    private static void initializeExtensions() {
331
        Iterator i = pluginsConfig.keySet().iterator();
332

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

    
338
            Extension[] exts = pc.getExtensions().getExtension();
339

    
340
            TreeMap orderedExtensions = new TreeMap(new ExtensionComparator());
341

    
342
            for (int j = 0; j < exts.length; j++) {
343
                    if (!exts[j].getActive()) continue;
344
                if (orderedExtensions.containsKey(exts[j])) {
345
                    logger.error(
346
                        "Two extensions with the same priority. Only will load one. " +
347
                        exts[j].getClassName());
348
                }
349

    
350
                orderedExtensions.put(exts[j], null);
351
            }
352

    
353
            Iterator e = orderedExtensions.keySet().iterator();
354

    
355
            while (e.hasNext()) {
356
                Extension extension = (Extension) e.next();
357
                com.iver.andami.plugins.Extension extensionInstance;
358

    
359
                try {
360
                    Class extensionClass = ps.getClassLoader().loadClass(extension.getClassName());
361
                    extensionInstance = (com.iver.andami.plugins.Extension) extensionClass.newInstance();
362
                    classesExtensions.put(extensionClass, extensionInstance);
363

    
364
                    extensionInstance.inicializar();
365
                } catch (InstantiationException e1) {
366
                    logger.error("Error instanciando la extension " +
367
                        extension.getClassName(), e1);
368
                } catch (IllegalAccessException e1) {
369
                    logger.error("Error instanciando la extension " +
370
                        extension.getClassName(), e1);
371
                } catch (ClassNotFoundException e1) {
372
                    logger.error("Error instanciando la extension " +
373
                        extension.getClassName(), e1);
374
                } catch (NoClassDefFoundError e1) {
375
                    logger.error("Error localizando la clase de la extension " +
376
                        extension.getClassName(), e1);
377
                }
378
            }
379
        }
380
    }
381

    
382
    /**
383
     * DOCUMENT ME!
384
     */
385
    private static void installPluginsMenus() {
386
        Iterator i = pluginsConfig.keySet().iterator();
387

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

    
394
                TreeMap orderedMenus = new TreeMap(new MenuComparator());
395

    
396
                Extension[] exts = pc.getExtensions().getExtension();
397

    
398
                for (int j = 0; j < exts.length; j++) {
399
                        if (!exts[j].getActive()) continue;
400
                    Menu[] menu = exts[j].getMenu();
401

    
402
                    for (int k = 0; k < menu.length; k++) {
403
                        SortableMenu sm = new SortableMenu(exts[j], menu[k]);
404

    
405
                        if (orderedMenus.containsKey(sm)) {
406
                            logger.error(
407
                                "Two menus with the same position. Only will load one. " +
408
                                exts[j].getClassName());
409
                        }
410

    
411
                        orderedMenus.put(sm, null);
412
                    }
413
                }
414

    
415
                // Se instalan las extensiones de MDI
416
                SkinExtension skinExt = pc.getExtensions().getSkinExtension();
417

    
418
                if (skinExt != null) {
419
                    Menu[] menu = skinExt.getMenu();
420

    
421
                    for (int k = 0; k < menu.length; k++) {
422
                        SortableMenu sm = new SortableMenu(skinExt, menu[k]);
423

    
424
                        if (orderedMenus.containsKey(sm)) {
425
                            logger.error(
426
                                "Two menus with the same position. Only will load one. " +
427
                                skinExt.getClassName());
428
                        }
429

    
430
                        orderedMenus.put(sm, null);
431
                    }
432
                }
433

    
434
                //Se itera por los menus ordenados
435
                Iterator e = orderedMenus.keySet().iterator();
436

    
437
                // Se ordenan los menues
438
                while (e.hasNext()) {
439
                    SortableMenu sm = (SortableMenu) e.next();
440

    
441
                    frame.addMenu(ps.getClassLoader(), sm.extension, sm.menu);
442
                }
443
            } catch (ClassNotFoundException e) {
444
                logger.error("No se pudo encontrar la clase de la extension", e);
445
            }
446
        }
447
    }
448

    
449
    /**
450
     *
451
     */
452
    private static void installPluginsControls() {
453
        Iterator i = pluginsConfig.keySet().iterator();
454

    
455
        while (i.hasNext()) {
456
            try {
457
                String pName = (String) i.next();
458
                PluginConfig pc = (PluginConfig) pluginsConfig.get(pName);
459
                PluginServices ps = (PluginServices) pluginsServices.get(pName);
460

    
461
                Extension[] exts = pc.getExtensions().getExtension();
462

    
463
                TreeMap orderedExtensions = new TreeMap(new ExtensionComparator());
464

    
465
                for (int j = 0; j < exts.length; j++) {
466
                        if (exts[j].getActive()){
467
                            if (orderedExtensions.containsKey(exts[j])) {
468
                                logger.error(
469
                                    "Two extensions with the same priority. Only will load one. " +
470
                                    exts[j].getClassName());
471
                            }
472
        
473
                            orderedExtensions.put(exts[j], null);
474
                        }
475
                }
476

    
477
                Iterator e = orderedExtensions.keySet().iterator();
478

    
479
                // Se instalan las extensiones
480
                while (e.hasNext()) {
481
                    Extension ext = (Extension) e.next();
482

    
483
                    ToolBar[] toolbars = ext.getToolBar();
484

    
485
                    for (int k = 0; k < toolbars.length; k++) {
486
                        ActionTool[] tools = toolbars[k].getActionTool();
487

    
488
                        for (int t = 0; t < tools.length; t++) {
489
                            frame.addTool(ps.getClassLoader(), ext,
490
                                toolbars[k], tools[t]);
491
                        }
492

    
493
                        SelectableTool[] sTools = toolbars[k].getSelectableTool();
494

    
495
                        for (int t = 0; t < sTools.length; t++) {
496
                            frame.addTool(ps.getClassLoader(), ext,
497
                                toolbars[k], sTools[t]);
498
                        }
499
                    }
500

    
501
                    /*
502
                       Menu[] menu = ext.getMenu();
503
                       for (int k = 0; k < menu.length; k++) {
504
                           frame.addMenu(ps.getClassLoader(), ext, menu[k]);
505
                       }
506
                     */
507
                }
508

    
509
                // Se instalan las extensiones de MDI
510
                SkinExtension skinExt = pc.getExtensions().getSkinExtension();
511

    
512
                if (skinExt != null) {
513
                    ToolBar[] toolbars = skinExt.getToolBar();
514

    
515
                    for (int k = 0; k < toolbars.length; k++) {
516
                        ActionTool[] tools = toolbars[k].getActionTool();
517

    
518
                        for (int t = 0; t < tools.length; t++) {
519
                            frame.addTool(ps.getClassLoader(), skinExt,
520
                                toolbars[k], tools[t]);
521
                        }
522

    
523
                        SelectableTool[] sTools = toolbars[k].getSelectableTool();
524

    
525
                        for (int t = 0; t < sTools.length; t++) {
526
                            frame.addTool(ps.getClassLoader(), skinExt,
527
                                toolbars[k], sTools[t]);
528
                        }
529
                    }
530

    
531
                    /*
532
                       Menu[] menu = skinExt.getMenu();
533
                       for (int k = 0; k < menu.length; k++) {
534
                           frame.addMenu(ps.getClassLoader(), skinExt, menu[k]);
535
                       }
536
                     */
537
                }
538

    
539
                //Se instalan los popup menus
540
                PopupMenus pus = pc.getPopupMenus();
541

    
542
                if (pus != null) {
543
                    PopupMenu[] menus = pus.getPopupMenu();
544

    
545
                    for (int j = 0; j < menus.length; j++) {
546
                        frame.addPopupMenu(ps.getClassLoader(), menus[j]);
547
                    }
548
                }
549
            } catch (ClassNotFoundException e) {
550
                logger.error("No se pudo encontrar la clase de la extension", e);
551
            }
552
        }
553
    }
554

    
555
    /**
556
     *
557
     */
558
    private static void updateAndamiConfig() {
559
        HashSet olds = new HashSet();
560

    
561
        Plugin[] plugins = andamiConfig.getPlugin();
562

    
563
        for (int i = 0; i < plugins.length; i++) {
564
            olds.add(plugins[i].getName());
565
        }
566

    
567
        Iterator i = pluginsServices.values().iterator();
568

    
569
        while (i.hasNext()) {
570
            PluginServices ps = (PluginServices) i.next();
571

    
572
            if (!olds.contains(ps.getPluginName())) {
573
                Plugin p = new Plugin();
574
                p.setName(ps.getPluginName());
575
                p.setUpdate(false);
576

    
577
                andamiConfig.addPlugin(p);
578
            }
579
        }
580
    }
581

    
582
    /**
583
     * DOCUMENT ME!
584
     */
585
    private static void pluginsClassLoaders() {
586
        HashSet instalados = new HashSet();
587

    
588
        // Se itera hasta que est?n todos instalados
589
        while (instalados.size() != pluginsConfig.size()) {
590
            boolean circle = true;
591

    
592
            //Hacemos una pasada por todos los plugins
593
            Iterator i = pluginsConfig.keySet().iterator();
594

    
595
            while (i.hasNext()) {
596
                String pluginName = (String) i.next();
597
                PluginConfig config = (PluginConfig) pluginsConfig.get(pluginName);
598

    
599
                if (instalados.contains(pluginName)) {
600
                    continue;
601
                }
602

    
603
                //Se obtienen las dependencias y sus class loaders
604
                boolean ready = true;
605
                Depends[] dependencies = config.getDepends();
606
                PluginClassLoader[] loaders = new PluginClassLoader[dependencies.length];
607

    
608
                for (int j = 0; j < dependencies.length; j++) {
609
                    if (pluginsConfig.get(dependencies[j].getPluginName()) == null) {
610
                        logger.error("Dependencia no resuelta en plugin " +
611
                            pluginName + ": " +
612
                            dependencies[j].getPluginName() +
613
                            ". Dependencia ignorada");
614

    
615
                        continue;
616
                    }
617

    
618
                    if (!instalados.contains(dependencies[j].getPluginName())) {
619
                        ready = false;
620
                    } else {
621
                        loaders[j] = ((PluginServices) pluginsServices.get(dependencies[j].getPluginName())).getClassLoader();
622
                    }
623
                }
624

    
625
                //Si no est?n sus dependencias satisfechas se aborta la instalaci?n
626
                if (!ready) {
627
                    continue;
628
                }
629

    
630
                //Se genera el class loader
631
                Library[] jars = config.getLibraries().getLibrary();
632
                URL[] urls = new URL[jars.length];
633

    
634
                for (int j = 0; j < jars.length; j++) {
635
                    try {
636
                        urls[j] = new URL("file:" +
637
                                andamiConfig.getPluginsDirectory() +
638
                                File.separator + pluginName + File.separator +
639
                                jars[j].getFile());
640
                    } catch (MalformedURLException e) {
641
                        logger.error("No se puede acceder a " +
642
                            jars[j].getFile());
643
                    }
644
                }
645

    
646
                PluginClassLoader loader;
647

    
648
                try {
649
                    loader = new PluginClassLoader(urls,
650
                            andamiConfig.getPluginsDirectory() +
651
                            File.separator + pluginName,
652
                            Launcher.class.getClassLoader(), loaders);
653

    
654
                    PluginServices ps = new PluginServices(loader);
655

    
656
                    pluginsServices.put(ps.getPluginName(), ps);
657

    
658
                    instalados.add(pluginName);
659

    
660
                    circle = false;
661
                } catch (IOException e) {
662
                    logger.error("Error con las librer?as del plugin", e);
663
                    pluginsConfig.remove(pluginName);
664
                    i = pluginsConfig.keySet().iterator();
665
                }
666
            }
667

    
668
            if (circle) {
669
                logger.error("Hay dependencias circulares entre los plugins");
670

    
671
                break;
672
            }
673
        }
674

    
675
        //Se eliminan los plugins que no fueron instalados
676
        Iterator i = pluginsConfig.keySet().iterator();
677

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

    
683
            if (ps == null) {
684
                pluginsConfig.remove(pluginName);
685
                i = pluginsConfig.keySet().iterator();
686
            }
687
        }
688
    }
689

    
690
    /**
691
     * DOCUMENT ME!
692
     */
693
    private static void pluginsMessages() {
694
        //Iteramos por todos los plugins
695
        Iterator i = pluginsConfig.keySet().iterator();
696

    
697
        while (i.hasNext()) {
698
            String pluginName = (String) i.next();
699
            PluginConfig config = (PluginConfig) pluginsConfig.get(pluginName);
700

    
701
            PluginServices ps = (PluginServices) pluginsServices.get(pluginName);
702

    
703
            if (config.getResourceBundle() != null) {
704
                ps.setResourceBundle(config.getResourceBundle().getName(),
705
                    locale);
706
            }
707
        }
708
    }
709

    
710
    /**
711
     * DOCUMENT ME!
712
     *
713
     * @param name DOCUMENT ME!
714
     *
715
     * @return DOCUMENT ME!
716
     */
717
    static PluginServices getPluginServices(String name) {
718
        return (PluginServices) pluginsServices.get(name);
719
    }
720
    
721
    static String getPluginsDir(){
722
            return andamiConfig.getPluginsDirectory();            
723
    }
724
    static void setPluginsDir(String s){
725
            andamiConfig.setPluginsDirectory(s);            
726
    }
727
    /**
728
     * DOCUMENT ME!
729
     *
730
     * @return DOCUMENT ME!
731
     */
732
    static MDIFrame getMDIFrame() {
733
        return frame;
734
    }
735

    
736
    /**
737
     * DOCUMENT ME!
738
     *
739
     * @param pluginsDirectory
740
     */
741
    private static void loadPlugins(String pluginsDirectory) {
742
        File pDir = new File(pluginsDirectory);
743

    
744
        if (!pDir.exists()) {
745
            return;
746
        }
747

    
748
        File[] pluginDirs = pDir.listFiles();
749

    
750
        for (int i = 0; i < pluginDirs.length; i++) {
751
            if (pluginDirs[i].isDirectory()) {
752
                File configXml = new File(pluginDirs[i].getAbsolutePath() +
753
                        File.separator + "config.xml");
754

    
755
                try {
756
                    FileReader xml = new FileReader(configXml);
757
                    PluginConfig pConfig = (PluginConfig) PluginConfig.unmarshal(xml);
758
                    pluginsConfig.put(pluginDirs[i].getName(), pConfig);
759
                } catch (FileNotFoundException e) {
760
                    logger.info("Ignorando el directorio " +
761
                        pluginDirs[i].getAbsolutePath() +
762
                        " por no encontrar su fichero 'config.xml'");
763
                } catch (MarshalException e) {
764
                    logger.info("Ignorando el directorio " +
765
                        pluginDirs[i].getAbsolutePath() +
766
                        " por fichero 'config.xml' mal formado", e);
767
                } catch (ValidationException e) {
768
                    logger.info("Ignorando el directorio " +
769
                        pluginDirs[i].getAbsolutePath() +
770
                        " por fichero 'config.xml' mal formado", e);
771
                }
772
            }
773
        }
774
    }
775

    
776
    /**
777
     * DOCUMENT ME!
778
     *
779
     * @param language
780
     * @param country
781
     * @param variant
782
     *
783
     * @return DOCUMENT ME!
784
     */
785
    private static Locale getLocale(String language, String country,
786
        String variant) {
787
        if (variant != null) {
788
            return new Locale(language, country, variant);
789
        } else if (country != null) {
790
            return new Locale(language, country);
791
        } else if (language != null) {
792
            return new Locale(language);
793
        } else {
794
            return new Locale("es");
795
        }
796
    }
797

    
798
    /**
799
     * DOCUMENT ME!
800
     *
801
     * @param file DOCUMENT ME!
802
     *
803
     * @throws IOException DOCUMENT ME!
804
     * @throws MarshalException DOCUMENT ME!
805
     * @throws ValidationException DOCUMENT ME!
806
     */
807
    private static void andamiConfigToXML(String file)
808
        throws IOException, MarshalException, ValidationException {
809
        File xml = new File(file);
810

    
811
        FileWriter writer = new FileWriter(xml);
812
        andamiConfig.marshal(writer);
813
    }
814

    
815
    /**
816
     * DOCUMENT ME!
817
     *
818
     * @param file DOCUMENT ME!
819
     *
820
     * @throws ConfigurationException DOCUMENT ME!
821
     */
822
    private static void andamiConfigFromXML(String file)
823
        throws ConfigurationException {
824
        File xml = new File(file);
825

    
826
        //Si no existe se ponen los valores por defecto
827
        if (!xml.exists()) {
828
            andamiConfig = new AndamiConfig();
829

    
830
            Andami andami = new Andami();
831
            andami.setUpdate(true);
832
            andamiConfig.setAndami(andami);
833
            andamiConfig.setLocaleCountry(Locale.getDefault().getCountry());
834
            andamiConfig.setLocaleLanguage(Locale.getDefault().getLanguage());
835
            andamiConfig.setLocaleVariant(Locale.getDefault().getVariant());
836
            andamiConfig.setPluginsDirectory(appName + File.separator + "extensiones");
837
            andamiConfig.setPlugin(new Plugin[0]);
838
        } else {
839
            //Se lee la configuraci?n
840
            FileReader reader;
841

    
842
            try {
843
                reader = new FileReader(xml);
844
                andamiConfig = (AndamiConfig) AndamiConfig.unmarshal(reader);
845
            } catch (FileNotFoundException e) {
846
                throw new ConfigurationException(e);
847
            } catch (MarshalException e) {
848
                throw new ConfigurationException(e);
849
            } catch (ValidationException e) {
850
                throw new ConfigurationException(e);
851
            }
852
        }
853
    }
854

    
855
    /**
856
     * DOCUMENT ME!
857
     *
858
     * @return DOCUMENT ME!
859
     *
860
     * @throws ConfigurationException DOCUMENT ME!
861
     */
862
    private static XMLEntity persistenceFromXML() throws ConfigurationException {
863
        File xml = new File(pluginsPersistencePath);
864

    
865
        if (xml.exists()) {
866
            FileReader reader;
867

    
868
            try {
869
                reader = new FileReader(xml);
870

    
871
                XmlTag tag = (XmlTag) XmlTag.unmarshal(reader);
872

    
873
                return new XMLEntity(tag);
874
            } catch (FileNotFoundException e) {
875
                throw new ConfigurationException(e);
876
            } catch (MarshalException e) {
877
                throw new ConfigurationException(e);
878
            } catch (ValidationException e) {
879
                throw new ConfigurationException(e);
880
            }
881
        } else {
882
            return new XMLEntity();
883
        }
884
    }
885

    
886
    /**
887
     * DOCUMENT ME!
888
     *
889
     * @param entity DOCUMENT ME!
890
     *
891
     * @throws ConfigurationException DOCUMENT ME!
892
     */
893
    private static void persistenceToXML(XMLEntity entity)
894
        throws ConfigurationException {
895
        File xml = new File(pluginsPersistencePath);
896

    
897
        FileWriter writer;
898

    
899
        try {
900
            writer = new FileWriter(xml);
901
            entity.getXmlTag().marshal(writer);
902
        } catch (FileNotFoundException e) {
903
            throw new ConfigurationException(e);
904
        } catch (MarshalException e) {
905
            throw new ConfigurationException(e);
906
        } catch (ValidationException e) {
907
            throw new ConfigurationException(e);
908
        } catch (IOException e) {
909
            throw new ConfigurationException(e);
910
        }
911
    }
912

    
913
    /**
914
     * Devuelve un array con los directorios de los plugins
915
     *
916
     * @param dirExt Directorio de las extensiones a partir del cual cuelgan
917
     *        todos los directorios de los plugins
918
     *
919
     * @return ArrayList con los directorios
920
     */
921
    private String[] getLocales(File dirExt) {
922
        ArrayList types = new ArrayList();
923
        File[] files = dirExt.listFiles();
924

    
925
        for (int i = 0; i < files.length; i++) {
926
            if (files[i].isDirectory()) {
927
                File[] textFile = files[i].listFiles(new FilenameFilter() {
928
                            public boolean accept(File dir, String fileName) {
929
                                return fileName.toLowerCase().startsWith("text_"); //$NON-NLS-1$
930
                            }
931
                        });
932

    
933
                for (int j = 0; j < textFile.length; j++) {
934
                    String s = (textFile[j]).getName().replaceAll("text_", "");
935
                    s = s.replaceAll(".properties", "");
936
                    s = s.trim();
937

    
938
                    if (!types.contains(s)) {
939
                        types.add(s);
940
                    }
941
                }
942
            }
943
        }
944

    
945
        return (String[]) types.toArray(new String[0]);
946
    }
947

    
948
    /**
949
     * DOCUMENT ME!
950
     *
951
     * @return Returns the frame.
952
     */
953
    static MDIFrame getFrame() {
954
        return frame;
955
    }
956

    
957
    /**
958
     * Secuencia de cerrado de Andami
959
     */
960
    public static void closeApplication() {
961
        //Configuraci?n de Andami
962
        try {
963
            andamiConfigToXML(andamiConfigPath);
964
        } catch (MarshalException e) {
965
            logger.error("No se pudo guardar la configuraci?n de Andami", e);
966
        } catch (ValidationException e) {
967
            logger.error("No se pudo guardar la configuraci?n de Andami", e);
968
        } catch (IOException e) {
969
            logger.error("No se pudo guardar la configuraci?n de Andami", e);
970
        }
971

    
972
        //Persistencia de los plugins
973
        Iterator i = pluginsConfig.keySet().iterator();
974

    
975
        XMLEntity entity = new XMLEntity();
976

    
977
        while (i.hasNext()) {
978
            String pName = (String) i.next();
979
            PluginServices ps = (PluginServices) pluginsServices.get(pName);
980
            XMLEntity ent = ps.getPersistentXML();
981

    
982
            if (ent != null) {
983
                ent.putProperty("com.iver.andami.pluginName", pName);
984
                entity.addChild(ent);
985
            }
986
        }
987

    
988
        try {
989
            persistenceToXML(entity);
990
        } catch (ConfigurationException e1) {
991
            logger.error("Se produjo un error guardando la configuraci?n de los plugins",
992
                e1);
993
        }
994

    
995
        System.exit(0);
996
    }
997

    
998
    /**
999
     * DOCUMENT ME!
1000
     *
1001
     * @return DOCUMENT ME!
1002
     */
1003
    static HashMap getClassesExtensions() {
1004
        return classesExtensions;
1005
    }
1006

    
1007
    /**
1008
     * DOCUMENT ME!
1009
     *
1010
     * @author $author$
1011
     * @version $Revision: 1013 $
1012
     */
1013
    public static class ExtensionComparator implements Comparator {
1014
        /**
1015
         * DOCUMENT ME!
1016
         *
1017
         * @param o1 DOCUMENT ME!
1018
         * @param o2 DOCUMENT ME!
1019
         *
1020
         * @return DOCUMENT ME!
1021
         */
1022
        public int compare(Object o1, Object o2) {
1023
            Extension e1 = (Extension) o1;
1024
            Extension e2 = (Extension) o2;
1025

    
1026
            if (!e1.hasPriority() && !e2.hasPriority()) {
1027
                return -1;
1028
            }
1029

    
1030
            if (e1.hasPriority() && !e2.hasPriority()) {
1031
                return -Integer.MAX_VALUE;
1032
            }
1033

    
1034
            if (e2.hasPriority() && !e1.hasPriority()) {
1035
                return Integer.MAX_VALUE;
1036
            }
1037

    
1038
            return e1.getPriority() - e2.getPriority();
1039
        }
1040
    }
1041

    
1042
    /**
1043
     * DOCUMENT ME!
1044
     */
1045
    public static class MenuComparator implements Comparator {
1046
        private static ExtensionComparator extComp = new ExtensionComparator();
1047

    
1048
        /**
1049
         * DOCUMENT ME!
1050
         *
1051
         * @param o1 DOCUMENT ME!
1052
         * @param o2 DOCUMENT ME!
1053
         *
1054
         * @return DOCUMENT ME!
1055
         */
1056
        public int compare(Object o1, Object o2) {
1057
            SortableMenu e1 = (SortableMenu) o1;
1058
            SortableMenu e2 = (SortableMenu) o2;
1059

    
1060
            if (!e1.menu.hasPosition() && !e2.menu.hasPosition()) {
1061
                if (e1.extension instanceof SkinExtensionType) {
1062
                    return 1;
1063
                } else if (e2.extension instanceof SkinExtensionType) {
1064
                    return -1;
1065
                } else {
1066
                    return extComp.compare(e1.extension, e2.extension);
1067
                }
1068
            }
1069

    
1070
            if (e1.menu.hasPosition() && !e2.menu.hasPosition()) {
1071
                return -Integer.MAX_VALUE;
1072
            }
1073

    
1074
            if (e2.menu.hasPosition() && !e1.menu.hasPosition()) {
1075
                return Integer.MAX_VALUE;
1076
            }
1077

    
1078
            return e1.menu.getPosition() - e2.menu.getPosition();
1079
        }
1080
    }
1081

    
1082
    /**
1083
     * DOCUMENT ME!
1084
     *
1085
     * @author $author$
1086
     * @version $Revision: 1013 $
1087
     */
1088
    public static class SortableMenu {
1089
        public Menu menu;
1090
        public SkinExtensionType extension;
1091

    
1092
        /**
1093
         * DOCUMENT ME!
1094
         *
1095
         * @param skinExt
1096
         * @param menu2
1097
         */
1098
        public SortableMenu(SkinExtensionType skinExt, Menu menu2) {
1099
            extension = skinExt;
1100
            menu = menu2;
1101
        }
1102
    }
1103
    /**
1104
     * DOCUMENT ME!
1105
     *
1106
     * @param extDir DOCUMENT ME!
1107
     */
1108
    private static void downloadExtensions(String extDir) {
1109
            try{
1110
            if (System.getProperty("javawebstart.version") != null) {
1111
                //Obtenemos la URL del servidor
1112
                BasicService bs = (BasicService) ServiceManager.lookup(
1113
                        "javax.jnlp.BasicService");
1114
                URL baseURL = bs.getCodeBase();
1115

    
1116
                //Se descargan las extensiones
1117
                SplashWindow.process(5, "Descargando las extensiones desde " 
1118
                                + baseURL + " a " + extDir);
1119
                
1120
                URL url = new URL(baseURL + "extensiones.zip");
1121
                URLConnection connection = url.openConnection();
1122
                
1123
                System.out.println(url.toExternalForm() + ":");
1124
                System.out.println("  Content Type: " + connection.getContentType());
1125
                System.out.println("  Content Length: " + connection.getContentLength());
1126
                System.out.println("  Last Modified: " + new Date(connection.getLastModified()));
1127
                System.out.println("  Expiration: " + connection.getExpiration());
1128
                System.out.println("  Content Encoding: " + connection.getContentEncoding());
1129
                
1130
                // Guardamos la fecha del fichero de extensiones que nos hemos bajado, y
1131
                // comprobamos el ?ltimo que se ha bajado. Si no son
1132
                // iguales, nos bajamos el nuevo. Si son iguales, no
1133
                // nos bajamos nada.
1134
                Long miliSecondsInWeb = new Long(connection.getLastModified());
1135
                // PluginServices ps = PluginServices.getPluginServices("com.iver.core");
1136
                
1137
                // if (ps.getPersistentXML().getStringProperty("timestamp") != null)
1138
                if (System.getProperty("timestamp") != null)
1139
                {
1140
                        
1141
                        Long lastMiliSeconds = (Long) new Long(Date.parse(System.getProperty("timestamp")));                
1142
                        if (lastMiliSeconds.longValue() == miliSecondsInWeb.longValue())
1143
                        {
1144
                                System.out.println("No hay nueva actualizaci?n");
1145
                                return;
1146
                        }
1147
                        System.out.println("timeStampWeb= " + miliSecondsInWeb);
1148
                        System.out.println("timeStampLocal= " + lastMiliSeconds);
1149
                }
1150
                else
1151
                {
1152
                        System.out.println("El timeStamp no est? escrito en el status");
1153
                }
1154
                
1155
                    
1156
                InputStream stream = connection.getInputStream();
1157
                File temp = File.createTempFile("gvsig", ".zip");
1158
                temp.deleteOnExit();
1159

    
1160
                FileOutputStream file = new FileOutputStream(temp);
1161
                BufferedInputStream in = new BufferedInputStream(stream);
1162
                BufferedOutputStream out = new BufferedOutputStream(file);
1163

    
1164
                int i;
1165
                int pct, desde, hasta;
1166

    
1167
                hasta = connection.getContentLength() / 1024;
1168
                desde = 0;
1169
                while ((i = in.read()) != -1) {
1170
                        pct = (desde/1024)*100/hasta;
1171
                        if (((desde % 10240) == 0) && (pct > 10) && ((pct % 10)==0)) 
1172
                                SplashWindow.process(pct, (desde / 1024) + "Kb de " + hasta + "Kb descargados..."); 
1173
                    out.write(i);
1174
                    desde++;
1175
                }
1176

    
1177
                out.flush();
1178
                out.close();
1179
                in.close();
1180

    
1181
                //Se extrae el zip
1182
                SplashWindow.process(5, "Extensiones descargadas.");
1183
                File destDir = new File(extDir);
1184
                
1185
                System.out.println("Extrayendo a " + destDir.getAbsolutePath());
1186
                if (!destDir.exists())
1187
                        if (!destDir.mkdir())
1188
                                System.err.println("Imposible crear el directorio " + destDir.getAbsolutePath());
1189

    
1190
                Date fechaDir = new Date(destDir.lastModified());
1191
                System.out.println("Fecha del directorio " + extDir + " = " + fechaDir.toString());
1192
                Utilities.extractTo(temp, new File(extDir), splashWindow);
1193
                
1194
                // Si todo ha ido bien, guardamos el timestamp.
1195
             ///  App.instance.getPc().addProperties("timestamp", miliSecondsInWeb);
1196
                // XMLEntity xml=ps.getPersistentXML();
1197
                    java.util.Date fechaActual = new java.util.Date();
1198
                    System.setProperty("timestamp",fechaActual.toGMTString());
1199
                    /* xml.putProperty("timestamp",fechaActual.toGMTString());
1200
                    ps.setPresistentXML(xml); */
1201
            }
1202
            }catch(IOException e){
1203
                    NotificationManager.addError("",e);
1204
            } catch (UnavailableServiceException e) {
1205
                    NotificationManager.addError("",e);
1206
                }
1207
    }
1208
        private static Extensions[] getExtensions(){
1209
        ArrayList array=new ArrayList();
1210
                Iterator iter=pluginsConfig.values().iterator();
1211
                while(iter.hasNext()){
1212
                        array.add(((PluginConfig)iter.next()).getExtensions());
1213
                }
1214
                return (Extensions[])array.toArray(new Extensions[0]);
1215
        }
1216
        
1217
        public static HashMap getPluginConfig(){
1218
                return pluginsConfig;
1219
        }
1220
        public static Extension getExtension(String s){
1221
                
1222
                Extensions[] exts=getExtensions();
1223
                for (int i=0;i<exts.length;i++){
1224
                        for (int j=0;j<exts[i].getExtensionCount();j++){
1225
                                if (exts[i].getExtension(j).getClassName().equals(s)){
1226
                                        return exts[i].getExtension(j);
1227
                                }
1228
                        }        
1229
                }
1230
                return null;
1231
        }
1232
        public static AndamiConfig getAndamiConfig(){
1233
                return andamiConfig;
1234
        }
1235
        /*public static Extension getExtension(Class s) {
1236
                //String aux=s.getName().substring(s.getName().lastIndexOf("."),s.getName().length());
1237
                String aux1=s.getName().substring(0,s.getName().lastIndexOf("."));
1238
                PluginConfig p=(PluginConfig)pluginsConfig.get(aux1);
1239
                Extension ext=null;
1240
                if (p!=null){
1241
                Extensions exts=p.getExtensions();
1242
                
1243
                for (int i=0;i<exts.getExtensionCount();i++){
1244
                        if (exts.getExtension(i).getClassName().equals(s.getName())){
1245
                                ext=exts.getExtension(i);
1246
                        }
1247
                }
1248
                }
1249
                return ext;
1250
        }
1251
        */
1252
}