Statistics
| Revision:

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

History | View | Annotate | Download (52.9 KB)

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

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

    
75
import javax.jnlp.BasicService;
76
import javax.jnlp.ServiceManager;
77
import javax.jnlp.UnavailableServiceException;
78
import javax.swing.ImageIcon;
79
import javax.swing.JComponent;
80
import javax.swing.JOptionPane;
81
import javax.swing.SwingUtilities;
82
import javax.swing.UIManager;
83

    
84
import org.apache.log4j.Logger;
85
import org.apache.log4j.PatternLayout;
86
import org.apache.log4j.PropertyConfigurator;
87
import org.apache.log4j.RollingFileAppender;
88
import org.exolab.castor.xml.MarshalException;
89
import org.exolab.castor.xml.ValidationException;
90

    
91
import com.iver.andami.authentication.IAuthentication;
92
import com.iver.andami.config.generate.Andami;
93
import com.iver.andami.config.generate.AndamiConfig;
94
import com.iver.andami.config.generate.Plugin;
95
import com.iver.andami.messages.Messages;
96
import com.iver.andami.messages.NotificationManager;
97
import com.iver.andami.plugins.ExtensionDecorator;
98
import com.iver.andami.plugins.PluginClassLoader;
99
import com.iver.andami.plugins.config.generate.ActionTool;
100
import com.iver.andami.plugins.config.generate.Depends;
101
import com.iver.andami.plugins.config.generate.Extension;
102
import com.iver.andami.plugins.config.generate.Extensions;
103
import com.iver.andami.plugins.config.generate.LabelSet;
104
import com.iver.andami.plugins.config.generate.Menu;
105
import com.iver.andami.plugins.config.generate.PluginConfig;
106
import com.iver.andami.plugins.config.generate.PopupMenu;
107
import com.iver.andami.plugins.config.generate.PopupMenus;
108
import com.iver.andami.plugins.config.generate.SelectableTool;
109
import com.iver.andami.plugins.config.generate.SkinExtension;
110
import com.iver.andami.plugins.config.generate.SkinExtensionType;
111
import com.iver.andami.plugins.config.generate.ToolBar;
112
import com.iver.andami.ui.AndamiEventQueue;
113
import com.iver.andami.ui.MDIManagerLoadException;
114
import com.iver.andami.ui.SplashWindow;
115
import com.iver.andami.ui.mdiFrame.MDIFrame;
116
import com.iver.andami.ui.mdiManager.MDIManagerFactory;
117
import com.iver.utiles.XMLEntity;
118
import com.iver.utiles.xmlEntity.generate.XmlTag;
119

    
120

    
121
/**
122
 * DOCUMENT ME!
123
 *
124
 * @author $author$
125
 * @version $Revision: 5597 $
126
 */
