Statistics
| Revision:

svn-gvsig-desktop / trunk / org.gvsig.desktop / org.gvsig.desktop.compat.cdc / org.gvsig.i18n / src / test / data / src / _fwAndami / src / com / iver / andami / Launcher.java @ 40559

History | View | Annotate | Download (52.8 KB)

1
/**
2
 * gvSIG. Desktop Geographic Information System.
3
 *
4
 * Copyright (C) 2007-2013 gvSIG Association.
5
 *
6
 * This program is free software; you can redistribute it and/or
7
 * modify it under the terms of the GNU General Public License
8
 * as published by the Free Software Foundation; either version 3
9
 * of the License, or (at your option) any later version.
10
 *
11
 * This program is distributed in the hope that it will be useful,
12
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14
 * GNU General Public License for more details.
15
 *
16
 * You should have received a copy of the GNU General Public License
17
 * along with this program; if not, write to the Free Software
18
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
19
 * MA  02110-1301, USA.
20
 *
21
 * For any additional information, do not hesitate to contact us
22
 * at info AT gvsig.com, or visit our website www.gvsig.com.
23
 */
24
package com.iver.andami;
25

    
26
import java.awt.Component;
27
import java.awt.Dimension;
28
import java.awt.EventQueue;
29
import java.awt.KeyboardFocusManager;
30
import java.awt.Point;
31
import java.awt.Toolkit;
32
import java.io.BufferedInputStream;
33
import java.io.BufferedOutputStream;
34
import java.io.File;
35
import java.io.FileFilter;
36
import java.io.FileInputStream;
37
import java.io.FileNotFoundException;
38
import java.io.FileOutputStream;
39
import java.io.FileReader;
40
import java.io.FileWriter;
41
import java.io.FilenameFilter;
42
import java.io.IOException;
43
import java.io.InputStream;
44
import java.lang.reflect.InvocationTargetException;
45
import java.net.MalformedURLException;
46
import java.net.URL;
47
import java.net.URLConnection;
48
import java.util.ArrayList;
49
import java.util.Comparator;
50
import java.util.Date;
51
import java.util.HashMap;
52
import java.util.HashSet;
53
import java.util.Iterator;
54
import java.util.Locale;
55
import java.util.Properties;
56
import java.util.Set;
57
import java.util.TreeMap;
58

    
59
import javax.jnlp.BasicService;
60
import javax.jnlp.ServiceManager;
61
import javax.jnlp.UnavailableServiceException;
62
import javax.swing.ImageIcon;
63
import javax.swing.JComponent;
64
import javax.swing.JOptionPane;
65
import javax.swing.SwingUtilities;
66
import javax.swing.UIManager;
67

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

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

    
104

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

    
127
        /**
128
         * DOCUMENT ME!
129
         *
130
         * @param args DOCUMENT ME!
131
         * @throws Exception
132
         *
133
         * @throws InterruptedException
134
         * @throws InvocationTargetException
135
         * @throws ConfigurationException
136
         * @throws MDIManagerLoadException
137
         * @throws IOException
138
         */
