Statistics
| Revision:

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

History | View | Annotate | Download (49.4 KB)

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

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

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

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

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

    
120

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

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

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

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

    
169
                appName = args[0];
170

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

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

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

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

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

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

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

    
247
                // Mostrar la ventana de inicio
248
                splashWindow = new SplashWindow(null);
249

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

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

    
258
                // Se configura el classloader del plugin
259
                pluginsClassLoaders();
260

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

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

    
268
                // Se configura la mensajer?a del plugin
269
                pluginsMessages();
270

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

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

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

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

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

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

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

    
309
                // Se instalan los bookmarks de los plugins
310
                splashWindow.close();
311

    
312
                //Se muestra el frame principal
313
                frame.show();
314

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

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

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

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

    
417
                XMLEntity entity = new XMLEntity();
418

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

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

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

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

    
454
                        LabelSet[] ls = pc.getLabelSet();
455

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

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

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

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

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

    
489
                                SkinExtension se = pc.getExtensions().getSkinExtension();
490

    
491
                                MDIManagerFactory.setSkinExtension(se, ps.getClassLoader());
492

    
493
                                Class skinClass;
494

    
495
                                try {
496
                                        skinClass = ps.getClassLoader().loadClass(se.getClassName());
497

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

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

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

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

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

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

    
554
                        Extension[] exts = pc.getExtensions().getExtension();
555

    
556
                        TreeMap orderedExtensions = new TreeMap(new ExtensionComparator());
557

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

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

    
569
                                orderedExtensions.put(exts[j], null);
570
                        }
571

    
572
                        Iterator e = orderedExtensions.keySet().iterator();
573

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

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

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

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

    
625
                Iterator i = pluginsConfig.keySet().iterator();
626

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

    
632
                        Extension[] exts = pc.getExtensions().getExtension();
633

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

    
639
                                Menu[] menus = exts[j].getMenu();
640

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

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

    
651
                                        orderedMenus.put(sm, null);
652
                                }
653
                        }
654

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

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

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

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

    
671
                                        orderedMenus.put(sm, null);
672
                                }
673
                        }
674
                }
675

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

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

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

    
692
        /**
693
         *
694
         */
695
        private static void installPluginsControls() {
696
                Iterator i = pluginsConfig.keySet().iterator();
697

    
698
                HashMap extensionPluginServices = new HashMap();
699
                HashMap extensionPluginConfig = new HashMap();
700
                TreeMap orderedExtensions = new TreeMap(new ExtensionComparator());
701
                while (i.hasNext()) {
702
                                String pName = (String) i.next();
703
                                PluginConfig pc = (PluginConfig) pluginsConfig.get(pName);
704
                                PluginServices ps = (PluginServices) pluginsServices.get(pName);
705

    
706
                                Extension[] exts = pc.getExtensions().getExtension();
707

    
708
                                for (int j = 0; j < exts.length; j++) {
709
                                        if (exts[j].getActive()) {
710
                                                if (orderedExtensions.containsKey(exts[j])) {
711
                                                        logger.error(Messages.getString(
712
                                                                        "Launcher.Two_extensions_with_the_same_priority") +
713
                                                                exts[j].getClassName());
714
                                                }
715

    
716
                                                orderedExtensions.put(exts[j], null);
717
                                                extensionPluginServices.put(exts[j], ps);
718
                                                extensionPluginConfig.put(exts[j], pc);
719
                                        }
720
                                }
721
                }
722

    
723
                ///try {
724
                        TreeMap orderedToolBars = new TreeMap(new ToolBarComparator());
725
                        Iterator e = orderedExtensions.keySet().iterator();
726

    
727
                        // Se instalan las extensiones
728
                        while (e.hasNext()) {
729
                                Extension ext = (Extension) e.next();
730

    
731
                                ToolBar[] toolbars = ext.getToolBar();
732

    
733
                                for (int k = 0; k < toolbars.length; k++) {
734
                                        ActionTool[] tools = toolbars[k].getActionTool();
735

    
736
                                        for (int t = 0; t < tools.length; t++) {
737
                                                SortableToolBar sm = new SortableToolBar(((PluginServices)extensionPluginServices.get(ext)).getClassLoader(), ext,
738
                                                                toolbars[k], tools[t]);
739
                                                orderedToolBars.put(sm, null);
740
                                                ///frame.addTool(((PluginServices)extensionPluginServices.get(ext)).getClassLoader(), ext,
741
                                                ///        toolbars[k], tools[t]);
742
                                        }
743

    
744
                                        SelectableTool[] sTools = toolbars[k].getSelectableTool();
745

    
746
                                        for (int t = 0; t < sTools.length; t++) {
747
                                                SortableToolBar sm=new SortableToolBar(((PluginServices)extensionPluginServices.get(ext)).getClassLoader(), ext,
748
                                                                toolbars[k], sTools[t]);
749
                                                orderedToolBars.put(sm, null);
750
                                                ///frame.addTool(((PluginServices)extensionPluginServices.get(ext)).getClassLoader(), ext,
751
                                                ///        toolbars[k], sTools[t]);
752
                                        }
753
                                }
754
                        }
755

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

    
799
                                if (pus != null) {
800
                                        PopupMenu[] menus = pus.getPopupMenu();
801

    
802
                                        for (int j = 0; j < menus.length; j++) {
803
                                                frame.addPopupMenu(ps.getClassLoader(), menus[j]);
804
                                        }
805
                                }
806
                        }
