Statistics
| Revision:

root / tags / gvSIGv0_6_1RELEASE / frameworks / _fwAndami / src / com / iver / andami / Launcher.java @ 5222

History | View | Annotate | Download (46.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.Dimension;
44
import java.awt.EventQueue;
45
import java.awt.Point;
46
import java.awt.Toolkit;
47
import java.io.BufferedInputStream;
48
import java.io.BufferedOutputStream;
49
import java.io.File;
50
import java.io.FileFilter;
51
import java.io.FileInputStream;
52
import java.io.FileNotFoundException;
53
import java.io.FileOutputStream;
54
import java.io.FileReader;
55
import java.io.FileWriter;
56
import java.io.FilenameFilter;
57
import java.io.IOException;
58
import java.io.InputStream;
59
import java.lang.reflect.InvocationTargetException;
60
import java.net.MalformedURLException;
61
import java.net.URL;
62
import java.net.URLConnection;
63
import java.util.ArrayList;
64
import java.util.Comparator;
65
import java.util.Date;
66
import java.util.HashMap;
67
import java.util.HashSet;
68
import java.util.Iterator;
69
import java.util.Locale;
70
import java.util.Properties;
71
import java.util.TreeMap;
72

    
73
import javax.jnlp.BasicService;
74
import javax.jnlp.ServiceManager;
75
import javax.jnlp.UnavailableServiceException;
76
import javax.swing.ImageIcon;
77
import javax.swing.JComponent;
78
import javax.swing.SwingUtilities;
79
import javax.swing.UIManager;
80

    
81
import org.apache.log4j.Logger;
82
import org.apache.log4j.PatternLayout;
83
import org.apache.log4j.PropertyConfigurator;
84
import org.apache.log4j.RollingFileAppender;
85
import org.exolab.castor.xml.MarshalException;
86
import org.exolab.castor.xml.ValidationException;
87

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

    
116

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

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

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

    
162
                appName = args[0];
163

    
164
                //Se crea el directorio de configuraci?n de la aplicaci?n
165
                File parent = new File(System.getProperty("user.home") +
166
                                File.separator + args[0] + File.separator);
167
                parent.mkdirs();
168

    
169
                andamiConfigPath = System.getProperty("user.home") + File.separator +
170
                        appName + File.separator + "andami-config.xml";
171
                pluginsPersistencePath = System.getProperty("user.home") +
172
                        File.separator + appName + File.separator +
173
                        "plugins-persistence.xml";
174

    
175
                // Configurar el log4j
176
                PropertyConfigurator.configure(Launcher.class.getClassLoader()
177
                                                                                                         .getResource("log4j.properties"));
178

    
179
                PatternLayout l = new PatternLayout("%p %t %C - %m%n");
180
                RollingFileAppender fa = new RollingFileAppender(l,
181
                                System.getProperty("user.home") + File.separator + args[0] +
182
                                File.separator + args[0] + ".log", false);
183
                fa.setMaxFileSize("512KB");
184
                fa.setMaxBackupIndex(3);
185
                Logger.getRootLogger().addAppender(fa);
186

    
187
                // Leer el fichero de configuraci?n de andami (andami-config.xsd)
188
                // locale
189
                // Buscar actualizaci?nes al comenzar
190
                //  Andami
191
                //  Plugins
192
                // Directorio de las extensiones
193
                andamiConfigFromXML(andamiConfigPath);
194
                andamiConfig.setPluginsDirectory(args[1]);
195

    
196
                
197
                // Hacemos visibles los argumentos como una propiedad est?tica
198
                // de plugin services para quien lo quiera usar (por ejemplo, para
199
                // cargar un proyecto por l?nea de comandos)
200
                PluginServices.setArguments(args);
201

    
202
                // Configurar el locale
203
        String localeStr = null;
204
        for (int i=2; i < args.length; i++)
205
        {
206
                int index = args[i].indexOf("language="); 
207
                if (index != -1)
208
                        localeStr = args[i].substring(index+9);
209
        }
210
                if (localeStr == null)
211
                {
212
            localeStr = andamiConfig.getLocaleLanguage();
213
                        /* locale = getLocale(localeStr,
214
                                        andamiConfig.getLocaleCountry(),
215
                                        andamiConfig.getLocaleVariant()); */
216
                }
217
        if (localeStr.compareTo("va")==0)
218
        {
219
            locale = new Locale("ca");
220
        }
221
        else
222
        {
223
            // locale = Locale.getDefault();
224
            locale = getLocale(localeStr,
225
                    andamiConfig.getLocaleCountry(),
226
                    andamiConfig.getLocaleVariant());
227
        }
228

    
229
                Locale.setDefault(locale);
230
                Messages.init(locale);
231
                JComponent.setDefaultLocale(locale);        
232
                
233

    
234
                //Se pone el lookAndFeel
235
                try {
236
                        UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
237
                } catch (Exception e) {
238
                        logger.warn(Messages.getString("Launcher.look_and_feel"), e);
239
                }
240

    
241
                // Mostrar la ventana de inicio
242
                splashWindow = new SplashWindow(null);
243

    
244
                // TODO Buscar actualizaciones de los plugins
245
                downloadExtensions(andamiConfig.getPluginsDirectory());
246

    
247
                // Se leen los config.xml de los plugins -----++++
248
                loadPlugins(andamiConfig.getPluginsDirectory());
249

    
250
                // Se configura el classloader del plugin
251
                pluginsClassLoaders();
252

    
253
                // Se carga un Skin si alguno de los plugins trae informaci?n para ello
254
                skinPlugin();
255

    
256
                //Se configura la cola de eventos
257
                EventQueue waitQueue = new AndamiEventQueue();
258
                Toolkit.getDefaultToolkit().getSystemEventQueue().push(waitQueue);
259

    
260
                // Se configura la mensajer?a del plugin
261
                pluginsMessages();
262

    
263
                // Se modifica el andami-config con los plugins nuevos
264
                updateAndamiConfig();
265

    
266
                // Se prepara el MainFrame para albergar las extensiones
267
                frame = new MDIFrame();
268

    
269
                // Se configura el nombre e icono de la aplicaci?n
270
                frameIcon();
271

    
272
                SwingUtilities.invokeAndWait(new Runnable() {
273
                                public void run() {
274
                                        frame.init();
275
                                }
276
                        });
277

    
278
                // Se instalan los controles de las extensiones de los plugins
279
                SwingUtilities.invokeAndWait(new Runnable() {
280
                                public void run() {
281
                                        installPluginsControls();
282
                                        installPluginsMenus();
283
                                        installPluginsLabels();
284
                                }
285
                        });
286

    
287
                // Leer el fichero de persistencia
288
                //  info de los plugins
289
                //  bookmarks de los plugins
290
                loadPluginsPersistence();
291

    
292
                // Se instalan los controles del skin
293
                // Se inicializan todas las extensiones de todos los plugins
294
                SwingUtilities.invokeAndWait(new Runnable() {
295
                                public void run() {
296
                                        initializeExtensions();
297
                                }
298
                        });
299
                frame.setClassesExtensions(classesExtensions);
300

    
301
                // Se instalan los bookmarks de los plugins
302
                splashWindow.close();
303

    
304
                //Se muestra el frame principal
305
                frame.show();
306

    
307
                SwingUtilities.invokeAndWait(new Runnable() {
308
                                public void run() {
309
                                        frame.enableControls();
310
                                }
311
                        });
312
            }catch(Exception e){
313
                logger.error("excepci?n al arrancar", e);
314
                System.exit(-1);
315
            }