139
        public static void main(String[] args) throws Exception {
140
            try{
141

    
142
            if (!validJVM()){
143
                System.exit(-1);
144
            }
145
                
146
            if (args.length < 1) {
147
                        System.err.println("Uso: Launcher appName plugins-directory [language=locale]");
148
                }
149

    
150
            //  Clean temporal files
151
                Utilities.cleanUpTempFiles();
152

    
153
                appName = args[0];
154

    
155
                //Se crea el directorio de configuraci?n de la aplicaci?n
156
                File parent = new File(System.getProperty("user.home") +
157
                                File.separator + args[0] + File.separator);
158
                parent.mkdirs();
159

    
160
                andamiConfigPath = System.getProperty("user.home") + File.separator +
161
                        appName + File.separator + "andami-config.xml";
162
                pluginsPersistencePath = System.getProperty("user.home") +
163
                        File.separator + appName + File.separator +
164
                        "plugins-persistence.xml";
165

    
166
                // Configurar el log4j
167
                PropertyConfigurator.configure(Launcher.class.getClassLoader()
168
                                                                                                         .getResource("log4j.properties"));
169

    
170
                PatternLayout l = new PatternLayout("%p %t %C - %m%n");
171
                RollingFileAppender fa = new RollingFileAppender(l,
172
                                System.getProperty("user.home") + File.separator + args[0] +
173
                                File.separator + args[0] + ".log", false);
174
                fa.setMaxFileSize("512KB");
175
                fa.setMaxBackupIndex(3);
176
                Logger.getRootLogger().addAppender(fa);
177

    
178
                // Leer el fichero de configuraci?n de andami (andami-config.xsd)
179
                // locale
180
                // Buscar actualizaci?nes al comenzar
181
                //  Andami
182
                //  Plugins
183
                // Directorio de las extensiones
184
                andamiConfigFromXML(andamiConfigPath);
185
                andamiConfig.setPluginsDirectory(args[1]);
186
                
187
                // Hacemos visibles los argumentos como una propiedad est?tica
188
                // de plugin services para quien lo quiera usar (por ejemplo, para
189
                // cargar un proyecto por l?nea de comandos)
190
                PluginServices.setArguments(args);
191

    
192
                // Configurar el locale
193
        String localeStr = null;
194
        for (int i=2; i < args.length; i++)
195
        {
196
                int index = args[i].indexOf("language="); 
197
                if (index != -1)
198
                        localeStr = args[i].substring(index+9);
199
        }
200
                if (localeStr == null)
201
                {
202
            localeStr = andamiConfig.getLocaleLanguage();
203
                        /* locale = getLocale(localeStr,
204
                                        andamiConfig.getLocaleCountry(),
205
                                        andamiConfig.getLocaleVariant()); */
206
                }
207
        if (localeStr.compareTo("va")==0)
208
        {
209
            locale = new Locale("ca");
210
        }
211
        else
212
        {
213
            // locale = Locale.getDefault();
214
            locale = getLocale(localeStr,
215
                    andamiConfig.getLocaleCountry(),
216
                    andamiConfig.getLocaleVariant());
217
        }
218
        org.gvsig.i18n.Messages.addLocale(locale);
219
                // add english as a fallback language
220
                org.gvsig.i18n.Messages.addLocale(new Locale("en"));
221
                org.gvsig.i18n.Messages.addLocale(new Locale("es"));
222
        org.gvsig.i18n.Messages.addResourceFamily("com.iver.andami.text", "com.iver.andami.text");
223
                Locale.setDefault(locale);
224
                JComponent.setDefaultLocale(locale);
225

    
226
                //Se pone el lookAndFeel
227
                try {
228
                        UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
229
                } catch (Exception e) {
230
                        logger.warn(Messages.getString("Launcher.look_and_feel"), e);
231
                }
232

    
233
                // Mostrar la ventana de inicio
234
                splashWindow = new SplashWindow(null);
235

    
236
                // TODO Buscar actualizaciones de los plugins
237
                downloadExtensions(andamiConfig.getPluginsDirectory());
238
                
239
                validate();
240

    
241
                // Se leen los config.xml de los plugins -----++++
242
                loadPlugins(andamiConfig.getPluginsDirectory());
243

    
244
                // Se configura el classloader del plugin
245
                pluginsClassLoaders();
246

    
247
                // Se carga un Skin si alguno de los plugins trae informaci?n para ello
248
                skinPlugin();
249

    
250
                //Se configura la cola de eventos
251
                EventQueue waitQueue = new AndamiEventQueue();
252
                Toolkit.getDefaultToolkit().getSystemEventQueue().push(waitQueue);
253

    
254
                // Se configura la mensajer?a del plugin
255
                pluginsMessages();
256

    
257
                // Se modifica el andami-config con los plugins nuevos
258
                updateAndamiConfig();
259

    
260
                // Se prepara el MainFrame para albergar las extensiones
261
                frame = new MDIFrame();
262

    
263
                // Se configura el nombre e icono de la aplicaci?n
264
                frameIcon();
265

    
266
                SwingUtilities.invokeAndWait(new Runnable() {
267
                                public void run() {
268
                                        frame.init();
269
                                }
270
                        });
271

    
272
                // Se instalan los controles de las extensiones de los plugins
273
                SwingUtilities.invokeAndWait(new Runnable() {
274
                                public void run() {
275
                                        installPluginsControls();
276
                                        installPluginsMenus();
277
                                        installPluginsLabels();
278
                                }
279
                        });
280

    
281
                // Leer el fichero de persistencia
282
                //  info de los plugins
283
                //  bookmarks de los plugins
284
                loadPluginsPersistence();
285

    
286
                // Se instalan los controles del skin
287
                // Se inicializan todas las extensiones de todos los plugins
288
                SwingUtilities.invokeAndWait(new Runnable() {
289
                                public void run() {
290
                                        initializeExtensions();
291
                                }
292
                        });
293
                frame.setClassesExtensions(classesExtensions);
294

    
295
                // Se instalan los bookmarks de los plugins
296
                splashWindow.close();
297

    
298
                //Se muestra el frame principal
299
                frame.show();
300
                
301
                // Definimos un KeyEventDispatcher global para que las extensiones
302
                // puedan registrar sus "teclas r?pidas".
303
                GlobalKeyEventDispatcher keyDispatcher = GlobalKeyEventDispatcher.getInstance();
304
                KeyboardFocusManager.getCurrentKeyboardFocusManager().addKeyEventDispatcher(keyDispatcher);
305

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

    
366
        /**
367
     * @return
368
     */
369
    private static boolean validJVM() {
370
        char thirdCharacter = System.getProperty("java.version").charAt(2);
371
        if (thirdCharacter < '4'){
372
            return false;
373
            }else{
374
                return true;
375
            }
376
    }
377

    
378
    /**
379
         * DOCUMENT ME!
380
         *
381
         * @throws ConfigurationException
382
         */
383
        private static void loadPluginsPersistence() throws ConfigurationException {
384
                XMLEntity entity = persistenceFromXML();
385

    
386
                //System.err.println("loadPluginPersistence()");
387
                for (int i = 0; i < entity.getNumChild(); i++) {
388
                        XMLEntity plugin = entity.getChild(i);
389
                        String pName = plugin.getStringProperty(
390
                                        "com.iver.andami.pluginName");
391
                        //System.err.println("--> "+pName);
392
                        if (pluginsServices.get(pName)!= null){
393
                                ((PluginServices) pluginsServices.get(pName)).setPersistentXML(plugin);
394
                        } else {
395
                                if (pName.startsWith("Andami.Launcher"))
396
                                        restoreMDIStatus(plugin);
397
                        }
398
                }
399
        }
400
        
401
        /**
402
         * Salva la persistencia de los plugins.
403
         * @author LWS
404
         */
405
        private static void savePluginPersistence() {
406
                Iterator i = pluginsConfig.keySet().iterator();
407

    
408
                XMLEntity entity = new XMLEntity();
409

    
410
                while (i.hasNext()) {
411
                        String pName = (String) i.next();
412
                        PluginServices ps = (PluginServices) pluginsServices.get(pName);
413
                        XMLEntity ent = ps.getPersistentXML();
414

    
415
                        if (ent != null) {
416
                                ent.putProperty("com.iver.andami.pluginName", pName);
417
                                entity.addChild(ent);
418
                        }
419
                }
420
                XMLEntity ent = saveMDIStatus();
421
                if (ent != null) {
422
                        ent.putProperty("com.iver.andami.pluginName", "Andami.Launcher");
423
                        entity.addChild(ent);
424
                }
425
                try {
426
                        persistenceToXML(entity);
427
                } catch (ConfigurationException e1) {
428
                        logger.error(Messages.getString(
429
                                        "Launcher.Se_produjo_un_error_guardando_la_configuracion_de_los_plugins"),
430
                                e1);
431
                }
432
        }
433

    
434
        /**
435
         * DOCUMENT ME!
436
         */
437
        private static void installPluginsLabels() {
438
                Iterator i = pluginsConfig.keySet().iterator();
439

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

    
445
                        LabelSet[] ls = pc.getLabelSet();
446

    
447
                        for (int j = 0; j < ls.length; j++) {
448
                                PluginClassLoader loader = ps.getClassLoader();
449

    
450
                                try {
451
                                        Class clase = loader.loadClass(ls[j].getClassName());
452
                                        frame.setLabels(clase, ls[j].getLabel());
453
                                } catch (ClassNotFoundException e) {
454
                                        logger.error(Messages.getString("Launcher.labelset_class"),
455
                                                e);
456
                                }
457
                        }
458
                }
459
        }
460

    
461
        /**
462
         * DOCUMENT ME!
463
         *
464
         * @throws MDIManagerLoadException
465
         */
466
        private static void skinPlugin() throws MDIManagerLoadException {
467
                Iterator i = pluginsConfig.keySet().iterator();
468

    
469
                while (i.hasNext()) {
470
                        String name = (String) i.next();
471
                        PluginConfig pc = (PluginConfig) pluginsConfig.get(name);
472
                        PluginServices ps = (PluginServices) pluginsServices.get(name);
473

    
474
                        if (pc.getExtensions().getSkinExtension() != null) {
475
                                if (MDIManagerFactory.getSkinExtension() != null) {
476
                                        logger.warn(Messages.getString(
477
                                                        "Launcher.Dos_skin_extension"));
478
                                }
479

    
480
                                SkinExtension se = pc.getExtensions().getSkinExtension();
481

    
482
                                MDIManagerFactory.setSkinExtension(se, ps.getClassLoader());
483

    
484
                                Class skinClass;
485

    
486
                                try {
487
                                        skinClass = ps.getClassLoader().loadClass(se.getClassName());
488

    
489
                                        com.iver.andami.plugins.IExtension skinInstance = (com.iver.andami.plugins.IExtension) skinClass.newInstance();
490
                                        // classesExtensions.put(skinClass, skinInstance);
491
                                        // jaume
492
                                        ExtensionDecorator newExtensionDecorator = new ExtensionDecorator(skinInstance, ExtensionDecorator.INACTIVE);
493
                                        classesExtensions.put(skinClass, newExtensionDecorator);
494
                                } catch (ClassNotFoundException e) {
495
                                        logger.error(Messages.getString(
496
                                                        "Launcher.No_se_encontro_la_clase_mdi_manager"), e);
497
                                        throw new MDIManagerLoadException(e);
498
                                } catch (InstantiationException e) {
499
                                        logger.error(Messages.getString(
500
                                                        "Launcher.No_se_pudo_instanciar_la_clase_mdi_manager"),
501
                                                e);
502
                                        throw new MDIManagerLoadException(e);
503
                                } catch (IllegalAccessException e) {
504
                                        logger.error(Messages.getString(
505
                                                        "Launcher.No_se_pudo_acceder_a_la_clase_mdi_manager"),
506
                                                e);
507
                                        throw new MDIManagerLoadException(e);
508
                                }
509
                        }
510
                }
511
        }
512

    
513
        /**
514
         *
515
         */
516
        private static void frameIcon() {
517
                Iterator i = pluginsConfig.keySet().iterator();
518

    
519
                while (i.hasNext()) {
520
                        String pName = (String) i.next();
521
                        PluginConfig pc = (PluginConfig) pluginsConfig.get(pName);
522
                        PluginServices ps = (PluginServices) pluginsServices.get(pName);
523

    
524
                        if (pc.getIcon() != null) {
525
                                ImageIcon icon = new ImageIcon(ps.getClassLoader().getResource(pc.getIcon()
526
                                                                                                                                                                 .getSrc()));
527
                                frame.setIconImage(icon.getImage());
528
                                frame.setTitlePrefix(pc.getIcon().getText());
529
                        }
530
                }
531
        }
532

    
533
        /**
534
         *
535
         */
536
        private static void initializeExtensions() {
537
                Iterator i = pluginsOrdered.iterator();
538

    
539
                while (i.hasNext()) {
540
                        String pName = (String) i.next();
541
            logger.debug("Initializing extensions from " + pName);
542
                        PluginConfig pc = (PluginConfig) pluginsConfig.get(pName);
543
                        PluginServices ps = (PluginServices) pluginsServices.get(pName);
544

    
545
                        Extension[] exts = pc.getExtensions().getExtension();
546

    
547
                        TreeMap orderedExtensions = new TreeMap(new ExtensionComparator());
548

    
549
                        for (int j = 0; j < exts.length; j++) {
550
                                if (!exts[j].getActive()) {
551
                                        continue;
552
                                }
553

    
554
                                if (orderedExtensions.containsKey(exts[j])) {
555
                                        logger.warn(Messages.getString(
556
                                                        "Launcher.Two_extensions_with_the_same_priority") +
557
                                                exts[j].getClassName());
558
                                }
559

    
560
                                orderedExtensions.put(exts[j], null);
561
                        }
562

    
563
                        Iterator e = orderedExtensions.keySet().iterator();
564

    
565
                        while (e.hasNext()) {
566
                                Extension extension = (Extension) e.next();
567
                                com.iver.andami.plugins.IExtension extensionInstance;
568

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

    
589
                                } catch (InstantiationException e1) {
590
                                        logger.error(Messages.getString(
591
                                                        "Launcher.Error_instanciando_la_extension") +
592
                                                extension.getClassName(), e1);
593
                                } catch (IllegalAccessException e1) {
594
                                        logger.error(Messages.getString(
595
                                                        "Launcher.Error_instanciando_la_extension") +
596
                                                extension.getClassName(), e1);
597
                                } catch (ClassNotFoundException e1) {
598
                                        logger.error(Messages.getString(
599
                                                        "Launcher.No_se_encontro_la_clase_de_la_extension") +
600
                                                extension.getClassName(), e1);
601
                                } catch (NoClassDefFoundError e1) {
602
                                        logger.error(Messages.getString(
603
                                                        "Launcher.Error_localizando_la_clase_de_la_extension") +
604
                                                extension.getClassName(), e1);
605
                                }
606
                        }
607
                }
608
        }
