Statistics
| Revision:

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

History | View | Annotate | Download (41.9 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: 759 $
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
        // Se leen los config.xml de los plugins -----++++
152
        loadPlugins(andamiConfig.getPluginsDirectory());
153

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

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

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

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

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

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

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

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

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

    
192
        // Leer el fichero de persistencia
193
        //  info de los plugins
194
        //  bookmarks de los plugins
195
        loadPluginsPersistence();
196
        downloadExtensions(andamiConfig.getPluginsDirectory());
197

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
285
                Class skinClass;
286

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
614
                        continue;
615
                    }
616

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

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

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

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

    
645
                PluginClassLoader loader;
646

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

    
653
                    PluginServices ps = new PluginServices(loader);
654

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

    
657
                    instalados.add(pluginName);
658

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

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

    
670
                break;
671
            }
672
        }
673

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

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

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

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

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

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

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

    
709
    /**
710
     * DOCUMENT ME!
711
     *
712
     * @param name DOCUMENT ME!
713
     *
714
     * @return DOCUMENT ME!
715
     */
716
    static PluginServices getPluginServices(String name) {
717
        return (PluginServices) pluginsServices.get(name);
718
    }
719
    
720
    static String getPluginsDir(){
721
            return andamiConfig.getPluginsDirectory();            
722
    }
723

    
724
    /**
725
     * DOCUMENT ME!
726
     *
727
     * @return DOCUMENT ME!
728
     */
729
    static MDIFrame getMDIFrame() {
730
        return frame;
731
    }
732

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

    
741
        if (!pDir.exists()) {
742
            return;
743
        }
744

    
745
        File[] pluginDirs = pDir.listFiles();
746

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

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

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

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

    
808
        FileWriter writer = new FileWriter(xml);
809
        andamiConfig.marshal(writer);
810
    }
811

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

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

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

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

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

    
862
        if (xml.exists()) {
863
            FileReader reader;
864

    
865
            try {
866
                reader = new FileReader(xml);
867

    
868
                XmlTag tag = (XmlTag) XmlTag.unmarshal(reader);
869

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

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

    
894
        FileWriter writer;
895

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

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

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

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

    
935
                    if (!types.contains(s)) {
936
                        types.add(s);
937
                    }
938
                }
939
            }
940
        }
941

    
942
        return (String[]) types.toArray(new String[0]);
943
    }
944

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

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

    
969
        //Persistencia de los plugins
970
        Iterator i = pluginsConfig.keySet().iterator();
971

    
972
        XMLEntity entity = new XMLEntity();
973

    
974
        while (i.hasNext()) {
975
            String pName = (String) i.next();
976
            PluginServices ps = (PluginServices) pluginsServices.get(pName);
977
            XMLEntity ent = ps.getPersistentXML();
978

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

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

    
992
        System.exit(0);
993
    }
994

    
995
    /**
996
     * DOCUMENT ME!
997
     *
998
     * @return DOCUMENT ME!
999
     */
1000
    static HashMap getClassesExtensions() {
1001
        return classesExtensions;
1002
    }
1003

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

    
1023
            if (!e1.hasPriority() && !e2.hasPriority()) {
1024
                return -1;
1025
            }
1026

    
1027
            if (e1.hasPriority() && !e2.hasPriority()) {
1028
                return -Integer.MAX_VALUE;
1029
            }
1030

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

    
1035
            return e1.getPriority() - e2.getPriority();
1036
        }
1037
    }
1038

    
1039
    /**
1040
     * DOCUMENT ME!
1041
     */
1042
    public static class MenuComparator implements Comparator {
1043
        private static ExtensionComparator extComp = new ExtensionComparator();
1044

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

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

    
1067
            if (e1.menu.hasPosition() && !e2.menu.hasPosition()) {
1068
                return -Integer.MAX_VALUE;
1069
            }
1070

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

    
1075
            return e1.menu.getPosition() - e2.menu.getPosition();
1076
        }
1077
    }
1078

    
1079
    /**
1080
     * DOCUMENT ME!
1081
     *
1082
     * @author $author$
1083
     * @version $Revision: 759 $
1084
     */
1085
    public static class SortableMenu {
1086
        public Menu menu;
1087
        public SkinExtensionType extension;
1088

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

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

    
1156
                FileOutputStream file = new FileOutputStream(temp);
1157
                BufferedInputStream in = new BufferedInputStream(stream);
1158
                BufferedOutputStream out = new BufferedOutputStream(file);
1159

    
1160
                int i;
1161
                int pct, desde, hasta;
1162

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

    
1173
                out.flush();
1174
                out.close();
1175
                in.close();
1176

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