316
            
317
            //  Clean temporal files
318
                Utilities.cleanUpTempFiles();
319
                
320
        }
321

    
322
        /**
323
     * @return
324
     */
325
    private static boolean validJVM() {
326
        char thirdCharacter = System.getProperty("java.version").charAt(2);
327
        if (thirdCharacter < '4'){
328
            return false;
329
            }else{
330
                return true;
331
            }
332
    }
333

    
334
        /**
335
         * Recupera la geometr?a (tama?o, posici?n y estado) de la ventana principal de Andami.
336
         * @author LWS
337
         */
338
        private static void restoreMDIStatus(XMLEntity xml) {
339
                //System.err.println("Launcher: restoreMDIStatus()");
340
                if (xml == null) xml = new XMLEntity();
341
                //  restore frame size
342
                Dimension sz = new Dimension(700,580);
343
                if (xml.contains("MDIFrameSize")) {
344
                        int [] wh = xml.getIntArrayProperty("MDIFrameSize");
345
                        sz = new Dimension(wh[0], wh[1]);
346
                }
347
                frame.setSize(sz);
348
                //  restore frame location
349
                Point pos = new Point(10,10);
350
                if (xml.contains("MDIFramePos")) {
351
                        int [] xy = xml.getIntArrayProperty("MDIFramePos");
352
                        pos = new Point(xy[0], xy[1]);
353
                }
354
                frame.setLocation(pos);
355
                
356
                //  restore frame status (Maximized, minimized, etc);
357
                int state = java.awt.Frame.MAXIMIZED_BOTH;
358
                if (xml.contains("MDIFrameState")) {
359
                        state = xml.getIntProperty("MDIFrameState");
360
                }
361
                frame.setExtendedState(state);
362
        }
363
        
364
        private static XMLEntity saveMDIStatus() {
365
                XMLEntity xml = new XMLEntity();
366
                // save frame size
367
                int [] wh = new int[2];
368
                wh[0] = frame.getWidth();
369
                wh[1] = frame.getHeight();
370
                xml.putProperty("MDIFrameSize", wh);
371
                // save frame location
372
                int [] xy = new int[2];
373
                xy[0] = frame.getX();
374
                xy[1] = frame.getY();
375
                xml.putProperty("MDIFramePos", xy);
376
                // save frame status
377
                xml.putProperty("MDIFrameState", frame.getExtendedState());
378
                return xml;
379
        }
380

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

    
389
                for (int i = 0; i < entity.getNumChild(); i++) {
390
                        XMLEntity plugin = entity.getChild(i);
391
                        String pName = plugin.getStringProperty(
392
                                        "com.iver.andami.pluginName");
393
                        if (pluginsServices.get(pName)!= null){
394
                                ((PluginServices) pluginsServices.get(pName)).setPersistentXML(plugin);
395
                        } else {
396
                                if (pName.startsWith("Andami.Launcher"))
397
                                        restoreMDIStatus(plugin);
398
                        }
399
                }
400
        }
401

    
402
        /**
403
         * DOCUMENT ME!
404
         */
405
        private static void installPluginsLabels() {
406
                Iterator i = pluginsConfig.keySet().iterator();
407

    
408
                while (i.hasNext()) {
409
                        String name = (String) i.next();
410
                        PluginConfig pc = (PluginConfig) pluginsConfig.get(name);
411
                        PluginServices ps = (PluginServices) pluginsServices.get(name);
412

    
413
                        LabelSet[] ls = pc.getLabelSet();
414

    
415
                        for (int j = 0; j < ls.length; j++) {
416
                                PluginClassLoader loader = ps.getClassLoader();
417

    
418
                                try {
419
                                        Class clase = loader.loadClass(ls[j].getClassName());
420
                                        frame.setLabels(clase, ls[j].getLabel());
421
                                } catch (ClassNotFoundException e) {
422
                                        logger.error(Messages.getString("Launcher.labelset_class"),
423
                                                e);
424
                                }
425
                        }
426
                }
427
        }
428

    
429
        /**
430
         * Salva la persistencia de los plugins.
431
         * @author LWS
432
         */