609

    
610
        /**
611
         * DOCUMENT ME!
612
         */
613
        private static void installPluginsMenus() {
614
                TreeMap orderedMenus = new TreeMap(new MenuComparator());
615

    
616
                Iterator i = pluginsConfig.keySet().iterator();
617

    
618
                while (i.hasNext()) {
619
                        String pName = (String) i.next();
620
                        PluginServices ps = (PluginServices) pluginsServices.get(pName);
621
                        PluginConfig pc = (PluginConfig) pluginsConfig.get(pName);
622

    
623
                        Extension[] exts = pc.getExtensions().getExtension();
624

    
625
                        for (int j = 0; j < exts.length; j++) {
626
                                if (!exts[j].getActive()) {
627
                                        continue;
628
                                }
629

    
630
                                Menu[] menus = exts[j].getMenu();
631

    
632
                                for (int k = 0; k < menus.length; k++) {
633
                                        SortableMenu sm = new SortableMenu(ps.getClassLoader(),
634
                                                        exts[j], menus[k]);
635

    
636
                                        if (orderedMenus.containsKey(sm)) {
637
                                                logger.error(Messages.getString(
638
                                                                "Launcher.Two_menus_with_the_same_position") +
639
                                                        exts[j].getClassName());
640
                                        }
641

    
642
                                        orderedMenus.put(sm, null);
643
                                }
644
                        }
645

    
646
                        // Se instalan las extensiones de MDI
647
                        SkinExtension skinExt = pc.getExtensions().getSkinExtension();
648

    
649
                        if (skinExt != null) {
650
                                Menu[] menu = skinExt.getMenu();
651

    
652
                                for (int k = 0; k < menu.length; k++) {
653
                                        SortableMenu sm = new SortableMenu(ps.getClassLoader(),
654
                                                        skinExt, menu[k]);
655

    
656
                                        if (orderedMenus.containsKey(sm)) {
657
                                                logger.error(Messages.getString(
658
                                                                "Launcher.Two_menus_with_the_same_position") +
659
                                                        skinExt.getClassName());
660
                                        }
661

    
662
                                        orderedMenus.put(sm, null);
663
                                }
664
                        }
665
                }
666

    
667
                //Se itera por los menus ordenados
668
                Iterator e = orderedMenus.keySet().iterator();
669

    
670
                // Se ordenan los menues
671
                while (e.hasNext()) {
672
                        try {
673
                                SortableMenu sm = (SortableMenu) e.next();
674

    
675
                                frame.addMenu(sm.loader, sm.extension, sm.menu);
676
                        } catch (ClassNotFoundException ex) {
677
                                logger.error(Messages.getString(
678
                                                "Launcher.No_se_encontro_la_clase_de_la_extension"), ex);
679
                        }
680
                }
681
        }
682

    
683
        /**
684
         * Installs the menus, toolbars, actiontools and selectable toolbars.
685
         * The order in which they are shown is determined here. 
686
         */
687
        private static void installPluginsControls() {
688
                Iterator i = pluginsConfig.keySet().iterator();
689

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

    
720
                ///try {
721
                TreeMap orderedTools = new TreeMap(new ToolComparator());
722
                Iterator e = orderedExtensions.keySet().iterator();
723
                
724
                // Ahora se ordenan las herramientas (actiontools y selectabletools) de las extensiones
725
                while (e.hasNext()) {
726
                        Extension ext = (Extension) e.next();
727
                        
728
                        ToolBar[] toolbars = ext.getToolBar();
729
                        
730
                        for (int k = 0; k < toolbars.length; k++) {
731
                                ActionTool[] tools = toolbars[k].getActionTool();
732
                                
733
                                for (int t = 0; t < tools.length; t++) {
734
                                        SortableToolBar sm = new SortableToolBar(((PluginServices)extensionPluginServices.get(ext)).getClassLoader(), ext,
735
                                                        toolbars[k], tools[t]);
736
                                        previous = orderedTools.put(sm, null);
737
                                        ///frame.addTool(((PluginServices)extensionPluginServices.get(ext)).getClassLoader(), ext,
738
                                        ///        toolbars[k], tools[t]);
739
                                }
740
                                
741
                                SelectableTool[] sTools = toolbars[k].getSelectableTool();
742
                                
743
                                for (int t = 0; t < sTools.length; t++) {
744
                                        SortableToolBar sm=new SortableToolBar(((PluginServices)extensionPluginServices.get(ext)).getClassLoader(), ext,
745
                                                        toolbars[k], sTools[t]);
746
                                        previous = orderedTools.put(sm, null);
747
                                        ///frame.addTool(((PluginServices)extensionPluginServices.get(ext)).getClassLoader(), ext,
748
                                        ///        toolbars[k], sTools[t]);
749
                                }
750
                        }
751
                }
752

    
753
                // Ahora se ordenan las herramientas (actiontools y selectabletools) de las extensiones de MDI
754
                i = pluginsConfig.keySet().iterator();
755
                while (i.hasNext()) {
756
                        String pName = (String) i.next();
757
                        PluginConfig pc = (PluginConfig) pluginsConfig.get(pName);
758
                        PluginServices ps = (PluginServices) pluginsServices.get(pName);
759
                         
760
                        SkinExtension skinExt = pc.getExtensions().getSkinExtension();
761
                        
762
                        if (skinExt != null) {
763
                                ToolBar[] toolbars = skinExt.getToolBar();
764
                                
765
                                for (int k = 0; k < toolbars.length; k++) {
766
                                        ActionTool[] tools = toolbars[k].getActionTool();
767
                                        
768
                                        for (int t = 0; t < tools.length; t++) {
769
                                                SortableToolBar stb=new SortableToolBar(ps.getClassLoader(), skinExt,
770
                                                                toolbars[k], tools[t]);
771
                                                previous = orderedTools.put(stb,null);
772
                                                ///frame.addTool(ps.getClassLoader(), skinExt,
773
                                                ///        toolbars[k], tools[t]);
774
                                        }
775
                                        
776
                                        SelectableTool[] sTools = toolbars[k].getSelectableTool();
777
                                        
778
                                        for (int t = 0; t < sTools.length; t++) {
779
                                                SortableToolBar stb=new SortableToolBar(ps.getClassLoader(), skinExt,
780
                                                                toolbars[k], sTools[t]);
781
                                                previous = orderedTools.put(stb,null);
782
                                                ///frame.addTool(ps.getClassLoader(), skinExt,
783
                                                ///        toolbars[k], sTools[t]);
784
                                        }
785
                                }
786
                        }
787
                        //Se instalan los popup menus
788
                        PopupMenus pus = pc.getPopupMenus();
789
                        
790
                        if (pus != null) {
791
                                PopupMenu[] menus = pus.getPopupMenu();
792
                                
793
                                for (int j = 0; j < menus.length; j++) {
794
                                        frame.addPopupMenu(ps.getClassLoader(), menus[j]);
795
                                }
796
                        }
797
                }
798

    
799
                Iterator tt = orderedTools.keySet().iterator();                
800
                while (tt.hasNext()) {
801
                        SortableToolBar kk = (SortableToolBar) tt.next();
802
                        kk.getClass();
803
                }
804
                
805
                
806
                // Se itera por las herramientas ordenadas, para
807
                // a?adirlas a la interfaz de forma ordenada
808
                Iterator t = orderedTools.keySet().iterator();                
809
                while (t.hasNext()) {
810
                        try {
811
                                SortableToolBar stb = (SortableToolBar) t.next();
812
                                if (stb.actiontool!=null)
813
                                        frame.addTool(stb.loader, stb.extension,stb.toolbar, stb.actiontool);
814
                                else
815
                                        frame.addTool(stb.loader, stb.extension,stb.toolbar, stb.selectabletool);
816
                        } catch (ClassNotFoundException ex) {
817
                                logger.error(Messages.getString(
818
                                "Launcher.No_se_encontro_la_clase_de_la_extension"), ex);
819
                        }
820
                }
821
                ///} catch (ClassNotFoundException e) {
822
                ///        logger.error(Messages.getString(
823
                ///                        "Launcher.No_se_encontro_la_clase_de_la_extension"), e);
824
                ///}
825
        }
