Statistics
| Revision:

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

History | View | Annotate | Download (53.3 KB)

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

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

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

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

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

    
121

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

    
143
    private static ArrayList pluginsOrdered = new ArrayList();
144

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

    
160
            if (!validJVM()){
161
                System.exit(-1);
162
            }
163

    
164
            if (args.length < 1) {
165
                        System.err.println("Uso: Launcher appName plugins-directory [language=locale]");
166
                }
167

    
168
            //  Clean temporal files
169
                Utilities.cleanUpTempFiles();
170

    
171
                appName = args[0];
172

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

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

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

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

    
196
                // Leer el fichero de configuraci?n de andami (andami-config.xsd)
197
                // locale
198
                // Buscar actualizaci?nes al comenzar
199
                //  Andami
200
                //  Plugins
201
                // Directorio de las extensiones
202
                andamiConfigFromXML(andamiConfigPath);
203
                andamiConfig.setPluginsDirectory(args[1]);
204

    
205
                // Hacemos visibles los argumentos como una propiedad est?tica
206
                // de plugin services para quien lo quiera usar (por ejemplo, para
207
                // cargar un proyecto por l?nea de comandos)
208
                PluginServices.setArguments(args);
209

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

    
244

    
245
                //Se pone el lookAndFeel
246
                try {
247
                        String lookAndFeel = getAndamiConfig().getLookAndFeel();
248
                        if (lookAndFeel == null)
249
                                lookAndFeel = getDefaultLookAndFeel();
250
                        UIManager.setLookAndFeel(lookAndFeel);
251
                } catch (Exception e) {
252
                        logger.warn(Messages.getString("Launcher.look_and_feel"), e);
253
                }
254

    
255
                // Mostrar la ventana de inicio
256
                splashWindow = new SplashWindow(null);
257

    
258
                // TODO Buscar actualizaciones de los plugins
259
                downloadExtensions(andamiConfig.getPluginsDirectory());
260

    
261
                validate();
262

    
263
                // Se leen los config.xml de los plugins -----++++
264
                loadPlugins(andamiConfig.getPluginsDirectory());
265

    
266
                // Se configura el classloader del plugin
267
                pluginsClassLoaders();
268

    
269
                // Se carga un Skin si alguno de los plugins trae informaci?n para ello
270
                skinPlugin();
271

    
272
                //Se configura la cola de eventos
273
                EventQueue waitQueue = new AndamiEventQueue();
274
                Toolkit.getDefaultToolkit().getSystemEventQueue().push(waitQueue);
275

    
276
                // Se configura la mensajer?a del plugin
277
                pluginsMessages();
278

    
279
                // Se modifica el andami-config con los plugins nuevos
280
                updateAndamiConfig();
281

    
282
                // Se prepara el MainFrame para albergar las extensiones
283
                frame = new MDIFrame();
284

    
285
                // Se configura el nombre e icono de la aplicaci?n
286
                frameIcon();
287

    
288
                SwingUtilities.invokeAndWait(new Runnable() {
289
                                public void run() {
290
                                        frame.init();
291
                                }
292
                        });
293

    
294
                // Se instalan los controles de las extensiones de los plugins
295
                SwingUtilities.invokeAndWait(new Runnable() {
296
                                public void run() {
297
                                        installPluginsControls();
298
                                        installPluginsMenus();
299
                                        installPluginsLabels();
300
                                }
301
                        });
302

    
303
                // Leer el fichero de persistencia
304
                //  info de los plugins
305
                //  bookmarks de los plugins
306
                loadPluginsPersistence();
307

    
308
                // Se instalan los controles del skin
309
                // Se inicializan todas las extensiones de todos los plugins
310
                SwingUtilities.invokeAndWait(new Runnable() {
311
                                public void run() {
312
                                        initializeExtensions();
313
                                }
314
                        });
315
                frame.setClassesExtensions(classesExtensions);
316

    
317
                // Se instalan los bookmarks de los plugins
318
                splashWindow.close();
319

    
320
                //Se muestra el frame principal
321
                frame.show();
322

    
323
                // Definimos un KeyEventDispatcher global para que las extensiones
324
                // puedan registrar sus "teclas r?pidas".
325
                GlobalKeyEventDispatcher keyDispatcher = GlobalKeyEventDispatcher.getInstance();
326
                KeyboardFocusManager.getCurrentKeyboardFocusManager().addKeyEventDispatcher(keyDispatcher);
327

    
328
                SwingUtilities.invokeAndWait(new Runnable() {
329
                                public void run() {
330
                                        frame.enableControls();
331
                                }
332
                        });
333
            }catch(Exception e){
334
                logger.error("excepci?n al arrancar", e);
335
                System.exit(-1);
336
            }
337

    
338
        }
339

    
340
        /**
341
         * Recupera la geometr?a (tama?o, posici?n y estado) de la ventana principal de Andami.
342
         * TODO Pendiente de ver como se asigna un pluginServices para el launcher.
343
         * @author LWS
344
         */
345
        private static void restoreMDIStatus(XMLEntity xml) {
346
                //System.err.println("Launcher: restoreMDIStatus()");
347
                if (xml == null) xml = new XMLEntity();
348
                //  restore frame size
349
                Dimension sz = new Dimension(700,580);
350
                if (xml.contains("MDIFrameSize")) {
351
                        int [] wh = xml.getIntArrayProperty("MDIFrameSize");
352
                        sz = new Dimension(wh[0], wh[1]);
353
                }
354
                frame.setSize(sz);
355
                //  restore frame location
356
                Point pos = new Point(10,10);
357
                if (xml.contains("MDIFramePos")) {
358
                        int [] xy = xml.getIntArrayProperty("MDIFramePos");
359
                        pos = new Point(xy[0], xy[1]);
360
                }
361
                frame.setLocation(pos);
362

    
363
                //  restore frame status (Maximized, minimized, etc);
364
                int state = java.awt.Frame.MAXIMIZED_BOTH;
365
                if (xml.contains("MDIFrameState")) {
366
                        state = xml.getIntProperty("MDIFrameState");
367
                }
368
                frame.setExtendedState(state);
369
        }
370

    
371
        private static XMLEntity saveMDIStatus() {
372
                XMLEntity xml = new XMLEntity();
373
                // save frame size
374
                int [] wh = new int[2];
375
                wh[0] = frame.getWidth();
376
                wh[1] = frame.getHeight();
377
                xml.putProperty("MDIFrameSize", wh);
378
                // save frame location
379
                int [] xy = new int[2];
380
                xy[0] = frame.getX();
381
                xy[1] = frame.getY();
382
                xml.putProperty("MDIFramePos", xy);
383
                // save frame status
384
                xml.putProperty("MDIFrameState", frame.getExtendedState());
385
                return xml;
386
        }
387

    
388
        /**
389
     * @return
390
     */
391
    private static boolean validJVM() {
392
        char thirdCharacter = System.getProperty("java.version").charAt(2);
393
        if (thirdCharacter < '4'){
394
            return false;
395
            }else{
396
                return true;
397
            }
398
    }
399

    
400
    /**
401
         * DOCUMENT ME!
402
         *
403
         * @throws ConfigurationException
404
         */
405
        private static void loadPluginsPersistence() throws ConfigurationException {
406
                XMLEntity entity = persistenceFromXML();
407

    
408
                //System.err.println("loadPluginPersistence()");
409
                for (int i = 0; i < entity.getNumChild(); i++) {
410
                        XMLEntity plugin = entity.getChild(i);
411
                        String pName = plugin.getStringProperty(
412
                                        "com.iver.andami.pluginName");
413
                        //System.err.println("--> "+pName);
414
                        if (pluginsServices.get(pName)!= null){
415
                                ((PluginServices) pluginsServices.get(pName)).setPersistentXML(plugin);
416
                        } else {
417
                                if (pName.startsWith("Andami.Launcher"))
418
                                        restoreMDIStatus(plugin);
419
                        }
420
                }
421
        }