127
public class Launcher {
128
        private static Logger logger = Logger.getLogger(Launcher.class.getName());
129
        private static AndamiConfig andamiConfig;
130
        private static SplashWindow splashWindow;
131
        private static String userHome = System.getProperty("user.home");
132
        private static String appName;
133
        private static Locale locale;
134
        private static HashMap pluginsConfig = new HashMap();
135
        private static HashMap pluginsServices = new HashMap();
136
        private static MDIFrame frame;
137
        private static HashMap classesExtensions = new HashMap();
138
        private static String andamiConfigPath;
139
        private static String pluginsPersistencePath;
140
    
141
    private static ArrayList pluginsOrdered = new ArrayList();
142

    
143
        /**
144
         * DOCUMENT ME!
145
         *
146
         * @param args DOCUMENT ME!
147
         * @throws Exception
148
         *
149
         * @throws InterruptedException
150
         * @throws InvocationTargetException
151
         * @throws ConfigurationException
152
         * @throws MDIManagerLoadException
153
         * @throws IOException
154
         */
155
        public static void main(String[] args) throws Exception {
156
            try{
157

    
158
            if (!validJVM()){
159
                System.exit(-1);
160
            }
161
                
162
            if (args.length < 1) {
163
                        System.err.println("Uso: Launcher appName plugins-directory [language=locale]");
164
                }
165

    
166
            //  Clean temporal files
167
                Utilities.cleanUpTempFiles();
168

    
169
                appName = args[0];
170

    
171
                //Se crea el directorio de configuraci?n de la aplicaci?n
172
                File parent = new File(System.getProperty("user.home") +
173
                                File.separator + args[0] + File.separator);
174
                parent.mkdirs();
175

    
176
                andamiConfigPath = System.getProperty("user.home") + File.separator +
177
                        appName + File.separator + "andami-config.xml";
178
                pluginsPersistencePath = System.getProperty("user.home") +
179
                        File.separator + appName + File.separator +
180
                        "plugins-persistence.xml";
181

    
182
                // Configurar el log4j
183
                PropertyConfigurator.configure(Launcher.class.getClassLoader()
184
                                                                                                         .getResource("log4j.properties"));
185

    
186
                PatternLayout l = new PatternLayout("%p %t %C - %m%n");
187
                RollingFileAppender fa = new RollingFileAppender(l,
188
                                System.getProperty("user.home") + File.separator + args[0] +
189
                                File.separator + args[0] + ".log", false);
190
                fa.setMaxFileSize("512KB");
191
                fa.setMaxBackupIndex(3);
192
                Logger.getRootLogger().addAppender(fa);
193

    
194
                // Leer el fichero de configuraci?n de andami (andami-config.xsd)
195
                // locale
196
                // Buscar actualizaci?nes al comenzar
197
                //  Andami
198
                //  Plugins
199
                // Directorio de las extensiones
200
                andamiConfigFromXML(andamiConfigPath);
201
                andamiConfig.setPluginsDirectory(args[1]);
202
                
203
                // Hacemos visibles los argumentos como una propiedad est?tica
204
                // de plugin services para quien lo quiera usar (por ejemplo, para
205
                // cargar un proyecto por l?nea de comandos)
206
                PluginServices.setArguments(args);
207

    
208
                // Configurar el locale
209
        String localeStr = null;
210
        for (int i=2; i < args.length; i++)
211
        {
212
                int index = args[i].indexOf("language="); 
213
                if (index != -1)
214
                        localeStr = args[i].substring(index+9);
215
        }
216
                if (localeStr == null)
217
                {
218
            localeStr = andamiConfig.getLocaleLanguage();
219
                        /* locale = getLocale(localeStr,
220
                                        andamiConfig.getLocaleCountry(),
221
                                        andamiConfig.getLocaleVariant()); */
222
                }
223
        if (localeStr.compareTo("va")==0)
224
        {
225
            locale = new Locale("ca");
226
        }
227
        else
228
        {
229
            // locale = Locale.getDefault();
230
            locale = getLocale(localeStr,
231
                    andamiConfig.getLocaleCountry(),
232
                    andamiConfig.getLocaleVariant());
233
        }
234
        org.gvsig.i18n.Messages.addLocale(locale);
235
                // add english as a fallback language
236
                org.gvsig.i18n.Messages.addLocale(new Locale("en"));
237
                org.gvsig.i18n.Messages.addLocale(new Locale("es"));
238
        org.gvsig.i18n.Messages.addResourceFamily("com.iver.andami.text", "com.iver.andami.text");
239
                Locale.setDefault(locale);
240
                JComponent.setDefaultLocale(locale);
241

    
242
                //Se pone el lookAndFeel
243
                try {
244
                        UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
245
                } catch (Exception e) {
246
                        logger.warn(Messages.getString("Launcher.look_and_feel"), e);
247
                }
248

    
249
                // Mostrar la ventana de inicio
250
                splashWindow = new SplashWindow(null);
251

    
252
                // TODO Buscar actualizaciones de los plugins
253
                downloadExtensions(andamiConfig.getPluginsDirectory());
254
                
255
                validate();
256

    
257
                // Se leen los config.xml de los plugins -----++++
258
                loadPlugins(andamiConfig.getPluginsDirectory());
259

    
260
                // Se configura el classloader del plugin
261
                pluginsClassLoaders();
262

    
263
                // Se carga un Skin si alguno de los plugins trae informaci?n para ello
264
                skinPlugin();
265

    
266
                //Se configura la cola de eventos
267
                EventQueue waitQueue = new AndamiEventQueue();
268
                Toolkit.getDefaultToolkit().getSystemEventQueue().push(waitQueue);
269

    
270
                // Se configura la mensajer?a del plugin
271
                pluginsMessages();
272

    
273
                // Se modifica el andami-config con los plugins nuevos
274
                updateAndamiConfig();
275

    
276
                // Se prepara el MainFrame para albergar las extensiones
277
                frame = new MDIFrame();
278

    
279
                // Se configura el nombre e icono de la aplicaci?n
280
                frameIcon();
281

    
282
                SwingUtilities.invokeAndWait(new Runnable() {
283
                                public void run() {
284
                                        frame.init();
285
                                }
286
                        });
287

    
288
                // Se instalan los controles de las extensiones de los plugins
289
                SwingUtilities.invokeAndWait(new Runnable() {
290
                                public void run() {
291
                                        installPluginsControls();
292
                                        installPluginsMenus();
293
                                        installPluginsLabels();
294
                                }
295
                        });
296

    
297
                // Leer el fichero de persistencia
298
                //  info de los plugins
299
                //  bookmarks de los plugins
300
                loadPluginsPersistence();
301

    
302
                // Se instalan los controles del skin
303
                // Se inicializan todas las extensiones de todos los plugins
304
                SwingUtilities.invokeAndWait(new Runnable() {
305
                                public void run() {
306
                                        initializeExtensions();
307
                                }
308
                        });
309
                frame.setClassesExtensions(classesExtensions);
310

    
311
                // Se instalan los bookmarks de los plugins
312
                splashWindow.close();
313

    
314
                //Se muestra el frame principal
315
                frame.show();
316

    
317
                SwingUtilities.invokeAndWait(new Runnable() {
318
                                public void run() {
319
                                        frame.enableControls();
320
                                }
321
                        });
322
            }catch(Exception e){
323
                logger.error("excepci?n al arrancar", e);
324
                System.exit(-1);
325
            }
326
            
327
        }
328
        
329
        /**
330
         * Recupera la geometr?a (tama?o, posici?n y estado) de la ventana principal de Andami.
331
         * TODO Pendiente de ver como se asigna un pluginServices para el launcher.
332
         * @author LWS
333
         */
334
        private static void restoreMDIStatus(XMLEntity xml) {
335
                //System.err.println("Launcher: restoreMDIStatus()");
336
                if (xml == null) xml = new XMLEntity();
337
                //  restore frame size
338
                Dimension sz = new Dimension(700,580);
339
                if (xml.contains("MDIFrameSize")) {
340
                        int [] wh = xml.getIntArrayProperty("MDIFrameSize");
341
                        sz = new Dimension(wh[0], wh[1]);
342
                }
343
                frame.setSize(sz);
344
                //  restore frame location
345
                Point pos = new Point(10,10);
346
                if (xml.contains("MDIFramePos")) {
347
                        int [] xy = xml.getIntArrayProperty("MDIFramePos");
348
                        pos = new Point(xy[0], xy[1]);
349
                }
350
                frame.setLocation(pos);
351
                
352
                //  restore frame status (Maximized, minimized, etc);
353
                int state = java.awt.Frame.MAXIMIZED_BOTH;
354
                if (xml.contains("MDIFrameState")) {
355
                        state = xml.getIntProperty("MDIFrameState");
356
                }
357
                frame.setExtendedState(state);
358
        }
359
        
360
        private static XMLEntity saveMDIStatus() {
361
                XMLEntity xml = new XMLEntity();
362
                // save frame size
363
                int [] wh = new int[2];
364
                wh[0] = frame.getWidth();
365
                wh[1] = frame.getHeight();
366
                xml.putProperty("MDIFrameSize", wh);
367
                // save frame location
368
                int [] xy = new int[2];
369
                xy[0] = frame.getX();
370
                xy[1] = frame.getY();
371
                xml.putProperty("MDIFramePos", xy);
372
                // save frame status
373
                xml.putProperty("MDIFrameState", frame.getExtendedState());
374
                return xml;
375
        }
376

    
377
        /**
378
     * @return
379
     */
380
    private static boolean validJVM() {
381
        char thirdCharacter = System.getProperty("java.version").charAt(2);
382
        if (thirdCharacter < '4'){
383
            return false;
384
            }else{
385
                return true;
386
            }
387
    }
388

    
389
    /**
390
         * DOCUMENT ME!
391
         *
392
         * @throws ConfigurationException
393
         */
394
        private static void loadPluginsPersistence() throws ConfigurationException {
395
                XMLEntity entity = persistenceFromXML();
396

    
397
                //System.err.println("loadPluginPersistence()");
398
                for (int i = 0; i < entity.getNumChild(); i++) {
399
                        XMLEntity plugin = entity.getChild(i);
400
                        String pName = plugin.getStringProperty(
401
                                        "com.iver.andami.pluginName");
402
                        //System.err.println("--> "+pName);
403
                        if (pluginsServices.get(pName)!= null){
404
                                ((PluginServices) pluginsServices.get(pName)).setPersistentXML(plugin);
405
                        } else {
406
                                if (pName.startsWith("Andami.Launcher"))
407
                                        restoreMDIStatus(plugin);
408
                        }
409
                }
410
        }
411
        
412
        /**
413
         * Salva la persistencia de los plugins.
414
         * @author LWS
415
         */
416
        private static void savePluginPersistence() {
417
                Iterator i = pluginsConfig.keySet().iterator();
418

    
419
                XMLEntity entity = new XMLEntity();
420

    
421
                while (i.hasNext()) {
422
                        String pName = (String) i.next();
423
                        PluginServices ps = (PluginServices) pluginsServices.get(pName);
424
                        XMLEntity ent = ps.getPersistentXML();
425

    
426
                        if (ent != null) {
427
                                ent.putProperty("com.iver.andami.pluginName", pName);
428
                                entity.addChild(ent);
429
                        }
430
                }
431
                XMLEntity ent = saveMDIStatus();
432
                if (ent != null) {
433
                        ent.putProperty("com.iver.andami.pluginName", "Andami.Launcher");
434
                        entity.addChild(ent);
435
                }
436
                try {
437
                        persistenceToXML(entity);
438
                } catch (ConfigurationException e1) {
439
                        logger.error(Messages.getString(
440
                                        "Launcher.Se_produjo_un_error_guardando_la_configuracion_de_los_plugins"),
441
                                e1);
442
                }
443
        }
444

    
445
        /**
446
         * DOCUMENT ME!
447
         */
448
        private static void installPluginsLabels() {
449
                Iterator i = pluginsConfig.keySet().iterator();
450

    
451
                while (i.hasNext()) {
452
                        String name = (String) i.next();
453
                        PluginConfig pc = (PluginConfig) pluginsConfig.get(name);
454
                        PluginServices ps = (PluginServices) pluginsServices.get(name);
455

    
456
                        LabelSet[] ls = pc.getLabelSet();
457

    
458
                        for (int j = 0; j < ls.length; j++) {
459
                                PluginClassLoader loader = ps.getClassLoader();
460

    
461
                                try {
462
                                        Class clase = loader.loadClass(ls[j].getClassName());
463
                                        frame.setLabels(clase, ls[j].getLabel());
464
                                } catch (ClassNotFoundException e) {
465
                                        logger.error(Messages.getString("Launcher.labelset_class"),
466
                                                e);
467
                                }
468
                        }
469
                }
470
        }
471

    
472
        /**
473
         * DOCUMENT ME!
474
         *
475
         * @throws MDIManagerLoadException
476
         */
477
        private static void skinPlugin() throws MDIManagerLoadException {
478
                Iterator i = pluginsConfig.keySet().iterator();
479

    
480
                while (i.hasNext()) {
481
                        String name = (String) i.next();
482
                        PluginConfig pc = (PluginConfig) pluginsConfig.get(name);
483
                        PluginServices ps = (PluginServices) pluginsServices.get(name);
484

    
485
                        if (pc.getExtensions().getSkinExtension() != null) {
486
                                if (MDIManagerFactory.getSkinExtension() != null) {
487
                                        logger.warn(Messages.getString(
488
                                                        "Launcher.Dos_skin_extension"));
489
                                }
490

    
491
                                SkinExtension se = pc.getExtensions().getSkinExtension();
492

    
493
                                MDIManagerFactory.setSkinExtension(se, ps.getClassLoader());
494

    
495
                                Class skinClass;
496

    
497
                                try {
498
                                        skinClass = ps.getClassLoader().loadClass(se.getClassName());
499

    
500
                                        com.iver.andami.plugins.IExtension skinInstance = (com.iver.andami.plugins.IExtension) skinClass.newInstance();
501
                                        // classesExtensions.put(skinClass, skinInstance);
502
                                        // jaume
503
                                        ExtensionDecorator newExtensionDecorator = new ExtensionDecorator(skinInstance, ExtensionDecorator.INACTIVE);
504
                                        classesExtensions.put(skinClass, newExtensionDecorator);
505
                                } catch (ClassNotFoundException e) {
506
                                        logger.error(Messages.getString(
507
                                                        "Launcher.No_se_encontro_la_clase_mdi_manager"), e);
508
                                        throw new MDIManagerLoadException(e);
509
                                } catch (InstantiationException e) {
510
                                        logger.error(Messages.getString(
511
                                                        "Launcher.No_se_pudo_instanciar_la_clase_mdi_manager"),
512
                                                e);
513
                                        throw new MDIManagerLoadException(e);
514
                                } catch (IllegalAccessException e) {
515
                                        logger.error(Messages.getString(
516
                                                        "Launcher.No_se_pudo_acceder_a_la_clase_mdi_manager"),
517
                                                e);
518
                                        throw new MDIManagerLoadException(e);
519
                                }
520
                        }
521
                }
522
        }
523

    
524
        /**
525
         *
526
         */
527
        private static void frameIcon() {
528
                Iterator i = pluginsConfig.keySet().iterator();
529

    
530
                while (i.hasNext()) {
531
                        String pName = (String) i.next();
532
                        PluginConfig pc = (PluginConfig) pluginsConfig.get(pName);
533
                        PluginServices ps = (PluginServices) pluginsServices.get(pName);
534

    
535
                        if (pc.getIcon() != null) {
536
                                ImageIcon icon = new ImageIcon(ps.getClassLoader().getResource(pc.getIcon()
537
                                                                                                                                                                 .getSrc()));
538
                                frame.setIconImage(icon.getImage());
539
                                frame.setTitlePrefix(pc.getIcon().getText());
540
                        }
541
                }
542
        }
543

    
544
        /**
545
         *
546
         */
547
        private static void initializeExtensions() {
548
                Iterator i = pluginsOrdered.iterator();
549

    
550
                while (i.hasNext()) {
551
                        String pName = (String) i.next();
552
            logger.debug("Initializing extensions from " + pName);
553
                        PluginConfig pc = (PluginConfig) pluginsConfig.get(pName);
554
                        PluginServices ps = (PluginServices) pluginsServices.get(pName);
555

    
556
                        Extension[] exts = pc.getExtensions().getExtension();
557

    
558
                        TreeMap orderedExtensions = new TreeMap(new ExtensionComparator());
559

    
560
                        for (int j = 0; j < exts.length; j++) {
561
                                if (!exts[j].getActive()) {
562
                                        continue;
563
                                }
564

    
565
                                if (orderedExtensions.containsKey(exts[j])) {
566
                                        logger.warn(Messages.getString(
567
                                                        "Launcher.Two_extensions_with_the_same_priority") +
568
                                                exts[j].getClassName());
569
                                }
570

    
571
                                orderedExtensions.put(exts[j], null);
572
                        }
573

    
574
                        Iterator e = orderedExtensions.keySet().iterator();
575

    
576
                        while (e.hasNext()) {
577
                                Extension extension = (Extension) e.next();
578
                                com.iver.andami.plugins.IExtension extensionInstance;
579

    
580
                                try {
581
                                        Class extensionClass = ps.getClassLoader().loadClass(extension.getClassName());
582
                                        extensionInstance = (com.iver.andami.plugins.IExtension) extensionClass.newInstance();
583
                                        
584
                                        // CON DECORATOR                                        
585
                                        // ANTES: classesExtensions.put(extensionClass, extensionInstance);
586
                                        // AHORA: CREAMOS UNA ExtensionDecorator y asignamos esta instancia para
587
                                        // poder ampliar con nuevas propiedades (AlwaysVisible, por ejemplo)
588
                                        // Para crear la nueva clase ExtensionDecorator, le pasamos como par?metro
589
                                        // la extensi?n original que acabamos de crear
590
                                        // 0-> Inactivo, controla la extension
591
                                        // 1-> Siempre visible
592
                                        // 2-> Invisible
593
                                        ExtensionDecorator newExtensionDecorator = new ExtensionDecorator(extensionInstance, ExtensionDecorator.INACTIVE);
594
                                        classesExtensions.put(extensionClass, newExtensionDecorator);
595
                                        System.err.println("Loading "+extension.getClassName()+"...");
596
                    // logger.debug("Initializing " + extension.getClassName());
597
                    extensionInstance.initialize();
598
                    // logger.debug(extension.getClassName() + " initialized.");
599

    
600
                                } catch (InstantiationException e1) {
601
                                        logger.error(Messages.getString(
602
                                                        "Launcher.Error_instanciando_la_extension") +
603
                                                extension.getClassName(), e1);
604
                                } catch (IllegalAccessException e1) {
605
                                        logger.error(Messages.getString(
606
                                                        "Launcher.Error_instanciando_la_extension") +
607
                                                extension.getClassName(), e1);
608
                                } catch (ClassNotFoundException e1) {
609
                                        logger.error(Messages.getString(
610
                                                        "Launcher.No_se_encontro_la_clase_de_la_extension") +
611
                                                extension.getClassName(), e1);
612
                                } catch (NoClassDefFoundError e1) {
613
                                        logger.error(Messages.getString(
614
                                                        "Launcher.Error_localizando_la_clase_de_la_extension") +
615
                                                extension.getClassName(), e1);
616
                                }
617
                        }
618
                }
619
        }
620

    
621
        /**
622
         * DOCUMENT ME!
623
         */
624
        private static void installPluginsMenus() {
625
                TreeMap orderedMenus = new TreeMap(new MenuComparator());
626

    
627
                Iterator i = pluginsConfig.keySet().iterator();
628

    
629
                while (i.hasNext()) {
630
                        String pName = (String) i.next();
631
                        PluginServices ps = (PluginServices) pluginsServices.get(pName);
632
                        PluginConfig pc = (PluginConfig) pluginsConfig.get(pName);
633

    
634
                        Extension[] exts = pc.getExtensions().getExtension();
635

    
636
                        for (int j = 0; j < exts.length; j++) {
637
                                if (!exts[j].getActive()) {
638
                                        continue;
639
                                }
640

    
641
                                Menu[] menus = exts[j].getMenu();
642

    
643
                                for (int k = 0; k < menus.length; k++) {
644
                                        SortableMenu sm = new SortableMenu(ps.getClassLoader(),
645
                                                        exts[j], menus[k]);
646

    
647
                                        if (orderedMenus.containsKey(sm)) {
648
                                                logger.error(Messages.getString(
649
                                                                "Launcher.Two_menus_with_the_same_position") +
650
                                                        exts[j].getClassName());
651
                                        }
652

    
653
                                        orderedMenus.put(sm, null);
654
                                }
655
                        }
656

    
657
                        // Se instalan las extensiones de MDI
658
                        SkinExtension skinExt = pc.getExtensions().getSkinExtension();
659

    
660
                        if (skinExt != null) {
661
                                Menu[] menu = skinExt.getMenu();
662

    
663
                                for (int k = 0; k < menu.length; k++) {
664
                                        SortableMenu sm = new SortableMenu(ps.getClassLoader(),
665
                                                        skinExt, menu[k]);
666

    
667
                                        if (orderedMenus.containsKey(sm)) {
668
                                                logger.error(Messages.getString(
669
                                                                "Launcher.Two_menus_with_the_same_position") +
670
                                                        skinExt.getClassName());
671
                                        }
672

    
673
                                        orderedMenus.put(sm, null);
674
                                }
675
                        }
676
                }
677

    
678
                //Se itera por los menus ordenados
679
                Iterator e = orderedMenus.keySet().iterator();
680

    
681
                // Se ordenan los menues
682
                while (e.hasNext()) {
683
                        try {
684
                                SortableMenu sm = (SortableMenu) e.next();
685

    
686
                                frame.addMenu(sm.loader, sm.extension, sm.menu);
687
                        } catch (ClassNotFoundException ex) {
688
                                logger.error(Messages.getString(
689
                                                "Launcher.No_se_encontro_la_clase_de_la_extension"), ex);
690
                        }
691
                }
692
        }
693

    
694
        /**
695
         * Installs the menus, toolbars, actiontools and selectable toolbars.
696
         * The order in which they are shown is determined here. 
697
         */
698
        private static void installPluginsControls() {
699
                Iterator i = pluginsConfig.keySet().iterator();
700

    
701
                HashMap extensionPluginServices = new HashMap();
702
                HashMap extensionPluginConfig = new HashMap();
703
                TreeMap orderedExtensions = new TreeMap(new ExtensionComparator());
704
                Object previous;
705
                
706
                // First of all, sort the extensions.
707
                // We need to iterate on the plugins, and iterate on each plugin's extensions
708
                // (each plugin may contain one or more extensions) 
709
                while (i.hasNext()) { // iterate on the plugins
710
                        String pName = (String) i.next();
711
                        PluginConfig pc = (PluginConfig) pluginsConfig.get(pName);
712
                        PluginServices ps = (PluginServices) pluginsServices.get(pName);
713
                        
714
                        Extension[] exts = pc.getExtensions().getExtension();
715
                        
716
                        for (int j = 0; j < exts.length; j++) { // iterate on the extensions
717
                                if (exts[j].getActive()) {
718
                                        if (orderedExtensions.containsKey(exts[j])) {
719
                                                logger.error(Messages.getString(
720
                                                "Launcher.Two_extensions_with_the_same_priority") +
721
                                                exts[j].getClassName());
722
                                        }
723
                                        
724
                                        orderedExtensions.put(exts[j], null);
725
                                        extensionPluginServices.put(exts[j], ps);
726
                                        extensionPluginConfig.put(exts[j], pc);
727
                                }
728
                        }
729
                }
730

    
731
                ///try {
732
                TreeMap orderedTools = new TreeMap(new ToolComparator());
733
                Iterator e = orderedExtensions.keySet().iterator();
734
                
735
                // Ahora se ordenan las herramientas (actiontools y selectabletools) de las extensiones
736
                while (e.hasNext()) {
737
                        Extension ext = (Extension) e.next();
738
                        
739
                        ToolBar[] toolbars = ext.getToolBar();
740
                        
741
                        for (int k = 0; k < toolbars.length; k++) {
742
                                ActionTool[] tools = toolbars[k].getActionTool();
743
                                
744
                                for (int t = 0; t < tools.length; t++) {
745
                                        SortableToolBar sm = new SortableToolBar(((PluginServices)extensionPluginServices.get(ext)).getClassLoader(), ext,
746
                                                        toolbars[k], tools[t]);
747
                                        previous = orderedTools.put(sm, null);
748
                                        logger.warn("previous: "+previous);
749
                                        ///frame.addTool(((PluginServices)extensionPluginServices.get(ext)).getClassLoader(), ext,
750
                                        ///        toolbars[k], tools[t]);
751
                                }
752
                                
753
                                SelectableTool[] sTools = toolbars[k].getSelectableTool();
754
                                
755
                                for (int t = 0; t < sTools.length; t++) {
756
                                        SortableToolBar sm=new SortableToolBar(((PluginServices)extensionPluginServices.get(ext)).getClassLoader(), ext,
757
                                                        toolbars[k], sTools[t]);
758
                                        previous = orderedTools.put(sm, null);
759
                                        logger.warn("previous: "+previous);
760
                                        ///frame.addTool(((PluginServices)extensionPluginServices.get(ext)).getClassLoader(), ext,
761
                                        ///        toolbars[k], sTools[t]);
762
                                }
763
                        }
764
                }
765

    
766
                // Ahora se ordenan las herramientas (actiontools y selectabletools) de las extensiones de MDI
767
                i = pluginsConfig.keySet().iterator();
768
                while (i.hasNext()) {
769
                        String pName = (String) i.next();
770
                        PluginConfig pc = (PluginConfig) pluginsConfig.get(pName);
771
                        PluginServices ps = (PluginServices) pluginsServices.get(pName);
772
                         
773
                        SkinExtension skinExt = pc.getExtensions().getSkinExtension();
774
                        
775
                        if (skinExt != null) {
776
                                ToolBar[] toolbars = skinExt.getToolBar();
777
                                
778
                                for (int k = 0; k < toolbars.length; k++) {
779
                                        ActionTool[] tools = toolbars[k].getActionTool();
780
                                        
781
                                        for (int t = 0; t < tools.length; t++) {
782
                                                SortableToolBar stb=new SortableToolBar(ps.getClassLoader(), skinExt,
783
                                                                toolbars[k], tools[t]);
784
                                                previous = orderedTools.put(stb,null);
785
                                                logger.warn("previous: "+previous);
786
                                                ///frame.addTool(ps.getClassLoader(), skinExt,
787
                                                ///        toolbars[k], tools[t]);
788
                                        }
789
                                        
790
                                        SelectableTool[] sTools = toolbars[k].getSelectableTool();
791
                                        
792
                                        for (int t = 0; t < sTools.length; t++) {
793
                                                SortableToolBar stb=new SortableToolBar(ps.getClassLoader(), skinExt,
794
                                                                toolbars[k], sTools[t]);
795
                                                previous = orderedTools.put(stb,null);
796
                                                logger.warn("previous: "+previous);
797
                                                ///frame.addTool(ps.getClassLoader(), skinExt,
798
                                                ///        toolbars[k], sTools[t]);
799
                                        }
800
                                }
801
                        }
802
                        //Se instalan los popup menus
803
                        PopupMenus pus = pc.getPopupMenus();
804
                        
805
                        if (pus != null) {
806
                                PopupMenu[] menus = pus.getPopupMenu();
807
                                
808
                                for (int j = 0; j < menus.length; j++) {
809
                                        frame.addPopupMenu(ps.getClassLoader(), menus[j]);
810
                                }
811
                        }
812
                }
813

    
814
                Iterator tt = orderedTools.keySet().iterator();                
815
                while (tt.hasNext()) {
816
                        SortableToolBar kk = (SortableToolBar) tt.next();
817
                        kk.getClass();
818
                }
819
                
820
                
821
                // Se itera por las herramientas ordenadas, para
822
                // a?adirlas a la interfaz de forma ordenada
823
                Iterator t = orderedTools.keySet().iterator();                
824
                while (t.hasNext()) {
825
                        try {
826
                                SortableToolBar stb = (SortableToolBar) t.next();
827
                                if (stb.actiontool!=null)
828
                                        frame.addTool(stb.loader, stb.extension,stb.toolbar, stb.actiontool);
829
                                else
830
                                        frame.addTool(stb.loader, stb.extension,stb.toolbar, stb.selectabletool);
831
                        } catch (ClassNotFoundException ex) {
832
                                logger.error(Messages.getString(
833
                                "Launcher.No_se_encontro_la_clase_de_la_extension"), ex);
834
                        }
835
                }
836
                ///} catch (ClassNotFoundException e) {
837
                ///        logger.error(Messages.getString(
838
                ///                        "Launcher.No_se_encontro_la_clase_de_la_extension"), e);
839
                ///}
840
        }
841

    
842
        /**
843
         *
844
         */
845
        private static void updateAndamiConfig() {
846
                HashSet olds = new HashSet();
847

    
848
                Plugin[] plugins = andamiConfig.getPlugin();
849

    
850
                for (int i = 0; i < plugins.length; i++) {
851
                        olds.add(plugins[i].getName());
852
                }
853

    
854
                Iterator i = pluginsServices.values().iterator();
855

    
856
                while (i.hasNext()) {
857
                        PluginServices ps = (PluginServices) i.next();
858

    
859
                        if (!olds.contains(ps.getPluginName())) {
860
                                Plugin p = new Plugin();
861
                                p.setName(ps.getPluginName());
862
                                p.setUpdate(false);
863

    
864
                                andamiConfig.addPlugin(p);
865
                        }
866
                }
867
        }
868

    
869
        /**
870
         * DOCUMENT ME!
871
         */
872
        private static void pluginsClassLoaders() {
873
                HashSet instalados = new HashSet();
874

    
875
                // Se itera hasta que est?n todos instalados
876
                while (instalados.size() != pluginsConfig.size()) {
877
                        boolean circle = true;
878

    
879
                        //Hacemos una pasada por todos los plugins
880
                        Iterator i = pluginsConfig.keySet().iterator();
881

    
882
                        while (i.hasNext()) {
883
                                String pluginName = (String) i.next();
884
                                PluginConfig config = (PluginConfig) pluginsConfig.get(pluginName);
885

    
886
                                if (instalados.contains(pluginName)) {
887
                                        continue;
888
                                }
889

    
890
                                //Se obtienen las dependencias y sus class loaders
891
                                boolean ready = true;
892
                                Depends[] dependencies = config.getDepends();
893
                                PluginClassLoader[] loaders = new PluginClassLoader[dependencies.length];
894

    
895
                                for (int j = 0; j < dependencies.length; j++) {
896
                                        if (pluginsConfig.get(dependencies[j].getPluginName()) == null) {
897
                                                logger.error(Messages.getString(
898
                                                                "Launcher.Dependencia_no_resuelta_en_plugin") +
899
                                                        pluginName + ": " +
900
                                                        dependencies[j].getPluginName());
901

    
902
                                                continue;
903
                                        }
904

    
905
                                        if (!instalados.contains(dependencies[j].getPluginName())) {
906
                                                ready = false;
907
                                        } else {
908
                                                loaders[j] = ((PluginServices) pluginsServices.get(dependencies[j].getPluginName())).getClassLoader();
909
                                        }
910
                                }
911

    
912
                                //Si no est?n sus dependencias satisfechas se aborta la instalaci?n
913
                                if (!ready) {
914
                                        continue;
915
                                }
916

    
917
                                //Se genera el class loader
918
                                String jardir = config.getLibraries().getLibraryDir();
919
                                File jarDir = new File(andamiConfig.getPluginsDirectory() +
920
                                                File.separator + pluginName + File.separator + jardir);
921
                                File[] jarFiles = jarDir.listFiles(new FileFilter() {
922
                                                        public boolean accept(File pathname) {
923
                                                                return (pathname.getName().toUpperCase()
924
                                                                                                .endsWith(".JAR")) ||
925
                                                                (pathname.getName().toUpperCase().endsWith(".ZIP"));
926
                                                        }
927
                                                });
928

    
929
                                URL[] urls = new URL[jarFiles.length];
930

    
931
                                for (int j = 0; j < jarFiles.length; j++) {
932
                                        try {
933
                                                urls[j] = new URL("file:" + jarFiles[j]);
934
                                        } catch (MalformedURLException e) {
935
                                                logger.error(Messages.getString(
936
                                                                "Launcher.No_se_puede_acceder_a") +
937
                                                        jarFiles[j]);
938
                                        }
939
                                }
940

    
941
                                PluginClassLoader loader;
942

    
943
                                try {
944
                                        loader = new PluginClassLoader(urls,
945
                                                        andamiConfig.getPluginsDirectory() +
946
                                                        File.separator + pluginName,
947
                                                        Launcher.class.getClassLoader(), loaders);
948

    
949
                                        PluginServices ps = new PluginServices(loader);
950

    
951
                                        pluginsServices.put(ps.getPluginName(), ps);
952

    
953
                                        instalados.add(pluginName);
954
                    // FJP: Los metemos ordenados para luego no cargar uno que necesita de otro antes de tiempo. Esto lo usaremos al 
955
                    // inicializar los plugins
956
                    pluginsOrdered.add(pluginName);
957

    
958
                                        circle = false;
959
                                } catch (IOException e) {
960
                                        logger.error(Messages.getString(
961
                                                        "Launcher.Error_con_las_librerias_del_plugin"), e);
962
                                        pluginsConfig.remove(pluginName);
963
                                        i = pluginsConfig.keySet().iterator();
964
                                }
965
                        }
966

    
967
                        if (circle) {
968
                                logger.error(Messages.getString(
969
                                                "Launcher.Hay_dependencias_circulares"));
970

    
971
                                break;
972
                        }
973
                }
974

    
975
                //Se eliminan los plugins que no fueron instalados
976
                Iterator i = pluginsConfig.keySet().iterator();
977

    
978
                while (i.hasNext()) {
979
                        String pluginName = (String) i.next();
980
                        PluginConfig config = (PluginConfig) pluginsConfig.get(pluginName);
981
                        PluginServices ps = (PluginServices) pluginsServices.get(pluginName);
982

    
983
                        if (ps == null) {
984
                                pluginsConfig.remove(pluginName);
985
                                i = pluginsConfig.keySet().iterator();
986
                        }
987
                } 
988
        }
989

    
990
        /**
991
         * DOCUMENT ME!
992
         */
993
        private static void pluginsMessages() {
994
                /* add gvsig translations first. This should be done using a generic "appPlugin" variable, instead 
995
                 * of using "com.iver.cit.gvsig" directly, but I'll do it when we use the new appgvSIG launcher.
996
                 * I keep this workaround for the moment. 
997
                 */
998
                PluginConfig config = (PluginConfig) pluginsConfig.get("com.iver.cit.gvsig");
999
                PluginServices ps = (PluginServices) pluginsServices.get("com.iver.cit.gvsig");
1000
                if (config.getResourceBundle() != null) {
1001
                        org.gvsig.i18n.Messages.addResourceFamily(config.getResourceBundle().getName(), ps.getClassLoader(), "com.iver.cit.gvsig");
1002
                }
1003

    
1004
                //Iteramos por todos los plugins
1005
                Iterator i = pluginsConfig.keySet().iterator();
1006
                
1007
                while (i.hasNext()) {
1008
                        String pluginName = (String) i.next();
1009
                        if (!pluginName.equals("com.iver.cit.gvsig")) { // we've already loaded com.iver.cit.gvsig
1010
                                config = (PluginConfig) pluginsConfig.get(pluginName);
1011
                                ps = (PluginServices) pluginsServices.get(pluginName);
1012
                        
1013
                                if (config.getResourceBundle() != null && !config.getResourceBundle().getName().equals("")) {
1014
                                        // add the locale files associated with the plugin
1015
                                        org.gvsig.i18n.Messages.addResourceFamily(config.getResourceBundle().getName(), ps.getClassLoader(), pluginName);
1016
                                }
1017
                        }
1018
                }
1019
        }
1020

    
1021
        /**
1022
         * DOCUMENT ME!
1023
         *
1024
         * @param name DOCUMENT ME!
1025
         *
1026
         * @return DOCUMENT ME!
1027
         */
1028
        static PluginServices getPluginServices(String name) {
1029
                return (PluginServices) pluginsServices.get(name);
1030
        }
1031

    
1032
        /**
1033
         * DOCUMENT ME!
1034
         *
1035
         * @return DOCUMENT ME!
1036
         */
1037
        static String getPluginsDir() {
1038
                return andamiConfig.getPluginsDirectory();
1039
        }
1040

    
1041
        /**
1042
         * DOCUMENT ME!
1043
         *
1044
         * @param s DOCUMENT ME!
1045
         */
1046
        static void setPluginsDir(String s) {
1047
                andamiConfig.setPluginsDirectory(s);
1048
        }
1049

    
1050
        /**
1051
         * DOCUMENT ME!
1052
         *
1053
         * @return DOCUMENT ME!
1054
         */
1055
        static MDIFrame getMDIFrame() {
1056
                return frame;
1057
        }
1058

    
1059
        /**
1060
         * DOCUMENT ME!
1061
         *
1062
         * @param pluginsDirectory
1063
         */
1064
        private static void loadPlugins(String pluginsDirectory) {
1065
                File pDir = new File(pluginsDirectory);
1066

    
1067
                if (!pDir.exists()) {
1068
                        return;
1069
                }
1070

    
1071
                File[] pluginDirs = pDir.listFiles();
1072

    
1073
                for (int i = 0; i < pluginDirs.length; i++) {
1074
                        if (pluginDirs[i].isDirectory()) {
1075
                                File configXml = new File(pluginDirs[i].getAbsolutePath() +
1076
                                                File.separator + "config.xml");
1077

    
1078
                                try {
1079
                                        FileReader xml = new FileReader(configXml);
1080
                                        PluginConfig pConfig = (PluginConfig) PluginConfig.unmarshal(xml);
1081
                                        pluginsConfig.put(pluginDirs[i].getName(), pConfig);
1082
                                } catch (FileNotFoundException e) {
1083
                                        logger.info(Messages.getString(
1084
                                                        "Launcher.Ignorando_el_directorio") +
1085
                                                pluginDirs[i].getAbsolutePath() +
1086
                                                Messages.getString("Launcher.config_no_encontrado"));
1087
                                } catch (MarshalException e) {
1088
                                        logger.info(Messages.getString(
1089
                                                        "Launcher.Ignorando_el_directorio") +
1090
                                                pluginDirs[i].getAbsolutePath() +
1091
                                                Messages.getString("Launcher.config_mal_formado"), e);
1092
                                } catch (ValidationException e) {
1093
                                        logger.info(Messages.getString(
1094
                                                        "Launcher.Ignorando_el_directorio") +
1095
                                                pluginDirs[i].getAbsolutePath() +
1096
                                                Messages.getString("Launcher.config_mal_formado"), e);
1097
                                }
1098
                        }
1099
                }
1100
        }
1101

    
1102
        /**
1103
         * DOCUMENT ME!
1104
         *
1105
         * @param language
1106
         * @param country
1107
         * @param variant
1108
         *
1109
         * @return DOCUMENT ME!
1110
         */
1111
        private static Locale getLocale(String language, String country,
1112
                String variant) {
1113
                if (variant != null) {
1114
                        return new Locale(language, country, variant);
1115
                } else if (country != null) {
1116
                        return new Locale(language, country);
1117
                } else if (language != null) {
1118
                        return new Locale(language);
1119
                } else {
1120
                        return new Locale("es");
1121
                }
1122
        }
1123

    
1124
        /**
1125
         * DOCUMENT ME!
1126
         *
1127
         * @param file DOCUMENT ME!
1128
         *
1129
         * @throws IOException DOCUMENT ME!
1130
         * @throws MarshalException DOCUMENT ME!
1131
         * @throws ValidationException DOCUMENT ME!
1132
         */
1133
        private static void andamiConfigToXML(String file)
1134
                throws IOException, MarshalException, ValidationException {
1135
                File xml = new File(file);
1136
                File parent = xml.getParentFile();
1137
                parent.mkdirs();
1138

    
1139
                FileWriter writer = new FileWriter(xml);
1140
                andamiConfig.marshal(writer);
1141
        }
1142

    
1143
        /**
1144
         * DOCUMENT ME!
1145
         *
1146
         * @param file DOCUMENT ME!
1147
         *
1148
         * @throws ConfigurationException DOCUMENT ME!
1149
         */
1150
        private static void andamiConfigFromXML(String file)
1151
                throws ConfigurationException {
1152
                File xml = new File(file);
1153

    
1154
                //Si no existe se ponen los valores por defecto
1155
                if (!xml.exists()) {
1156
                        andamiConfig = new AndamiConfig();
1157

    
1158
                        Andami andami = new Andami();
1159
                        andami.setUpdate(true);
1160
                        andamiConfig.setAndami(andami);
1161
                        andamiConfig.setLocaleCountry(Locale.getDefault().getCountry());
1162
                        andamiConfig.setLocaleLanguage(Locale.getDefault().getLanguage());
1163
                        andamiConfig.setLocaleVariant(Locale.getDefault().getVariant());
1164

    
1165
                        if (System.getProperty("javawebstart.version") != null) // Es java web start)
1166
                         {
1167
                                andamiConfig.setPluginsDirectory(new File(System.getProperty(
1168
                                                        "user.home") + File.separator + appName +
1169
                                                File.separator + "extensiones").getAbsolutePath());
1170
                        } else {
1171
                                andamiConfig.setPluginsDirectory(new File(appName +
1172
                                                File.separator + "extensiones").getAbsolutePath());
1173
                        }
1174

    
1175
                        andamiConfig.setPlugin(new Plugin[0]);
1176
                } else {
1177
                        //Se lee la configuraci?n
1178
                        FileReader reader;
1179

    
1180
                        try {
1181
                                reader = new FileReader(xml);
1182
                                andamiConfig = (AndamiConfig) AndamiConfig.unmarshal(reader);
1183
                        } catch (FileNotFoundException e) {
1184
                                throw new ConfigurationException(e);
1185
                        } catch (MarshalException e) {
1186
                                throw new ConfigurationException(e);
1187
                        } catch (ValidationException e) {
1188
                                throw new ConfigurationException(e);
1189
                        }
1190
                }
1191
        }
1192

    
1193
        /**
1194
         * DOCUMENT ME!
1195
         *
1196
         * @return DOCUMENT ME!
1197
         *
1198
         * @throws ConfigurationException DOCUMENT ME!
1199
         */
1200
        private static XMLEntity persistenceFromXML() throws ConfigurationException {
1201
                File xml = new File(pluginsPersistencePath);
1202

    
1203
                if (xml.exists()) {
1204
                        FileReader reader;
1205

    
1206
                        try {
1207
                                reader = new FileReader(xml);
1208

    
1209
                                XmlTag tag = (XmlTag) XmlTag.unmarshal(reader);
1210

    
1211
                                return new XMLEntity(tag);
1212
                        } catch (FileNotFoundException e) {
1213
                                throw new ConfigurationException(e);
1214
                        } catch (MarshalException e) {
1215
                                throw new ConfigurationException(e);
1216
                        } catch (ValidationException e) {
1217
                                throw new ConfigurationException(e);
1218
                        }
1219
                } else {
1220
                        return new XMLEntity();
1221
                }
1222
        }
1223

    
1224
        /**
1225
         * DOCUMENT ME!
1226
         *
1227
         * @param entity DOCUMENT ME!
1228
         *
1229
         * @throws ConfigurationException DOCUMENT ME!
1230
         */
1231
        private static void persistenceToXML(XMLEntity entity)
1232
                throws ConfigurationException {
1233
                File xml = new File(pluginsPersistencePath);
1234

    
1235
                FileWriter writer;
1236

    
1237
                try {
1238
                        writer = new FileWriter(xml);
1239
                        entity.getXmlTag().marshal(writer);
1240
                } catch (FileNotFoundException e) {
1241
                        throw new ConfigurationException(e);
1242
                } catch (MarshalException e) {
1243
                        throw new ConfigurationException(e);
1244
                } catch (ValidationException e) {
1245
                        throw new ConfigurationException(e);
1246
                } catch (IOException e) {
1247
                        throw new ConfigurationException(e);
1248
                }
1249
        }
1250

    
1251
        /**
1252
         * Devuelve un array con los directorios de los plugins
1253
         *
1254
         * @param dirExt Directorio de las extensiones a partir del cual cuelgan
1255
         *                   todos los directorios de los plugins
1256
         *
1257
         * @return ArrayList con los directorios
1258
         */
1259
        private String[] getLocales(File dirExt) {
1260
                ArrayList types = new ArrayList();
1261
                File[] files = dirExt.listFiles();
1262

    
1263
                for (int i = 0; i < files.length; i++) {
1264
                        if (files[i].isDirectory()) {
1265
                                File[] textFile = files[i].listFiles(new FilenameFilter() {
1266
                                                        public boolean accept(File dir, String fileName) {
1267
                                                                return fileName.toLowerCase().startsWith("text_"); //$NON-NLS-1$
1268
                                                        }
1269
                                                });
1270

    
1271
                                for (int j = 0; j < textFile.length; j++) {
1272
                                        String s = (textFile[j]).getName().replaceAll("text_", "");
1273
                                        s = s.replaceAll(".properties", "");
1274
                                        s = s.trim();
1275

    
1276
                                        if (!types.contains(s)) {
1277
                                                types.add(s);
1278
                                        }
1279
                                }
1280
                        }
1281
                }
1282

    
1283
                return (String[]) types.toArray(new String[0]);
1284
        }
1285

    
1286
        /**
1287
         * DOCUMENT ME!
1288
         *
1289
         * @return Returns the frame.
1290
         */
1291
        static MDIFrame getFrame() {
1292
                return frame;
1293
        }
1294

    
1295
        /**
1296
         * Secuencia de cerrado de Andami
1297
         */
1298
        public static void closeApplication() {
1299
                //Configuraci?n de Andami
1300
                try {
1301
                        andamiConfigToXML(andamiConfigPath);
1302
                } catch (MarshalException e) {
1303
                        logger.error(Messages.getString(
1304
                                        "Launcher.No_se_pudo_guardar_la_configuracion_de_andami"), e);
1305
                } catch (ValidationException e) {
1306
                        logger.error(Messages.getString(
1307
                                        "Launcher.No_se_pudo_guardar_la_configuracion_de_andami"), e);
1308
                } catch (IOException e) {
1309
                        logger.error(Messages.getString(
1310
                                        "Launcher.No_se_pudo_guardar_la_configuracion_de_andami"), e);
1311
                }
1312

    
1313
                //Persistencia de los plugins
1314
                savePluginPersistence();
1315
                
1316
                //Finalize all the extensions
1317
                finalizeExtensions();
1318
                
1319
                // Clean any temp data created
1320
                Utilities.cleanUpTempFiles();
1321
                
1322
                //Para la depuraci?n de memory leaks
1323
                System.gc();
1324

    
1325
        System.exit(0);
1326
        }
1327
        
1328
        /**
1329
         * Exectutes the finalize method for all the extensions
1330
         *
1331
         */
1332
        private static void finalizeExtensions() {
1333
                Set extensions = getClassesExtensions().keySet();
1334
                Object[] keys = extensions.toArray(); 
1335
                
1336
                for (int i=0 ; i<keys.length ; i++){
1337
                        ExtensionDecorator extensionDecorator = 
1338
                                (ExtensionDecorator) getClassesExtensions().get(keys[i]);
1339
                        extensionDecorator.getExtension().finalize();
1340
                }                
1341
        }
1342

    
1343

    
1344
        /**
1345
         * DOCUMENT ME!
1346
         *
1347
         * @return DOCUMENT ME!
1348
         */
1349
        static HashMap getClassesExtensions() {
1350
                return classesExtensions;
1351
        }
1352

    
1353
        /**
1354
         * DOCUMENT ME!
1355
         *
1356
         * @param extDir DOCUMENT ME!
1357
         */
1358
        private static void downloadExtensions(String extDir) {
1359
                java.util.Date fechaActual = null;
1360

    
1361
                try {
1362
                        if (System.getProperty("javawebstart.version") != null) {
1363
                                //Obtenemos la URL del servidor
1364
                                BasicService bs = (BasicService) ServiceManager.lookup(
1365
                                                "javax.jnlp.BasicService");
1366
                                URL baseURL = bs.getCodeBase();
1367

    
1368
                                //Se descargan las extensiones
1369
                                SplashWindow.process(5,
1370
                                        "Descargando las extensiones desde " + baseURL + " a " +
1371
                                        extDir);
1372

    
1373
                                URL url = new URL(baseURL + "extensiones.zip");
1374
                                URLConnection connection = url.openConnection();
1375

    
1376
                                System.out.println(url.toExternalForm() + ":");
1377
                                System.out.println("  Content Type: " +
1378
                                        connection.getContentType());
1379
                                System.out.println("  Content Length: " +
1380
                                        connection.getContentLength());
1381
                                System.out.println("  Last Modified: " +
1382
                                        new Date(connection.getLastModified()));
1383
                                System.out.println("  Expiration: " +
1384
                                        connection.getExpiration());
1385
                                System.out.println("  Content Encoding: " +
1386
                                        connection.getContentEncoding());
1387

    
1388
                                // Guardamos la fecha del fichero de extensiones que nos hemos bajado, y
1389
                                // comprobamos el ?ltimo que se ha bajado. Si no son
1390
                                // iguales, nos bajamos el nuevo. Si son iguales, no
1391
                                // nos bajamos nada.
1392
                                Long miliSecondsInWeb = new Long(connection.getLastModified());
1393

    
1394
                                // PluginServices ps = PluginServices.getPluginServices("com.iver.core");
1395
                                // if (ps.getPersistentXML().getStringProperty("timestamp") != null)
1396
                                File destDir = new File(extDir);
1397

    
1398
                                if (!destDir.exists()) {
1399
                                        // Creamos gvSIG
1400
                                        destDir.getParentFile().mkdir();
1401

    
1402
                                        if (!destDir.mkdir()) {
1403
                                                System.err.println("Imposible crear el directorio " +
1404
                                                        destDir.getAbsolutePath());
1405
                                        }
1406
                                }
1407

    
1408
                                File timeFile = new File(destDir.getParent() + File.separator +
1409
                                                "timeStamp.properties");
1410

    
1411
                                if (!timeFile.exists()) {
1412
                                        timeFile.createNewFile();
1413
                                }
1414

    
1415
                                FileInputStream inAux = new FileInputStream(timeFile);
1416
                                Properties prop = new Properties();
1417
                                prop.load(inAux);
1418
                                inAux.close();
1419

    
1420
                                if (prop.getProperty("timestamp") != null) {
1421
                                        Long lastMiliSeconds = (Long) new Long(prop.getProperty(
1422
                                                                "timestamp"));
1423

    
1424
                                        if (lastMiliSeconds.longValue() == miliSecondsInWeb.longValue()) {
1425
                                                System.out.println("No hay nueva actualizaci?n");
1426

    
1427
                                                return;
1428
                                        }
1429

    
1430
                                        System.out.println("timeStampWeb= " + miliSecondsInWeb);
1431
                                        System.out.println("timeStampLocal= " + lastMiliSeconds);
1432
                                } else {
1433
                                        System.out.println("El timeStamp no est? escrito en " +
1434
                                                timeFile.getAbsolutePath());
1435
                                }
1436

    
1437
                                InputStream stream = connection.getInputStream();
1438
                                File temp = File.createTempFile("gvsig", ".zip");
1439
                                temp.deleteOnExit();
1440

    
1441
                                FileOutputStream file = new FileOutputStream(temp);
1442
                                BufferedInputStream in = new BufferedInputStream(stream);
1443
                                BufferedOutputStream out = new BufferedOutputStream(file);
1444

    
1445
                                int i;
1446
                                int pct;
1447
                                int desde;
1448
                                int hasta;
1449

    
1450
                                hasta = connection.getContentLength() / 1024;
1451
                                desde = 0;
1452

    
1453
                                while ((i = in.read()) != -1) {
1454
                                        pct = ((desde / 1024) * 100) / hasta;
1455

    
1456
                                        if (((desde % 10240) == 0) && (pct > 10) &&
1457
                                                        ((pct % 10) == 0)) {
1458
                                                SplashWindow.process(pct,
1459
                                                        (desde / 1024) + "Kb de " + hasta +
1460
                                                        "Kb descargados...");
1461
                                        }
1462

    
1463
                                        out.write(i);
1464
                                        desde++;
1465
                                }
1466

    
1467
                                out.flush();
1468
                                out.close();
1469
                                in.close();
1470

    
1471
                                //Se extrae el zip
1472
                                SplashWindow.process(5, "Extensiones descargadas.");
1473

    
1474
                                System.out.println("Extrayendo a " + destDir.getAbsolutePath());
1475

    
1476
                                Date fechaDir = new Date(destDir.lastModified());
1477
                                System.out.println("Fecha del directorio " + extDir + " = " +
1478
                                        fechaDir.toString());
1479
                                Utilities.extractTo(temp, new File(extDir), splashWindow);
1480

    
1481
                                // Si todo ha ido bien, guardamos el timestamp.
1482
                                ///  App.instance.getPc().addProperties("timestamp", miliSecondsInWeb);
1483
                                // XMLEntity xml=ps.getPersistentXML();
1484
                                fechaActual = new java.util.Date();
1485

    
1486
                                FileOutputStream outAux = new FileOutputStream(timeFile);
1487
                                prop.setProperty("timestamp", miliSecondsInWeb.toString());
1488
                                prop.store(outAux, "last download");
1489
                                outAux.close();
1490
                                System.out.println("Fecha actual guardada: " +
1491
                                        fechaActual.toGMTString());
1492

    
1493
                                /* xml.putProperty("timestamp",fechaActual.toGMTString());
1494
                                   ps.setPresistentXML(xml); */
1495
                        }
1496
                } catch (IOException e) {
1497
                        NotificationManager.addError("", e);
1498
                } catch (UnavailableServiceException e) {
1499
                        NotificationManager.addError("", e);
1500
                } catch (SecurityException e) {
1501
                        System.err.println("No se puede escribir el timeStamp " +
1502
                                fechaActual.toGMTString());
1503
                        NotificationManager.addError("", e);
1504
                }
1505
        }
1506

    
1507
        /**
1508
         * DOCUMENT ME!
1509
         *
1510
         * @return DOCUMENT ME!
1511
         */
1512
        private static Extensions[] getExtensions() {
1513
                ArrayList array = new ArrayList();
1514
                Iterator iter = pluginsConfig.values().iterator();
1515

    
1516
                while (iter.hasNext()) {
1517
                        array.add(((PluginConfig) iter.next()).getExtensions());
1518
                }
1519

    
1520
                return (Extensions[]) array.toArray(new Extensions[0]);
1521
        }
1522

    
1523
        /**
1524
         * DOCUMENT ME!
1525
         *
1526
         * @return DOCUMENT ME!
1527
         */
1528
        public static HashMap getPluginConfig() {
1529
                return pluginsConfig;
1530
        }
1531

    
1532
        /**
1533
         * DOCUMENT ME!
1534
         *
1535
         * @param s DOCUMENT ME!
1536
         *
1537
         * @return DOCUMENT ME!
1538
         */
1539
        public static Extension getExtension(String s) {
1540
                Extensions[] exts = getExtensions();
1541

    
1542
                for (int i = 0; i < exts.length; i++) {
1543
                        for (int j = 0; j < exts[i].getExtensionCount(); j++) {
1544
                                if (exts[i].getExtension(j).getClassName().equals(s)) {
1545
                                        return exts[i].getExtension(j);
1546
                                }
1547
                        }
1548
                }
1549

    
1550
                return null;
1551
        }
1552

    
1553
        /**
1554
         * DOCUMENT ME!
1555
         *
1556
         * @return DOCUMENT ME!
1557
         */
1558
        public static AndamiConfig getAndamiConfig() {
1559
                return andamiConfig;
1560
        }
1561

    
1562
        /**
1563
         * DOCUMENT ME!
1564
         *
1565
         * @author $author$
1566
         * @version $Revision: 5597 $
1567
         */
1568
        private static class ExtensionComparator implements Comparator {
1569
                /**
1570
                 * DOCUMENT ME!
1571
                 *
1572
                 * @param o1 DOCUMENT ME!
1573
                 * @param o2 DOCUMENT ME!
1574
                 *
1575
                 * @return DOCUMENT ME!
1576
                 */
1577
                public int compare(Object o1, Object o2) {
1578
                        Extension e1 = (Extension) o1;
1579
                        Extension e2 = (Extension) o2;
1580

    
1581
                        if (!e1.hasPriority() && !e2.hasPriority()) {
1582
                                return -1;
1583
                        }
1584

    
1585
                        if (e1.hasPriority() && !e2.hasPriority()) {
1586
                                return -Integer.MAX_VALUE;
1587
                        }
1588

    
1589
                        if (e2.hasPriority() && !e1.hasPriority()) {
1590
                                return Integer.MAX_VALUE;
1591
                        }
1592

    
1593
                        if (e1.getPriority() != e2.getPriority()){
1594
                                return e2.getPriority() - e1.getPriority();
1595
                        }else{
1596
                                return (e2.toString().compareTo(e1.toString()));
1597
                        }
1598
                }
1599
        }
1600

    
1601
        /**
1602
         * DOCUMENT ME!
1603
         */
1604
        private static class MenuComparator implements Comparator {
1605
                private static ExtensionComparator extComp = new ExtensionComparator();
1606

    
1607
                /**
1608
                 * DOCUMENT ME!
1609
                 *
1610
                 * @param o1 DOCUMENT ME!
1611
                 * @param o2 DOCUMENT ME!
1612
                 *
1613
                 * @return DOCUMENT ME!
1614
                 */
1615
                public int compare(Object o1, Object o2) {
1616
                        SortableMenu e1 = (SortableMenu) o1;
1617
                        SortableMenu e2 = (SortableMenu) o2;
1618

    
1619
                        if (!e1.menu.hasPosition() && !e2.menu.hasPosition()) {
1620
                                if (e1.extension instanceof SkinExtensionType) {
1621
                                        return 1;
1622
                                } else if (e2.extension instanceof SkinExtensionType) {
1623
                                        return -1;
1624
                                } else {
1625
                                        return extComp.compare(e1.extension, e2.extension);
1626
                                }
1627
                        }
1628

    
1629
                        if (e1.menu.hasPosition() && !e2.menu.hasPosition()) {
1630
                                return -Integer.MAX_VALUE;
1631
                        }
1632

    
1633
                        if (e2.menu.hasPosition() && !e1.menu.hasPosition()) {
1634
                                return Integer.MAX_VALUE;
1635
                        }
1636

    
1637
                        return e1.menu.getPosition() - e2.menu.getPosition();
1638
                }
1639
        }
1640

    
1641
        /**
1642
         * DOCUMENT ME!
1643
         *
1644
         * @author $author$
1645
         * @version $Revision: 5597 $
1646
         */
1647
        private static class SortableMenu {
1648
                public PluginClassLoader loader;
1649
                public Menu menu;
1650
                public SkinExtensionType extension;
1651

    
1652
                /**
1653
                 * DOCUMENT ME!
1654
                 *
1655
                 * @param loader DOCUMENT ME!
1656
                 * @param skinExt
1657
                 * @param menu2
1658
                 */
1659
                public SortableMenu(PluginClassLoader loader,
1660
                        SkinExtensionType skinExt, Menu menu2) {
1661
                        extension = skinExt;
1662
                        menu = menu2;
1663
                        this.loader = loader;
1664
                }
1665
        }
1666
        /**
1667
         * DOCUMENT ME!
1668
         */
1669
        private static class SortableToolBar {
1670
                public PluginClassLoader loader;
1671
                public ToolBar toolbar;
1672
                public ActionTool actiontool;
1673
                public SelectableTool selectabletool;
1674
                public SkinExtensionType extension;
1675

    
1676
                /**
1677
                 * DOCUMENT ME!
1678
                 *
1679
                 * @param loader DOCUMENT ME!
1680
                 * @param skinExt
1681
                 * @param menu2
1682
                 */
1683
                public SortableToolBar(PluginClassLoader loader,
1684
                        SkinExtensionType skinExt, ToolBar toolbar2,ActionTool actiontool2) {
1685
                        extension = skinExt;
1686
                        toolbar = toolbar2;
1687
                        actiontool=actiontool2;
1688
                        this.loader = loader;
1689
                }
1690
                public SortableToolBar(PluginClassLoader loader,
1691
                                SkinExtensionType skinExt, ToolBar toolbar2,SelectableTool selectabletool2) {
1692
                        extension = skinExt;
1693
                        toolbar = toolbar2;
1694
                        selectabletool=selectabletool2;
1695
                        this.loader = loader;
1696
                }
1697
        }
1698
        /**
1699
         * DOCUMENT ME!
1700
         */
1701
        private static class ToolBarComparator implements Comparator {
1702
                private static ExtensionComparator extComp = new ExtensionComparator();
1703

    
1704
                /**
1705
                 * DOCUMENT ME!
1706
                 *
1707
                 * @param o1 DOCUMENT ME!
1708
                 * @param o2 DOCUMENT ME!
1709
                 *
1710
                 * @return DOCUMENT ME!
1711
                 */
1712
                public int compare(Object o1, Object o2) {
1713
                        SortableToolBar e1 = (SortableToolBar) o1;
1714
                        SortableToolBar e2 = (SortableToolBar) o2;
1715
                        
1716
                        // if the toolbars have the same name, they are considered to be
1717
                        // the same toolbar, so we don't need to do further comparing
1718
                        if (e1.toolbar.getName().equals(e2.toolbar.getName()))
1719
                                return 0;
1720
                        
1721
                        if (!e1.toolbar.hasPosition() && !e2.toolbar.hasPosition()) {
1722
                                if (e1.extension instanceof SkinExtensionType) {
1723
                                        return 1;
1724
                                } else if (e2.extension instanceof SkinExtensionType) {
1725
                                        return -1;
1726
                                } else {
1727
                                        return extComp.compare(e1.extension, e2.extension);
1728
                                }
1729
                        }
1730

    
1731
                        if (e1.toolbar.hasPosition() && !e2.toolbar.hasPosition()) {
1732
                                return -Integer.MAX_VALUE;
1733
                        }
1734

    
1735
                        if (e2.toolbar.hasPosition() && !e1.toolbar.hasPosition()) {
1736
                                return Integer.MAX_VALUE;
1737
                        }
1738
                        if (e1.toolbar.getPosition() != e2.toolbar.getPosition())
1739
                                return e1.toolbar.getPosition() - e2.toolbar.getPosition();
1740
                        
1741
                        if (e1.toolbar.getActionTool().equals(e2.toolbar.getActionTool()) && e1.toolbar.getSelectableTool().equals(e2.toolbar.getSelectableTool())){
1742
                                return 0;
1743
                        }
1744
                        return (e1.toolbar.toString().compareTo(e2.toolbar.toString()));
1745
                }
1746
        }
1747
        
1748
        /**
1749
         * <p>This class is used to compare tools (selectabletool and actiontool),
1750
         * using the "position"
1751
         * attribute.</p>
1752
         * <p>The ordering criteria are:</p>
1753
         * <ul><li>If the tools are placed in different toolbars, they use the toolbars'
1754
         * order.
1755
         * (using the ToolBarComparator).</li>
1756
         * <li></li>
1757
         * <li>If any of the tools has not 'position' attribute, the tool which
1758
         * <strong>has</strong> the attribute will be placed first.</li>
1759
         * <li>If both tools have the same position (or they don't have a
1760
         * 'position' attribute), the priority of the extensions where the tool is defined.</li></ul>
1761
         *
1762
         * @author cesar
1763
         * @version $Revision: 5597 $
1764
         */
1765
        private static class ToolComparator implements Comparator {
1766
                private static ToolBarComparator toolBarComp = new ToolBarComparator();
1767
                /**
1768
                 * DOCUMENT ME!
1769
                 *
1770
                 * @param o1 DOCUMENT ME!
1771
                 * @param o2 DOCUMENT ME!
1772
                 *
1773
                 * @return DOCUMENT ME!
1774
                 */
1775
                public int compare(Object o1, Object o2) {
1776
                        // compare the toolbars which contain the tools
1777
                        int result = toolBarComp.compare(o1, o2);
1778
                        if (result != 0) { // if the toolbars are different, use their order
1779
                                return result;
1780
                        }
1781
                        // otherwise, compare the tools
1782
                        SortableToolBar e1 = (SortableToolBar) o1;
1783
                        SortableToolBar e2 = (SortableToolBar) o2;
1784
                        int e1Position=-1, e2Position=-1;
1785

    
1786
                        if (e1.actiontool!=null) {
1787
                                if (e1.actiontool.hasPosition())
1788
                                        e1Position = e1.actiontool.getPosition();
1789
                        }
1790
                        else if (e1.selectabletool!=null) {
1791
                                if (e1.selectabletool.hasPosition())
1792
                                        e1Position = e1.selectabletool.getPosition();
1793
                        }
1794
                        
1795
                        if (e2.actiontool!=null) {
1796
                                if (e2.actiontool.hasPosition())
1797
                                        e2Position = e2.actiontool.getPosition();
1798
                        }
1799
                        else if (e2.selectabletool!=null){
1800
                                if (e2.selectabletool.hasPosition())
1801
                                        e2Position = e2.selectabletool.getPosition();
1802
                        }
1803
                        
1804
                        if (e1Position==-1 && e2Position!=-1) {
1805
                                return 1;
1806
                        }
1807
                        if (e1Position!=-1 && e2Position==-1) {
1808
                                return -1;
1809
                        }
1810
                        if (e1Position!=-1 && e2Position!=-1) {
1811
                                result = e1Position - e2Position;
1812
                                // we don't return 0 unless both objects are the same, otherwise the objects get overwritten in the treemap
1813
                                if (result!=0) return result;
1814
                        }
1815
                        /*if (e1.toolbar.getActionTool().equals(e2.toolbar.getActionTool()) && e1.toolbar.getSelectableTool().equals(e2.toolbar.getSelectableTool())){
1816
                                return 0;
1817
                        }*/
1818
                        //logger.warn(Messages.getString("Different_tools_have_the_same_position_at_toolbar_")+e1.toolbar.getName());
1819
                        return e1.toString().compareTo(e2.toString());
1820
                }
1821
        }
1822
        
1823
        
1824
        /**
1825
         * validates the user before starting gvsig
1826
         *
1827
         */
1828
        private static void validate(){
1829
                
1830
                IAuthentication session =  null;
1831
                try {
1832
                        
1833
                        //String location = getClassLocation(Class.forName("com.iver.andami.authentication.Session"));
1834
                        session = (IAuthentication)Class.forName("com.iver.andami.authentication.Session").newInstance();
1835

    
1836
                } catch (ClassNotFoundException e) {
1837
                        // TODO Auto-generated catch block
1838
                        //e.printStackTrace();
1839
                        return;
1840
                } catch (InstantiationException e) {
1841
                        // TODO Auto-generated catch block
1842
                        //e.printStackTrace();
1843
                        return;
1844
                } catch (IllegalAccessException e) {
1845
                        // TODO Auto-generated catch block
1846
                        //e.printStackTrace();
1847
                        return;
1848
                }
1849
                
1850
                session.setPluginDirectory( andamiConfig.getPluginsDirectory() );
1851
                if (session.validationRequired()){
1852
                        
1853
                        //opens the login dialog for the user to validate
1854
                        //session.loging does not need arguments: they are read in the internal hashtable
1855
                        session.getUser();
1856
                        if(session.Login((String)session.get("user"),(String)session.get("pwd"))){
1857
                                System.out.println("You are logged in");
1858
                                //PluginServices.setSession( session );        
1859
                        }
1860
                        else{
1861
                                JOptionPane.showMessageDialog((Component)PluginServices.getMainFrame(),
1862
                                                 "You are not logged in");                                
1863
                                System.exit(0);
1864
                        }
1865
                        PluginServices.setAuthentication(session);
1866
                }                
1867
        }
1868
}