826

    
827
        /**
828
         *
829
         */
830
        private static void updateAndamiConfig() {
831
                HashSet olds = new HashSet();
832

    
833
                Plugin[] plugins = andamiConfig.getPlugin();
834

    
835
                for (int i = 0; i < plugins.length; i++) {
836
                        olds.add(plugins[i].getName());
837
                }
838

    
839
                Iterator i = pluginsServices.values().iterator();
840

    
841
                while (i.hasNext()) {
842
                        PluginServices ps = (PluginServices) i.next();
843

    
844
                        if (!olds.contains(ps.getPluginName())) {
845
                                Plugin p = new Plugin();
846
                                p.setName(ps.getPluginName());
847
                                p.setUpdate(false);
848

    
849
                                andamiConfig.addPlugin(p);
850
                        }
851
                }
852
        }
853

    
854
        /**
855
         * DOCUMENT ME!
856
         */
857
        private static void pluginsClassLoaders() {
858
                HashSet instalados = new HashSet();
859

    
860
                // Se itera hasta que est?n todos instalados
861
                while (instalados.size() != pluginsConfig.size()) {
862
                        boolean circle = true;
863

    
864
                        //Hacemos una pasada por todos los plugins
865
                        Iterator i = pluginsConfig.keySet().iterator();
866

    
867
                        while (i.hasNext()) {
868
                                String pluginName = (String) i.next();
869
                                PluginConfig config = (PluginConfig) pluginsConfig.get(pluginName);
870

    
871
                                if (instalados.contains(pluginName)) {
872
                                        continue;
873
                                }
874

    
875
                                //Se obtienen las dependencias y sus class loaders
876
                                boolean ready = true;
877
                                Depends[] dependencies = config.getDepends();
878
                                PluginClassLoader[] loaders = new PluginClassLoader[dependencies.length];
879

    
880
                                for (int j = 0; j < dependencies.length; j++) {
881
                                        if (pluginsConfig.get(dependencies[j].getPluginName()) == null) {
882
                                                logger.error(Messages.getString(
883
                                                                "Launcher.Dependencia_no_resuelta_en_plugin") +
884
                                                        pluginName + ": " +
885
                                                        dependencies[j].getPluginName());
886

    
887
                                                continue;
888
                                        }
889

    
890
                                        if (!instalados.contains(dependencies[j].getPluginName())) {
891
                                                ready = false;
892
                                        } else {
893
                                                loaders[j] = ((PluginServices) pluginsServices.get(dependencies[j].getPluginName())).getClassLoader();
894
                                        }
895
                                }
896

    
897
                                //Si no est?n sus dependencias satisfechas se aborta la instalaci?n
898
                                if (!ready) {
899
                                        continue;
900
                                }
901

    
902
                                //Se genera el class loader
903
                                String jardir = config.getLibraries().getLibraryDir();
904
                                File jarDir = new File(andamiConfig.getPluginsDirectory() +
905
                                                File.separator + pluginName + File.separator + jardir);
906
                                File[] jarFiles = jarDir.listFiles(new FileFilter() {
907
                                                        public boolean accept(File pathname) {
908
                                                                return (pathname.getName().toUpperCase()
909
                                                                                                .endsWith(".JAR")) ||
910
                                                                (pathname.getName().toUpperCase().endsWith(".ZIP"));
911
                                                        }
912
                                                });
913

    
914
                                URL[] urls = new URL[jarFiles.length];
915

    
916
                                for (int j = 0; j < jarFiles.length; j++) {
917
                                        try {
918
                                                urls[j] = new URL("file:" + jarFiles[j]);
919
                                        } catch (MalformedURLException e) {
920
                                                logger.error(Messages.getString(
921
                                                                "Launcher.No_se_puede_acceder_a") +
922
                                                        jarFiles[j]);
923
                                        }
924
                                }
925

    
926
                                PluginClassLoader loader;
927

    
928
                                try {
929
                                        loader = new PluginClassLoader(urls,
930
                                                        andamiConfig.getPluginsDirectory() +
931
                                                        File.separator + pluginName,
932
                                                        Launcher.class.getClassLoader(), loaders);
933

    
934
                                        PluginServices ps = new PluginServices(loader);
935

    
936
                                        pluginsServices.put(ps.getPluginName(), ps);
937

    
938
                                        instalados.add(pluginName);
939
                    // FJP: Los metemos ordenados para luego no cargar uno que necesita de otro antes de tiempo. Esto lo usaremos al 
940
                    // inicializar los plugins
941
                    pluginsOrdered.add(pluginName);
942

    
943
                                        circle = false;
944
                                } catch (IOException e) {
945
                                        logger.error(Messages.getString(
946
                                                        "Launcher.Error_con_las_librerias_del_plugin"), e);
947
                                        pluginsConfig.remove(pluginName);
948
                                        i = pluginsConfig.keySet().iterator();
949
                                }
950
                        }
951

    
952
                        if (circle) {
953
                                logger.error(Messages.getString(
954
                                                "Launcher.Hay_dependencias_circulares"));
955

    
956
                                break;
957
                        }
958
                }
959

    
960
                //Se eliminan los plugins que no fueron instalados
961
                Iterator i = pluginsConfig.keySet().iterator();
962

    
963
                while (i.hasNext()) {
964
                        String pluginName = (String) i.next();
965
                        PluginConfig config = (PluginConfig) pluginsConfig.get(pluginName);
966
                        PluginServices ps = (PluginServices) pluginsServices.get(pluginName);
967

    
968
                        if (ps == null) {
969
                                pluginsConfig.remove(pluginName);
970
                                i = pluginsConfig.keySet().iterator();
971
                        }
972
                } 
973
        }
974

    
975
        /**
976
         * DOCUMENT ME!
977
         */