422

    
423
        /**
424
         * Salva la persistencia de los plugins.
425
         * @author LWS
426
         */
427
        private static void savePluginPersistence() {
428
                Iterator i = pluginsConfig.keySet().iterator();
429

    
430
                XMLEntity entity = new XMLEntity();
431

    
432
                while (i.hasNext()) {
433
                        String pName = (String) i.next();
434
                        PluginServices ps = (PluginServices) pluginsServices.get(pName);
435
                        XMLEntity ent = ps.getPersistentXML();
436

    
437
                        if (ent != null) {
438
                                ent.putProperty("com.iver.andami.pluginName", pName);
439
                                entity.addChild(ent);
440
                        }
441
                }
442
                XMLEntity ent = saveMDIStatus();
443
                if (ent != null) {
444
                        ent.putProperty("com.iver.andami.pluginName", "Andami.Launcher");
445
                        entity.addChild(ent);
446
                }
447
                try {
448
                        persistenceToXML(entity);
449
                } catch (ConfigurationException e1) {
450
                        logger.error(Messages.getString(
451
                                        "Launcher.Se_produjo_un_error_guardando_la_configuracion_de_los_plugins"),
452
                                e1);
453
                }
454
        }
455

    
456
        /**
457
         * DOCUMENT ME!
458
         */
459
        private static void installPluginsLabels() {
460
                Iterator i = pluginsConfig.keySet().iterator();
461

    
462
                while (i.hasNext()) {
463
                        String name = (String) i.next();
464
                        PluginConfig pc = (PluginConfig) pluginsConfig.get(name);
465
                        PluginServices ps = (PluginServices) pluginsServices.get(name);
466

    
467
                        LabelSet[] ls = pc.getLabelSet();
468

    
469
                        for (int j = 0; j < ls.length; j++) {
470
                                PluginClassLoader loader = ps.getClassLoader();
471

    
472
                                try {
473
                                        Class clase = loader.loadClass(ls[j].getClassName());
474
                                        frame.setLabels(clase, ls[j].getLabel());
475
                                } catch (ClassNotFoundException e) {
476
                                        logger.error(Messages.getString("Launcher.labelset_class"),
477
                                                e);
478
                                }
479
                        }
480
                }
481
        }
482

    
483
        /**
484
         * DOCUMENT ME!
485
         *
486
         * @throws MDIManagerLoadException
487
         */
488
        private static void skinPlugin() throws MDIManagerLoadException {
489
                Iterator i = pluginsConfig.keySet().iterator();
490

    
491
                while (i.hasNext()) {
492
                        String name = (String) i.next();
493
                        PluginConfig pc = (PluginConfig) pluginsConfig.get(name);
494
                        PluginServices ps = (PluginServices) pluginsServices.get(name);
495

    
496
                        if (pc.getExtensions().getSkinExtension() != null) {
497
                                if (MDIManagerFactory.getSkinExtension() != null) {
498
                                        logger.warn(Messages.getString(
499
                                                        "Launcher.Dos_skin_extension"));
500
                                }
501

    
502
                                SkinExtension se = pc.getExtensions().getSkinExtension();
503

    
504
                                MDIManagerFactory.setSkinExtension(se, ps.getClassLoader());
505

    
506
                                Class skinClass;
507

    
508
                                try {
509
                                        skinClass = ps.getClassLoader().loadClass(se.getClassName());
510

    
511
                                        com.iver.andami.plugins.IExtension skinInstance = (com.iver.andami.plugins.IExtension) skinClass.newInstance();
512
                                        // classesExtensions.put(skinClass, skinInstance);
513
                                        // jaume
514
                                        ExtensionDecorator newExtensionDecorator = new ExtensionDecorator(skinInstance, ExtensionDecorator.INACTIVE);
515
                                        classesExtensions.put(skinClass, newExtensionDecorator);
516
                                } catch (ClassNotFoundException e) {
517
                                        logger.error(Messages.getString(
518
                                                        "Launcher.No_se_encontro_la_clase_mdi_manager"), e);
519
                                        throw new MDIManagerLoadException(e);
520
                                } catch (InstantiationException e) {
521
                                        logger.error(Messages.getString(
522
                                                        "Launcher.No_se_pudo_instanciar_la_clase_mdi_manager"),
523
                                                e);
524
                                        throw new MDIManagerLoadException(e);
525
                                } catch (IllegalAccessException e) {
526
                                        logger.error(Messages.getString(
527
                                                        "Launcher.No_se_pudo_acceder_a_la_clase_mdi_manager"),
528
                                                e);
529
                                        throw new MDIManagerLoadException(e);
530
                                }
531
                        }
532
                }
533
        }
534

    
535
        /**
536
         *
537
         */
538
        private static void frameIcon() {
539
                Iterator i = pluginsConfig.keySet().iterator();
540

    
541
                while (i.hasNext()) {
542
                        String pName = (String) i.next();
543
                        PluginConfig pc = (PluginConfig) pluginsConfig.get(pName);
544
                        PluginServices ps = (PluginServices) pluginsServices.get(pName);
545

    
546
                        if (pc.getIcon() != null) {
547
                                ImageIcon icon = new ImageIcon(ps.getClassLoader().getResource(pc.getIcon()
548
                                                                                                                                                                 .getSrc()));
549
                                frame.setIconImage(icon.getImage());
550
                                frame.setTitlePrefix(pc.getIcon().getText());
551
                        }
552
                }
553
        }
554

    
555
        /**
556
         *
557
         */
558
        private static void initializeExtensions() {
559
                Iterator i = pluginsOrdered.iterator();
560

    
561
                while (i.hasNext()) {
562
                        String pName = (String) i.next();
563
            logger.debug("Initializing extensions from " + pName);
564
                        PluginConfig pc = (PluginConfig) pluginsConfig.get(pName);
565
                        PluginServices ps = (PluginServices) pluginsServices.get(pName);
566

    
567
                        Extension[] exts = pc.getExtensions().getExtension();
568

    
569
                        TreeMap orderedExtensions = new TreeMap(new ExtensionComparator());
570

    
571
                        for (int j = 0; j < exts.length; j++) {
572
                                if (!exts[j].getActive()) {
573
                                        continue;
574
                                }
575

    
576
                                if (orderedExtensions.containsKey(exts[j])) {
577
                                        logger.warn(Messages.getString(
578
                                                        "Launcher.Two_extensions_with_the_same_priority") +
579
                                                exts[j].getClassName());
580
                                }
581

    
582
                                orderedExtensions.put(exts[j], null);
583
                        }
584

    
585
                        Iterator e = orderedExtensions.keySet().iterator();
586

    
587
                        while (e.hasNext()) {
588
                                Extension extension = (Extension) e.next();
589
                                com.iver.andami.plugins.IExtension extensionInstance;
590

    
591
                                try {
592
                                        Class extensionClass = ps.getClassLoader().loadClass(extension.getClassName());
593
                                        extensionInstance = (com.iver.andami.plugins.IExtension) extensionClass.newInstance();
594

    
595
                                        // CON DECORATOR
596
                                        // ANTES: classesExtensions.put(extensionClass, extensionInstance);
597
                                        // AHORA: CREAMOS UNA ExtensionDecorator y asignamos esta instancia para
598
                                        // poder ampliar con nuevas propiedades (AlwaysVisible, por ejemplo)
599
                                        // Para crear la nueva clase ExtensionDecorator, le pasamos como par?metro
600
                                        // la extensi?n original que acabamos de crear
601
                                        // 0-> Inactivo, controla la extension
602
                                        // 1-> Siempre visible
603
                                        // 2-> Invisible
604
                                        ExtensionDecorator newExtensionDecorator = new ExtensionDecorator(extensionInstance, ExtensionDecorator.INACTIVE);
605
                                        classesExtensions.put(extensionClass, newExtensionDecorator);
606
                                        System.err.println("Loading "+extension.getClassName()+"...");
607
                    // logger.debug("Initializing " + extension.getClassName());
608
                    extensionInstance.initialize();
609
                    // logger.debug(extension.getClassName() + " initialized.");
610

    
611
                                } catch (InstantiationException e1) {
612
                                        logger.error(Messages.getString(
613
                                                        "Launcher.Error_instanciando_la_extension") +
614
                                                extension.getClassName(), e1);
615
                                } catch (IllegalAccessException e1) {
616
                                        logger.error(Messages.getString(
617
                                                        "Launcher.Error_instanciando_la_extension") +
618
                                                extension.getClassName(), e1);
619
                                } catch (ClassNotFoundException e1) {
620
                                        logger.error(Messages.getString(
621
                                                        "Launcher.No_se_encontro_la_clase_de_la_extension") +
622
                                                extension.getClassName(), e1);
623
                                } catch (NoClassDefFoundError e1) {
624
                                        logger.error(Messages.getString(
625
                                                        "Launcher.Error_localizando_la_clase_de_la_extension") +
626
                                                extension.getClassName(), e1);
627
                                }
628
                        }
629
                }
630
        }
