Statistics
| Revision:

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

History | View | Annotate | Download (48.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.JarURLConnection;
62
import java.net.MalformedURLException;
63
import java.net.URL;
64
import java.net.URLClassLoader;
65
import java.net.URLConnection;
66
import java.security.SecureClassLoader;
67
import java.util.ArrayList;
68
import java.util.Comparator;
69
import java.util.Date;
70
import java.util.HashMap;
71
import java.util.HashSet;
72
import java.util.Iterator;
73
import java.util.Locale;
74
import java.util.Properties;
75
import java.util.TreeMap;
76
import java.util.Vector;
77

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

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

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

    
124

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

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

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

    
170
            //  Clean temporal files
171
                Utilities.cleanUpTempFiles();
172

    
173
                appName = args[0];
174

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

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

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

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

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

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

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

    
251
                // Mostrar la ventana de inicio
252
                splashWindow = new SplashWindow(null);
253

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

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

    
262
                // Se configura el classloader del plugin
263
                pluginsClassLoaders();
264

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

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

    
272
                // Se configura la mensajer?a del plugin
273
                pluginsMessages();
274

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

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

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

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

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

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

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

    
313
                // Se instalan los bookmarks de los plugins
314
                splashWindow.close();
315

    
316
                //Se muestra el frame principal
317
                frame.show();
318

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

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

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

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

    
421
                XMLEntity entity = new XMLEntity();
422

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

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

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

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

    
458
                        LabelSet[] ls = pc.getLabelSet();
459

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

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

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

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

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

    
493
                                SkinExtension se = pc.getExtensions().getSkinExtension();
494

    
495
                                MDIManagerFactory.setSkinExtension(se, ps.getClassLoader());
496

    
497
                                Class skinClass;
498

    
499
                                try {
500
                                        skinClass = ps.getClassLoader().loadClass(se.getClassName());
501

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

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

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

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

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

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

    
558
                        Extension[] exts = pc.getExtensions().getExtension();
559

    
560
                        TreeMap orderedExtensions = new TreeMap(new ExtensionComparator());
561

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

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

    
573
                                orderedExtensions.put(exts[j], null);
574
                        }
575

    
576
                        Iterator e = orderedExtensions.keySet().iterator();
577

    
578
                        while (e.hasNext()) {
579
                                Extension extension = (Extension) e.next();
580
                                com.iver.andami.plugins.Extension extensionInstance;
581

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

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

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

    
629
                Iterator i = pluginsConfig.keySet().iterator();
630

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

    
636
                        Extension[] exts = pc.getExtensions().getExtension();
637

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

    
643
                                Menu[] menus = exts[j].getMenu();
644

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

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

    
655
                                        orderedMenus.put(sm, null);
656
                                }
657
                        }
658

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

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

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

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

    
675
                                        orderedMenus.put(sm, null);
676
                                }
677
                        }
678
                }
679

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

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

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

    
696
        /**
697
         *
698
         */
699
        private static void installPluginsControls() {
700
                Iterator i = pluginsConfig.keySet().iterator();
701

    
702
                HashMap extensionPluginServices = new HashMap();
703
                HashMap extensionPluginConfig = new HashMap();
704
                TreeMap orderedExtensions = new TreeMap(new ExtensionComparator());
705
                while (i.hasNext()) {
706
                                String pName = (String) i.next();
707
                                PluginConfig pc = (PluginConfig) pluginsConfig.get(pName);
708
                                PluginServices ps = (PluginServices) pluginsServices.get(pName);
709

    
710
                                Extension[] exts = pc.getExtensions().getExtension();
711

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

    
720
                                                orderedExtensions.put(exts[j], null);
721
                                                extensionPluginServices.put(exts[j], ps);
722
                                                extensionPluginConfig.put(exts[j], pc);
723
                                        }
724
                                }
725
                }
726

    
727
                ///try {
728
                        TreeMap orderedToolBars = new TreeMap(new ToolBarComparator());
729
                        Iterator e = orderedExtensions.keySet().iterator();
730

    
731
                        // Se instalan las extensiones