978
        private static void pluginsMessages() {
979
                /* add gvsig translations first. This should be done using a generic "appPlugin" variable, instead 
980
                 * of using "com.iver.cit.gvsig" directly, but I'll do it when we use the new appgvSIG launcher.
981
                 * I keep this workaround for the moment. 
982
                 */
983
                PluginConfig config = (PluginConfig) pluginsConfig.get("com.iver.cit.gvsig");
984
                PluginServices ps = (PluginServices) pluginsServices.get("com.iver.cit.gvsig");
985
                if (config.getResourceBundle() != null) {
986
                        org.gvsig.i18n.Messages.addResourceFamily(config.getResourceBundle().getName(), ps.getClassLoader(), "com.iver.cit.gvsig");
987
                }
988

    
989
                //Iteramos por todos los plugins
990
                Iterator i = pluginsConfig.keySet().iterator();
991
                
992
                while (i.hasNext()) {
993
                        String pluginName = (String) i.next();
994
                        if (!pluginName.equals("com.iver.cit.gvsig")) { // we've already loaded com.iver.cit.gvsig
995
                                config = (PluginConfig) pluginsConfig.get(pluginName);
996
                                ps = (PluginServices) pluginsServices.get(pluginName);
997
                        
998
                                if (config.getResourceBundle() != null && !config.getResourceBundle().getName().equals("")) {
999
                                        // add the locale files associated with the plugin
1000
                                        org.gvsig.i18n.Messages.addResourceFamily(config.getResourceBundle().getName(), ps.getClassLoader(), pluginName);
1001
                                }
1002
                        }
1003
                }
1004
        }
1005

    
1006
        /**
1007
         * DOCUMENT ME!
1008
         *
1009
         * @param name DOCUMENT ME!
1010
         *
1011
         * @return DOCUMENT ME!
1012
         */
1013
        static PluginServices getPluginServices(String name) {
1014
                return (PluginServices) pluginsServices.get(name);
1015
        }
1016

    
1017
        /**
1018
         * DOCUMENT ME!
1019
         *
1020
         * @return DOCUMENT ME!
1021
         */
1022
        static String getPluginsDir() {
1023
                return andamiConfig.getPluginsDirectory();
1024
        }
1025

    
1026
        /**
1027
         * DOCUMENT ME!
1028
         *
1029
         * @param s DOCUMENT ME!
1030
         */
1031
        static void setPluginsDir(String s) {
1032
                andamiConfig.setPluginsDirectory(s);
1033
        }
1034

    
1035
        /**
1036
         * DOCUMENT ME!
1037
         *
1038
         * @return DOCUMENT ME!
1039
         */
1040
        static MDIFrame getMDIFrame() {
1041
                return frame;
1042
        }
1043

    
1044
        /**
1045
         * DOCUMENT ME!
1046
         *
1047
         * @param pluginsDirectory
1048
         */
1049
        private static void loadPlugins(String pluginsDirectory) {
1050
                File pDir = new File(pluginsDirectory);
1051

    
1052
                if (!pDir.exists()) {
1053
                        return;
1054
                }
1055

    
1056
                File[] pluginDirs = pDir.listFiles();
1057

    
1058
                for (int i = 0; i < pluginDirs.length; i++) {
1059
                        if (pluginDirs[i].isDirectory()) {
1060
                                File configXml = new File(pluginDirs[i].getAbsolutePath() +
1061
                                                File.separator + "config.xml");
1062

    
1063
                                try {
1064
                                        FileReader xml = new FileReader(configXml);
1065
                                        PluginConfig pConfig = (PluginConfig) PluginConfig.unmarshal(xml);
1066
                                        pluginsConfig.put(pluginDirs[i].getName(), pConfig);
1067
                                } catch (FileNotFoundException e) {
1068
                                        logger.info(Messages.getString(
1069
                                                        "Launcher.Ignorando_el_directorio") +
1070
                                                pluginDirs[i].getAbsolutePath() +
1071
                                                Messages.getString("Launcher.config_no_encontrado"));
1072
                                } catch (MarshalException e) {
1073
                                        logger.info(Messages.getString(
1074
                                                        "Launcher.Ignorando_el_directorio") +
1075
                                                pluginDirs[i].getAbsolutePath() +
1076
                                                Messages.getString("Launcher.config_mal_formado"), e);
1077
                                } catch (ValidationException e) {
1078
                                        logger.info(Messages.getString(
1079
                                                        "Launcher.Ignorando_el_directorio") +
1080
                                                pluginDirs[i].getAbsolutePath() +
1081
                                                Messages.getString("Launcher.config_mal_formado"), e);
1082
                                }
1083
                        }
1084
                }
1085
        }
1086

    
1087
        /**
1088
         * DOCUMENT ME!
1089
         *
1090
         * @param language
1091
         * @param country
1092
         * @param variant
1093
         *
1094
         * @return DOCUMENT ME!
1095
         */
1096
        private static Locale getLocale(String language, String country,
1097
                String variant) {
1098
                if (variant != null) {
1099
                        return new Locale(language, country, variant);
1100
                } else if (country != null) {
1101
                        return new Locale(language, country);
1102
                } else if (language != null) {
1103
                        return new Locale(language);
1104
                } else {
1105
                        return new Locale("es");
1106
                }
1107
        }
1108

    
1109
        /**
1110
         * DOCUMENT ME!
1111
         *
1112
         * @param file DOCUMENT ME!
1113
         *
1114
         * @throws IOException DOCUMENT ME!
1115
         * @throws MarshalException DOCUMENT ME!
1116
         * @throws ValidationException DOCUMENT ME!
1117
         */
1118
        private static void andamiConfigToXML(String file)
1119
                throws IOException, MarshalException, ValidationException {
1120
                File xml = new File(file);
1121
                File parent = xml.getParentFile();
1122
                parent.mkdirs();
1123

    
1124
                FileWriter writer = new FileWriter(xml);
1125
                andamiConfig.marshal(writer);
1126
        }
1127

    
1128
        /**
1129
         * DOCUMENT ME!
1130
         *
1131
         * @param file DOCUMENT ME!
1132
         *
1133
         * @throws ConfigurationException DOCUMENT ME!
1134
         */
1135
        private static void andamiConfigFromXML(String file)
1136
                throws ConfigurationException {
1137
                File xml = new File(file);
1138

    
1139
                //Si no existe se ponen los valores por defecto
1140
                if (!xml.exists()) {
1141
                        andamiConfig = new AndamiConfig();
1142

    
1143
                        Andami andami = new Andami();
1144
                        andami.setUpdate(true);
1145
                        andamiConfig.setAndami(andami);
1146
                        andamiConfig.setLocaleCountry(Locale.getDefault().getCountry());
1147
                        andamiConfig.setLocaleLanguage(Locale.getDefault().getLanguage());
1148
                        andamiConfig.setLocaleVariant(Locale.getDefault().getVariant());
1149

    
1150
                        if (System.getProperty("javawebstart.version") != null) // Es java web start)
1151
                         {
1152
                                andamiConfig.setPluginsDirectory(new File(System.getProperty(
1153
                                                        "user.home") + File.separator + appName +
1154
                                                File.separator + "extensiones").getAbsolutePath());
1155
                        } else {
1156
                                andamiConfig.setPluginsDirectory(new File(appName +
1157
                                                File.separator + "extensiones").getAbsolutePath());
1158
                        }
1159

    
1160
                        andamiConfig.setPlugin(new Plugin[0]);
1161
                } else {
1162
                        //Se lee la configuraci?n
1163
                        FileReader reader;
1164

    
1165
                        try {
1166
                                reader = new FileReader(xml);
1167
                                andamiConfig = (AndamiConfig) AndamiConfig.unmarshal(reader);
1168
                        } catch (FileNotFoundException e) {
1169
                                throw new ConfigurationException(e);
1170
                        } catch (MarshalException e) {
1171
                                throw new ConfigurationException(e);
1172
                        } catch (ValidationException e) {
1173
                                throw new ConfigurationException(e);
1174
                        }
1175
                }
1176
        }
