Statistics
| Revision:

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

History | View | Annotate | Download (48.2 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

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

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

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

    
123

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

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

    
161
            if (!validJVM()){
162
                System.exit(-1);
163
            }
164
                
165
            if (args.length < 1) {
166
                        System.err.println("Uso: Launcher appName plugins-directory [language=locale]");
167
                }
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
            Messages.init("va");
227
        }
228
        else
229
        {
230
            // locale = Locale.getDefault();
231
            locale = getLocale(localeStr,
232
                    andamiConfig.getLocaleCountry(),
233
                    andamiConfig.getLocaleVariant());
234
            Messages.init(locale);
235
        }
236

    
237
                Locale.setDefault(locale);
238
                JComponent.setDefaultLocale(locale);        
239
                
240

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
420
                XMLEntity entity = new XMLEntity();
421

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

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

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

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

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

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

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

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

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

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

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

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

    
496
                                Class skinClass;
497

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
892
                                                continue;
893
                                        }
894

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

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

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

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

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

    
931
                                PluginClassLoader loader;
932

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

    
939
                                        PluginServices ps = new PluginServices(loader);
940

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

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

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

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

    
961
                                break;
962
                        }
963
                }
964

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

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

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

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

    
987
                while (i.hasNext()) {
988
                        String pluginName = (String) i.next();
989
                        PluginConfig config = (PluginConfig) pluginsConfig.get(pluginName);
990

    
991
                        PluginServices ps = (PluginServices) pluginsServices.get(pluginName);
992

    
993
                        if (config.getResourceBundle() != null) {
994
                                ps.setResourceBundle(config.getResourceBundle().getName(),
995
                                        locale);
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: 4308 $
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: 4308 $
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: 4308 $
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
                }                
1749
        }
1750
}