732
                        while (e.hasNext()) {
733
                                Extension ext = (Extension) e.next();
734

    
735
                                ToolBar[] toolbars = ext.getToolBar();
736

    
737
                                for (int k = 0; k < toolbars.length; k++) {
738
                                        ActionTool[] tools = toolbars[k].getActionTool();
739

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

    
748
                                        SelectableTool[] sTools = toolbars[k].getSelectableTool();
749

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

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

    
803
                                if (pus != null) {
804
                                        PopupMenu[] menus = pus.getPopupMenu();
805

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

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

    
833
        /**
834
         *
835
         */
836
        private static void updateAndamiConfig() {
837
                HashSet olds = new HashSet();
838

    
839
                Plugin[] plugins = andamiConfig.getPlugin();
840

    
841
                for (int i = 0; i < plugins.length; i++) {
842
                        olds.add(plugins[i].getName());
843
                }
844

    
845
                Iterator i = pluginsServices.values().iterator();
846

    
847
                while (i.hasNext()) {
848
                        PluginServices ps = (PluginServices) i.next();
849

    
850
                        if (!olds.contains(ps.getPluginName())) {
851
                                Plugin p = new Plugin();
852
                                p.setName(ps.getPluginName());
853
                                p.setUpdate(false);
854

    
855
                                andamiConfig.addPlugin(p);
856
                        }
857
                }
858
        }
859

    
860
        /**
861
         * DOCUMENT ME!
862
         */
863
        private static void pluginsClassLoaders() {
864
                HashSet instalados = new HashSet();
865

    
866
                // Se itera hasta que est?n todos instalados
867
                while (instalados.size() != pluginsConfig.size()) {
868
                        boolean circle = true;
869

    
870
                        //Hacemos una pasada por todos los plugins
871
                        Iterator i = pluginsConfig.keySet().iterator();
872

    
873
                        while (i.hasNext()) {
874
                                String pluginName = (String) i.next();
875
                                PluginConfig config = (PluginConfig) pluginsConfig.get(pluginName);
876

    
877
                                if (instalados.contains(pluginName)) {
878
                                        continue;
879
                                }
880

    
881
                                //Se obtienen las dependencias y sus class loaders
882
                                boolean ready = true;
883
                                Depends[] dependencies = config.getDepends();
884
                                PluginClassLoader[] loaders = new PluginClassLoader[dependencies.length];
885

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

    
893
                                                continue;
894
                                        }
895

    
896
                                        if (!instalados.contains(dependencies[j].getPluginName())) {
897
                                                ready = false;
898
                                        } else {
899
                                                loaders[j] = ((PluginServices) pluginsServices.get(dependencies[j].getPluginName())).getClassLoader();
900
                                        }
901
                                }
902

    
903
                                //Si no est?n sus dependencias satisfechas se aborta la instalaci?n
904
                                if (!ready) {
905
                                        continue;
906
                                }
907

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

    
920
                                URL[] urls = new URL[jarFiles.length];
921

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

    
932
                                PluginClassLoader loader;
933

    
934
                                try {
935
                                        loader = new PluginClassLoader(urls,
936
                                                        andamiConfig.getPluginsDirectory() +
937
                                                        File.separator + pluginName,
938
                                                        Launcher.class.getClassLoader(), loaders);
939

    
940
                                        PluginServices ps = new PluginServices(loader);
941

    
942
                                        pluginsServices.put(ps.getPluginName(), ps);
943

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

    
949
                                        circle = false;
950
                                } catch (IOException e) {
951
                                        logger.error(Messages.getString(
952
                                                        "Launcher.Error_con_las_librerias_del_plugin"), e);
953
                                        pluginsConfig.remove(pluginName);
954
                                        i = pluginsConfig.keySet().iterator();
955
                                }
956
                        }
957

    
958
                        if (circle) {
959
                                logger.error(Messages.getString(
960
                                                "Launcher.Hay_dependencias_circulares"));
961

    
962
                                break;
963
                        }
964
                }
965

    
966
                //Se eliminan los plugins que no fueron instalados
967
                Iterator i = pluginsConfig.keySet().iterator();
968

    
969
                while (i.hasNext()) {
970
                        String pluginName = (String) i.next();
971
                        PluginConfig config = (PluginConfig) pluginsConfig.get(pluginName);
972
                        PluginServices ps = (PluginServices) pluginsServices.get(pluginName);
973

    
974
                        if (ps == null) {
975
                                pluginsConfig.remove(pluginName);
976
                                i = pluginsConfig.keySet().iterator();
977
                        }
978
                } 
979
        }
980

    
981
        /**
982
         * DOCUMENT ME!
983
         */
984
        private static void pluginsMessages() {
985
                //Iteramos por todos los plugins
986
                Iterator i = pluginsConfig.keySet().iterator();
987

    
988
                while (i.hasNext()) {
989
                        String pluginName = (String) i.next();
990
                        PluginConfig config = (PluginConfig) pluginsConfig.get(pluginName);
991
                        PluginServices ps = (PluginServices) pluginsServices.get(pluginName);
992

    
993
                        if (config.getResourceBundle() != null) {
994
                                // add the locale files associated with the plugin
995
                                org.gvsig.i18n.Messages.addResourceFamily(config.getResourceBundle().getName(), ps.getClassLoader(), pluginName);
996
                        }
997
                }
998
        }
999

    
1000
        /**
1001
         * DOCUMENT ME!
1002
         *
1003
         * @param name DOCUMENT ME!
1004
         *
1005
         * @return DOCUMENT ME!
1006
         */
1007
        static PluginServices getPluginServices(String name) {
1008
                return (PluginServices) pluginsServices.get(name);
1009
        }
1010

    
1011
        /**
1012
         * DOCUMENT ME!
1013
         *
1014
         * @return DOCUMENT ME!
1015
         */
1016
        static String getPluginsDir() {
1017
                return andamiConfig.getPluginsDirectory();
1018
        }
1019

    
1020
        /**
1021
         * DOCUMENT ME!
1022
         *
1023
         * @param s DOCUMENT ME!
1024
         */
1025
        static void setPluginsDir(String s) {
1026
                andamiConfig.setPluginsDirectory(s);
1027
        }
1028

    
1029
        /**
1030
         * DOCUMENT ME!
1031
         *
1032
         * @return DOCUMENT ME!
1033
         */
1034
        static MDIFrame getMDIFrame() {
1035
                return frame;
1036
        }
1037

    
1038
        /**
1039
         * DOCUMENT ME!
1040
         *
1041
         * @param pluginsDirectory
1042
         */
1043
        private static void loadPlugins(String pluginsDirectory) {
1044
                File pDir = new File(pluginsDirectory);
1045

    
1046
                if (!pDir.exists()) {
1047
                        return;
1048
                }
1049

    
1050
                File[] pluginDirs = pDir.listFiles();
1051

    
1052
                for (int i = 0; i < pluginDirs.length; i++) {
1053
                        if (pluginDirs[i].isDirectory()) {
1054
                                File configXml = new File(pluginDirs[i].getAbsolutePath() +
1055
                                                File.separator + "config.xml");
1056

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

    
1081
        /**
1082
         * DOCUMENT ME!
1083
         *
1084
         * @param language
1085
         * @param country
1086
         * @param variant
1087
         *
1088
         * @return DOCUMENT ME!
1089
         */
1090
        private static Locale getLocale(String language, String country,
1091
                String variant) {
1092
                if (variant != null) {
1093
                        return new Locale(language, country, variant);
1094
                } else if (country != null) {
1095
                        return new Locale(language, country);
1096
                } else if (language != null) {
1097
                        return new Locale(language);
1098
                } else {
1099
                        return new Locale("es");
1100
                }
1101
        }
1102

    
1103
        /**
1104
         * DOCUMENT ME!
1105
         *
1106
         * @param file DOCUMENT ME!
1107
         *
1108
         * @throws IOException DOCUMENT ME!
1109
         * @throws MarshalException DOCUMENT ME!
1110
         * @throws ValidationException DOCUMENT ME!
1111
         */
1112
        private static void andamiConfigToXML(String file)
1113
                throws IOException, MarshalException, ValidationException {
1114
                File xml = new File(file);
1115
                File parent = xml.getParentFile();
1116
                parent.mkdirs();
1117

    
1118
                FileWriter writer = new FileWriter(xml);
1119
                andamiConfig.marshal(writer);
1120
        }
1121

    
1122
        /**
1123
         * DOCUMENT ME!
1124
         *
1125
         * @param file DOCUMENT ME!
1126
         *
1127
         * @throws ConfigurationException DOCUMENT ME!
1128
         */
1129
        private static void andamiConfigFromXML(String file)
1130
                throws ConfigurationException {
1131
                File xml = new File(file);
1132

    
1133
                //Si no existe se ponen los valores por defecto
1134
                if (!xml.exists()) {
1135
                        andamiConfig = new AndamiConfig();
1136

    
1137
                        Andami andami = new Andami();
1138
                        andami.setUpdate(true);
1139
                        andamiConfig.setAndami(andami);
1140
                        andamiConfig.setLocaleCountry(Locale.getDefault().getCountry());
1141
                        andamiConfig.setLocaleLanguage(Locale.getDefault().getLanguage());
1142
                        andamiConfig.setLocaleVariant(Locale.getDefault().getVariant());
1143

    
1144
                        if (System.getProperty("javawebstart.version") != null) // Es java web start)
1145
                         {
1146
                                andamiConfig.setPluginsDirectory(new File(System.getProperty(
1147
                                                        "user.home") + File.separator + appName +
1148
                                                File.separator + "extensiones").getAbsolutePath());
1149
                        } else {
1150
                                andamiConfig.setPluginsDirectory(new File(appName +
1151
                                                File.separator + "extensiones").getAbsolutePath());
1152
                        }
1153

    
1154
                        andamiConfig.setPlugin(new Plugin[0]);
1155
                } else {
1156
                        //Se lee la configuraci?n
1157
                        FileReader reader;
1158

    
1159
                        try {
1160
                                reader = new FileReader(xml);
1161
                                andamiConfig = (AndamiConfig) AndamiConfig.unmarshal(reader);
1162
                        } catch (FileNotFoundException e) {
1163
                                throw new ConfigurationException(e);
1164
                        } catch (MarshalException e) {
1165
                                throw new ConfigurationException(e);
1166
                        } catch (ValidationException e) {
1167
                                throw new ConfigurationException(e);
1168
                        }
1169
                }
1170
        }
1171

    
1172
        /**
1173
         * DOCUMENT ME!
1174
         *
1175
         * @return DOCUMENT ME!
1176
         *
1177
         * @throws ConfigurationException DOCUMENT ME!
1178
         */
1179
        private static XMLEntity persistenceFromXML() throws ConfigurationException {
1180
                File xml = new File(pluginsPersistencePath);
1181

    
1182
                if (xml.exists()) {
1183
                        FileReader reader;
1184

    
1185
                        try {
1186
                                reader = new FileReader(xml);
1187

    
1188
                                XmlTag tag = (XmlTag) XmlTag.unmarshal(reader);
1189

    
1190
                                return new XMLEntity(tag);
1191
                        } catch (FileNotFoundException e) {
1192
                                throw new ConfigurationException(e);
1193
                        } catch (MarshalException e) {
1194
                                throw new ConfigurationException(e);
1195
                        } catch (ValidationException e) {
1196
                                throw new ConfigurationException(e);
1197
                        }
1198
                } else {
1199
                        return new XMLEntity();
1200
                }
1201
        }
1202

    
1203
        /**
1204
         * DOCUMENT ME!
1205
         *
1206
         * @param entity DOCUMENT ME!
1207
         *
1208
         * @throws ConfigurationException DOCUMENT ME!
1209
         */
1210
        private static void persistenceToXML(XMLEntity entity)
1211
                throws ConfigurationException {
1212
                File xml = new File(pluginsPersistencePath);
1213

    
1214
                FileWriter writer;
1215

    
1216
                try {
1217
                        writer = new FileWriter(xml);
1218
                        entity.getXmlTag().marshal(writer);
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
                } catch (IOException e) {
1226
                        throw new ConfigurationException(e);
1227
                }
1228
        }
1229

    
1230
        /**
1231
         * Devuelve un array con los directorios de los plugins
1232
         *
1233
         * @param dirExt Directorio de las extensiones a partir del cual cuelgan
1234
         *                   todos los directorios de los plugins
1235
         *
1236
         * @return ArrayList con los directorios
1237
         */
1238
        private String[] getLocales(File dirExt) {
1239
                ArrayList types = new ArrayList();
1240
                File[] files = dirExt.listFiles();
1241

    
1242
                for (int i = 0; i < files.length; i++) {
1243
                        if (files[i].isDirectory()) {
1244
                                File[] textFile = files[i].listFiles(new FilenameFilter() {
1245
                                                        public boolean accept(File dir, String fileName) {
1246
                                                                return fileName.toLowerCase().startsWith("text_"); //$NON-NLS-1$
1247
                                                        }
1248
                                                });
1249

    
1250
                                for (int j = 0; j < textFile.length; j++) {
1251
                                        String s = (textFile[j]).getName().replaceAll("text_", "");
1252
                                        s = s.replaceAll(".properties", "");
1253
                                        s = s.trim();
1254

    
1255
                                        if (!types.contains(s)) {
1256
                                                types.add(s);
1257
                                        }
1258
                                }
1259
                        }
1260
                }
1261

    
1262
                return (String[]) types.toArray(new String[0]);
1263
        }
1264

    
1265
        /**
1266
         * DOCUMENT ME!
1267
         *
1268
         * @return Returns the frame.
1269
         */
1270
        static MDIFrame getFrame() {
1271
                return frame;
1272
        }
1273

    
1274
        /**
1275
         * Secuencia de cerrado de Andami
1276
         */
1277
        public static void closeApplication() {
1278
                //Configuraci?n de Andami
1279
                try {
1280
                        andamiConfigToXML(andamiConfigPath);
1281
                } catch (MarshalException e) {
1282
                        logger.error(Messages.getString(
1283
                                        "Launcher.No_se_pudo_guardar_la_configuracion_de_andami"), e);
1284
                } catch (ValidationException e) {
1285
                        logger.error(Messages.getString(
1286
                                        "Launcher.No_se_pudo_guardar_la_configuracion_de_andami"), e);
1287
                } catch (IOException e) {
1288
                        logger.error(Messages.getString(
1289
                                        "Launcher.No_se_pudo_guardar_la_configuracion_de_andami"), e);
1290
                }
1291

    
1292
                //Persistencia de los plugins
1293
                savePluginPersistence();
1294
                
1295
                // Clean any temp data created
1296
                Utilities.cleanUpTempFiles();
1297
                
1298
                //Para la depuraci?n de memory leaks
1299
                System.gc();
1300

    
1301
        System.exit(0);
1302
        }
1303

    
1304
        /**
1305
         * DOCUMENT ME!
1306
         *
1307
         * @return DOCUMENT ME!
1308
         */
1309
        static HashMap getClassesExtensions() {
1310
                return classesExtensions;
1311
        }
1312

    
1313
        /**
1314
         * DOCUMENT ME!
1315
         *
1316
         * @param extDir DOCUMENT ME!
1317
         */
1318
        private static void downloadExtensions(String extDir) {
1319
                java.util.Date fechaActual = null;
1320

    
1321
                try {
1322
                        if (System.getProperty("javawebstart.version") != null) {
1323
                                //Obtenemos la URL del servidor
1324
                                BasicService bs = (BasicService) ServiceManager.lookup(
1325
                                                "javax.jnlp.BasicService");
1326
                                URL baseURL = bs.getCodeBase();
1327

    
1328
                                //Se descargan las extensiones
1329
                                SplashWindow.process(5,
1330
                                        "Descargando las extensiones desde " + baseURL + " a " +
1331
                                        extDir);
1332

    
1333
                                URL url = new URL(baseURL + "extensiones.zip");
1334
                                URLConnection connection = url.openConnection();
1335

    
1336
                                System.out.println(url.toExternalForm() + ":");
1337
                                System.out.println("  Content Type: " +
1338
                                        connection.getContentType());
1339
                                System.out.println("  Content Length: " +
1340
                                        connection.getContentLength());
1341
                                System.out.println("  Last Modified: " +
1342
                                        new Date(connection.getLastModified()));
1343
                                System.out.println("  Expiration: " +
1344
                                        connection.getExpiration());
1345
                                System.out.println("  Content Encoding: " +
1346
                                        connection.getContentEncoding());
1347

    
1348
                                // Guardamos la fecha del fichero de extensiones que nos hemos bajado, y
1349
                                // comprobamos el ?ltimo que se ha bajado. Si no son
1350
                                // iguales, nos bajamos el nuevo. Si son iguales, no
1351
                                // nos bajamos nada.
1352
                                Long miliSecondsInWeb = new Long(connection.getLastModified());
1353

    
1354
                                // PluginServices ps = PluginServices.getPluginServices("com.iver.core");
1355
                                // if (ps.getPersistentXML().getStringProperty("timestamp") != null)
1356
                                File destDir = new File(extDir);
1357

    
1358
                                if (!destDir.exists()) {
1359
                                        // Creamos gvSIG
1360
                                        destDir.getParentFile().mkdir();
1361

    
1362
                                        if (!destDir.mkdir()) {
1363
                                                System.err.println("Imposible crear el directorio " +
1364
                                                        destDir.getAbsolutePath());
1365
                                        }
1366
                                }
1367

    
1368
                                File timeFile = new File(destDir.getParent() + File.separator +
1369
                                                "timeStamp.properties");
1370

    
1371
                                if (!timeFile.exists()) {
1372
                                        timeFile.createNewFile();
1373
                                }
1374

    
1375
                                FileInputStream inAux = new FileInputStream(timeFile);
1376
                                Properties prop = new Properties();
1377
                                prop.load(inAux);
1378
                                inAux.close();
1379

    
1380
                                if (prop.getProperty("timestamp") != null) {
1381
                                        Long lastMiliSeconds = (Long) new Long(prop.getProperty(
1382
                                                                "timestamp"));
1383

    
1384
                                        if (lastMiliSeconds.longValue() == miliSecondsInWeb.longValue()) {
1385
                                                System.out.println("No hay nueva actualizaci?n");
1386

    
1387
                                                return;
1388
                                        }
1389

    
1390
                                        System.out.println("timeStampWeb= " + miliSecondsInWeb);
1391
                                        System.out.println("timeStampLocal= " + lastMiliSeconds);
1392
                                } else {
1393
                                        System.out.println("El timeStamp no est? escrito en " +
1394
                                                timeFile.getAbsolutePath());
1395
                                }
1396

    
1397
                                InputStream stream = connection.getInputStream();
1398
                                File temp = File.createTempFile("gvsig", ".zip");
1399
                                temp.deleteOnExit();
1400

    
1401
                                FileOutputStream file = new FileOutputStream(temp);
1402
                                BufferedInputStream in = new BufferedInputStream(stream);
1403
                                BufferedOutputStream out = new BufferedOutputStream(file);
1404

    
1405
                                int i;
1406
                                int pct;
1407
                                int desde;
1408
                                int hasta;
1409

    
1410
                                hasta = connection.getContentLength() / 1024;
1411
                                desde = 0;
1412

    
1413
                                while ((i = in.read()) != -1) {
1414
                                        pct = ((desde / 1024) * 100) / hasta;
1415

    
1416
                                        if (((desde % 10240) == 0) && (pct > 10) &&
1417
                                                        ((pct % 10) == 0)) {
1418
                                                SplashWindow.process(pct,
1419
                                                        (desde / 1024) + "Kb de " + hasta +
1420
                                                        "Kb descargados...");
1421
                                        }
1422

    
1423
                                        out.write(i);
1424
                                        desde++;
1425
                                }
1426

    
1427
                                out.flush();
1428
                                out.close();
1429
                                in.close();
1430

    
1431
                                //Se extrae el zip
1432
                                SplashWindow.process(5, "Extensiones descargadas.");
1433

    
1434
                                System.out.println("Extrayendo a " + destDir.getAbsolutePath());
1435

    
1436
                                Date fechaDir = new Date(destDir.lastModified());
1437
                                System.out.println("Fecha del directorio " + extDir + " = " +
1438
                                        fechaDir.toString());
1439
                                Utilities.extractTo(temp, new File(extDir), splashWindow);
1440

    
1441
                                // Si todo ha ido bien, guardamos el timestamp.
1442
                                ///  App.instance.getPc().addProperties("timestamp", miliSecondsInWeb);
1443
                                // XMLEntity xml=ps.getPersistentXML();
1444
                                fechaActual = new java.util.Date();
1445

    
1446
                                FileOutputStream outAux = new FileOutputStream(timeFile);
1447
                                prop.setProperty("timestamp", miliSecondsInWeb.toString());
1448
                                prop.store(outAux, "last download");
1449
                                outAux.close();
1450
                                System.out.println("Fecha actual guardada: " +
1451
                                        fechaActual.toGMTString());
1452

    
1453
                                /* xml.putProperty("timestamp",fechaActual.toGMTString());
1454
                                   ps.setPresistentXML(xml); */
1455
                        }
1456
                } catch (IOException e) {
1457
                        NotificationManager.addError("", e);
1458
                } catch (UnavailableServiceException e) {
1459
                        NotificationManager.addError("", e);
1460
                } catch (SecurityException e) {
1461
                        System.err.println("No se puede escribir el timeStamp " +
1462
                                fechaActual.toGMTString());
1463
                        NotificationManager.addError("", e);
1464
                }
1465
        }
1466

    
1467
        /**
1468
         * DOCUMENT ME!
1469
         *
1470
         * @return DOCUMENT ME!
1471
         */
1472
        private static Extensions[] getExtensions() {
1473
                ArrayList array = new ArrayList();
1474
                Iterator iter = pluginsConfig.values().iterator();
1475

    
1476
                while (iter.hasNext()) {
1477
                        array.add(((PluginConfig) iter.next()).getExtensions());
1478
                }
1479

    
1480
                return (Extensions[]) array.toArray(new Extensions[0]);
1481
        }
1482

    
1483
        /**
1484
         * DOCUMENT ME!
1485
         *
1486
         * @return DOCUMENT ME!
1487
         */
1488
        public static HashMap getPluginConfig() {
1489
                return pluginsConfig;
1490
        }
1491

    
1492
        /**
1493
         * DOCUMENT ME!
1494
         *
1495
         * @param s DOCUMENT ME!
1496
         *
1497
         * @return DOCUMENT ME!
1498
         */
1499
        public static Extension getExtension(String s) {
1500
                Extensions[] exts = getExtensions();
1501

    
1502
                for (int i = 0; i < exts.length; i++) {
1503
                        for (int j = 0; j < exts[i].getExtensionCount(); j++) {
1504
                                if (exts[i].getExtension(j).getClassName().equals(s)) {
1505
                                        return exts[i].getExtension(j);
1506
                                }
1507
                        }
1508
                }
1509

    
1510
                return null;
1511
        }
1512

    
1513
        /**
1514
         * DOCUMENT ME!
1515
         *
1516
         * @return DOCUMENT ME!
1517
         */
1518
        public static AndamiConfig getAndamiConfig() {
1519
                return andamiConfig;
1520
        }
1521

    
1522
        /**
1523
         * DOCUMENT ME!
1524
         *
1525
         * @author $author$
1526
         * @version $Revision: 4732 $
1527
         */
1528
        private static class ExtensionComparator implements Comparator {
1529
                /**
1530
                 * DOCUMENT ME!
1531
                 *
1532
                 * @param o1 DOCUMENT ME!
1533
                 * @param o2 DOCUMENT ME!
1534
                 *
1535
                 * @return DOCUMENT ME!
1536
                 */
1537
                public int compare(Object o1, Object o2) {
1538
                        Extension e1 = (Extension) o1;
1539
                        Extension e2 = (Extension) o2;
1540

    
1541
                        if (!e1.hasPriority() && !e2.hasPriority()) {
1542
                                return -1;
1543
                        }
1544

    
1545
                        if (e1.hasPriority() && !e2.hasPriority()) {
1546
                                return -Integer.MAX_VALUE;
1547
                        }
1548

    
1549
                        if (e2.hasPriority() && !e1.hasPriority()) {
1550
                                return Integer.MAX_VALUE;
1551
                        }
1552

    
1553
                        if (e1.getPriority() != e2.getPriority()){
1554
                                return e2.getPriority() - e1.getPriority();
1555
                        }else{
1556
                                return (e2.toString().compareTo(e1.toString()));
1557
                        }
1558
                }
1559
        }
1560

    
1561
        /**
1562
         * DOCUMENT ME!
1563
         */
1564
        private static class MenuComparator implements Comparator {
1565
                private static ExtensionComparator extComp = new ExtensionComparator();
1566

    
1567
                /**
1568
                 * DOCUMENT ME!
1569
                 *
1570
                 * @param o1 DOCUMENT ME!
1571
                 * @param o2 DOCUMENT ME!
1572
                 *
1573
                 * @return DOCUMENT ME!
1574
                 */
1575
                public int compare(Object o1, Object o2) {
1576
                        SortableMenu e1 = (SortableMenu) o1;
1577
                        SortableMenu e2 = (SortableMenu) o2;
1578

    
1579
                        if (!e1.menu.hasPosition() && !e2.menu.hasPosition()) {
1580
                                if (e1.extension instanceof SkinExtensionType) {
1581
                                        return 1;
1582
                                } else if (e2.extension instanceof SkinExtensionType) {
1583
                                        return -1;
1584
                                } else {
1585
                                        return extComp.compare(e1.extension, e2.extension);
1586
                                }
1587
                        }
1588

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

    
1593
                        if (e2.menu.hasPosition() && !e1.menu.hasPosition()) {
1594
                                return Integer.MAX_VALUE;
1595
                        }
1596

    
1597
                        return e1.menu.getPosition() - e2.menu.getPosition();
1598
                }
1599
        }
1600

    
1601
        /**
1602
         * DOCUMENT ME!
1603
         *
1604
         * @author $author$
1605
         * @version $Revision: 4732 $
1606
         */
1607
        private static class SortableMenu {
1608
                public PluginClassLoader loader;
1609
                public Menu menu;
1610
                public SkinExtensionType extension;
1611

    
1612
                /**
1613
                 * DOCUMENT ME!
1614
                 *
1615
                 * @param loader DOCUMENT ME!
1616
                 * @param skinExt
1617
                 * @param menu2
1618
                 */
1619
                public SortableMenu(PluginClassLoader loader,
1620
                        SkinExtensionType skinExt, Menu menu2) {
1621
                        extension = skinExt;
1622
                        menu = menu2;
1623
                        this.loader = loader;
1624
                }
1625
        }
1626
        /**
1627
         * DOCUMENT ME!
1628
         */
1629
        private static class ToolBarComparator implements Comparator {
1630
                private static ExtensionComparator extComp = new ExtensionComparator();
1631

    
1632
                /**
1633
                 * DOCUMENT ME!
1634
                 *
1635
                 * @param o1 DOCUMENT ME!
1636
                 * @param o2 DOCUMENT ME!
1637
                 *
1638
                 * @return DOCUMENT ME!
1639
                 */
1640
                public int compare(Object o1, Object o2) {
1641
                        SortableToolBar e1 = (SortableToolBar) o1;
1642
                        SortableToolBar e2 = (SortableToolBar) o2;
1643

    
1644
                        if (!e1.toolbar.hasPosition() && !e2.toolbar.hasPosition()) {
1645
                                if (e1.extension instanceof SkinExtensionType) {
1646
                                        return 1;
1647
                                } else if (e2.extension instanceof SkinExtensionType) {
1648
                                        return -1;
1649
                                } else {
1650
                                        return extComp.compare(e1.extension, e2.extension);
1651
                                }
1652
                        }
1653

    
1654
                        if (e1.toolbar.hasPosition() && !e2.toolbar.hasPosition()) {
1655
                                return -Integer.MAX_VALUE;
1656
                        }
1657

    
1658
                        if (e2.toolbar.hasPosition() && !e1.toolbar.hasPosition()) {
1659
                                return Integer.MAX_VALUE;
1660
                        }
1661
                        if (e1.toolbar.getPosition() != e2.toolbar.getPosition())
1662
                        return e1.toolbar.getPosition() - e2.toolbar.getPosition();
1663
                        
1664
                        if (e1.toolbar.getActionTool().equals(e2.toolbar.getActionTool()) && e1.toolbar.getSelectableTool().equals(e2.toolbar.getSelectableTool())){
1665
                                return 0;
1666
                        }
1667
                        return 1; 
1668
                }
1669
        }
1670
        /**
1671
         * DOCUMENT ME!
1672
         *
1673
         * @author $author$
1674
         * @version $Revision: 4732 $
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
        
1707
        /**
1708
         * validates the user before starting gvsig
1709
         *
1710
         */
1711
        private static void validate(){
1712
                
1713
                IAuthentication session =  null;
1714
                try {
1715
                        
1716
                        //String location = getClassLocation(Class.forName("com.iver.andami.authentication.Session"));
1717
                        session = (IAuthentication)Class.forName("com.iver.andami.authentication.Session").newInstance();
1718

    
1719
                } catch (ClassNotFoundException e) {
1720
                        // TODO Auto-generated catch block
1721
                        //e.printStackTrace();
1722
                        return;
1723
                } catch (InstantiationException e) {
1724
                        // TODO Auto-generated catch block
1725
                        //e.printStackTrace();
1726
                        return;
1727
                } catch (IllegalAccessException e) {
1728
                        // TODO Auto-generated catch block
1729
                        //e.printStackTrace();
1730
                        return;
1731
                }
1732
                
1733
                session.setPluginDirectory( andamiConfig.getPluginsDirectory() );
1734
                if (session.validationRequired()){
1735
                        
1736
                        //opens the login dialog for the user to validate
1737
                        //session.loging does not need arguments: they are read in the internal hashtable
1738
                        session.getUser();
1739
                        if(session.Login((String)session.get("user"),(String)session.get("pwd"))){
1740
                                System.out.println("You are logged in");
1741
                                //PluginServices.setSession( session );        
1742
                        }
1743
                        else{
1744
                                JOptionPane.showMessageDialog((Component)PluginServices.getMainFrame(),
1745
                                                 "You are not logged in");                                
1746
                                System.exit(0);
1747
                        }
1748
                        PluginServices.setAuthentication(session);
1749
                }                
1750
        }
1751
}