1177

    
1178
        /**
1179
         * DOCUMENT ME!
1180
         *
1181
         * @return DOCUMENT ME!
1182
         *
1183
         * @throws ConfigurationException DOCUMENT ME!
1184
         */
1185
        private static XMLEntity persistenceFromXML() throws ConfigurationException {
1186
                File xml = new File(pluginsPersistencePath);
1187

    
1188
                if (xml.exists()) {
1189
                        FileReader reader;
1190

    
1191
                        try {
1192
                                reader = new FileReader(xml);
1193

    
1194
                                XmlTag tag = (XmlTag) XmlTag.unmarshal(reader);
1195

    
1196
                                return new XMLEntity(tag);
1197
                        } catch (FileNotFoundException e) {
1198
                                throw new ConfigurationException(e);
1199
                        } catch (MarshalException e) {
1200
                                throw new ConfigurationException(e);
1201
                        } catch (ValidationException e) {
1202
                                throw new ConfigurationException(e);
1203
                        }
1204
                } else {
1205
                        return new XMLEntity();
1206
                }
1207
        }
1208

    
1209
        /**
1210
         * DOCUMENT ME!
1211
         *
1212
         * @param entity DOCUMENT ME!
1213
         *
1214
         * @throws ConfigurationException DOCUMENT ME!
1215
         */
1216
        private static void persistenceToXML(XMLEntity entity)
1217
                throws ConfigurationException {
1218
                File xml = new File(pluginsPersistencePath);
1219

    
1220
                FileWriter writer;
1221

    
1222
                try {
1223
                        writer = new FileWriter(xml);
1224
                        entity.getXmlTag().marshal(writer);
1225
                } catch (FileNotFoundException e) {
1226
                        throw new ConfigurationException(e);
1227
                } catch (MarshalException e) {
1228
                        throw new ConfigurationException(e);
1229
                } catch (ValidationException e) {
1230
                        throw new ConfigurationException(e);
1231
                } catch (IOException e) {
1232
                        throw new ConfigurationException(e);
1233
                }
1234
        }
1235

    
1236
        /**
1237
         * Devuelve un array con los directorios de los plugins
1238
         *
1239
         * @param dirExt Directorio de las extensiones a partir del cual cuelgan
1240
         *                   todos los directorios de los plugins
1241
         *
1242
         * @return ArrayList con los directorios
1243
         */
1244
        private String[] getLocales(File dirExt) {
1245
                ArrayList types = new ArrayList();
1246
                File[] files = dirExt.listFiles();
1247

    
1248
                for (int i = 0; i < files.length; i++) {
1249
                        if (files[i].isDirectory()) {
1250
                                File[] textFile = files[i].listFiles(new FilenameFilter() {
1251
                                                        public boolean accept(File dir, String fileName) {
1252
                                                                return fileName.toLowerCase().startsWith("text_"); //$NON-NLS-1$
1253
                                                        }
1254
                                                });
1255

    
1256
                                for (int j = 0; j < textFile.length; j++) {
1257
                                        String s = (textFile[j]).getName().replaceAll("text_", "");
1258
                                        s = s.replaceAll(".properties", "");
1259
                                        s = s.trim();
1260

    
1261
                                        if (!types.contains(s)) {
1262
                                                types.add(s);
1263
                                        }
1264
                                }
1265
                        }
1266
                }
1267

    
1268
                return (String[]) types.toArray(new String[0]);
1269
        }
1270

    
1271
        /**
1272
         * DOCUMENT ME!
1273
         *
1274
         * @return Returns the frame.
1275
         */
1276
        static MDIFrame getFrame() {
1277
                return frame;
1278
        }
1279

    
1280
        /**
1281
         * Secuencia de cerrado de Andami
1282
         */
1283
        public static void closeApplication() {
1284
                //Configuraci?n de Andami
1285
                try {
1286
                        andamiConfigToXML(andamiConfigPath);
1287
                } catch (MarshalException e) {
1288
                        logger.error(Messages.getString(
1289
                                        "Launcher.No_se_pudo_guardar_la_configuracion_de_andami"), e);
1290
                } catch (ValidationException e) {
1291
                        logger.error(Messages.getString(
1292
                                        "Launcher.No_se_pudo_guardar_la_configuracion_de_andami"), e);
1293
                } catch (IOException e) {
1294
                        logger.error(Messages.getString(
1295
                                        "Launcher.No_se_pudo_guardar_la_configuracion_de_andami"), e);
1296
                }
1297

    
1298
                //Persistencia de los plugins
1299
                savePluginPersistence();
1300
                
1301
                //Finalize all the extensions
1302
                finalizeExtensions();
1303
                
1304
                // Clean any temp data created
1305
                Utilities.cleanUpTempFiles();
1306
                
1307
                //Para la depuraci?n de memory leaks
1308
                System.gc();
1309

    
1310
        System.exit(0);
1311
        }
1312
        
1313
        /**
1314
         * Exectutes the finalize method for all the extensions
1315
         *
1316
         */
1317
        private static void finalizeExtensions() {
1318
                Set extensions = getClassesExtensions().keySet();
1319
                Object[] keys = extensions.toArray(); 
1320
                
1321
                for (int i=0 ; i<keys.length ; i++){
1322
                        ExtensionDecorator extensionDecorator = 
1323
                                (ExtensionDecorator) getClassesExtensions().get(keys[i]);
1324
                        extensionDecorator.getExtension().finalize();
1325
                }                
1326
        }
1327

    
1328

    
1329
        /**
1330
         * DOCUMENT ME!
1331
         *
1332
         * @return DOCUMENT ME!
1333
         */
1334
        static HashMap getClassesExtensions() {
1335
                return classesExtensions;
1336
        }
1337

    
1338
        /**
1339
         * DOCUMENT ME!
1340
         *
1341
         * @param extDir DOCUMENT ME!
1342
         */