807
//                        Se itera por los menus ordenados
808
                        Iterator t = orderedToolBars.keySet().iterator();
809

    
810
                        // Se ordenan los menues
811
                        while (t.hasNext()) {
812
                                try {
813
                                        SortableToolBar stb = (SortableToolBar) t.next();
814
                                        if (stb.actiontool!=null)
815
                                                frame.addTool(stb.loader, stb.extension,stb.toolbar, stb.actiontool);
816
                                        else
817
                                                frame.addTool(stb.loader, stb.extension,stb.toolbar, stb.selectabletool);
818
                                } catch (ClassNotFoundException ex) {
819
                                        logger.error(Messages.getString(
820
                                                        "Launcher.No_se_encontro_la_clase_de_la_extension"), ex);
821
                                }
822
                        }
823
                ///} catch (ClassNotFoundException e) {
824
                ///        logger.error(Messages.getString(
825
                ///                        "Launcher.No_se_encontro_la_clase_de_la_extension"), e);
826
                ///}
827
        }
828

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

    
835
                Plugin[] plugins = andamiConfig.getPlugin();
836

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

    
841
                Iterator i = pluginsServices.values().iterator();
842

    
843
                while (i.hasNext()) {
844
                        PluginServices ps = (PluginServices) i.next();
845

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

    
851
                                andamiConfig.addPlugin(p);
852
                        }
853
                }
854
        }
855

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

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

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

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

    
873
                                if (instalados.contains(pluginName)) {
874
                                        continue;
875
                                }
876

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

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

    
889
                                                continue;
890
                                        }
891

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

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

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

    
916
                                URL[] urls = new URL[jarFiles.length];
917

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

    
928
                                PluginClassLoader loader;
929

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

    
936
                                        PluginServices ps = new PluginServices(loader);
937

    
938
                                        pluginsServices.put(ps.getPluginName(), ps);
939

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

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

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

    
958
                                break;
959
                        }
960
                }
961

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

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

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

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

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

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

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

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

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

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

    
1054
                if (!pDir.exists()) {
1055
                        return;
1056
                }
1057

    
1058
                File[] pluginDirs = pDir.listFiles();
1059

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

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

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

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

    
1126
                FileWriter writer = new FileWriter(xml);
1127
                andamiConfig.marshal(writer);
1128
        }
1129

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

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

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

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

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

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

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

    
1190
                if (xml.exists()) {
1191
                        FileReader reader;
1192

    
1193
                        try {
1194
                                reader = new FileReader(xml);
1195

    
1196
                                XmlTag tag = (XmlTag) XmlTag.unmarshal(reader);
1197

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

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

    
1222
                FileWriter writer;
1223

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

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

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

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

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

    
1270
                return (String[]) types.toArray(new String[0]);
1271
        }
1272

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

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

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

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

    
1330

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

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

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

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

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

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

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

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

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

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

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

    
1398
                                if (!timeFile.exists()) {
1399
                                        timeFile.createNewFile();
1400
                                }
1401

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

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

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

    
1414
                                                return;
1415
                                        }
1416

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

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

    
1428
                                FileOutputStream file = new FileOutputStream(temp);
1429
                                BufferedInputStream in = new BufferedInputStream(stream);
1430
                                BufferedOutputStream out = new BufferedOutputStream(file);
1431

    
1432
                                int i;
1433
                                int pct;
1434
                                int desde;
1435
                                int hasta;
1436

    
1437
                                hasta = connection.getContentLength() / 1024;
1438
                                desde = 0;
1439

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

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

    
1450
                                        out.write(i);
1451
                                        desde++;
1452
                                }
1453

    
1454
                                out.flush();
1455
                                out.close();
1456
                                in.close();
1457

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

    
1461
                                System.out.println("Extrayendo a " + destDir.getAbsolutePath());
1462

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

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

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

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

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

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

    
1507
                return (Extensions[]) array.toArray(new Extensions[0]);
1508
        }
1509

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

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

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

    
1537
                return null;
1538
        }
1539

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

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

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

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

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

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

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

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

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

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

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

    
1624
                        return e1.menu.getPosition() - e2.menu.getPosition();
1625
                }
1626
        }
1627

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

    
1639
                /**
1640
                 * DOCUMENT ME!
1641
                 *
1642
                 * @param loader DOCUMENT ME!
1643
                 * @param skinExt
1644
                 * @param menu2
1645
                 */
1646
                public SortableMenu(PluginClassLoader loader,
1647
                        SkinExtensionType skinExt, Menu menu2) {
1648
                        extension = skinExt;
1649
                        menu = menu2;
1650
                        this.loader = loader;
1651
                }
1652
        }