631

    
632
        /**
633
         * DOCUMENT ME!
634
         */
635
        private static void installPluginsMenus() {
636
                TreeMap orderedMenus = new TreeMap(new MenuComparator());
637

    
638
                Iterator i = pluginsConfig.keySet().iterator();
639

    
640
                while (i.hasNext()) {
641
                        String pName = (String) i.next();
642
                        PluginServices ps = (PluginServices) pluginsServices.get(pName);
643
                        PluginConfig pc = (PluginConfig) pluginsConfig.get(pName);
644

    
645
                        Extension[] exts = pc.getExtensions().getExtension();
646

    
647
                        for (int j = 0; j < exts.length; j++) {
648
                                if (!exts[j].getActive()) {
649
                                        continue;
650
                                }
651

    
652
                                Menu[] menus = exts[j].getMenu();
653

    
654
                                for (int k = 0; k < menus.length; k++) {
655
                                        SortableMenu sm = new SortableMenu(ps.getClassLoader(),
656
                                                        exts[j], menus[k]);
657

    
658
                                        if (orderedMenus.containsKey(sm)) {
659
                                                logger.error(Messages.getString(
660
                                                                "Launcher.Two_menus_with_the_same_position") +
661
                                                        exts[j].getClassName());
662
                                        }
663

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

    
668
                        // Se instalan las extensiones de MDI
669
                        SkinExtension skinExt = pc.getExtensions().getSkinExtension();
670

    
671
                        if (skinExt != null) {
672
                                Menu[] menu = skinExt.getMenu();
673

    
674
                                for (int k = 0; k < menu.length; k++) {
675
                                        SortableMenu sm = new SortableMenu(ps.getClassLoader(),
676
                                                        skinExt, menu[k]);
677

    
678
                                        if (orderedMenus.containsKey(sm)) {
679
                                                logger.error(Messages.getString(
680
                                                                "Launcher.Two_menus_with_the_same_position") +
681
                                                        skinExt.getClassName());
682
                                        }
683

    
684
                                        orderedMenus.put(sm, null);
685
                                }
686
                        }
687
                }
688

    
689
                //Se itera por los menus ordenados
690
                Iterator e = orderedMenus.keySet().iterator();
691

    
692
                // Se ordenan los menues
693
                while (e.hasNext()) {
694
                        try {
695
                                SortableMenu sm = (SortableMenu) e.next();
696

    
697
                                frame.addMenu(sm.loader, sm.extension, sm.menu);
698
                        } catch (ClassNotFoundException ex) {
699
                                logger.error(Messages.getString(
700
                                                "Launcher.No_se_encontro_la_clase_de_la_extension"), ex);
701
                        }
702
                }
703
        }
704

    
705
        /**
706
         * Installs the menus, toolbars, actiontools and selectable toolbars.
707
         * The order in which they are shown is determined here.
708
         */
709
        private static void installPluginsControls() {
710
                Iterator i = pluginsConfig.keySet().iterator();
711

    
712
                HashMap extensionPluginServices = new HashMap();
713
                HashMap extensionPluginConfig = new HashMap();
714
                TreeMap orderedExtensions = new TreeMap(new ExtensionComparator());
715
                Object previous;
716

    
717
                // First of all, sort the extensions.
718
                // We need to iterate on the plugins, and iterate on each plugin's extensions
719
                // (each plugin may contain one or more extensions)
720
                while (i.hasNext()) { // iterate on the plugins
721
                        String pName = (String) i.next();
722
                        PluginConfig pc = (PluginConfig) pluginsConfig.get(pName);
723
                        PluginServices ps = (PluginServices) pluginsServices.get(pName);
724

    
725
                        Extension[] exts = pc.getExtensions().getExtension();
726

    
727
                        for (int j = 0; j < exts.length; j++) { // iterate on the extensions
728
                                if (exts[j].getActive()) {
729
                                        if (orderedExtensions.containsKey(exts[j])) {
730
                                                logger.error(Messages.getString(
731
                                                "Launcher.Two_extensions_with_the_same_priority") +
732
                                                exts[j].getClassName());
733
                                        }
734

    
735
                                        orderedExtensions.put(exts[j], null);
736
                                        extensionPluginServices.put(exts[j], ps);
737
                                        extensionPluginConfig.put(exts[j], pc);
738
                                }
739
                        }
740
                }
741

    
742
                ///try {
743
                TreeMap orderedTools = new TreeMap(new ToolComparator());
744
                Iterator e = orderedExtensions.keySet().iterator();
745

    
746
                // Ahora se ordenan las herramientas (actiontools y selectabletools) de las extensiones
747
                while (e.hasNext()) {
748
                        Extension ext = (Extension) e.next();
749

    
750
                        ToolBar[] toolbars = ext.getToolBar();
751

    
752
                        for (int k = 0; k < toolbars.length; k++) {
753
                                ActionTool[] tools = toolbars[k].getActionTool();
754

    
755
                                for (int t = 0; t < tools.length; t++) {
756
                                        SortableToolBar sm = new SortableToolBar(((PluginServices)extensionPluginServices.get(ext)).getClassLoader(), ext,
757
                                                        toolbars[k], tools[t]);
758
                                        previous = orderedTools.put(sm, null);
759
                                        ///frame.addTool(((PluginServices)extensionPluginServices.get(ext)).getClassLoader(), ext,
760
                                        ///        toolbars[k], tools[t]);
761
                                }
762

    
763
                                SelectableTool[] sTools = toolbars[k].getSelectableTool();
764

    
765
                                for (int t = 0; t < sTools.length; t++) {
766
                                        SortableToolBar sm=new SortableToolBar(((PluginServices)extensionPluginServices.get(ext)).getClassLoader(), ext,
767
                                                        toolbars[k], sTools[t]);
768
                                        previous = orderedTools.put(sm, null);
769
                                        ///frame.addTool(((PluginServices)extensionPluginServices.get(ext)).getClassLoader(), ext,
770
                                        ///        toolbars[k], sTools[t]);
771
                                }
772
                        }
773
                }
774

    
775
                // Ahora se ordenan las herramientas (actiontools y selectabletools) de las extensiones de MDI
776
                i = pluginsConfig.keySet().iterator();
777
                while (i.hasNext()) {
778
                        String pName = (String) i.next();
779
                        PluginConfig pc = (PluginConfig) pluginsConfig.get(pName);
780
                        PluginServices ps = (PluginServices) pluginsServices.get(pName);
781

    
782
                        SkinExtension skinExt = pc.getExtensions().getSkinExtension();
783

    
784
                        if (skinExt != null) {
785
                                ToolBar[] toolbars = skinExt.getToolBar();
786

    
787
                                for (int k = 0; k < toolbars.length; k++) {
788
                                        ActionTool[] tools = toolbars[k].getActionTool();
789

    
790
                                        for (int t = 0; t < tools.length; t++) {
791
                                                SortableToolBar stb=new SortableToolBar(ps.getClassLoader(), skinExt,
792
                                                                toolbars[k], tools[t]);
793
                                                previous = orderedTools.put(stb,null);
794
                                                ///frame.addTool(ps.getClassLoader(), skinExt,
795
                                                ///        toolbars[k], tools[t]);
796
                                        }
797

    
798
                                        SelectableTool[] sTools = toolbars[k].getSelectableTool();
799

    
800
                                        for (int t = 0; t < sTools.length; t++) {
801
                                                SortableToolBar stb=new SortableToolBar(ps.getClassLoader(), skinExt,
802
                                                                toolbars[k], sTools[t]);
803
                                                previous = orderedTools.put(stb,null);
804
                                                ///frame.addTool(ps.getClassLoader(), skinExt,
805
                                                ///        toolbars[k], sTools[t]);
806
                                        }
807
                                }
808
                        }
809
                        //Se instalan los popup menus
810
                        PopupMenus pus = pc.getPopupMenus();
811

    
812
                        if (pus != null) {
813
                                PopupMenu[] menus = pus.getPopupMenu();
814

    
815
                                for (int j = 0; j < menus.length; j++) {
816
                                        frame.addPopupMenu(ps.getClassLoader(), menus[j]);
817
                                }
818
                        }
819
                }
820

    
821
                Iterator tt = orderedTools.keySet().iterator();
822
                while (tt.hasNext()) {
823
                        SortableToolBar kk = (SortableToolBar) tt.next();
824
                        kk.getClass();
825
                }
826

    
827

    
828
                // Se itera por las herramientas ordenadas, para
829
                // a?adirlas a la interfaz de forma ordenada
830
                Iterator t = orderedTools.keySet().iterator();
831
                while (t.hasNext()) {
832
                        try {
833
                                SortableToolBar stb = (SortableToolBar) t.next();
834
                                if (stb.actiontool!=null)
835
                                        frame.addTool(stb.loader, stb.extension,stb.toolbar, stb.actiontool);
836
                                else
837
                                        frame.addTool(stb.loader, stb.extension,stb.toolbar, stb.selectabletool);
838
                        } catch (ClassNotFoundException ex) {
839
                                logger.error(Messages.getString(
840
                                "Launcher.No_se_encontro_la_clase_de_la_extension"), ex);
841
                        }
842
                }
843
                ///} catch (ClassNotFoundException e) {
844
                ///        logger.error(Messages.getString(
845
                ///                        "Launcher.No_se_encontro_la_clase_de_la_extension"), e);
846
                ///}
847
        }
848

    
849
        /**
850
         *
851
         */
852
        private static void updateAndamiConfig() {
853
                HashSet olds = new HashSet();
854

    
855
                Plugin[] plugins = andamiConfig.getPlugin();
856

    
857
                for (int i = 0; i < plugins.length; i++) {
858
                        olds.add(plugins[i].getName());
859
                }
860

    
861
                Iterator i = pluginsServices.values().iterator();
862

    
863
                while (i.hasNext()) {
864
                        PluginServices ps = (PluginServices) i.next();
865

    
866
                        if (!olds.contains(ps.getPluginName())) {
867
                                Plugin p = new Plugin();
868
                                p.setName(ps.getPluginName());
869
                                p.setUpdate(false);
870

    
871
                                andamiConfig.addPlugin(p);
872
                        }
873
                }
874
        }
875

    
876
        /**
877
         * DOCUMENT ME!
878
         */
879
        private static void pluginsClassLoaders() {
880
                HashSet instalados = new HashSet();
881

    
882
                // Se itera hasta que est?n todos instalados
883
                while (instalados.size() != pluginsConfig.size()) {
884
                        boolean circle = true;
885

    
886
                        //Hacemos una pasada por todos los plugins
887
                        Iterator i = pluginsConfig.keySet().iterator();
888

    
889
                        while (i.hasNext()) {
890
                                String pluginName = (String) i.next();
891
                                PluginConfig config = (PluginConfig) pluginsConfig.get(pluginName);
892

    
893
                                if (instalados.contains(pluginName)) {
894
                                        continue;
895
                                }
896

    
897
                                //Se obtienen las dependencias y sus class loaders
898
                                boolean ready = true;
899
                                Depends[] dependencies = config.getDepends();
900
                                PluginClassLoader[] loaders = new PluginClassLoader[dependencies.length];
901

    
902
                                for (int j = 0; j < dependencies.length; j++) {
903
                                        if (pluginsConfig.get(dependencies[j].getPluginName()) == null) {
904
                                                logger.error(Messages.getString(
905
                                                                "Launcher.Dependencia_no_resuelta_en_plugin") +
906
                                                        pluginName + ": " +
907
                                                        dependencies[j].getPluginName());
908

    
909
                                                continue;
910
                                        }
911

    
912
                                        if (!instalados.contains(dependencies[j].getPluginName())) {
913
                                                ready = false;
914
                                        } else {
915
                                                loaders[j] = ((PluginServices) pluginsServices.get(dependencies[j].getPluginName())).getClassLoader();
916
                                        }
917
                                }
918

    
919
                                //Si no est?n sus dependencias satisfechas se aborta la instalaci?n
920
                                if (!ready) {
921
                                        continue;
922
                                }
923

    
924
                                //Se genera el class loader
925
                                String jardir = config.getLibraries().getLibraryDir();
926
                                File jarDir = new File(andamiConfig.getPluginsDirectory() +
927
                                                File.separator + pluginName + File.separator + jardir);
928
                                File[] jarFiles = jarDir.listFiles(new FileFilter() {
929
                                                        public boolean accept(File pathname) {
930
                                                                return (pathname.getName().toUpperCase()
931
                                                                                                .endsWith(".JAR")) ||
932
                                                                (pathname.getName().toUpperCase().endsWith(".ZIP"));
933
                                                        }
934
                                                });
935

    
936
                                URL[] urls = new URL[jarFiles.length];
937

    
938
                                for (int j = 0; j < jarFiles.length; j++) {
939
                                        try {
940
                                                urls[j] = new URL("file:" + jarFiles[j]);
941
                                        } catch (MalformedURLException e) {
942
                                                logger.error(Messages.getString(
943
                                                                "Launcher.No_se_puede_acceder_a") +
944
                                                        jarFiles[j]);
945
                                        }
946
                                }
947

    
948
                                PluginClassLoader loader;
949

    
950
                                try {
951
                                        loader = new PluginClassLoader(urls,
952
                                                        andamiConfig.getPluginsDirectory() +
953
                                                        File.separator + pluginName,
954
                                                        Launcher.class.getClassLoader(), loaders);
955

    
956
                                        PluginServices ps = new PluginServices(loader);
957

    
958
                                        pluginsServices.put(ps.getPluginName(), ps);
959

    
960
                                        instalados.add(pluginName);
961
                    // FJP: Los metemos ordenados para luego no cargar uno que necesita de otro antes de tiempo. Esto lo usaremos al
962
                    // inicializar los plugins
963
                    pluginsOrdered.add(pluginName);
964

    
965
                                        circle = false;
966
                                } catch (IOException e) {
967
                                        logger.error(Messages.getString(
968
                                                        "Launcher.Error_con_las_librerias_del_plugin"), e);
969
                                        pluginsConfig.remove(pluginName);
970
                                        i = pluginsConfig.keySet().iterator();
971
                                }
972
                        }
973

    
974
                        if (circle) {
975
                                logger.error(Messages.getString(
976
                                                "Launcher.Hay_dependencias_circulares"));
977

    
978
                                break;
979
                        }
980
                }
981

    
982
                //Se eliminan los plugins que no fueron instalados
983
                Iterator i = pluginsConfig.keySet().iterator();
984

    
985
                while (i.hasNext()) {
986
                        String pluginName = (String) i.next();
987
                        PluginConfig config = (PluginConfig) pluginsConfig.get(pluginName);
988
                        PluginServices ps = (PluginServices) pluginsServices.get(pluginName);
989

    
990
                        if (ps == null) {
991
                                pluginsConfig.remove(pluginName);
992
                                i = pluginsConfig.keySet().iterator();
993
                        }
994
                }
995
        }
996

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

    
1011
                //Iteramos por todos los plugins
1012
                Iterator i = pluginsConfig.keySet().iterator();
1013

    
1014
                while (i.hasNext()) {
1015
                        String pluginName = (String) i.next();
1016
                        if (!pluginName.equals("com.iver.cit.gvsig")) { // we've already loaded com.iver.cit.gvsig
1017
                                config = (PluginConfig) pluginsConfig.get(pluginName);
1018
                                ps = (PluginServices) pluginsServices.get(pluginName);
1019

    
1020
                                if (config.getResourceBundle() != null && !config.getResourceBundle().getName().equals("")) {
1021
                                        // add the locale files associated with the plugin
1022
                                        org.gvsig.i18n.Messages.addResourceFamily(config.getResourceBundle().getName(), ps.getClassLoader(), pluginName);
1023
                                }
1024
                        }
1025
                }
1026
        }
1027

    
1028
        /**
1029
         * DOCUMENT ME!
1030
         *
1031
         * @param name DOCUMENT ME!
1032
         *
1033
         * @return DOCUMENT ME!
1034
         */
1035
        static PluginServices getPluginServices(String name) {
1036
                return (PluginServices) pluginsServices.get(name);
1037
        }
1038

    
1039
        /**
1040
         * DOCUMENT ME!
1041
         *
1042
         * @return DOCUMENT ME!
1043
         */
1044
        static String getPluginsDir() {
1045
                return andamiConfig.getPluginsDirectory();
1046
        }
1047

    
1048
        /**
1049
         * DOCUMENT ME!
1050
         *
1051
         * @param s DOCUMENT ME!
1052
         */
1053
        static void setPluginsDir(String s) {
1054
                andamiConfig.setPluginsDirectory(s);
1055
        }
1056

    
1057
        /**
1058
         * DOCUMENT ME!
1059
         *
1060
         * @return DOCUMENT ME!
1061
         */
1062
        static MDIFrame getMDIFrame() {
1063
                return frame;
1064
        }
1065

    
1066
        /**
1067
         * DOCUMENT ME!
1068
         *
1069
         * @param pluginsDirectory
1070
         */
1071
        private static void loadPlugins(String pluginsDirectory) {
1072
                File pDir = new File(pluginsDirectory);
1073

    
1074
                if (!pDir.exists()) {
1075
                        return;
1076
                }
1077

    
1078
                File[] pluginDirs = pDir.listFiles();
1079

    
1080
                for (int i = 0; i < pluginDirs.length; i++) {
1081
                        if (pluginDirs[i].isDirectory()) {
1082
                                File configXml = new File(pluginDirs[i].getAbsolutePath() +
1083
                                                File.separator + "config.xml");
1084

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

    
1109
        /**
1110
         * DOCUMENT ME!
1111
         *
1112
         * @param language
1113
         * @param country
1114
         * @param variant
1115
         *
1116
         * @return DOCUMENT ME!
1117
         */
1118
        private static Locale getLocale(String language, String country,
1119
                String variant) {
1120
                if (variant != null) {
1121
                        return new Locale(language, country, variant);
1122
                } else if (country != null) {
1123
                        return new Locale(language, country);
1124
                } else if (language != null) {
1125
                        return new Locale(language);
1126
                } else {
1127
                        return new Locale("es");
1128
                }
1129
        }
1130

    
1131
        /**
1132
         * DOCUMENT ME!
1133
         *
1134
         * @param file DOCUMENT ME!
1135
         *
1136
         * @throws IOException DOCUMENT ME!
1137
         * @throws MarshalException DOCUMENT ME!
1138
         * @throws ValidationException DOCUMENT ME!
1139
         */
1140
        private static void andamiConfigToXML(String file)
1141
                throws IOException, MarshalException, ValidationException {
1142
                File xml = new File(file);
1143
                File parent = xml.getParentFile();
1144
                parent.mkdirs();
1145

    
1146
                FileWriter writer = new FileWriter(xml);
1147
                andamiConfig.marshal(writer);
1148
        }
1149

    
1150
        /**
1151
         * DOCUMENT ME!
1152
         *
1153
         * @param file DOCUMENT ME!
1154
         *
1155
         * @throws ConfigurationException DOCUMENT ME!
1156
         */
1157
        private static void andamiConfigFromXML(String file)
1158
                throws ConfigurationException {
1159
                File xml = new File(file);
1160

    
1161
                //Si no existe se ponen los valores por defecto
1162
                if (!xml.exists()) {
1163
                        andamiConfig = new AndamiConfig();
1164

    
1165
                        Andami andami = new Andami();
1166
                        andami.setUpdate(true);
1167
                        andamiConfig.setAndami(andami);
1168
                        andamiConfig.setLocaleCountry(Locale.getDefault().getCountry());
1169
                        andamiConfig.setLocaleLanguage(Locale.getDefault().getLanguage());
1170
                        andamiConfig.setLocaleVariant(Locale.getDefault().getVariant());
1171

    
1172
                        if (System.getProperty("javawebstart.version") != null) // Es java web start)
1173
                         {
1174
                                andamiConfig.setPluginsDirectory(new File(System.getProperty(
1175
                                                        "user.home") + File.separator + appName +
1176
                                                File.separator + "extensiones").getAbsolutePath());
1177
                        } else {
1178
                                andamiConfig.setPluginsDirectory(new File(appName +
1179
                                                File.separator + "extensiones").getAbsolutePath());
1180
                        }
1181

    
1182
                        andamiConfig.setPlugin(new Plugin[0]);
1183
                } else {
1184
                        //Se lee la configuraci?n
1185
                        FileReader reader;
1186

    
1187
                        try {
1188
                                reader = new FileReader(xml);
1189
                                andamiConfig = (AndamiConfig) AndamiConfig.unmarshal(reader);
1190
                        } catch (FileNotFoundException e) {
1191
                                throw new ConfigurationException(e);
1192
                        } catch (MarshalException e) {
1193
                                throw new ConfigurationException(e);
1194
                        } catch (ValidationException e) {
1195
                                throw new ConfigurationException(e);
1196
                        }
1197
                }
1198
        }
1199

    
1200
        /**
1201
         * DOCUMENT ME!
1202
         *
1203
         * @return DOCUMENT ME!
1204
         *
1205
         * @throws ConfigurationException DOCUMENT ME!
1206
         */
1207
        private static XMLEntity persistenceFromXML() throws ConfigurationException {
1208
                File xml = new File(pluginsPersistencePath);
1209

    
1210
                if (xml.exists()) {
1211
                        FileReader reader;
1212

    
1213
                        try {
1214
                                reader = new FileReader(xml);
1215

    
1216
                                XmlTag tag = (XmlTag) XmlTag.unmarshal(reader);
1217

    
1218
                                return new XMLEntity(tag);
1219
                        } catch (FileNotFoundException e) {
1220
                                throw new ConfigurationException(e);
1221
                        } catch (MarshalException e) {
1222
                                throw new ConfigurationException(e);
1223
                        } catch (ValidationException e) {
1224
                                throw new ConfigurationException(e);
1225
                        }
1226
                } else {
1227
                        return new XMLEntity();
1228
                }
1229
        }
1230

    
1231
        /**
1232
         * DOCUMENT ME!
1233
         *
1234
         * @param entity DOCUMENT ME!
1235
         *
1236
         * @throws ConfigurationException DOCUMENT ME!
1237
         */
1238
        private static void persistenceToXML(XMLEntity entity)
1239
                throws ConfigurationException {
1240
                File xml = new File(pluginsPersistencePath);
1241

    
1242
                FileWriter writer;
1243

    
1244
                try {
1245
                        writer = new FileWriter(xml);
1246
                        entity.getXmlTag().marshal(writer);
1247
                } catch (FileNotFoundException e) {
1248
                        throw new ConfigurationException(e);
1249
                } catch (MarshalException e) {
1250
                        throw new ConfigurationException(e);
1251
                } catch (ValidationException e) {
1252
                        throw new ConfigurationException(e);
1253
                } catch (IOException e) {
1254
                        throw new ConfigurationException(e);
1255
                }
1256
        }
1257

    
1258
        /**
1259
         * Devuelve un array con los directorios de los plugins
1260
         *
1261
         * @param dirExt Directorio de las extensiones a partir del cual cuelgan
1262
         *                   todos los directorios de los plugins
1263
         *
1264
         * @return ArrayList con los directorios
1265
         */
1266
        private String[] getLocales(File dirExt) {
1267
                ArrayList types = new ArrayList();
1268
                File[] files = dirExt.listFiles();
1269

    
1270
                for (int i = 0; i < files.length; i++) {
1271
                        if (files[i].isDirectory()) {
1272
                                File[] textFile = files[i].listFiles(new FilenameFilter() {
1273
                                                        public boolean accept(File dir, String fileName) {
1274
                                                                return fileName.toLowerCase().startsWith("text_"); //$NON-NLS-1$
1275
                                                        }
1276
                                                });
1277

    
1278
                                for (int j = 0; j < textFile.length; j++) {
1279
                                        String s = (textFile[j]).getName().replaceAll("text_", "");
1280
                                        s = s.replaceAll(".properties", "");
1281
                                        s = s.trim();
1282

    
1283
                                        if (!types.contains(s)) {
1284
                                                types.add(s);
1285
                                        }
1286
                                }
1287
                        }
1288
                }
1289

    
1290
                return (String[]) types.toArray(new String[0]);
1291
        }
1292

    
1293
        /**
1294
         * DOCUMENT ME!
1295
         *
1296
         * @return Returns the frame.
1297
         */
1298
        static MDIFrame getFrame() {
1299
                return frame;
1300
        }
1301

    
1302
        /**
1303
         * Secuencia de cerrado de Andami
1304
         */
1305
        public static void closeApplication() {
1306
                //Configuraci?n de Andami
1307
                try {
1308
                        andamiConfigToXML(andamiConfigPath);
1309
                } catch (MarshalException e) {
1310
                        logger.error(Messages.getString(
1311
                                        "Launcher.No_se_pudo_guardar_la_configuracion_de_andami"), e);
1312
                } catch (ValidationException e) {
1313
                        logger.error(Messages.getString(
1314
                                        "Launcher.No_se_pudo_guardar_la_configuracion_de_andami"), e);
1315
                } catch (IOException e) {
1316
                        logger.error(Messages.getString(
1317
                                        "Launcher.No_se_pudo_guardar_la_configuracion_de_andami"), e);
1318
                }
1319

    
1320
                //Persistencia de los plugins
1321
                savePluginPersistence();
1322

    
1323
                //Finalize all the extensions
1324
                finalizeExtensions();
1325

    
1326
                // Clean any temp data created
1327
                Utilities.cleanUpTempFiles();
1328

    
1329
                //Para la depuraci?n de memory leaks
1330
                System.gc();
1331

    
1332
        System.exit(0);
1333
        }
1334

    
1335
        /**
1336
         * Exectutes the finalize method for all the extensions
1337
         *
1338
         */
1339
        private static void finalizeExtensions() {
1340
                Set extensions = getClassesExtensions().keySet();
1341
                Object[] keys = extensions.toArray();
1342

    
1343
                for (int i=0 ; i<keys.length ; i++){
1344
                        ExtensionDecorator extensionDecorator =
1345
                                (ExtensionDecorator) getClassesExtensions().get(keys[i]);
1346
                        extensionDecorator.getExtension().finalize();
1347
                }
1348
        }
1349

    
1350

    
1351
        /**
1352
         * DOCUMENT ME!
1353
         *
1354
         * @return DOCUMENT ME!
1355
         */
1356
        static HashMap getClassesExtensions() {
1357
                return classesExtensions;
1358
        }
1359

    
1360
        /**
1361
         * DOCUMENT ME!
1362
         *
1363
         * @param extDir DOCUMENT ME!
1364
         */
1365
        private static void downloadExtensions(String extDir) {
1366
                java.util.Date fechaActual = null;
1367

    
1368
                try {
1369
                        if (System.getProperty("javawebstart.version") != null) {
1370
                                //Obtenemos la URL del servidor
1371
                                BasicService bs = (BasicService) ServiceManager.lookup(
1372
                                                "javax.jnlp.BasicService");
1373
                                URL baseURL = bs.getCodeBase();
1374

    
1375
                                //Se descargan las extensiones
1376
                                SplashWindow.process(5,
1377
                                        "Descargando las extensiones desde " + baseURL + " a " +
1378
                                        extDir);
1379

    
1380
                                URL url = new URL(baseURL + "extensiones.zip");
1381
                                URLConnection connection = url.openConnection();
1382

    
1383
                                System.out.println(url.toExternalForm() + ":");
1384
                                System.out.println("  Content Type: " +
1385
                                        connection.getContentType());
1386
                                System.out.println("  Content Length: " +
1387
                                        connection.getContentLength());
1388
                                System.out.println("  Last Modified: " +
1389
                                        new Date(connection.getLastModified()));
1390
                                System.out.println("  Expiration: " +
1391
                                        connection.getExpiration());
1392
                                System.out.println("  Content Encoding: " +
1393
                                        connection.getContentEncoding());
1394

    
1395
                                // Guardamos la fecha del fichero de extensiones que nos hemos bajado, y
1396
                                // comprobamos el ?ltimo que se ha bajado. Si no son
1397
                                // iguales, nos bajamos el nuevo. Si son iguales, no
1398
                                // nos bajamos nada.
1399
                                Long miliSecondsInWeb = new Long(connection.getLastModified());
1400

    
1401
                                // PluginServices ps = PluginServices.getPluginServices("com.iver.core");
1402
                                // if (ps.getPersistentXML().getStringProperty("timestamp") != null)
1403
                                File destDir = new File(extDir);
1404

    
1405
                                if (!destDir.exists()) {
1406
                                        // Creamos gvSIG
1407
                                        destDir.getParentFile().mkdir();
1408

    
1409
                                        if (!destDir.mkdir()) {
1410
                                                System.err.println("Imposible crear el directorio " +
1411
                                                        destDir.getAbsolutePath());
1412
                                        }
1413
                                }
1414

    
1415
                                File timeFile = new File(destDir.getParent() + File.separator +
1416
                                                "timeStamp.properties");
1417

    
1418
                                if (!timeFile.exists()) {
1419
                                        timeFile.createNewFile();
1420
                                }
1421

    
1422
                                FileInputStream inAux = new FileInputStream(timeFile);
1423
                                Properties prop = new Properties();
1424
                                prop.load(inAux);
1425
                                inAux.close();
1426

    
1427
                                if (prop.getProperty("timestamp") != null) {
1428
                                        Long lastMiliSeconds = (Long) new Long(prop.getProperty(
1429
                                                                "timestamp"));
1430

    
1431
                                        if (lastMiliSeconds.longValue() == miliSecondsInWeb.longValue()) {
1432
                                                System.out.println("No hay nueva actualizaci?n");
1433

    
1434
                                                return;
1435
                                        }
1436

    
1437
                                        System.out.println("timeStampWeb= " + miliSecondsInWeb);
1438
                                        System.out.println("timeStampLocal= " + lastMiliSeconds);
1439
                                } else {
1440
                                        System.out.println("El timeStamp no est? escrito en " +
1441
                                                timeFile.getAbsolutePath());
1442
                                }
1443

    
1444
                                InputStream stream = connection.getInputStream();
1445
                                File temp = File.createTempFile("gvsig", ".zip");
1446
                                temp.deleteOnExit();
1447

    
1448
                                FileOutputStream file = new FileOutputStream(temp);
1449
                                BufferedInputStream in = new BufferedInputStream(stream);
1450
                                BufferedOutputStream out = new BufferedOutputStream(file);
1451

    
1452
                                int i;
1453
                                int pct;
1454
                                int desde;
1455
                                int hasta;
1456

    
1457
                                hasta = connection.getContentLength() / 1024;
1458
                                desde = 0;
1459

    
1460
                                while ((i = in.read()) != -1) {
1461
                                        pct = ((desde / 1024) * 100) / hasta;
1462

    
1463
                                        if (((desde % 10240) == 0) && (pct > 10) &&
1464
                                                        ((pct % 10) == 0)) {
1465
                                                SplashWindow.process(pct,
1466
                                                        (desde / 1024) + "Kb de " + hasta +
1467
                                                        "Kb descargados...");
1468
                                        }
1469

    
1470
                                        out.write(i);
1471
                                        desde++;
1472
                                }
1473

    
1474
                                out.flush();
1475
                                out.close();
1476
                                in.close();
1477

    
1478
                                //Se extrae el zip
1479
                                SplashWindow.process(5, "Extensiones descargadas.");
1480

    
1481
                                System.out.println("Extrayendo a " + destDir.getAbsolutePath());
1482

    
1483
                                Date fechaDir = new Date(destDir.lastModified());
1484
                                System.out.println("Fecha del directorio " + extDir + " = " +
1485
                                        fechaDir.toString());
1486
                                Utilities.extractTo(temp, new File(extDir), splashWindow);
1487

    
1488
                                // Si todo ha ido bien, guardamos el timestamp.
1489
                                ///  App.instance.getPc().addProperties("timestamp", miliSecondsInWeb);
1490
                                // XMLEntity xml=ps.getPersistentXML();
1491
                                fechaActual = new java.util.Date();
1492

    
1493
                                FileOutputStream outAux = new FileOutputStream(timeFile);
1494
                                prop.setProperty("timestamp", miliSecondsInWeb.toString());
1495
                                prop.store(outAux, "last download");
1496
                                outAux.close();
1497
                                System.out.println("Fecha actual guardada: " +
1498
                                        fechaActual.toGMTString());
1499

    
1500
                                /* xml.putProperty("timestamp",fechaActual.toGMTString());
1501
                                   ps.setPresistentXML(xml); */
1502
                        }
1503
                } catch (IOException e) {
1504
                        NotificationManager.addError("", e);
1505
                } catch (UnavailableServiceException e) {
1506
                        NotificationManager.addError("", e);
1507
                } catch (SecurityException e) {
1508
                        System.err.println("No se puede escribir el timeStamp " +
1509
                                fechaActual.toGMTString());
1510
                        NotificationManager.addError("", e);
1511
                }
1512
        }
1513

    
1514
        /**
1515
         * DOCUMENT ME!
1516
         *
1517
         * @return DOCUMENT ME!
1518
         */
1519
        private static Extensions[] getExtensions() {
1520
                ArrayList array = new ArrayList();
1521
                Iterator iter = pluginsConfig.values().iterator();
1522

    
1523
                while (iter.hasNext()) {
1524
                        array.add(((PluginConfig) iter.next()).getExtensions());
1525
                }
1526

    
1527
                return (Extensions[]) array.toArray(new Extensions[0]);
1528
        }
1529

    
1530
        /**
1531
         * DOCUMENT ME!
1532
         *
1533
         * @return DOCUMENT ME!
1534
         */
1535
        public static HashMap getPluginConfig() {
1536
                return pluginsConfig;
1537
        }
1538

    
1539
        /**
1540
         * DOCUMENT ME!
1541
         *
1542
         * @param s DOCUMENT ME!
1543
         *
1544
         * @return DOCUMENT ME!
1545
         */
1546
        public static Extension getExtension(String s) {
1547
                Extensions[] exts = getExtensions();
1548

    
1549
                for (int i = 0; i < exts.length; i++) {
1550
                        for (int j = 0; j < exts[i].getExtensionCount(); j++) {
1551
                                if (exts[i].getExtension(j).getClassName().equals(s)) {
1552
                                        return exts[i].getExtension(j);
1553
                                }
1554
                        }
1555
                }
1556

    
1557
                return null;
1558
        }
1559

    
1560
        /**
1561
         * DOCUMENT ME!
1562
         *
1563
         * @return DOCUMENT ME!
1564
         */
1565
        public static AndamiConfig getAndamiConfig() {
1566
                return andamiConfig;
1567
        }
1568

    
1569
        /**
1570
         * DOCUMENT ME!
1571
         *
1572
         * @author $author$
1573
         * @version $Revision: 6101 $
1574
         */
1575
        private static class ExtensionComparator implements Comparator {
1576
                /**
1577
                 * DOCUMENT ME!
1578
                 *
1579
                 * @param o1 DOCUMENT ME!
1580
                 * @param o2 DOCUMENT ME!
1581
                 *
1582
                 * @return DOCUMENT ME!
1583
                 */
1584
                public int compare(Object o1, Object o2) {
1585
                        Extension e1 = (Extension) o1;
1586
                        Extension e2 = (Extension) o2;
1587

    
1588
                        if (!e1.hasPriority() && !e2.hasPriority()) {
1589
                                return -1;
1590
                        }
1591

    
1592
                        if (e1.hasPriority() && !e2.hasPriority()) {
1593
                                return -Integer.MAX_VALUE;
1594
                        }
1595

    
1596
                        if (e2.hasPriority() && !e1.hasPriority()) {
1597
                                return Integer.MAX_VALUE;
1598
                        }
1599

    
1600
                        if (e1.getPriority() != e2.getPriority()){
1601
                                return e2.getPriority() - e1.getPriority();
1602
                        }else{
1603
                                return (e2.toString().compareTo(e1.toString()));
1604
                        }
1605
                }
1606
        }
1607

    
1608
        /**
1609
         * DOCUMENT ME!
1610
         */
1611
        private static class MenuComparator implements Comparator {
1612
                private static ExtensionComparator extComp = new ExtensionComparator();
1613

    
1614
                /**
1615
                 * DOCUMENT ME!
1616
                 *
1617
                 * @param o1 DOCUMENT ME!
1618
                 * @param o2 DOCUMENT ME!
1619
                 *
1620
                 * @return DOCUMENT ME!
1621
                 */
1622
                public int compare(Object o1, Object o2) {
1623
                        SortableMenu e1 = (SortableMenu) o1;
1624
                        SortableMenu e2 = (SortableMenu) o2;
1625

    
1626
                        if (!e1.menu.hasPosition() && !e2.menu.hasPosition()) {
1627
                                if (e1.extension instanceof SkinExtensionType) {
1628
                                        return 1;
1629
                                } else if (e2.extension instanceof SkinExtensionType) {
1630
                                        return -1;
1631
                                } else {
1632
                                        return extComp.compare(e1.extension, e2.extension);
1633
                                }
1634
                        }
1635

    
1636
                        if (e1.menu.hasPosition() && !e2.menu.hasPosition()) {
1637
                                return -Integer.MAX_VALUE;
1638
                        }
1639

    
1640
                        if (e2.menu.hasPosition() && !e1.menu.hasPosition()) {
1641
                                return Integer.MAX_VALUE;
1642
                        }
1643

    
1644
                        return e1.menu.getPosition() - e2.menu.getPosition();
1645
                }
1646
        }
1647

    
1648
        /**
1649
         * DOCUMENT ME!
1650
         *
1651
         * @author $author$
1652
         * @version $Revision: 6101 $
1653
         */
1654
        private static class SortableMenu {
1655
                public PluginClassLoader loader;
1656
                public Menu menu;
1657
                public SkinExtensionType extension;
1658

    
1659
                /**
1660
                 * DOCUMENT ME!
1661
                 *
1662
                 * @param loader DOCUMENT ME!
1663
                 * @param skinExt
1664
                 * @param menu2
1665
                 */
1666
                public SortableMenu(PluginClassLoader loader,
1667
                        SkinExtensionType skinExt, Menu menu2) {
1668
                        extension = skinExt;
1669
                        menu = menu2;
1670
                        this.loader = loader;
1671
                }
1672
        }
1673
        /**
1674
         * DOCUMENT ME!
1675
         */
1676
        private static class SortableToolBar {
1677
                public PluginClassLoader loader;
1678
                public ToolBar toolbar;
1679
                public ActionTool actiontool;
1680
                public SelectableTool selectabletool;
1681
                public SkinExtensionType extension;
1682

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

    
1711
                /**
1712
                 * DOCUMENT ME!
1713
                 *
1714
                 * @param o1 DOCUMENT ME!
1715
                 * @param o2 DOCUMENT ME!
1716
                 *
1717
                 * @return DOCUMENT ME!
1718
                 */
1719
                public int compare(Object o1, Object o2) {
1720
                        SortableToolBar e1 = (SortableToolBar) o1;
1721
                        SortableToolBar e2 = (SortableToolBar) o2;
1722

    
1723
                        // if the toolbars have the same name, they are considered to be
1724
                        // the same toolbar, so we don't need to do further comparing
1725
                        if (e1.toolbar.getName().equals(e2.toolbar.getName()))
1726
                                return 0;
1727

    
1728
                        if (!e1.toolbar.hasPosition() && !e2.toolbar.hasPosition()) {
1729
                                if (e1.extension instanceof SkinExtensionType) {
1730
                                        return 1;
1731
                                } else if (e2.extension instanceof SkinExtensionType) {
1732
                                        return -1;
1733
                                } else {
1734
                                        return extComp.compare(e1.extension, e2.extension);
1735
                                }
1736
                        }
1737

    
1738
                        if (e1.toolbar.hasPosition() && !e2.toolbar.hasPosition()) {
1739
                                return -Integer.MAX_VALUE;
1740
                        }
1741

    
1742
                        if (e2.toolbar.hasPosition() && !e1.toolbar.hasPosition()) {
1743
                                return Integer.MAX_VALUE;
1744
                        }
1745
                        if (e1.toolbar.getPosition() != e2.toolbar.getPosition())
1746
                                return e1.toolbar.getPosition() - e2.toolbar.getPosition();
1747

    
1748
                        if (e1.toolbar.getActionTool().equals(e2.toolbar.getActionTool()) && e1.toolbar.getSelectableTool().equals(e2.toolbar.getSelectableTool())){
1749
                                return 0;
1750
                        }
1751
                        return (e1.toolbar.toString().compareTo(e2.toolbar.toString()));
1752
                }
1753
        }
1754

    
1755
        /**
1756
         * <p>This class is used to compare tools (selectabletool and actiontool),
1757
         * using the "position"
1758
         * attribute.</p>
1759
         * <p>The ordering criteria are:</p>
1760
         * <ul><li>If the tools are placed in different toolbars, they use the toolbars'
1761
         * order.
1762
         * (using the ToolBarComparator).</li>
1763
         * <li></li>
1764
         * <li>If any of the tools has not 'position' attribute, the tool which
1765
         * <strong>has</strong> the attribute will be placed first.</li>
1766
         * <li>If both tools have the same position (or they don't have a
1767
         * 'position' attribute), the priority of the extensions where the tool is defined.</li></ul>
1768
         *
1769
         * @author cesar
1770
         * @version $Revision: 6101 $
1771
         */
1772
        private static class ToolComparator implements Comparator {
1773
                private static ToolBarComparator toolBarComp = new ToolBarComparator();
1774
                /**
1775
                 * DOCUMENT ME!
1776
                 *
1777
                 * @param o1 DOCUMENT ME!
1778
                 * @param o2 DOCUMENT ME!
1779
                 *
1780
                 * @return DOCUMENT ME!
1781
                 */
1782
                public int compare(Object o1, Object o2) {
1783
                        // compare the toolbars which contain the tools
1784
                        int result = toolBarComp.compare(o1, o2);
1785
                        if (result != 0) { // if the toolbars are different, use their order
1786
                                return result;
1787
                        }
1788
                        // otherwise, compare the tools
1789
                        SortableToolBar e1 = (SortableToolBar) o1;
1790
                        SortableToolBar e2 = (SortableToolBar) o2;
1791
                        int e1Position=-1, e2Position=-1;
1792

    
1793
                        if (e1.actiontool!=null) {
1794
                                if (e1.actiontool.hasPosition())
1795
                                        e1Position = e1.actiontool.getPosition();
1796
                        }
1797
                        else if (e1.selectabletool!=null) {
1798
                                if (e1.selectabletool.hasPosition())
1799
                                        e1Position = e1.selectabletool.getPosition();
1800
                        }
1801

    
1802
                        if (e2.actiontool!=null) {
1803
                                if (e2.actiontool.hasPosition())
1804
                                        e2Position = e2.actiontool.getPosition();
1805
                        }
1806
                        else if (e2.selectabletool!=null){
1807
                                if (e2.selectabletool.hasPosition())
1808
                                        e2Position = e2.selectabletool.getPosition();
1809
                        }
1810

    
1811
                        if (e1Position==-1 && e2Position!=-1) {
1812
                                return 1;
1813
                        }
1814
                        if (e1Position!=-1 && e2Position==-1) {
1815
                                return -1;
1816
                        }
1817
                        if (e1Position!=-1 && e2Position!=-1) {
1818
                                result = e1Position - e2Position;
1819
                                // we don't return 0 unless both objects are the same, otherwise the objects get overwritten in the treemap
1820
                                if (result!=0) return result;
1821
                        }
1822
                        /*if (e1.toolbar.getActionTool().equals(e2.toolbar.getActionTool()) && e1.toolbar.getSelectableTool().equals(e2.toolbar.getSelectableTool())){
1823
                                return 0;
1824
                        }*/
1825
                        //logger.warn(Messages.getString("Different_tools_have_the_same_position_at_toolbar_")+e1.toolbar.getName());
1826
                        return e1.toString().compareTo(e2.toString());
1827
                }
1828
        }
1829

    
1830

    
1831
        /**
1832
         * validates the user before starting gvsig
1833
         *
1834
         */
1835
        private static void validate(){
1836

    
1837
                IAuthentication session =  null;
1838
                try {
1839

    
1840
                        //String location = getClassLocation(Class.forName("com.iver.andami.authentication.Session"));
1841
                        session = (IAuthentication)Class.forName("com.iver.andami.authentication.Session").newInstance();
1842

    
1843
                } catch (ClassNotFoundException e) {
1844
                        // TODO Auto-generated catch block
1845
                        //e.printStackTrace();
1846
                        return;
1847
                } catch (InstantiationException e) {
1848
                        // TODO Auto-generated catch block
1849
                        //e.printStackTrace();
1850
                        return;
1851
                } catch (IllegalAccessException e) {
1852
                        // TODO Auto-generated catch block
1853
                        //e.printStackTrace();
1854
                        return;
1855
                }
1856

    
1857
                session.setPluginDirectory( andamiConfig.getPluginsDirectory() );
1858
                if (session.validationRequired()){
1859

    
1860
                        //opens the login dialog for the user to validate
1861
                        //session.loging does not need arguments: they are read in the internal hashtable
1862
                        session.getUser();
1863
                        if(session.Login((String)session.get("user"),(String)session.get("pwd"))){
1864
                                System.out.println("You are logged in");
1865
                                //PluginServices.setSession( session );
1866
                        }
1867
                        else{
1868
                                JOptionPane.showMessageDialog((Component)PluginServices.getMainFrame(),
1869
                                                 "You are not logged in");
1870
                                System.exit(0);
1871
                        }
1872
                        PluginServices.setAuthentication(session);
1873
                }
1874
        }
1875

    
1876
        public static String getDefaultLookAndFeel() {
1877
                String osName = (String) System.getProperty("os.name");
1878

    
1879
            if (osName.substring(0,3).toLowerCase().equals("win"))
1880
                    return UIManager.getSystemLookAndFeelClassName();
1881
        else
1882
                return nonWinDefaultLookAndFeel;
1883
        }
1884
}