1343
        private static void downloadExtensions(String extDir) {
1344
                java.util.Date fechaActual = null;
1345

    
1346
                try {
1347
                        if (System.getProperty("javawebstart.version") != null) {
1348
                                //Obtenemos la URL del servidor
1349
                                BasicService bs = (BasicService) ServiceManager.lookup(
1350
                                                "javax.jnlp.BasicService");
1351
                                URL baseURL = bs.getCodeBase();
1352

    
1353
                                //Se descargan las extensiones
1354
                                SplashWindow.process(5,
1355
                                        "Descargando las extensiones desde " + baseURL + " a " +
1356
                                        extDir);
1357

    
1358
                                URL url = new URL(baseURL + "extensiones.zip");
1359
                                URLConnection connection = url.openConnection();
1360

    
1361
                                System.out.println(url.toExternalForm() + ":");
1362
                                System.out.println("  Content Type: " +
1363
                                        connection.getContentType());
1364
                                System.out.println("  Content Length: " +
1365
                                        connection.getContentLength());
1366
                                System.out.println("  Last Modified: " +
1367
                                        new Date(connection.getLastModified()));
1368
                                System.out.println("  Expiration: " +
1369
                                        connection.getExpiration());
1370
                                System.out.println("  Content Encoding: " +
1371
                                        connection.getContentEncoding());
1372

    
1373
                                // Guardamos la fecha del fichero de extensiones que nos hemos bajado, y
1374
                                // comprobamos el ?ltimo que se ha bajado. Si no son
1375
                                // iguales, nos bajamos el nuevo. Si son iguales, no
1376
                                // nos bajamos nada.
1377
                                Long miliSecondsInWeb = new Long(connection.getLastModified());
1378

    
1379
                                // PluginServices ps = PluginServices.getPluginServices("com.iver.core");
1380
                                // if (ps.getPersistentXML().getStringProperty("timestamp") != null)
1381
                                File destDir = new File(extDir);
1382

    
1383
                                if (!destDir.exists()) {
1384
                                        // Creamos gvSIG
1385
                                        destDir.getParentFile().mkdir();
1386

    
1387
                                        if (!destDir.mkdir()) {
1388
                                                System.err.println("Imposible crear el directorio " +
1389
                                                        destDir.getAbsolutePath());
1390
                                        }
1391
                                }
1392

    
1393
                                File timeFile = new File(destDir.getParent() + File.separator +
1394
                                                "timeStamp.properties");
1395

    
1396
                                if (!timeFile.exists()) {
1397
                                        timeFile.createNewFile();
1398
                                }
1399

    
1400
                                FileInputStream inAux = new FileInputStream(timeFile);
1401
                                Properties prop = new Properties();
1402
                                prop.load(inAux);
1403
                                inAux.close();
1404

    
1405
                                if (prop.getProperty("timestamp") != null) {
1406
                                        Long lastMiliSeconds = (Long) new Long(prop.getProperty(
1407
                                                                "timestamp"));
1408

    
1409
                                        if (lastMiliSeconds.longValue() == miliSecondsInWeb.longValue()) {
1410
                                                System.out.println("No hay nueva actualizaci?n");
1411

    
1412
                                                return;
1413
                                        }
1414

    
1415
                                        System.out.println("timeStampWeb= " + miliSecondsInWeb);
1416
                                        System.out.println("timeStampLocal= " + lastMiliSeconds);
1417
                                } else {
1418
                                        System.out.println("El timeStamp no est? escrito en " +
1419
                                                timeFile.getAbsolutePath());
1420
                                }
1421

    
1422
                                InputStream stream = connection.getInputStream();
1423
                                File temp = File.createTempFile("gvsig", ".zip");
1424
                                temp.deleteOnExit();
1425

    
1426
                                FileOutputStream file = new FileOutputStream(temp);
1427
                                BufferedInputStream in = new BufferedInputStream(stream);
1428
                                BufferedOutputStream out = new BufferedOutputStream(file);
1429

    
1430
                                int i;
1431
                                int pct;
1432
                                int desde;
1433
                                int hasta;
1434

    
1435
                                hasta = connection.getContentLength() / 1024;
1436
                                desde = 0;
1437

    
1438
                                while ((i = in.read()) != -1) {
1439
                                        pct = ((desde / 1024) * 100) / hasta;
1440

    
1441
                                        if (((desde % 10240) == 0) && (pct > 10) &&
1442
                                                        ((pct % 10) == 0)) {
1443
                                                SplashWindow.process(pct,
1444
                                                        (desde / 1024) + "Kb de " + hasta +
1445
                                                        "Kb descargados...");
1446
                                        }
1447

    
1448
                                        out.write(i);
1449
                                        desde++;
1450
                                }
1451

    
1452
                                out.flush();
1453
                                out.close();
1454
                                in.close();
1455

    
1456
                                //Se extrae el zip
1457
                                SplashWindow.process(5, "Extensiones descargadas.");
1458

    
1459
                                System.out.println("Extrayendo a " + destDir.getAbsolutePath());
1460

    
1461
                                Date fechaDir = new Date(destDir.lastModified());
1462
                                System.out.println("Fecha del directorio " + extDir + " = " +
1463
                                        fechaDir.toString());
1464
                                Utilities.extractTo(temp, new File(extDir), splashWindow);
1465

    
1466
                                // Si todo ha ido bien, guardamos el timestamp.
1467
                                ///  App.instance.getPc().addProperties("timestamp", miliSecondsInWeb);
1468
                                // XMLEntity xml=ps.getPersistentXML();
1469
                                fechaActual = new java.util.Date();
1470

    
1471
                                FileOutputStream outAux = new FileOutputStream(timeFile);
1472
                                prop.setProperty("timestamp", miliSecondsInWeb.toString());
1473
                                prop.store(outAux, "last download");
1474
                                outAux.close();
1475
                                System.out.println("Fecha actual guardada: " +
1476
                                        fechaActual.toGMTString());
1477

    
1478
                                /* xml.putProperty("timestamp",fechaActual.toGMTString());
1479
                                   ps.setPresistentXML(xml); */
1480
                        }
1481
                } catch (IOException e) {
1482
                        NotificationManager.addError("", e);
1483
                } catch (UnavailableServiceException e) {
1484
                        NotificationManager.addError("", e);
1485
                } catch (SecurityException e) {
1486
                        System.err.println("No se puede escribir el timeStamp " +
1487
                                fechaActual.toGMTString());
1488
                        NotificationManager.addError("", e);
1489
                }
1490
        }
1491

    
1492
        /**
1493
         * DOCUMENT ME!
1494
         *
1495
         * @return DOCUMENT ME!
1496
         */
1497
        private static Extensions[] getExtensions() {
1498
                ArrayList array = new ArrayList();
1499
                Iterator iter = pluginsConfig.values().iterator();
1500

    
1501
                while (iter.hasNext()) {
1502
                        array.add(((PluginConfig) iter.next()).getExtensions());
1503
                }
1504

    
1505
                return (Extensions[]) array.toArray(new Extensions[0]);
1506
        }
1507

    
1508
        /**
1509
         * DOCUMENT ME!
1510
         *
1511
         * @return DOCUMENT ME!
1512
         */
1513
        public static HashMap getPluginConfig() {
1514
                return pluginsConfig;
1515
        }
1516

    
1517
        /**
1518
         * DOCUMENT ME!
1519
         *
1520
         * @param s DOCUMENT ME!
1521
         *
1522
         * @return DOCUMENT ME!
1523
         */
1524
        public static Extension getExtension(String s) {
1525
                Extensions[] exts = getExtensions();
1526

    
1527
                for (int i = 0; i < exts.length; i++) {
1528
                        for (int j = 0; j < exts[i].getExtensionCount(); j++) {
1529
                                if (exts[i].getExtension(j).getClassName().equals(s)) {
1530
                                        return exts[i].getExtension(j);
1531
                                }
1532
                        }
1533
                }
1534

    
1535
                return null;
1536
        }
1537

    
1538
        /**
1539
         * DOCUMENT ME!
1540
         *
1541
         * @return DOCUMENT ME!
1542
         */
1543
        public static AndamiConfig getAndamiConfig() {
1544
                return andamiConfig;
1545
        }
1546

    
1547
        /**
1548
         * DOCUMENT ME!
1549
         *
1550
         * @author $author$
1551
         * @version $Revision: 6128 $
1552
         */
1553
        private static class ExtensionComparator implements Comparator {
1554
                /**
1555
                 * DOCUMENT ME!
1556
                 *
1557
                 * @param o1 DOCUMENT ME!
1558
                 * @param o2 DOCUMENT ME!
1559
                 *
1560
                 * @return DOCUMENT ME!
1561
                 */
1562
                public int compare(Object o1, Object o2) {
1563
                        Extension e1 = (Extension) o1;
1564
                        Extension e2 = (Extension) o2;
1565

    
1566
                        if (!e1.hasPriority() && !e2.hasPriority()) {
1567
                                return -1;
1568
                        }
1569

    
1570
                        if (e1.hasPriority() && !e2.hasPriority()) {
1571
                                return -Integer.MAX_VALUE;
1572
                        }
1573

    
1574
                        if (e2.hasPriority() && !e1.hasPriority()) {
1575
                                return Integer.MAX_VALUE;
1576
                        }
1577

    
1578
                        if (e1.getPriority() != e2.getPriority()){
1579
                                return e2.getPriority() - e1.getPriority();
1580
                        }else{
1581
                                return (e2.toString().compareTo(e1.toString()));
1582
                        }
1583
                }
1584
        }
1585

    
1586
        /**
1587
         * DOCUMENT ME!
1588
         */