1653
        /**
1654
         * DOCUMENT ME!
1655
         */
1656
        private static class ToolBarComparator implements Comparator {
1657
                private static ExtensionComparator extComp = new ExtensionComparator();
1658

    
1659
                /**
1660
                 * DOCUMENT ME!
1661
                 *
1662
                 * @param o1 DOCUMENT ME!
1663
                 * @param o2 DOCUMENT ME!
1664
                 *
1665
                 * @return DOCUMENT ME!
1666
                 */
1667
                public int compare(Object o1, Object o2) {
1668
                        SortableToolBar e1 = (SortableToolBar) o1;
1669
                        SortableToolBar e2 = (SortableToolBar) o2;
1670

    
1671
                        if (!e1.toolbar.hasPosition() && !e2.toolbar.hasPosition()) {
1672
                                if (e1.extension instanceof SkinExtensionType) {
1673
                                        return 1;
1674
                                } else if (e2.extension instanceof SkinExtensionType) {
1675
                                        return -1;
1676
                                } else {
1677
                                        return extComp.compare(e1.extension, e2.extension);
1678
                                }
1679
                        }
1680

    
1681
                        if (e1.toolbar.hasPosition() && !e2.toolbar.hasPosition()) {
1682
                                return -Integer.MAX_VALUE;
1683
                        }
1684

    
1685
                        if (e2.toolbar.hasPosition() && !e1.toolbar.hasPosition()) {
1686
                                return Integer.MAX_VALUE;
1687
                        }
1688
                        if (e1.toolbar.getPosition() != e2.toolbar.getPosition())
1689
                        return e1.toolbar.getPosition() - e2.toolbar.getPosition();
1690
                        
1691
                        if (e1.toolbar.getActionTool().equals(e2.toolbar.getActionTool()) && e1.toolbar.getSelectableTool().equals(e2.toolbar.getSelectableTool())){
1692
                                return 0;
1693
                        }
1694
                        return 1; 
1695
                }
1696
        }
1697
        /**
1698
         * DOCUMENT ME!
1699
         *
1700
         * @author $author$
1701
         * @version $Revision: 5361 $
1702
         */
1703
        private static class SortableToolBar {
1704
                public PluginClassLoader loader;
1705
                public ToolBar toolbar;
1706
                public ActionTool actiontool;
1707
                public SelectableTool selectabletool;
1708
                public SkinExtensionType extension;
1709

    
1710
                /**
1711
                 * DOCUMENT ME!
1712
                 *
1713
                 * @param loader DOCUMENT ME!
1714
                 * @param skinExt
1715
                 * @param menu2
1716
                 */
1717
                public SortableToolBar(PluginClassLoader loader,
1718
                        SkinExtensionType skinExt, ToolBar toolbar2,ActionTool actiontool2) {
1719
                        extension = skinExt;
1720
                        toolbar = toolbar2;
1721
                        actiontool=actiontool2;
1722
                        this.loader = loader;
1723
                }
1724
                        public SortableToolBar(PluginClassLoader loader,
1725
                                SkinExtensionType skinExt, ToolBar toolbar2,SelectableTool selectabletool2) {
1726
                                extension = skinExt;
1727
                                toolbar = toolbar2;
1728
                                selectabletool=selectabletool2;
1729
                                this.loader = loader;
1730
                        }
1731
        }
1732
        
1733
        
1734
        /**
1735
         * validates the user before starting gvsig
1736
         *
1737
         */
1738
        private static void validate(){
1739
                
1740
                IAuthentication session =  null;
1741
                try {
1742
                        
1743
                        //String location = getClassLocation(Class.forName("com.iver.andami.authentication.Session"));
1744
                        session = (IAuthentication)Class.forName("com.iver.andami.authentication.Session").newInstance();
1745

    
1746
                } catch (ClassNotFoundException e) {
1747
                        // TODO Auto-generated catch block
1748
                        //e.printStackTrace();
1749
                        return;
1750
                } catch (InstantiationException e) {
1751
                        // TODO Auto-generated catch block
1752
                        //e.printStackTrace();
1753
                        return;
1754
                } catch (IllegalAccessException e) {
1755
                        // TODO Auto-generated catch block
1756
                        //e.printStackTrace();
1757
                        return;
1758
                }
1759
                
1760
                session.setPluginDirectory( andamiConfig.getPluginsDirectory() );
1761
                if (session.validationRequired()){
1762
                        
1763
                        //opens the login dialog for the user to validate
1764
                        //session.loging does not need arguments: they are read in the internal hashtable
1765
                        session.getUser();
1766
                        if(session.Login((String)session.get("user"),(String)session.get("pwd"))){
1767
                                System.out.println("You are logged in");
1768
                                //PluginServices.setSession( session );        
1769
                        }
1770
                        else{
1771
                                JOptionPane.showMessageDialog((Component)PluginServices.getMainFrame(),
1772
                                                 "You are not logged in");                                
1773
                                System.exit(0);
1774
                        }
1775
                        PluginServices.setAuthentication(session);
1776
                }                
1777
        }
1778
}