433
        private static void savePluginPersistence() {
434
                Iterator i = pluginsConfig.keySet().iterator();
435

    
436
                XMLEntity entity = new XMLEntity();
437

    
438
                while (i.hasNext()) {
439
                        String pName = (String) i.next();
440
                        PluginServices ps = (PluginServices) pluginsServices.get(pName);
441
                        XMLEntity ent = ps.getPersistentXML();
442

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

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

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

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

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

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

    
485
                                Class skinClass;
486

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
684
        /**
685
         *
686
         */
687
        private static void installPluginsControls() {
688
                Iterator i = pluginsConfig.keySet().iterator();
689

    
690
                HashMap extensionPluginServices = new HashMap();
691
                HashMap extensionPluginConfig = new HashMap();
692
                TreeMap orderedExtensions = new TreeMap(new ExtensionComparator());
693
                while (i.hasNext()) {
694
                                String pName = (String) i.next();
695
                                PluginConfig pc = (PluginConfig) pluginsConfig.get(pName);
696
                                PluginServices ps = (PluginServices) pluginsServices.get(pName);
697

    
698
                                Extension[] exts = pc.getExtensions().getExtension();
699

    
700
                                for (int j = 0; j < exts.length; j++) {
701
                                        if (exts[j].getActive()) {
702
                                                if (orderedExtensions.containsKey(exts[j])) {
703
                                                        logger.error(Messages.getString(
704
                                                                        "Launcher.Two_extensions_with_the_same_priority") +
705
                                                                exts[j].getClassName());
706
                                                }
707

    
708
                                                orderedExtensions.put(exts[j], null);
709
                                                extensionPluginServices.put(exts[j], ps);
710
                                                extensionPluginConfig.put(exts[j], pc);
711
                                        }
712
                                }
713
                }
714

    
715
                ///try {
716
                        TreeMap orderedToolBars = new TreeMap(new ToolBarComparator());
717
                        Iterator e = orderedExtensions.keySet().iterator();
718

    
719
                        // Se instalan las extensiones
720
                        while (e.hasNext()) {
721
                                Extension ext = (Extension) e.next();
722

    
723
                                ToolBar[] toolbars = ext.getToolBar();
724

    
725
                                for (int k = 0; k < toolbars.length; k++) {
726
                                        ActionTool[] tools = toolbars[k].getActionTool();
727

    
728
                                        for (int t = 0; t < tools.length; t++) {
729
                                                SortableToolBar sm = new SortableToolBar(((PluginServices)extensionPluginServices.get(ext)).getClassLoader(), ext,
730
                                                                toolbars[k], tools[t]);
731
                                                orderedToolBars.put(sm, null);
732
                                                ///frame.addTool(((PluginServices)extensionPluginServices.get(ext)).getClassLoader(), ext,
733
                                                ///        toolbars[k], tools[t]);
734
                                        }
735

    
736
                                        SelectableTool[] sTools = toolbars[k].getSelectableTool();
737

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

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

    
791
                                if (pus != null) {
792
                                        PopupMenu[] menus = pus.getPopupMenu();
793

    
794
                                        for (int j = 0; j < menus.length; j++) {
795
                                                frame.addPopupMenu(ps.getClassLoader(), menus[j]);
796
                                        }
797
                                }
798
                        }
799
//                        Se itera por los menus ordenados
800
                        Iterator t = orderedToolBars.keySet().iterator();
801

    
802
                        // Se ordenan los menues
803
                        while (t.hasNext()) {
804
                                try {
805
                                        SortableToolBar stb = (SortableToolBar) t.next();
806
                                        if (stb.actiontool!=null)
807
                                                frame.addTool(stb.loader, stb.extension,stb.toolbar, stb.actiontool);
808
                                        else
809
                                                frame.addTool(stb.loader, stb.extension,stb.toolbar, stb.selectabletool);
810
                                } catch (ClassNotFoundException ex) {
811
                                        logger.error(Messages.getString(
812
                                                        "Launcher.No_se_encontro_la_clase_de_la_extension"), ex);
813
                                }
814
                        }
815
                ///} catch (ClassNotFoundException e) {
816
                ///        logger.error(Messages.getString(
817
                ///                        "Launcher.No_se_encontro_la_clase_de_la_extension"), e);
818
                ///}
819
        }
820

    
821
        /**
822
         *
823
         */
824
        private static void updateAndamiConfig() {
825
                HashSet olds = new HashSet();
826

    
827
                Plugin[] plugins = andamiConfig.getPlugin();
828

    
829
                for (int i = 0; i < plugins.length; i++) {
830
                        olds.add(plugins[i].getName());
831
                }
832

    
833
                Iterator i = pluginsServices.values().iterator();
834

    
835
                while (i.hasNext()) {
836
                        PluginServices ps = (PluginServices) i.next();
837

    
838
                        if (!olds.contains(ps.getPluginName())) {
839
                                Plugin p = new Plugin();
840
                                p.setName(ps.getPluginName());
841
                                p.setUpdate(false);
842

    
843
                                andamiConfig.addPlugin(p);
844
                        }
845
                }
846
        }
847

    
848
        /**
849
         * DOCUMENT ME!
850
         */
851
        private static void pluginsClassLoaders() {
852
                HashSet instalados = new HashSet();
853

    
854
                // Se itera hasta que est?n todos instalados
855
                while (instalados.size() != pluginsConfig.size()) {
856
                        boolean circle = true;
857

    
858
                        //Hacemos una pasada por todos los plugins
859
                        Iterator i = pluginsConfig.keySet().iterator();
860

    
861
                        while (i.hasNext()) {
862
                                String pluginName = (String) i.next();
863
                                PluginConfig config = (PluginConfig) pluginsConfig.get(pluginName);
864

    
865
                                if (instalados.contains(pluginName)) {
866
                                        continue;
867
                                }
868

    
869
                                //Se obtienen las dependencias y sus class loaders
870
                                boolean ready = true;
871
                                Depends[] dependencies = config.getDepends();
872
                                PluginClassLoader[] loaders = new PluginClassLoader[dependencies.length];
873

    
874
                                for (int j = 0; j < dependencies.length; j++) {
875
                                        if (pluginsConfig.get(dependencies[j].getPluginName()) == null) {
876
                                                logger.error(Messages.getString(
877
                                                                "Launcher.Dependencia_no_resuelta_en_plugin") +
878
                                                        pluginName + ": " +
879
                                                        dependencies[j].getPluginName());
880

    
881
                                                continue;
882
                                        }
883

    
884
                                        if (!instalados.contains(dependencies[j].getPluginName())) {
885
                                                ready = false;
886
                                        } else {
887
                                                loaders[j] = ((PluginServices) pluginsServices.get(dependencies[j].getPluginName())).getClassLoader();
888
                                        }
889
                                }
890

    
891
                                //Si no est?n sus dependencias satisfechas se aborta la instalaci?n
892
                                if (!ready) {
893
                                        continue;
894
                                }
895

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

    
908
                                URL[] urls = new URL[jarFiles.length];
909

    
910
                                for (int j = 0; j < jarFiles.length; j++) {
911
                                        try {
912
                                                urls[j] = new URL("file:" + jarFiles[j]);
913
                                        } catch (MalformedURLException e) {
914
                                                logger.error(Messages.getString(
915
                                                                "Launcher.No_se_puede_acceder_a") +
916
                                                        jarFiles[j]);
917
                                        }
918
                                }
919

    
920
                                PluginClassLoader loader;
921

    
922
                                try {
923
                                        loader = new PluginClassLoader(urls,
924
                                                        andamiConfig.getPluginsDirectory() +
925
                                                        File.separator + pluginName,
926
                                                        Launcher.class.getClassLoader(), loaders);
927

    
928
                                        PluginServices ps = new PluginServices(loader);
929

    
930
                                        pluginsServices.put(ps.getPluginName(), ps);
931

    
932
                                        instalados.add(pluginName);
933
                    // FJP: Los metemos ordenados para luego no cargar uno que necesita de otro antes de tiempo. Esto lo usaremos al 
934
                    // inicializar los plugins
935
                    pluginsOrdered.add(pluginName);
936

    
937
                                        circle = false;
938
                                } catch (IOException e) {
939
                                        logger.error(Messages.getString(
940
                                                        "Launcher.Error_con_las_librerias_del_plugin"), e);
941
                                        pluginsConfig.remove(pluginName);
942
                                        i = pluginsConfig.keySet().iterator();
943
                                }
944
                        }
945

    
946
                        if (circle) {
947
                                logger.error(Messages.getString(
948
                                                "Launcher.Hay_dependencias_circulares"));
949

    
950
                                break;
951
                        }
952
                }
953

    
954
                //Se eliminan los plugins que no fueron instalados
955
                Iterator i = pluginsConfig.keySet().iterator();
956

    
957
                while (i.hasNext()) {
958
                        String pluginName = (String) i.next();
959
                        PluginConfig config = (PluginConfig) pluginsConfig.get(pluginName);
960
                        PluginServices ps = (PluginServices) pluginsServices.get(pluginName);
961

    
962
                        if (ps == null) {
963
                                pluginsConfig.remove(pluginName);
964
                                i = pluginsConfig.keySet().iterator();
965
                        }
966
                } 
967
        }
968

    
969
        /**
970
         * DOCUMENT ME!
971
         */
972
        private static void pluginsMessages() {
973
                //Iteramos por todos los plugins
974
                Iterator i = pluginsConfig.keySet().iterator();
975

    
976
                while (i.hasNext()) {
977
                        String pluginName = (String) i.next();
978
                        PluginConfig config = (PluginConfig) pluginsConfig.get(pluginName);
979

    
980
                        PluginServices ps = (PluginServices) pluginsServices.get(pluginName);
981

    
982
                        if (config.getResourceBundle() != null) {
983
                                ps.setResourceBundle(config.getResourceBundle().getName(),
984
                                        locale);
985
                        }
986
                }
987
        }
988

    
989
        /**
990
         * DOCUMENT ME!
991
         *
992
         * @param name DOCUMENT ME!
993
         *
994
         * @return DOCUMENT ME!
995
         */
996
        static PluginServices getPluginServices(String name) {
997
                return (PluginServices) pluginsServices.get(name);
998
        }
999

    
1000
        /**
1001
         * DOCUMENT ME!
1002
         *
1003
         * @return DOCUMENT ME!
1004
         */
1005
        static String getPluginsDir() {
1006
                return andamiConfig.getPluginsDirectory();
1007
        }
1008

    
1009
        /**
1010
         * DOCUMENT ME!
1011
         *
1012
         * @param s DOCUMENT ME!
1013
         */
1014
        static void setPluginsDir(String s) {
1015
                andamiConfig.setPluginsDirectory(s);
1016
        }
1017

    
1018
        /**
1019
         * DOCUMENT ME!
1020
         *
1021
         * @return DOCUMENT ME!
1022
         */
1023
        static MDIFrame getMDIFrame() {
1024
                return frame;
1025
        }
1026

    
1027
        /**
1028
         * DOCUMENT ME!
1029
         *
1030
         * @param pluginsDirectory
1031
         */
1032
        private static void loadPlugins(String pluginsDirectory) {
1033
                File pDir = new File(pluginsDirectory);
1034

    
1035
                if (!pDir.exists()) {
1036
                        return;
1037
                }
1038

    
1039
                File[] pluginDirs = pDir.listFiles();
1040

    
1041
                for (int i = 0; i < pluginDirs.length; i++) {
1042
                        if (pluginDirs[i].isDirectory()) {
1043
                                File configXml = new File(pluginDirs[i].getAbsolutePath() +
1044
                                                File.separator + "config.xml");
1045

    
1046
                                try {
1047
                                        FileReader xml = new FileReader(configXml);
1048
                                        PluginConfig pConfig = (PluginConfig) PluginConfig.unmarshal(xml);
1049
                                        pluginsConfig.put(pluginDirs[i].getName(), pConfig);
1050
                                } catch (FileNotFoundException e) {
1051
                                        logger.info(Messages.getString(
1052
                                                        "Launcher.Ignorando_el_directorio") +
1053
                                                pluginDirs[i].getAbsolutePath() +
1054
                                                Messages.getString("Launcher.config_no_encontrado"));
1055
                                } catch (MarshalException e) {
1056
                                        logger.info(Messages.getString(
1057
                                                        "Launcher.Ignorando_el_directorio") +
1058
                                                pluginDirs[i].getAbsolutePath() +
1059
                                                Messages.getString("Launcher.config_mal_formado"), e);
1060
                                } catch (ValidationException e) {
1061
                                        logger.info(Messages.getString(
1062
                                                        "Launcher.Ignorando_el_directorio") +
1063
                                                pluginDirs[i].getAbsolutePath() +
1064
                                                Messages.getString("Launcher.config_mal_formado"), e);
1065
                                }
1066
                        }
1067
                }
1068
        }
1069

    
1070
        /**
1071
         * DOCUMENT ME!
1072
         *
1073
         * @param language
1074
         * @param country
1075
         * @param variant
1076
         *
1077
         * @return DOCUMENT ME!
1078
         */
1079
        private static Locale getLocale(String language, String country,
1080
                String variant) {
1081
                if (variant != null) {
1082
                        return new Locale(language, country, variant);
1083
                } else if (country != null) {
1084
                        return new Locale(language, country);
1085
                } else if (language != null) {
1086
                        return new Locale(language);
1087
                } else {
1088
                        return new Locale("es");
1089
                }
1090
        }
1091

    
1092
        /**
1093
         * DOCUMENT ME!
1094
         *
1095
         * @param file DOCUMENT ME!
1096
         *
1097
         * @throws IOException DOCUMENT ME!
1098
         * @throws MarshalException DOCUMENT ME!
1099
         * @throws ValidationException DOCUMENT ME!
1100
         */
1101
        private static void andamiConfigToXML(String file)
1102
                throws IOException, MarshalException, ValidationException {
1103
                File xml = new File(file);
1104
                File parent = xml.getParentFile();
1105
                parent.mkdirs();
1106

    
1107
                FileWriter writer = new FileWriter(xml);
1108
                andamiConfig.marshal(writer);
1109
        }
1110

    
1111
        /**
1112
         * DOCUMENT ME!
1113
         *
1114
         * @param file DOCUMENT ME!
1115
         *
1116
         * @throws ConfigurationException DOCUMENT ME!
1117
         */
1118
        private static void andamiConfigFromXML(String file)
1119
                throws ConfigurationException {
1120
                File xml = new File(file);
1121

    
1122
                //Si no existe se ponen los valores por defecto
1123
                if (!xml.exists()) {
1124
                        andamiConfig = new AndamiConfig();
1125

    
1126
                        Andami andami = new Andami();
1127
                        andami.setUpdate(true);
1128
                        andamiConfig.setAndami(andami);
1129
                        andamiConfig.setLocaleCountry(Locale.getDefault().getCountry());
1130
                        andamiConfig.setLocaleLanguage(Locale.getDefault().getLanguage());
1131
                        andamiConfig.setLocaleVariant(Locale.getDefault().getVariant());
1132

    
1133
                        if (System.getProperty("javawebstart.version") != null) // Es java web start)
1134
                         {
1135
                                andamiConfig.setPluginsDirectory(new File(System.getProperty(
1136
                                                        "user.home") + File.separator + appName +
1137
                                                File.separator + "extensiones").getAbsolutePath());
1138
                        } else {
1139
                                andamiConfig.setPluginsDirectory(new File(appName +
1140
                                                File.separator + "extensiones").getAbsolutePath());
1141
                        }
1142

    
1143
                        andamiConfig.setPlugin(new Plugin[0]);
1144
                } else {
1145
                        //Se lee la configuraci?n
1146
                        FileReader reader;
1147

    
1148
                        try {
1149
                                reader = new FileReader(xml);
1150
                                andamiConfig = (AndamiConfig) AndamiConfig.unmarshal(reader);
1151
                        } catch (FileNotFoundException e) {
1152
                                throw new ConfigurationException(e);
1153
                        } catch (MarshalException e) {
1154
                                throw new ConfigurationException(e);
1155
                        } catch (ValidationException e) {
1156
                                throw new ConfigurationException(e);
1157
                        }
1158
                }
1159
        }
1160

    
1161
        /**
1162
         * DOCUMENT ME!
1163
         *
1164
         * @return DOCUMENT ME!
1165
         *
1166
         * @throws ConfigurationException DOCUMENT ME!
1167
         */
1168
        private static XMLEntity persistenceFromXML() throws ConfigurationException {
1169
                File xml = new File(pluginsPersistencePath);
1170

    
1171
                if (xml.exists()) {
1172
                        FileReader reader;
1173

    
1174
                        try {
1175
                                reader = new FileReader(xml);
1176

    
1177
                                XmlTag tag = (XmlTag) XmlTag.unmarshal(reader);
1178

    
1179
                                return new XMLEntity(tag);
1180
                        } catch (FileNotFoundException e) {
1181
                                throw new ConfigurationException(e);
1182
                        } catch (MarshalException e) {
1183
                                throw new ConfigurationException(e);
1184
                        } catch (ValidationException e) {
1185
                                throw new ConfigurationException(e);
1186
                        }
1187
                } else {
1188
                        return new XMLEntity();
1189
                }
1190
        }
1191

    
1192
        /**
1193
         * DOCUMENT ME!
1194
         *
1195
         * @param entity DOCUMENT ME!
1196
         *
1197
         * @throws ConfigurationException DOCUMENT ME!
1198
         */
1199
        private static void persistenceToXML(XMLEntity entity)
1200
                throws ConfigurationException {
1201
                File xml = new File(pluginsPersistencePath);
1202

    
1203
                FileWriter writer;
1204

    
1205
                try {
1206
                        writer = new FileWriter(xml);
1207
                        entity.getXmlTag().marshal(writer);
1208
                } catch (FileNotFoundException e) {
1209
                        throw new ConfigurationException(e);
1210
                } catch (MarshalException e) {
1211
                        throw new ConfigurationException(e);
1212
                } catch (ValidationException e) {
1213
                        throw new ConfigurationException(e);
1214
                } catch (IOException e) {
1215
                        throw new ConfigurationException(e);
1216
                }
1217
        }
1218

    
1219
        /**
1220
         * Devuelve un array con los directorios de los plugins
1221
         *
1222
         * @param dirExt Directorio de las extensiones a partir del cual cuelgan
1223
         *                   todos los directorios de los plugins
1224
         *
1225
         * @return ArrayList con los directorios
1226
         */
1227
        private String[] getLocales(File dirExt) {
1228
                ArrayList types = new ArrayList();
1229
                File[] files = dirExt.listFiles();
1230

    
1231
                for (int i = 0; i < files.length; i++) {
1232
                        if (files[i].isDirectory()) {
1233
                                File[] textFile = files[i].listFiles(new FilenameFilter() {
1234
                                                        public boolean accept(File dir, String fileName) {
1235
                                                                return fileName.toLowerCase().startsWith("text_"); //$NON-NLS-1$
1236
                                                        }
1237
                                                });
1238

    
1239
                                for (int j = 0; j < textFile.length; j++) {
1240
                                        String s = (textFile[j]).getName().replaceAll("text_", "");
1241
                                        s = s.replaceAll(".properties", "");
1242
                                        s = s.trim();
1243

    
1244
                                        if (!types.contains(s)) {
1245
                                                types.add(s);
1246
                                        }
1247
                                }
1248
                        }
1249
                }
1250

    
1251
                return (String[]) types.toArray(new String[0]);
1252
        }
1253

    
1254
        /**
1255
         * DOCUMENT ME!
1256
         *
1257
         * @return Returns the frame.
1258
         */
1259
        static MDIFrame getFrame() {
1260
                return frame;
1261
        }
1262

    
1263
        /**
1264
         * Secuencia de cerrado de Andami
1265
         */
1266
        public static void closeApplication() {
1267
                //Configuraci?n de Andami
1268
                try {
1269
                        andamiConfigToXML(andamiConfigPath);
1270
                } catch (MarshalException e) {
1271
                        logger.error(Messages.getString(
1272
                                        "Launcher.No_se_pudo_guardar_la_configuracion_de_andami"), e);
1273
                } catch (ValidationException e) {
1274
                        logger.error(Messages.getString(
1275
                                        "Launcher.No_se_pudo_guardar_la_configuracion_de_andami"), e);
1276
                } catch (IOException e) {
1277
                        logger.error(Messages.getString(
1278
                                        "Launcher.No_se_pudo_guardar_la_configuracion_de_andami"), e);
1279
                }
1280

    
1281
                //Persistencia de los plugins
1282
                savePluginPersistence();
1283

    
1284
                // Clean any temp data created
1285
                Utilities.cleanUpTempFiles();
1286
                
1287
                //Para la depuraci?n de memory leaks
1288
                System.gc();
1289

    
1290
        System.exit(0);
1291
        }
1292

    
1293
        /**
1294
         * DOCUMENT ME!
1295
         *
1296
         * @return DOCUMENT ME!
1297
         */
1298
        static HashMap getClassesExtensions() {
1299
                return classesExtensions;
1300
        }
1301

    
1302
        /**
1303
         * DOCUMENT ME!
1304
         *
1305
         * @param extDir DOCUMENT ME!
1306
         */
1307
        private static void downloadExtensions(String extDir) {
1308
                java.util.Date fechaActual = null;
1309

    
1310
                try {
1311
                        if (System.getProperty("javawebstart.version") != null) {
1312
                                //Obtenemos la URL del servidor
1313
                                BasicService bs = (BasicService) ServiceManager.lookup(
1314
                                                "javax.jnlp.BasicService");
1315
                                URL baseURL = bs.getCodeBase();
1316

    
1317
                                //Se descargan las extensiones
1318
                                SplashWindow.process(5,
1319
                                        "Descargando las extensiones desde " + baseURL + " a " +
1320
                                        extDir);
1321

    
1322
                                URL url = new URL(baseURL + "extensiones.zip");
1323
                                URLConnection connection = url.openConnection();
1324

    
1325
                                System.out.println(url.toExternalForm() + ":");
1326
                                System.out.println("  Content Type: " +
1327
                                        connection.getContentType());
1328
                                System.out.println("  Content Length: " +
1329
                                        connection.getContentLength());
1330
                                System.out.println("  Last Modified: " +
1331
                                        new Date(connection.getLastModified()));
1332
                                System.out.println("  Expiration: " +
1333
                                        connection.getExpiration());
1334
                                System.out.println("  Content Encoding: " +
1335
                                        connection.getContentEncoding());
1336

    
1337
                                // Guardamos la fecha del fichero de extensiones que nos hemos bajado, y
1338
                                // comprobamos el ?ltimo que se ha bajado. Si no son
1339
                                // iguales, nos bajamos el nuevo. Si son iguales, no
1340
                                // nos bajamos nada.
1341
                                Long miliSecondsInWeb = new Long(connection.getLastModified());
1342

    
1343
                                // PluginServices ps = PluginServices.getPluginServices("com.iver.core");
1344
                                // if (ps.getPersistentXML().getStringProperty("timestamp") != null)
1345
                                File destDir = new File(extDir);
1346

    
1347
                                if (!destDir.exists()) {
1348
                                        // Creamos gvSIG
1349
                                        destDir.getParentFile().mkdir();
1350

    
1351
                                        if (!destDir.mkdir()) {
1352
                                                System.err.println("Imposible crear el directorio " +
1353
                                                        destDir.getAbsolutePath());
1354
                                        }
1355
                                }
1356

    
1357
                                File timeFile = new File(destDir.getParent() + File.separator +
1358
                                                "timeStamp.properties");
1359

    
1360
                                if (!timeFile.exists()) {
1361
                                        timeFile.createNewFile();
1362
                                }
1363

    
1364
                                FileInputStream inAux = new FileInputStream(timeFile);
1365
                                Properties prop = new Properties();
1366
                                prop.load(inAux);
1367
                                inAux.close();
1368

    
1369
                                if (prop.getProperty("timestamp") != null) {
1370
                                        Long lastMiliSeconds = (Long) new Long(prop.getProperty(
1371
                                                                "timestamp"));
1372

    
1373
                                        if (lastMiliSeconds.longValue() == miliSecondsInWeb.longValue()) {
1374
                                                System.out.println("No hay nueva actualizaci?n");
1375

    
1376
                                                return;
1377
                                        }
1378

    
1379
                                        System.out.println("timeStampWeb= " + miliSecondsInWeb);
1380
                                        System.out.println("timeStampLocal= " + lastMiliSeconds);
1381
                                } else {
1382
                                        System.out.println("El timeStamp no est? escrito en " +
1383
                                                timeFile.getAbsolutePath());
1384
                                }
1385

    
1386
                                InputStream stream = connection.getInputStream();
1387
                                File temp = File.createTempFile("gvsig", ".zip");
1388
                                temp.deleteOnExit();
1389

    
1390
                                FileOutputStream file = new FileOutputStream(temp);
1391
                                BufferedInputStream in = new BufferedInputStream(stream);
1392
                                BufferedOutputStream out = new BufferedOutputStream(file);
1393

    
1394
                                int i;
1395
                                int pct;
1396
                                int desde;
1397
                                int hasta;
1398

    
1399
                                hasta = connection.getContentLength() / 1024;
1400
                                desde = 0;
1401

    
1402
                                while ((i = in.read()) != -1) {
1403
                                        pct = ((desde / 1024) * 100) / hasta;
1404

    
1405
                                        if (((desde % 10240) == 0) && (pct > 10) &&
1406
                                                        ((pct % 10) == 0)) {
1407
                                                SplashWindow.process(pct,
1408
                                                        (desde / 1024) + "Kb de " + hasta +
1409
                                                        "Kb descargados...");
1410
                                        }
1411

    
1412
                                        out.write(i);
1413
                                        desde++;
1414
                                }
1415

    
1416
                                out.flush();
1417
                                out.close();
1418
                                in.close();
1419

    
1420
                                //Se extrae el zip
1421
                                SplashWindow.process(5, "Extensiones descargadas.");
1422

    
1423
                                System.out.println("Extrayendo a " + destDir.getAbsolutePath());
1424

    
1425
                                Date fechaDir = new Date(destDir.lastModified());
1426
                                System.out.println("Fecha del directorio " + extDir + " = " +
1427
                                        fechaDir.toString());
1428
                                Utilities.extractTo(temp, new File(extDir), splashWindow);
1429

    
1430
                                // Si todo ha ido bien, guardamos el timestamp.
1431
                                ///  App.instance.getPc().addProperties("timestamp", miliSecondsInWeb);
1432
                                // XMLEntity xml=ps.getPersistentXML();
1433
                                fechaActual = new java.util.Date();
1434

    
1435
                                FileOutputStream outAux = new FileOutputStream(timeFile);
1436
                                prop.setProperty("timestamp", miliSecondsInWeb.toString());
1437
                                prop.store(outAux, "last download");
1438
                                outAux.close();
1439
                                System.out.println("Fecha actual guardada: " +
1440
                                        fechaActual.toGMTString());
1441

    
1442
                                /* xml.putProperty("timestamp",fechaActual.toGMTString());
1443
                                   ps.setPresistentXML(xml); */
1444
                        }
1445
                } catch (IOException e) {
1446
                        NotificationManager.addError("", e);
1447
                } catch (UnavailableServiceException e) {
1448
                        NotificationManager.addError("", e);
1449
                } catch (SecurityException e) {
1450
                        System.err.println("No se puede escribir el timeStamp " +
1451
                                fechaActual.toGMTString());
1452
                        NotificationManager.addError("", e);
1453
                }
1454
        }
1455

    
1456
        /**
1457
         * DOCUMENT ME!
1458
         *
1459
         * @return DOCUMENT ME!
1460
         */
1461
        private static Extensions[] getExtensions() {
1462
                ArrayList array = new ArrayList();
1463
                Iterator iter = pluginsConfig.values().iterator();
1464

    
1465
                while (iter.hasNext()) {
1466
                        array.add(((PluginConfig) iter.next()).getExtensions());
1467
                }
1468

    
1469
                return (Extensions[]) array.toArray(new Extensions[0]);
1470
        }
1471

    
1472
        /**
1473
         * DOCUMENT ME!
1474
         *
1475
         * @return DOCUMENT ME!
1476
         */
1477
        public static HashMap getPluginConfig() {
1478
                return pluginsConfig;
1479
        }
1480

    
1481
        /**
1482
         * DOCUMENT ME!
1483
         *
1484
         * @param s DOCUMENT ME!
1485
         *
1486
         * @return DOCUMENT ME!
1487
         */
1488
        public static Extension getExtension(String s) {
1489
                Extensions[] exts = getExtensions();
1490

    
1491
                for (int i = 0; i < exts.length; i++) {
1492
                        for (int j = 0; j < exts[i].getExtensionCount(); j++) {
1493
                                if (exts[i].getExtension(j).getClassName().equals(s)) {
1494
                                        return exts[i].getExtension(j);
1495
                                }
1496
                        }
1497
                }
1498

    
1499
                return null;
1500
        }
1501

    
1502
        /**
1503
         * DOCUMENT ME!
1504
         *
1505
         * @return DOCUMENT ME!
1506
         */
1507
        public static AndamiConfig getAndamiConfig() {
1508
                return andamiConfig;
1509
        }
1510

    
1511
        /**
1512
         * DOCUMENT ME!
1513
         *
1514
         * @author $author$
1515
         * @version $Revision: 5222 $
1516
         */
1517
        private static class ExtensionComparator implements Comparator {
1518
                /**
1519
                 * DOCUMENT ME!
1520
                 *
1521
                 * @param o1 DOCUMENT ME!
1522
                 * @param o2 DOCUMENT ME!
1523
                 *
1524
                 * @return DOCUMENT ME!
1525
                 */
1526
                public int compare(Object o1, Object o2) {
1527
                        Extension e1 = (Extension) o1;
1528
                        Extension e2 = (Extension) o2;
1529

    
1530
                        if (!e1.hasPriority() && !e2.hasPriority()) {
1531
                                return -1;
1532
                        }
1533

    
1534
                        if (e1.hasPriority() && !e2.hasPriority()) {
1535
                                return -Integer.MAX_VALUE;
1536
                        }
1537

    
1538
                        if (e2.hasPriority() && !e1.hasPriority()) {
1539
                                return Integer.MAX_VALUE;
1540
                        }
1541

    
1542
                        if (e1.getPriority() != e2.getPriority()){
1543
                                return e2.getPriority() - e1.getPriority();
1544
                        }else{
1545
                                return (e2.toString().compareTo(e1.toString()));
1546
                        }
1547
                }
1548
        }
1549

    
1550
        /**
1551
         * DOCUMENT ME!
1552
         */
1553
        private static class MenuComparator implements Comparator {
1554
                private static ExtensionComparator extComp = new ExtensionComparator();
1555

    
1556
                /**
1557
                 * DOCUMENT ME!
1558
                 *
1559
                 * @param o1 DOCUMENT ME!
1560
                 * @param o2 DOCUMENT ME!
1561
                 *
1562
                 * @return DOCUMENT ME!
1563
                 */
1564
                public int compare(Object o1, Object o2) {
1565
                        SortableMenu e1 = (SortableMenu) o1;
1566
                        SortableMenu e2 = (SortableMenu) o2;
1567

    
1568
                        if (!e1.menu.hasPosition() && !e2.menu.hasPosition()) {
1569
                                if (e1.extension instanceof SkinExtensionType) {
1570
                                        return 1;
1571
                                } else if (e2.extension instanceof SkinExtensionType) {
1572
                                        return -1;
1573
                                } else {
1574
                                        return extComp.compare(e1.extension, e2.extension);
1575
                                }
1576
                        }
1577

    
1578
                        if (e1.menu.hasPosition() && !e2.menu.hasPosition()) {
1579
                                return -Integer.MAX_VALUE;
1580
                        }
1581

    
1582
                        if (e2.menu.hasPosition() && !e1.menu.hasPosition()) {
1583
                                return Integer.MAX_VALUE;
1584
                        }
1585

    
1586
                        return e1.menu.getPosition() - e2.menu.getPosition();
1587
                }
1588
        }
1589

    
1590
        /**
1591
         * DOCUMENT ME!
1592
         *
1593
         * @author $author$
1594
         * @version $Revision: 5222 $
1595
         */
1596
        private static class SortableMenu {
1597
                public PluginClassLoader loader;
1598
                public Menu menu;
1599
                public SkinExtensionType extension;
1600

    
1601
                /**
1602
                 * DOCUMENT ME!
1603
                 *
1604
                 * @param loader DOCUMENT ME!
1605
                 * @param skinExt
1606
                 * @param menu2
1607
                 */
1608
                public SortableMenu(PluginClassLoader loader,
1609
                        SkinExtensionType skinExt, Menu menu2) {
1610
                        extension = skinExt;
1611
                        menu = menu2;
1612
                        this.loader = loader;
1613
                }
1614
        }
1615
        /**
1616
         * DOCUMENT ME!
1617
         */
1618
        private static class ToolBarComparator implements Comparator {
1619
                private static ExtensionComparator extComp = new ExtensionComparator();
1620

    
1621
                /**
1622
                 * DOCUMENT ME!
1623
                 *
1624
                 * @param o1 DOCUMENT ME!
1625
                 * @param o2 DOCUMENT ME!
1626
                 *
1627
                 * @return DOCUMENT ME!
1628
                 */
1629
                public int compare(Object o1, Object o2) {
1630
                        SortableToolBar e1 = (SortableToolBar) o1;
1631
                        SortableToolBar e2 = (SortableToolBar) o2;
1632

    
1633
                        if (!e1.toolbar.hasPosition() && !e2.toolbar.hasPosition()) {
1634
                                if (e1.extension instanceof SkinExtensionType) {
1635
                                        return 1;
1636
                                } else if (e2.extension instanceof SkinExtensionType) {
1637
                                        return -1;
1638
                                } else {
1639
                                        return extComp.compare(e1.extension, e2.extension);
1640
                                }
1641
                        }
1642

    
1643
                        if (e1.toolbar.hasPosition() && !e2.toolbar.hasPosition()) {
1644
                                return -Integer.MAX_VALUE;
1645
                        }
1646

    
1647
                        if (e2.toolbar.hasPosition() && !e1.toolbar.hasPosition()) {
1648
                                return Integer.MAX_VALUE;
1649
                        }
1650
                        if (e1.toolbar.getPosition() != e2.toolbar.getPosition())
1651
                        return e1.toolbar.getPosition() - e2.toolbar.getPosition();
1652
                        
1653
                        if (e1.toolbar.getActionTool().equals(e2.toolbar.getActionTool()) && e1.toolbar.getSelectableTool().equals(e2.toolbar.getSelectableTool())){
1654
                                return 0;
1655
                        }
1656
                        return 1; 
1657
                }
1658
        }
1659
        /**
1660
         * DOCUMENT ME!
1661
         *
1662
         * @author $author$
1663
         * @version $Revision: 5222 $
1664
         */
1665
        private static class SortableToolBar {
1666
                public PluginClassLoader loader;
1667
                public ToolBar toolbar;
1668
                public ActionTool actiontool;
1669
                public SelectableTool selectabletool;
1670
                public SkinExtensionType extension;
1671

    
1672
                /**
1673
                 * DOCUMENT ME!
1674
                 *
1675
                 * @param loader DOCUMENT ME!
1676
                 * @param skinExt
1677
                 * @param menu2
1678
                 */
1679
                public SortableToolBar(PluginClassLoader loader,
1680
                        SkinExtensionType skinExt, ToolBar toolbar2,ActionTool actiontool2) {
1681
                        extension = skinExt;
1682
                        toolbar = toolbar2;
1683
                        actiontool=actiontool2;
1684
                        this.loader = loader;
1685
                }
1686
                        public SortableToolBar(PluginClassLoader loader,
1687
                                SkinExtensionType skinExt, ToolBar toolbar2,SelectableTool selectabletool2) {
1688
                                extension = skinExt;
1689
                                toolbar = toolbar2;
1690
                                selectabletool=selectabletool2;
1691
                                this.loader = loader;
1692
                        }
1693
        }
1694
}