1589
        private static class MenuComparator implements Comparator {
1590
                private static ExtensionComparator extComp = new ExtensionComparator();
1591

    
1592
                /**
1593
                 * DOCUMENT ME!
1594
                 *
1595
                 * @param o1 DOCUMENT ME!
1596
                 * @param o2 DOCUMENT ME!
1597
                 *
1598
                 * @return DOCUMENT ME!
1599
                 */
1600
                public int compare(Object o1, Object o2) {
1601
                        SortableMenu e1 = (SortableMenu) o1;
1602
                        SortableMenu e2 = (SortableMenu) o2;
1603

    
1604
                        if (!e1.menu.hasPosition() && !e2.menu.hasPosition()) {
1605
                                if (e1.extension instanceof SkinExtensionType) {
1606
                                        return 1;
1607
                                } else if (e2.extension instanceof SkinExtensionType) {
1608
                                        return -1;
1609
                                } else {
1610
                                        return extComp.compare(e1.extension, e2.extension);
1611
                                }
1612
                        }
1613

    
1614
                        if (e1.menu.hasPosition() && !e2.menu.hasPosition()) {
1615
                                return -Integer.MAX_VALUE;
1616
                        }
1617

    
1618
                        if (e2.menu.hasPosition() && !e1.menu.hasPosition()) {
1619
                                return Integer.MAX_VALUE;
1620
                        }
1621

    
1622
                        return e1.menu.getPosition() - e2.menu.getPosition();
1623
                }
1624
        }
1625

    
1626
        /**
1627
         * DOCUMENT ME!
1628
         *
1629
         * @author $author$
1630
         * @version $Revision: 6128 $
1631
         */
1632
        private static class SortableMenu {
1633
                public PluginClassLoader loader;
1634
                public Menu menu;
1635
                public SkinExtensionType extension;
1636

    
1637
                /**
1638
                 * DOCUMENT ME!
1639
                 *
1640
                 * @param loader DOCUMENT ME!
1641
                 * @param skinExt
1642
                 * @param menu2
1643
                 */
1644
                public SortableMenu(PluginClassLoader loader,
1645
                        SkinExtensionType skinExt, Menu menu2) {
1646
                        extension = skinExt;
1647
                        menu = menu2;
1648
                        this.loader = loader;
1649
                }
1650
        }
1651
        /**
1652
         * DOCUMENT ME!
1653
         */
1654
        private static class SortableToolBar {
1655
                public PluginClassLoader loader;
1656
                public ToolBar toolbar;
1657
                public ActionTool actiontool;
1658
                public SelectableTool selectabletool;
1659
                public SkinExtensionType extension;
1660

    
1661
                /**
1662
                 * DOCUMENT ME!
1663
                 *
1664
                 * @param loader DOCUMENT ME!
1665
                 * @param skinExt
1666
                 * @param menu2
1667
                 */
1668
                public SortableToolBar(PluginClassLoader loader,
1669
                        SkinExtensionType skinExt, ToolBar toolbar2,ActionTool actiontool2) {
1670
                        extension = skinExt;
1671
                        toolbar = toolbar2;
1672
                        actiontool=actiontool2;
1673
                        this.loader = loader;
1674
                }
1675
                public SortableToolBar(PluginClassLoader loader,
1676
                                SkinExtensionType skinExt, ToolBar toolbar2,SelectableTool selectabletool2) {
1677
                        extension = skinExt;
1678
                        toolbar = toolbar2;
1679
                        selectabletool=selectabletool2;
1680
                        this.loader = loader;
1681
                }
1682
        }
1683
        /**
1684
         * DOCUMENT ME!
1685
         */
1686
        private static class ToolBarComparator implements Comparator {
1687
                private static ExtensionComparator extComp = new ExtensionComparator();
1688

    
1689
                /**
1690
                 * DOCUMENT ME!
1691
                 *
1692
                 * @param o1 DOCUMENT ME!
1693
                 * @param o2 DOCUMENT ME!
1694
                 *
1695
                 * @return DOCUMENT ME!
1696
                 */
1697
                public int compare(Object o1, Object o2) {
1698
                        SortableToolBar e1 = (SortableToolBar) o1;
1699
                        SortableToolBar e2 = (SortableToolBar) o2;
1700
                        
1701
                        // if the toolbars have the same name, they are considered to be
1702
                        // the same toolbar, so we don't need to do further comparing
1703
                        if (e1.toolbar.getName().equals(e2.toolbar.getName()))
1704
                                return 0;
1705
                        
1706
                        if (!e1.toolbar.hasPosition() && !e2.toolbar.hasPosition()) {
1707
                                if (e1.extension instanceof SkinExtensionType) {
1708
                                        return 1;
1709
                                } else if (e2.extension instanceof SkinExtensionType) {
1710
                                        return -1;
1711
                                } else {
1712
                                        return extComp.compare(e1.extension, e2.extension);
1713
                                }
1714
                        }
1715

    
1716
                        if (e1.toolbar.hasPosition() && !e2.toolbar.hasPosition()) {
1717
                                return -Integer.MAX_VALUE;
1718
                        }
1719

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

    
1771
                        if (e1.actiontool!=null) {
1772
                                if (e1.actiontool.hasPosition())
1773
                                        e1Position = e1.actiontool.getPosition();
1774
                        }
1775
                        else if (e1.selectabletool!=null) {
1776
                                if (e1.selectabletool.hasPosition())
1777
                                        e1Position = e1.selectabletool.getPosition();
1778
                        }
1779
                        
1780
                        if (e2.actiontool!=null) {
1781
                                if (e2.actiontool.hasPosition())
1782
                                        e2Position = e2.actiontool.getPosition();
1783
                        }
1784
                        else if (e2.selectabletool!=null){
1785
                                if (e2.selectabletool.hasPosition())
1786
                                        e2Position = e2.selectabletool.getPosition();
1787
                        }
1788
                        
1789
                        if (e1Position==-1 && e2Position!=-1) {
1790
                                return 1;
1791
                        }
1792
                        if (e1Position!=-1 && e2Position==-1) {
1793
                                return -1;
1794
                        }
1795
                        if (e1Position!=-1 && e2Position!=-1) {
1796
                                result = e1Position - e2Position;
1797
                                // we don't return 0 unless both objects are the same, otherwise the objects get overwritten in the treemap
1798
                                if (result!=0) return result;
1799
                        }
1800
                        /*if (e1.toolbar.getActionTool().equals(e2.toolbar.getActionTool()) && e1.toolbar.getSelectableTool().equals(e2.toolbar.getSelectableTool())){
1801
                                return 0;
1802
                        }*/
1803
                        //logger.warn(Messages.getString("Different_tools_have_the_same_position_at_toolbar_")+e1.toolbar.getName());
1804
                        return e1.toString().compareTo(e2.toString());
1805
                }
1806
        }
1807
        
1808
        
1809
        /**
1810
         * validates the user before starting gvsig
1811
         *
1812
         */
1813
        private static void validate(){
1814
                
1815
                IAuthentication session =  null;
1816
                try {
1817
                        
1818
                        //String location = getClassLocation(Class.forName("com.iver.andami.authentication.Session"));
1819
                        session = (IAuthentication)Class.forName("com.iver.andami.authentication.Session").newInstance();
1820

    
1821
                } catch (ClassNotFoundException e) {
1822
                        // TODO Auto-generated catch block
1823
                        //e.printStackTrace();
1824
                        return;
1825
                } catch (InstantiationException e) {
1826
                        // TODO Auto-generated catch block
1827
                        //e.printStackTrace();
1828
                        return;
1829
                } catch (IllegalAccessException e) {
1830
                        // TODO Auto-generated catch block
1831
                        //e.printStackTrace();
1832
                        return;
1833
                }
1834
                
1835
                session.setPluginDirectory( andamiConfig.getPluginsDirectory() );
1836
                if (session.validationRequired()){
1837
                        
1838
                        //opens the login dialog for the user to validate
1839
                        //session.loging does not need arguments: they are read in the internal hashtable
1840
                        session.getUser();
1841
                        if(session.Login((String)session.get("user"),(String)session.get("pwd"))){
1842
                                System.out.println("You are logged in");
1843
                                //PluginServices.setSession( session );        
1844
                        }
1845
                        else{
1846
                                JOptionPane.showMessageDialog((Component)PluginServices.getMainFrame(),
1847
                                                 "You are not logged in");                                
1848
                                System.exit(0);
1849
                        }
1850
                        PluginServices.setAuthentication(session);
1851
                }                
1852
        }
1853
}