Statistics
| Revision:

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

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

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

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

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

    
115

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

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

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

    
161
                appName = args[0];
162

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

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

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

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

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

    
200
                // Configurar el locale
201
        String localeStr = "";
202
                if (args.length == 3) {
203
            localeStr = args[2];
204
            
205
                } else {
206
            localeStr = andamiConfig.getLocaleLanguage();
207
                        /* locale = getLocale(localeStr,
208
                                        andamiConfig.getLocaleCountry(),
209
                                        andamiConfig.getLocaleVariant()); */
210
                }
211
        if (localeStr.compareTo("va")==0)
212
        {
213
            locale = new Locale("ca");
214
            Messages.init("va");
215
        }
216
        else
217
        {
218
            // locale = Locale.getDefault();
219
            locale = getLocale(localeStr,
220
                    andamiConfig.getLocaleCountry(),
221
                    andamiConfig.getLocaleVariant());
222
            Messages.init(locale);
223
        }
224

    
225
                Locale.setDefault(locale);
226
                JComponent.setDefaultLocale(locale);        
227
                
228

    
229
                //Se pone el lookAndFeel
230
                try {
231
                        UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
232
                } catch (Exception e) {
233
                        logger.warn(Messages.getString("Launcher.look_and_feel"), e);
234
                }
235

    
236
                // Mostrar la ventana de inicio
237
                splashWindow = new SplashWindow(null);
238

    
239
                // TODO Buscar actualizaciones de los plugins
240
                downloadExtensions(andamiConfig.getPluginsDirectory());
241

    
242
                // Se leen los config.xml de los plugins -----++++
243
                loadPlugins(andamiConfig.getPluginsDirectory());
244

    
245
                // Se configura el classloader del plugin
246
                pluginsClassLoaders();
247

    
248
                // Se carga un Skin si alguno de los plugins trae informaci?n para ello
249
                skinPlugin();
250

    
251
                //Se configura la cola de eventos
252
                EventQueue waitQueue = new AndamiEventQueue();
253
                Toolkit.getDefaultToolkit().getSystemEventQueue().push(waitQueue);
254

    
255
                // Se configura la mensajer?a del plugin
256
                pluginsMessages();
257

    
258
                // Se modifica el andami-config con los plugins nuevos
259
                updateAndamiConfig();
260

    
261
                // Se prepara el MainFrame para albergar las extensiones
262
                frame = new MDIFrame();
263

    
264
                // Se configura el nombre e icono de la aplicaci?n
265
                frameIcon();
266

    
267
                SwingUtilities.invokeAndWait(new Runnable() {
268
                                public void run() {
269
                                        frame.init();
270
                                }
271
                        });
272

    
273
                // Se instalan los controles de las extensiones de los plugins
274
                SwingUtilities.invokeAndWait(new Runnable() {
275
                                public void run() {
276
                                        installPluginsControls();
277
                                        installPluginsMenus();
278
                                        installPluginsLabels();
279
                                }
280
                        });
281

    
282
                // Leer el fichero de persistencia
283
                //  info de los plugins
284
                //  bookmarks de los plugins
285
                loadPluginsPersistence();
286

    
287
                // Se instalan los controles del skin
288
                // Se inicializan todas las extensiones de todos los plugins
289
                SwingUtilities.invokeAndWait(new Runnable() {
290
                                public void run() {
291
                                        initializeExtensions();
292
                                }
293
                        });
294
                frame.setClassesExtensions(classesExtensions);
295

    
296
                // Se instalan los bookmarks de los plugins
297
                splashWindow.close();
298

    
299
                //Se muestra el frame principal
300
                frame.show();
301

    
302
                SwingUtilities.invokeAndWait(new Runnable() {
303
                                public void run() {
304
                                        frame.enableControls();
305
                                }
306
                        });
307
            }catch(Exception e){
308
                logger.error("excepci?n al arrancar", e);
309
                System.exit(-1);
310
            }
311
        }
312

    
313
        /**
314
     * @return
315
     */
316
    private static boolean validJVM() {
317
        char thirdCharacter = System.getProperty("java.version").charAt(2);
318
        if (thirdCharacter < '4'){
319
            return false;
320
            }else{
321
                return true;
322
            }
323
    }
324

    
325
    /**
326
         * DOCUMENT ME!
327
         *
328
         * @throws ConfigurationException
329
         */
330
        private static void loadPluginsPersistence() throws ConfigurationException {
331
                XMLEntity entity = persistenceFromXML();
332

    
333
                for (int i = 0; i < entity.getNumChild(); i++) {
334
                        XMLEntity plugin = entity.getChild(i);
335
                        String pName = plugin.getStringProperty(
336
                                        "com.iver.andami.pluginName");
337
                        if (pluginsServices.get(pName)!= null){
338
                                ((PluginServices) pluginsServices.get(pName)).setPersistentXML(plugin);
339
                        }
340
                }
341
        }
342

    
343
        /**
344
         * DOCUMENT ME!
345
         */
346
        private static void installPluginsLabels() {
347
                Iterator i = pluginsConfig.keySet().iterator();
348

    
349
                while (i.hasNext()) {
350
                        String name = (String) i.next();
351
                        PluginConfig pc = (PluginConfig) pluginsConfig.get(name);
352
                        PluginServices ps = (PluginServices) pluginsServices.get(name);
353

    
354
                        LabelSet[] ls = pc.getLabelSet();
355

    
356
                        for (int j = 0; j < ls.length; j++) {
357
                                PluginClassLoader loader = ps.getClassLoader();
358

    
359
                                try {
360
                                        Class clase = loader.loadClass(ls[j].getClassName());
361
                                        frame.setLabels(clase, ls[j].getLabel());
362
                                } catch (ClassNotFoundException e) {
363
                                        logger.error(Messages.getString("Launcher.labelset_class"),
364
                                                e);
365
                                }
366
                        }
367
                }
368
        }
369

    
370
        /**
371
         * DOCUMENT ME!
372
         *
373
         * @throws MDIManagerLoadException
374
         */
375
        private static void skinPlugin() throws MDIManagerLoadException {
376
                Iterator i = pluginsConfig.keySet().iterator();
377

    
378
                while (i.hasNext()) {
379
                        String name = (String) i.next();
380
                        PluginConfig pc = (PluginConfig) pluginsConfig.get(name);
381
                        PluginServices ps = (PluginServices) pluginsServices.get(name);
382

    
383
                        if (pc.getExtensions().getSkinExtension() != null) {
384
                                if (MDIManagerFactory.getSkinExtension() != null) {
385
                                        logger.warn(Messages.getString(
386
                                                        "Launcher.Dos_skin_extension"));
387
                                }
388

    
389
                                SkinExtension se = pc.getExtensions().getSkinExtension();
390

    
391
                                MDIManagerFactory.setSkinExtension(se, ps.getClassLoader());
392

    
393
                                Class skinClass;
394

    
395
                                try {
396
                                        skinClass = ps.getClassLoader().loadClass(se.getClassName());
397

    
398
                                        com.iver.andami.plugins.Extension skinInstance = (com.iver.andami.plugins.Extension) skinClass.newInstance();
399
                                        // classesExtensions.put(skinClass, skinInstance);
400
                                        // jaume
401
                                        ExtensionDecorator newExtensionDecorator = new ExtensionDecorator(skinInstance, ExtensionDecorator.INACTIVE);
402
                                        classesExtensions.put(skinClass, newExtensionDecorator);
403
                                } catch (ClassNotFoundException e) {
404
                                        logger.error(Messages.getString(
405
                                                        "Launcher.No_se_encontro_la_clase_mdi_manager"), e);
406
                                        throw new MDIManagerLoadException(e);
407
                                } catch (InstantiationException e) {
408
                                        logger.error(Messages.getString(
409
                                                        "Launcher.No_se_pudo_instanciar_la_clase_mdi_manager"),
410
                                                e);
411
                                        throw new MDIManagerLoadException(e);
412
                                } catch (IllegalAccessException e) {
413
                                        logger.error(Messages.getString(
414
                                                        "Launcher.No_se_pudo_acceder_a_la_clase_mdi_manager"),
415
                                                e);
416
                                        throw new MDIManagerLoadException(e);
417
                                }
418
                        }
419
                }
420
        }
421

    
422
        /**
423
         *
424
         */
425
        private static void frameIcon() {
426
                Iterator i = pluginsConfig.keySet().iterator();
427

    
428
                while (i.hasNext()) {
429
                        String pName = (String) i.next();
430
                        PluginConfig pc = (PluginConfig) pluginsConfig.get(pName);
431
                        PluginServices ps = (PluginServices) pluginsServices.get(pName);
432

    
433
                        if (pc.getIcon() != null) {
434
                                ImageIcon icon = new ImageIcon(ps.getClassLoader().getResource(pc.getIcon()
435
                                                                                                                                                                 .getSrc()));
436
                                frame.setIconImage(icon.getImage());
437
                                frame.setTitlePrefix(pc.getIcon().getText());
438
                        }
439
                }
440
        }
441

    
442
        /**
443
         *
444
         */
445
        private static void initializeExtensions() {
446
                Iterator i = pluginsOrdered.iterator();
447

    
448
                while (i.hasNext()) {
449
                        String pName = (String) i.next();
450
            logger.debug("Initializing extensions from " + pName);
451
                        PluginConfig pc = (PluginConfig) pluginsConfig.get(pName);
452
                        PluginServices ps = (PluginServices) pluginsServices.get(pName);
453

    
454
                        Extension[] exts = pc.getExtensions().getExtension();
455

    
456
                        TreeMap orderedExtensions = new TreeMap(new ExtensionComparator());
457

    
458
                        for (int j = 0; j < exts.length; j++) {
459
                                if (!exts[j].getActive()) {
460
                                        continue;
461
                                }
462

    
463
                                if (orderedExtensions.containsKey(exts[j])) {
464
                                        logger.warn(Messages.getString(
465
                                                        "Launcher.Two_extensions_with_the_same_priority") +
466
                                                exts[j].getClassName());
467
                                }
468

    
469
                                orderedExtensions.put(exts[j], null);
470
                        }
471

    
472
                        Iterator e = orderedExtensions.keySet().iterator();
473

    
474
                        while (e.hasNext()) {
475
                                Extension extension = (Extension) e.next();
476
                                com.iver.andami.plugins.Extension extensionInstance;
477

    
478
                                try {
479
                                        Class extensionClass = ps.getClassLoader().loadClass(extension.getClassName());
480
                                        extensionInstance = (com.iver.andami.plugins.Extension) extensionClass.newInstance();
481
                                        
482
                                        // CON DECORATOR                                        
483
                                        // ANTES: classesExtensions.put(extensionClass, extensionInstance);
484
                                        // AHORA: CREAMOS UNA ExtensionDecorator y asignamos esta instancia para
485
                                        // poder ampliar con nuevas propiedades (AlwaysVisible, por ejemplo)
486
                                        // Para crear la nueva clase ExtensionDecorator, le pasamos como par?metro
487
                                        // la extensi?n original que acabamos de crear
488
                                        // 0-> Inactivo, controla la extension
489
                                        // 1-> Siempre visible
490
                                        // 2-> Invisible
491
                                        ExtensionDecorator newExtensionDecorator = new ExtensionDecorator(extensionInstance, ExtensionDecorator.INACTIVE);
492
                                        classesExtensions.put(extensionClass, newExtensionDecorator);
493
                                        System.err.println("Loading "+extension.getClassName()+"...");
494
                    // logger.debug("Initializing " + extension.getClassName());
495
                    extensionInstance.inicializar();
496
                    // logger.debug(extension.getClassName() + " initialized.");
497

    
498
                                } catch (InstantiationException e1) {
499
                                        logger.error(Messages.getString(
500
                                                        "Launcher.Error_instanciando_la_extension") +
501
                                                extension.getClassName(), e1);
502
                                } catch (IllegalAccessException e1) {
503
                                        logger.error(Messages.getString(
504
                                                        "Launcher.Error_instanciando_la_extension") +
505
                                                extension.getClassName(), e1);
506
                                } catch (ClassNotFoundException e1) {
507
                                        logger.error(Messages.getString(
508
                                                        "Launcher.No_se_encontro_la_clase_de_la_extension") +
509
                                                extension.getClassName(), e1);
510
                                } catch (NoClassDefFoundError e1) {
511
                                        logger.error(Messages.getString(
512
                                                        "Launcher.Error_localizando_la_clase_de_la_extension") +
513
                                                extension.getClassName(), e1);
514
                                }
515
                        }
516
                }
517
        }
518

    
519
        /**
520
         * DOCUMENT ME!
521
         */
522
        private static void installPluginsMenus() {
523
                TreeMap orderedMenus = new TreeMap(new MenuComparator());
524

    
525
                Iterator i = pluginsConfig.keySet().iterator();
526

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

    
532
                        Extension[] exts = pc.getExtensions().getExtension();
533

    
534
                        for (int j = 0; j < exts.length; j++) {
535
                                if (!exts[j].getActive()) {
536
                                        continue;
537
                                }
538

    
539
                                Menu[] menus = exts[j].getMenu();
540

    
541
                                for (int k = 0; k < menus.length; k++) {
542
                                        SortableMenu sm = new SortableMenu(ps.getClassLoader(),
543
                                                        exts[j], menus[k]);
544

    
545
                                        if (orderedMenus.containsKey(sm)) {
546
                                                logger.error(Messages.getString(
547
                                                                "Launcher.Two_menus_with_the_same_position") +
548
                                                        exts[j].getClassName());
549
                                        }
550

    
551
                                        orderedMenus.put(sm, null);
552
                                }
553
                        }
554

    
555
                        // Se instalan las extensiones de MDI
556
                        SkinExtension skinExt = pc.getExtensions().getSkinExtension();
557

    
558
                        if (skinExt != null) {
559
                                Menu[] menu = skinExt.getMenu();
560

    
561
                                for (int k = 0; k < menu.length; k++) {
562
                                        SortableMenu sm = new SortableMenu(ps.getClassLoader(),
563
                                                        skinExt, menu[k]);
564

    
565
                                        if (orderedMenus.containsKey(sm)) {
566
                                                logger.error(Messages.getString(
567
                                                                "Launcher.Two_menus_with_the_same_position") +
568
                                                        skinExt.getClassName());
569
                                        }
570

    
571
                                        orderedMenus.put(sm, null);
572
                                }
573
                        }
574
                }
575

    
576
                //Se itera por los menus ordenados
577
                Iterator e = orderedMenus.keySet().iterator();
578

    
579
                // Se ordenan los menues
580
                while (e.hasNext()) {
581
                        try {
582
                                SortableMenu sm = (SortableMenu) e.next();
583

    
584
                                frame.addMenu(sm.loader, sm.extension, sm.menu);
585
                        } catch (ClassNotFoundException ex) {
586
                                logger.error(Messages.getString(
587
                                                "Launcher.No_se_encontro_la_clase_de_la_extension"), ex);
588
                        }
589
                }
590
        }
591

    
592
        /**
593
         *
594
         */
595
        private static void installPluginsControls() {
596
                Iterator i = pluginsConfig.keySet().iterator();
597

    
598
                HashMap extensionPluginServices = new HashMap();
599
                HashMap extensionPluginConfig = new HashMap();
600
                TreeMap orderedExtensions = new TreeMap(new ExtensionComparator());
601
                while (i.hasNext()) {
602
                                String pName = (String) i.next();
603
                                PluginConfig pc = (PluginConfig) pluginsConfig.get(pName);
604
                                PluginServices ps = (PluginServices) pluginsServices.get(pName);
605

    
606
                                Extension[] exts = pc.getExtensions().getExtension();
607

    
608
                                for (int j = 0; j < exts.length; j++) {
609
                                        if (exts[j].getActive()) {
610
                                                if (orderedExtensions.containsKey(exts[j])) {
611
                                                        logger.error(Messages.getString(
612
                                                                        "Launcher.Two_extensions_with_the_same_priority") +
613
                                                                exts[j].getClassName());
614
                                                }
615

    
616
                                                orderedExtensions.put(exts[j], null);
617
                                                extensionPluginServices.put(exts[j], ps);
618
                                                extensionPluginConfig.put(exts[j], pc);
619
                                        }
620
                                }
621
                }
622

    
623
                ///try {
624
                        TreeMap orderedToolBars = new TreeMap(new ToolBarComparator());
625
                        Iterator e = orderedExtensions.keySet().iterator();
626

    
627
                        // Se instalan las extensiones
628
                        while (e.hasNext()) {
629
                                Extension ext = (Extension) e.next();
630

    
631
                                ToolBar[] toolbars = ext.getToolBar();
632

    
633
                                for (int k = 0; k < toolbars.length; k++) {
634
                                        ActionTool[] tools = toolbars[k].getActionTool();
635

    
636
                                        for (int t = 0; t < tools.length; t++) {
637
                                                SortableToolBar sm = new SortableToolBar(((PluginServices)extensionPluginServices.get(ext)).getClassLoader(), ext,
638
                                                                toolbars[k], tools[t]);
639
                                                orderedToolBars.put(sm, null);
640
                                                ///frame.addTool(((PluginServices)extensionPluginServices.get(ext)).getClassLoader(), ext,
641
                                                ///        toolbars[k], tools[t]);
642
                                        }
643

    
644
                                        SelectableTool[] sTools = toolbars[k].getSelectableTool();
645

    
646
                                        for (int t = 0; t < sTools.length; t++) {
647
                                                SortableToolBar sm=new SortableToolBar(((PluginServices)extensionPluginServices.get(ext)).getClassLoader(), ext,
648
                                                                toolbars[k], sTools[t]);
649
                                                orderedToolBars.put(sm, null);
650
                                                ///frame.addTool(((PluginServices)extensionPluginServices.get(ext)).getClassLoader(), ext,
651
                                                ///        toolbars[k], sTools[t]);
652
                                        }
653
                                }
654
                        }
655

    
656
                        i = pluginsConfig.keySet().iterator();
657
                        while (i.hasNext()) {
658
                                String pName = (String) i.next();
659
                                PluginConfig pc = (PluginConfig) pluginsConfig.get(pName);
660
                                PluginServices ps = (PluginServices) pluginsServices.get(pName);
661
                                // Se instalan las extensiones de MDI
662
                                SkinExtension skinExt = pc.getExtensions().getSkinExtension();
663
        
664
                                if (skinExt != null) {
665
                                        ToolBar[] toolbars = skinExt.getToolBar();
666
        
667
                                        for (int k = 0; k < toolbars.length; k++) {
668
                                                ActionTool[] tools = toolbars[k].getActionTool();
669
        
670
                                                for (int t = 0; t < tools.length; t++) {
671
                                                        SortableToolBar stb=new SortableToolBar(ps.getClassLoader(), skinExt,
672
                                                                        toolbars[k], tools[t]);
673
                                                        orderedToolBars.put(stb,null);
674
                                                        ///frame.addTool(ps.getClassLoader(), skinExt,
675
                                                        ///        toolbars[k], tools[t]);
676
                                                }
677
        
678
                                                SelectableTool[] sTools = toolbars[k].getSelectableTool();
679
        
680
                                                for (int t = 0; t < sTools.length; t++) {
681
                                                        SortableToolBar stb=new SortableToolBar(ps.getClassLoader(), skinExt,
682
                                                                        toolbars[k], sTools[t]);
683
                                                        orderedToolBars.put(stb,null);
684
                                                        ///frame.addTool(ps.getClassLoader(), skinExt,
685
                                                        ///        toolbars[k], sTools[t]);
686
                                                }
687
                                        }
688
        
689
                                        /*
690
                                           Menu[] menu = skinExt.getMenu();
691
                                           for (int k = 0; k < menu.length; k++) {
692
                                               frame.addMenu(ps.getClassLoader(), skinExt, menu[k]);
693
                                           }
694
                                         */
695
                                }
696
                                //Se instalan los popup menus
697
                                PopupMenus pus = pc.getPopupMenus();
698

    
699
                                if (pus != null) {
700
                                        PopupMenu[] menus = pus.getPopupMenu();
701

    
702
                                        for (int j = 0; j < menus.length; j++) {
703
                                                frame.addPopupMenu(ps.getClassLoader(), menus[j]);
704
                                        }
705
                                }
706
                        }
707
//                        Se itera por los menus ordenados
708
                        Iterator t = orderedToolBars.keySet().iterator();
709

    
710
                        // Se ordenan los menues
711
                        while (t.hasNext()) {
712
                                try {
713
                                        SortableToolBar stb = (SortableToolBar) t.next();
714
                                        if (stb.actiontool!=null)
715
                                                frame.addTool(stb.loader, stb.extension,stb.toolbar, stb.actiontool);
716
                                        else
717
                                                frame.addTool(stb.loader, stb.extension,stb.toolbar, stb.selectabletool);
718
                                } catch (ClassNotFoundException ex) {
719
                                        logger.error(Messages.getString(
720
                                                        "Launcher.No_se_encontro_la_clase_de_la_extension"), ex);
721
                                }
722
                        }
723
                ///} catch (ClassNotFoundException e) {
724
                ///        logger.error(Messages.getString(
725
                ///                        "Launcher.No_se_encontro_la_clase_de_la_extension"), e);
726
                ///}
727
        }
728

    
729
        /**
730
         *
731
         */
732
        private static void updateAndamiConfig() {
733
                HashSet olds = new HashSet();
734

    
735
                Plugin[] plugins = andamiConfig.getPlugin();
736

    
737
                for (int i = 0; i < plugins.length; i++) {
738
                        olds.add(plugins[i].getName());
739
                }
740

    
741
                Iterator i = pluginsServices.values().iterator();
742

    
743
                while (i.hasNext()) {
744
                        PluginServices ps = (PluginServices) i.next();
745

    
746
                        if (!olds.contains(ps.getPluginName())) {
747
                                Plugin p = new Plugin();
748
                                p.setName(ps.getPluginName());
749
                                p.setUpdate(false);
750

    
751
                                andamiConfig.addPlugin(p);
752
                        }
753
                }
754
        }
755

    
756
        /**
757
         * DOCUMENT ME!
758
         */
759
        private static void pluginsClassLoaders() {
760
                HashSet instalados = new HashSet();
761

    
762
                // Se itera hasta que est?n todos instalados
763
                while (instalados.size() != pluginsConfig.size()) {
764
                        boolean circle = true;
765

    
766
                        //Hacemos una pasada por todos los plugins
767
                        Iterator i = pluginsConfig.keySet().iterator();
768

    
769
                        while (i.hasNext()) {
770
                                String pluginName = (String) i.next();
771
                                PluginConfig config = (PluginConfig) pluginsConfig.get(pluginName);
772

    
773
                                if (instalados.contains(pluginName)) {
774
                                        continue;
775
                                }
776

    
777
                                //Se obtienen las dependencias y sus class loaders
778
                                boolean ready = true;
779
                                Depends[] dependencies = config.getDepends();
780
                                PluginClassLoader[] loaders = new PluginClassLoader[dependencies.length];
781

    
782
                                for (int j = 0; j < dependencies.length; j++) {
783
                                        if (pluginsConfig.get(dependencies[j].getPluginName()) == null) {
784
                                                logger.error(Messages.getString(
785
                                                                "Launcher.Dependencia_no_resuelta_en_plugin") +
786
                                                        pluginName + ": " +
787
                                                        dependencies[j].getPluginName());
788

    
789
                                                continue;
790
                                        }
791

    
792
                                        if (!instalados.contains(dependencies[j].getPluginName())) {
793
                                                ready = false;
794
                                        } else {
795
                                                loaders[j] = ((PluginServices) pluginsServices.get(dependencies[j].getPluginName())).getClassLoader();
796
                                        }
797
                                }
798

    
799
                                //Si no est?n sus dependencias satisfechas se aborta la instalaci?n
800
                                if (!ready) {
801
                                        continue;
802
                                }
803

    
804
                                //Se genera el class loader
805
                                String jardir = config.getLibraries().getLibraryDir();
806
                                File jarDir = new File(andamiConfig.getPluginsDirectory() +
807
                                                File.separator + pluginName + File.separator + jardir);
808
                                File[] jarFiles = jarDir.listFiles(new FileFilter() {
809
                                                        public boolean accept(File pathname) {
810
                                                                return (pathname.getName().toUpperCase()
811
                                                                                                .endsWith(".JAR")) ||
812
                                                                (pathname.getName().toUpperCase().endsWith(".ZIP"));
813
                                                        }
814
                                                });
815

    
816
                                URL[] urls = new URL[jarFiles.length];
817

    
818
                                for (int j = 0; j < jarFiles.length; j++) {
819
                                        try {
820
                                                urls[j] = new URL("file:" + jarFiles[j]);
821
                                        } catch (MalformedURLException e) {
822
                                                logger.error(Messages.getString(
823
                                                                "Launcher.No_se_puede_acceder_a") +
824
                                                        jarFiles[j]);
825
                                        }
826
                                }
827

    
828
                                PluginClassLoader loader;
829

    
830
                                try {
831
                                        loader = new PluginClassLoader(urls,
832
                                                        andamiConfig.getPluginsDirectory() +
833
                                                        File.separator + pluginName,
834
                                                        Launcher.class.getClassLoader(), loaders);
835

    
836
                                        PluginServices ps = new PluginServices(loader);
837

    
838
                                        pluginsServices.put(ps.getPluginName(), ps);
839

    
840
                                        instalados.add(pluginName);
841
                    // FJP: Los metemos ordenados para luego no cargar uno que necesita de otro antes de tiempo. Esto lo usaremos al 
842
                    // inicializar los plugins
843
                    pluginsOrdered.add(pluginName);
844

    
845
                                        circle = false;
846
                                } catch (IOException e) {
847
                                        logger.error(Messages.getString(
848
                                                        "Launcher.Error_con_las_librerias_del_plugin"), e);
849
                                        pluginsConfig.remove(pluginName);
850
                                        i = pluginsConfig.keySet().iterator();
851
                                }
852
                        }
853

    
854
                        if (circle) {
855
                                logger.error(Messages.getString(
856
                                                "Launcher.Hay_dependencias_circulares"));
857

    
858
                                break;
859
                        }
860
                }
861

    
862
                //Se eliminan los plugins que no fueron instalados
863
                Iterator i = pluginsConfig.keySet().iterator();
864

    
865
                while (i.hasNext()) {
866
                        String pluginName = (String) i.next();
867
                        PluginConfig config = (PluginConfig) pluginsConfig.get(pluginName);
868
                        PluginServices ps = (PluginServices) pluginsServices.get(pluginName);
869

    
870
                        if (ps == null) {
871
                                pluginsConfig.remove(pluginName);
872
                                i = pluginsConfig.keySet().iterator();
873
                        }
874
                } 
875
        }
876

    
877
        /**
878
         * DOCUMENT ME!
879
         */
880
        private static void pluginsMessages() {
881
                //Iteramos por todos los plugins
882
                Iterator i = pluginsConfig.keySet().iterator();
883

    
884
                while (i.hasNext()) {
885
                        String pluginName = (String) i.next();
886
                        PluginConfig config = (PluginConfig) pluginsConfig.get(pluginName);
887

    
888
                        PluginServices ps = (PluginServices) pluginsServices.get(pluginName);
889

    
890
                        if (config.getResourceBundle() != null) {
891
                                ps.setResourceBundle(config.getResourceBundle().getName(),
892
                                        locale);
893
                        }
894
                }
895
        }
896

    
897
        /**
898
         * DOCUMENT ME!
899
         *
900
         * @param name DOCUMENT ME!
901
         *
902
         * @return DOCUMENT ME!
903
         */
904
        static PluginServices getPluginServices(String name) {
905
                return (PluginServices) pluginsServices.get(name);
906
        }
907

    
908
        /**
909
         * DOCUMENT ME!
910
         *
911
         * @return DOCUMENT ME!
912
         */
913
        static String getPluginsDir() {
914
                return andamiConfig.getPluginsDirectory();
915
        }
916

    
917
        /**
918
         * DOCUMENT ME!
919
         *
920
         * @param s DOCUMENT ME!
921
         */
922
        static void setPluginsDir(String s) {
923
                andamiConfig.setPluginsDirectory(s);
924
        }
925

    
926
        /**
927
         * DOCUMENT ME!
928
         *
929
         * @return DOCUMENT ME!
930
         */
931
        static MDIFrame getMDIFrame() {
932
                return frame;
933
        }
934

    
935
        /**
936
         * DOCUMENT ME!
937
         *
938
         * @param pluginsDirectory
939
         */
940
        private static void loadPlugins(String pluginsDirectory) {
941
                File pDir = new File(pluginsDirectory);
942

    
943
                if (!pDir.exists()) {
944
                        return;
945
                }
946

    
947
                File[] pluginDirs = pDir.listFiles();
948

    
949
                for (int i = 0; i < pluginDirs.length; i++) {
950
                        if (pluginDirs[i].isDirectory()) {
951
                                File configXml = new File(pluginDirs[i].getAbsolutePath() +
952
                                                File.separator + "config.xml");
953

    
954
                                try {
955
                                        FileReader xml = new FileReader(configXml);
956
                                        PluginConfig pConfig = (PluginConfig) PluginConfig.unmarshal(xml);
957
                                        pluginsConfig.put(pluginDirs[i].getName(), pConfig);
958
                                } catch (FileNotFoundException e) {
959
                                        logger.info(Messages.getString(
960
                                                        "Launcher.Ignorando_el_directorio") +
961
                                                pluginDirs[i].getAbsolutePath() +
962
                                                Messages.getString("Launcher.config_no_encontrado"));
963
                                } catch (MarshalException e) {
964
                                        logger.info(Messages.getString(
965
                                                        "Launcher.Ignorando_el_directorio") +
966
                                                pluginDirs[i].getAbsolutePath() +
967
                                                Messages.getString("Launcher.config_mal_formado"), e);
968
                                } catch (ValidationException e) {
969
                                        logger.info(Messages.getString(
970
                                                        "Launcher.Ignorando_el_directorio") +
971
                                                pluginDirs[i].getAbsolutePath() +
972
                                                Messages.getString("Launcher.config_mal_formado"), e);
973
                                }
974
                        }
975
                }
976
        }
977

    
978
        /**
979
         * DOCUMENT ME!
980
         *
981
         * @param language
982
         * @param country
983
         * @param variant
984
         *
985
         * @return DOCUMENT ME!
986
         */
987
        private static Locale getLocale(String language, String country,
988
                String variant) {
989
                if (variant != null) {
990
                        return new Locale(language, country, variant);
991
                } else if (country != null) {
992
                        return new Locale(language, country);
993
                } else if (language != null) {
994
                        return new Locale(language);
995
                } else {
996
                        return new Locale("es");
997
                }
998
        }
999

    
1000
        /**
1001
         * DOCUMENT ME!
1002
         *
1003
         * @param file DOCUMENT ME!
1004
         *
1005
         * @throws IOException DOCUMENT ME!
1006
         * @throws MarshalException DOCUMENT ME!
1007
         * @throws ValidationException DOCUMENT ME!
1008
         */
1009
        private static void andamiConfigToXML(String file)
1010
                throws IOException, MarshalException, ValidationException {
1011
                File xml = new File(file);
1012
                File parent = xml.getParentFile();
1013
                parent.mkdirs();
1014

    
1015
                FileWriter writer = new FileWriter(xml);
1016
                andamiConfig.marshal(writer);
1017
        }
1018

    
1019
        /**
1020
         * DOCUMENT ME!
1021
         *
1022
         * @param file DOCUMENT ME!
1023
         *
1024
         * @throws ConfigurationException DOCUMENT ME!
1025
         */
1026
        private static void andamiConfigFromXML(String file)
1027
                throws ConfigurationException {
1028
                File xml = new File(file);
1029

    
1030
                //Si no existe se ponen los valores por defecto
1031
                if (!xml.exists()) {
1032
                        andamiConfig = new AndamiConfig();
1033

    
1034
                        Andami andami = new Andami();
1035
                        andami.setUpdate(true);
1036
                        andamiConfig.setAndami(andami);
1037
                        andamiConfig.setLocaleCountry(Locale.getDefault().getCountry());
1038
                        andamiConfig.setLocaleLanguage(Locale.getDefault().getLanguage());
1039
                        andamiConfig.setLocaleVariant(Locale.getDefault().getVariant());
1040

    
1041
                        if (System.getProperty("javawebstart.version") != null) // Es java web start)
1042
                         {
1043
                                andamiConfig.setPluginsDirectory(new File(System.getProperty(
1044
                                                        "user.home") + File.separator + appName +
1045
                                                File.separator + "extensiones").getAbsolutePath());
1046
                        } else {
1047
                                andamiConfig.setPluginsDirectory(new File(appName +
1048
                                                File.separator + "extensiones").getAbsolutePath());
1049
                        }
1050

    
1051
                        andamiConfig.setPlugin(new Plugin[0]);
1052
                } else {
1053
                        //Se lee la configuraci?n
1054
                        FileReader reader;
1055

    
1056
                        try {
1057
                                reader = new FileReader(xml);
1058
                                andamiConfig = (AndamiConfig) AndamiConfig.unmarshal(reader);
1059
                        } catch (FileNotFoundException e) {
1060
                                throw new ConfigurationException(e);
1061
                        } catch (MarshalException e) {
1062
                                throw new ConfigurationException(e);
1063
                        } catch (ValidationException e) {
1064
                                throw new ConfigurationException(e);
1065
                        }
1066
                }
1067
        }
1068

    
1069
        /**
1070
         * DOCUMENT ME!
1071
         *
1072
         * @return DOCUMENT ME!
1073
         *
1074
         * @throws ConfigurationException DOCUMENT ME!
1075
         */
1076
        private static XMLEntity persistenceFromXML() throws ConfigurationException {
1077
                File xml = new File(pluginsPersistencePath);
1078

    
1079
                if (xml.exists()) {
1080
                        FileReader reader;
1081

    
1082
                        try {
1083
                                reader = new FileReader(xml);
1084

    
1085
                                XmlTag tag = (XmlTag) XmlTag.unmarshal(reader);
1086

    
1087
                                return new XMLEntity(tag);
1088
                        } catch (FileNotFoundException e) {
1089
                                throw new ConfigurationException(e);
1090
                        } catch (MarshalException e) {
1091
                                throw new ConfigurationException(e);
1092
                        } catch (ValidationException e) {
1093
                                throw new ConfigurationException(e);
1094
                        }
1095
                } else {
1096
                        return new XMLEntity();
1097
                }
1098
        }
1099

    
1100
        /**
1101
         * DOCUMENT ME!
1102
         *
1103
         * @param entity DOCUMENT ME!
1104
         *
1105
         * @throws ConfigurationException DOCUMENT ME!
1106
         */
1107
        private static void persistenceToXML(XMLEntity entity)
1108
                throws ConfigurationException {
1109
                File xml = new File(pluginsPersistencePath);
1110

    
1111
                FileWriter writer;
1112

    
1113
                try {
1114
                        writer = new FileWriter(xml);
1115
                        entity.getXmlTag().marshal(writer);
1116
                } catch (FileNotFoundException e) {
1117
                        throw new ConfigurationException(e);
1118
                } catch (MarshalException e) {
1119
                        throw new ConfigurationException(e);
1120
                } catch (ValidationException e) {
1121
                        throw new ConfigurationException(e);
1122
                } catch (IOException e) {
1123
                        throw new ConfigurationException(e);
1124
                }
1125
        }
1126

    
1127
        /**
1128
         * Devuelve un array con los directorios de los plugins
1129
         *
1130
         * @param dirExt Directorio de las extensiones a partir del cual cuelgan
1131
         *                   todos los directorios de los plugins
1132
         *
1133
         * @return ArrayList con los directorios
1134
         */
1135
        private String[] getLocales(File dirExt) {
1136
                ArrayList types = new ArrayList();
1137
                File[] files = dirExt.listFiles();
1138

    
1139
                for (int i = 0; i < files.length; i++) {
1140
                        if (files[i].isDirectory()) {
1141
                                File[] textFile = files[i].listFiles(new FilenameFilter() {
1142
                                                        public boolean accept(File dir, String fileName) {
1143
                                                                return fileName.toLowerCase().startsWith("text_"); //$NON-NLS-1$
1144
                                                        }
1145
                                                });
1146

    
1147
                                for (int j = 0; j < textFile.length; j++) {
1148
                                        String s = (textFile[j]).getName().replaceAll("text_", "");
1149
                                        s = s.replaceAll(".properties", "");
1150
                                        s = s.trim();
1151

    
1152
                                        if (!types.contains(s)) {
1153
                                                types.add(s);
1154
                                        }
1155
                                }
1156
                        }
1157
                }
1158

    
1159
                return (String[]) types.toArray(new String[0]);
1160
        }
1161

    
1162
        /**
1163
         * DOCUMENT ME!
1164
         *
1165
         * @return Returns the frame.
1166
         */
1167
        static MDIFrame getFrame() {
1168
                return frame;
1169
        }
1170

    
1171
        /**
1172
         * Secuencia de cerrado de Andami
1173
         */
1174
        public static void closeApplication() {
1175
                //Configuraci?n de Andami
1176
                try {
1177
                        andamiConfigToXML(andamiConfigPath);
1178
                } catch (MarshalException e) {
1179
                        logger.error(Messages.getString(
1180
                                        "Launcher.No_se_pudo_guardar_la_configuracion_de_andami"), e);
1181
                } catch (ValidationException e) {
1182
                        logger.error(Messages.getString(
1183
                                        "Launcher.No_se_pudo_guardar_la_configuracion_de_andami"), e);
1184
                } catch (IOException e) {
1185
                        logger.error(Messages.getString(
1186
                                        "Launcher.No_se_pudo_guardar_la_configuracion_de_andami"), e);
1187
                }
1188

    
1189
                //Persistencia de los plugins
1190
                Iterator i = pluginsConfig.keySet().iterator();
1191

    
1192
                XMLEntity entity = new XMLEntity();
1193

    
1194
                while (i.hasNext()) {
1195
                        String pName = (String) i.next();
1196
                        PluginServices ps = (PluginServices) pluginsServices.get(pName);
1197
                        XMLEntity ent = ps.getPersistentXML();
1198

    
1199
                        if (ent != null) {
1200
                                ent.putProperty("com.iver.andami.pluginName", pName);
1201
                                entity.addChild(ent);
1202
                        }
1203
                }
1204

    
1205
                try {
1206
                        persistenceToXML(entity);
1207
                } catch (ConfigurationException e1) {
1208
                        logger.error(Messages.getString(
1209
                                        "Launcher.Se_produjo_un_error_guardando_la_configuracion_de_los_plugins"),
1210
                                e1);
1211
                }
1212

    
1213
                //Para la depuraci?n de memory leaks
1214
                System.gc();
1215

    
1216
        System.exit(0);
1217
        }
1218

    
1219
        /**
1220
         * DOCUMENT ME!
1221
         *
1222
         * @return DOCUMENT ME!
1223
         */
1224
        static HashMap getClassesExtensions() {
1225
                return classesExtensions;
1226
        }
1227

    
1228
        /**
1229
         * DOCUMENT ME!
1230
         *
1231
         * @param extDir DOCUMENT ME!
1232
         */
1233
        private static void downloadExtensions(String extDir) {
1234
                java.util.Date fechaActual = null;
1235

    
1236
                try {
1237
                        if (System.getProperty("javawebstart.version") != null) {
1238
                                //Obtenemos la URL del servidor
1239
                                BasicService bs = (BasicService) ServiceManager.lookup(
1240
                                                "javax.jnlp.BasicService");
1241
                                URL baseURL = bs.getCodeBase();
1242

    
1243
                                //Se descargan las extensiones
1244
                                SplashWindow.process(5,
1245
                                        "Descargando las extensiones desde " + baseURL + " a " +
1246
                                        extDir);
1247

    
1248
                                URL url = new URL(baseURL + "extensiones.zip");
1249
                                URLConnection connection = url.openConnection();
1250

    
1251
                                System.out.println(url.toExternalForm() + ":");
1252
                                System.out.println("  Content Type: " +
1253
                                        connection.getContentType());
1254
                                System.out.println("  Content Length: " +
1255
                                        connection.getContentLength());
1256
                                System.out.println("  Last Modified: " +
1257
                                        new Date(connection.getLastModified()));
1258
                                System.out.println("  Expiration: " +
1259
                                        connection.getExpiration());
1260
                                System.out.println("  Content Encoding: " +
1261
                                        connection.getContentEncoding());
1262

    
1263
                                // Guardamos la fecha del fichero de extensiones que nos hemos bajado, y
1264
                                // comprobamos el ?ltimo que se ha bajado. Si no son
1265
                                // iguales, nos bajamos el nuevo. Si son iguales, no
1266
                                // nos bajamos nada.
1267
                                Long miliSecondsInWeb = new Long(connection.getLastModified());
1268

    
1269
                                // PluginServices ps = PluginServices.getPluginServices("com.iver.core");
1270
                                // if (ps.getPersistentXML().getStringProperty("timestamp") != null)
1271
                                File destDir = new File(extDir);
1272

    
1273
                                if (!destDir.exists()) {
1274
                                        // Creamos gvSIG
1275
                                        destDir.getParentFile().mkdir();
1276

    
1277
                                        if (!destDir.mkdir()) {
1278
                                                System.err.println("Imposible crear el directorio " +
1279
                                                        destDir.getAbsolutePath());
1280
                                        }
1281
                                }
1282

    
1283
                                File timeFile = new File(destDir.getParent() + File.separator +
1284
                                                "timeStamp.properties");
1285

    
1286
                                if (!timeFile.exists()) {
1287
                                        timeFile.createNewFile();
1288
                                }
1289

    
1290
                                FileInputStream inAux = new FileInputStream(timeFile);
1291
                                Properties prop = new Properties();
1292
                                prop.load(inAux);
1293
                                inAux.close();
1294

    
1295
                                if (prop.getProperty("timestamp") != null) {
1296
                                        Long lastMiliSeconds = (Long) new Long(prop.getProperty(
1297
                                                                "timestamp"));
1298

    
1299
                                        if (lastMiliSeconds.longValue() == miliSecondsInWeb.longValue()) {
1300
                                                System.out.println("No hay nueva actualizaci?n");
1301

    
1302
                                                return;
1303
                                        }
1304

    
1305
                                        System.out.println("timeStampWeb= " + miliSecondsInWeb);
1306
                                        System.out.println("timeStampLocal= " + lastMiliSeconds);
1307
                                } else {
1308
                                        System.out.println("El timeStamp no est? escrito en " +
1309
                                                timeFile.getAbsolutePath());
1310
                                }
1311

    
1312
                                InputStream stream = connection.getInputStream();
1313
                                File temp = File.createTempFile("gvsig", ".zip");
1314
                                temp.deleteOnExit();
1315

    
1316
                                FileOutputStream file = new FileOutputStream(temp);
1317
                                BufferedInputStream in = new BufferedInputStream(stream);
1318
                                BufferedOutputStream out = new BufferedOutputStream(file);
1319

    
1320
                                int i;
1321
                                int pct;
1322
                                int desde;
1323
                                int hasta;
1324

    
1325
                                hasta = connection.getContentLength() / 1024;
1326
                                desde = 0;
1327

    
1328
                                while ((i = in.read()) != -1) {
1329
                                        pct = ((desde / 1024) * 100) / hasta;
1330

    
1331
                                        if (((desde % 10240) == 0) && (pct > 10) &&
1332
                                                        ((pct % 10) == 0)) {
1333
                                                SplashWindow.process(pct,
1334
                                                        (desde / 1024) + "Kb de " + hasta +
1335
                                                        "Kb descargados...");
1336
                                        }
1337

    
1338
                                        out.write(i);
1339
                                        desde++;
1340
                                }
1341

    
1342
                                out.flush();
1343
                                out.close();
1344
                                in.close();
1345

    
1346
                                //Se extrae el zip
1347
                                SplashWindow.process(5, "Extensiones descargadas.");
1348

    
1349
                                System.out.println("Extrayendo a " + destDir.getAbsolutePath());
1350

    
1351
                                Date fechaDir = new Date(destDir.lastModified());
1352
                                System.out.println("Fecha del directorio " + extDir + " = " +
1353
                                        fechaDir.toString());
1354
                                Utilities.extractTo(temp, new File(extDir), splashWindow);
1355

    
1356
                                // Si todo ha ido bien, guardamos el timestamp.
1357
                                ///  App.instance.getPc().addProperties("timestamp", miliSecondsInWeb);
1358
                                // XMLEntity xml=ps.getPersistentXML();
1359
                                fechaActual = new java.util.Date();
1360

    
1361
                                FileOutputStream outAux = new FileOutputStream(timeFile);
1362
                                prop.setProperty("timestamp", miliSecondsInWeb.toString());
1363
                                prop.store(outAux, "last download");
1364
                                outAux.close();
1365
                                System.out.println("Fecha actual guardada: " +
1366
                                        fechaActual.toGMTString());
1367

    
1368
                                /* xml.putProperty("timestamp",fechaActual.toGMTString());
1369
                                   ps.setPresistentXML(xml); */
1370
                        }
1371
                } catch (IOException e) {
1372
                        NotificationManager.addError("", e);
1373
                } catch (UnavailableServiceException e) {
1374
                        NotificationManager.addError("", e);
1375
                } catch (SecurityException e) {
1376
                        System.err.println("No se puede escribir el timeStamp " +
1377
                                fechaActual.toGMTString());
1378
                        NotificationManager.addError("", e);
1379
                }
1380
        }
1381

    
1382
        /**
1383
         * DOCUMENT ME!
1384
         *
1385
         * @return DOCUMENT ME!
1386
         */
1387
        private static Extensions[] getExtensions() {
1388
                ArrayList array = new ArrayList();
1389
                Iterator iter = pluginsConfig.values().iterator();
1390

    
1391
                while (iter.hasNext()) {
1392
                        array.add(((PluginConfig) iter.next()).getExtensions());
1393
                }
1394

    
1395
                return (Extensions[]) array.toArray(new Extensions[0]);
1396
        }
1397

    
1398
        /**
1399
         * DOCUMENT ME!
1400
         *
1401
         * @return DOCUMENT ME!
1402
         */
1403
        public static HashMap getPluginConfig() {
1404
                return pluginsConfig;
1405
        }
1406

    
1407
        /**
1408
         * DOCUMENT ME!
1409
         *
1410
         * @param s DOCUMENT ME!
1411
         *
1412
         * @return DOCUMENT ME!
1413
         */
1414
        public static Extension getExtension(String s) {
1415
                Extensions[] exts = getExtensions();
1416

    
1417
                for (int i = 0; i < exts.length; i++) {
1418
                        for (int j = 0; j < exts[i].getExtensionCount(); j++) {
1419
                                if (exts[i].getExtension(j).getClassName().equals(s)) {
1420
                                        return exts[i].getExtension(j);
1421
                                }
1422
                        }
1423
                }
1424

    
1425
                return null;
1426
        }
1427

    
1428
        /**
1429
         * DOCUMENT ME!
1430
         *
1431
         * @return DOCUMENT ME!
1432
         */
1433
        public static AndamiConfig getAndamiConfig() {
1434
                return andamiConfig;
1435
        }
1436

    
1437
        /**
1438
         * DOCUMENT ME!
1439
         *
1440
         * @author $author$
1441
         * @version $Revision: 3654 $
1442
         */
1443
        private static class ExtensionComparator implements Comparator {
1444
                /**
1445
                 * DOCUMENT ME!
1446
                 *
1447
                 * @param o1 DOCUMENT ME!
1448
                 * @param o2 DOCUMENT ME!
1449
                 *
1450
                 * @return DOCUMENT ME!
1451
                 */
1452
                public int compare(Object o1, Object o2) {
1453
                        Extension e1 = (Extension) o1;
1454
                        Extension e2 = (Extension) o2;
1455

    
1456
                        if (!e1.hasPriority() && !e2.hasPriority()) {
1457
                                return -1;
1458
                        }
1459

    
1460
                        if (e1.hasPriority() && !e2.hasPriority()) {
1461
                                return -Integer.MAX_VALUE;
1462
                        }
1463

    
1464
                        if (e2.hasPriority() && !e1.hasPriority()) {
1465
                                return Integer.MAX_VALUE;
1466
                        }
1467

    
1468
                        if (e1.getPriority() != e2.getPriority()){
1469
                                return e2.getPriority() - e1.getPriority();
1470
                        }else{
1471
                                return (e2.toString().compareTo(e1.toString()));
1472
                        }
1473
                }
1474
        }
1475

    
1476
        /**
1477
         * DOCUMENT ME!
1478
         */
1479
        private static class MenuComparator implements Comparator {
1480
                private static ExtensionComparator extComp = new ExtensionComparator();
1481

    
1482
                /**
1483
                 * DOCUMENT ME!
1484
                 *
1485
                 * @param o1 DOCUMENT ME!
1486
                 * @param o2 DOCUMENT ME!
1487
                 *
1488
                 * @return DOCUMENT ME!
1489
                 */
1490
                public int compare(Object o1, Object o2) {
1491
                        SortableMenu e1 = (SortableMenu) o1;
1492
                        SortableMenu e2 = (SortableMenu) o2;
1493

    
1494
                        if (!e1.menu.hasPosition() && !e2.menu.hasPosition()) {
1495
                                if (e1.extension instanceof SkinExtensionType) {
1496
                                        return 1;
1497
                                } else if (e2.extension instanceof SkinExtensionType) {
1498
                                        return -1;
1499
                                } else {
1500
                                        return extComp.compare(e1.extension, e2.extension);
1501
                                }
1502
                        }
1503

    
1504
                        if (e1.menu.hasPosition() && !e2.menu.hasPosition()) {
1505
                                return -Integer.MAX_VALUE;
1506
                        }
1507

    
1508
                        if (e2.menu.hasPosition() && !e1.menu.hasPosition()) {
1509
                                return Integer.MAX_VALUE;
1510
                        }
1511

    
1512
                        return e1.menu.getPosition() - e2.menu.getPosition();
1513
                }
1514
        }
1515

    
1516
        /**
1517
         * DOCUMENT ME!
1518
         *
1519
         * @author $author$
1520
         * @version $Revision: 3654 $
1521
         */
1522
        private static class SortableMenu {
1523
                public PluginClassLoader loader;
1524
                public Menu menu;
1525
                public SkinExtensionType extension;
1526

    
1527
                /**
1528
                 * DOCUMENT ME!
1529
                 *
1530
                 * @param loader DOCUMENT ME!
1531
                 * @param skinExt
1532
                 * @param menu2
1533
                 */
1534
                public SortableMenu(PluginClassLoader loader,
1535
                        SkinExtensionType skinExt, Menu menu2) {
1536
                        extension = skinExt;
1537
                        menu = menu2;
1538
                        this.loader = loader;
1539
                }
1540
        }
1541
        /**
1542
         * DOCUMENT ME!
1543
         */
1544
        private static class ToolBarComparator implements Comparator {
1545
                private static ExtensionComparator extComp = new ExtensionComparator();
1546

    
1547
                /**
1548
                 * DOCUMENT ME!
1549
                 *
1550
                 * @param o1 DOCUMENT ME!
1551
                 * @param o2 DOCUMENT ME!
1552
                 *
1553
                 * @return DOCUMENT ME!
1554
                 */
1555
                public int compare(Object o1, Object o2) {
1556
                        SortableToolBar e1 = (SortableToolBar) o1;
1557
                        SortableToolBar e2 = (SortableToolBar) o2;
1558

    
1559
                        if (!e1.toolbar.hasPosition() && !e2.toolbar.hasPosition()) {
1560
                                if (e1.extension instanceof SkinExtensionType) {
1561
                                        return 1;
1562
                                } else if (e2.extension instanceof SkinExtensionType) {
1563
                                        return -1;
1564
                                } else {
1565
                                        return extComp.compare(e1.extension, e2.extension);
1566
                                }
1567
                        }
1568

    
1569
                        if (e1.toolbar.hasPosition() && !e2.toolbar.hasPosition()) {
1570
                                return -Integer.MAX_VALUE;
1571
                        }
1572

    
1573
                        if (e2.toolbar.hasPosition() && !e1.toolbar.hasPosition()) {
1574
                                return Integer.MAX_VALUE;
1575
                        }
1576
                        if (e1.toolbar.getPosition() != e2.toolbar.getPosition())
1577
                        return e1.toolbar.getPosition() - e2.toolbar.getPosition();
1578
                        
1579
                        if (e1.toolbar.getActionTool().equals(e2.toolbar.getActionTool()) && e1.toolbar.getSelectableTool().equals(e2.toolbar.getSelectableTool())){
1580
                                return 0;
1581
                        }
1582
                        return 1; 
1583
                }
1584
        }
1585
        /**
1586
         * DOCUMENT ME!
1587
         *
1588
         * @author $author$
1589
         * @version $Revision: 3654 $
1590
         */
1591
        private static class SortableToolBar {
1592
                public PluginClassLoader loader;
1593
                public ToolBar toolbar;
1594
                public ActionTool actiontool;
1595
                public SelectableTool selectabletool;
1596
                public SkinExtensionType extension;
1597

    
1598
                /**
1599
                 * DOCUMENT ME!
1600
                 *
1601
                 * @param loader DOCUMENT ME!
1602
                 * @param skinExt
1603
                 * @param menu2
1604
                 */
1605
                public SortableToolBar(PluginClassLoader loader,
1606
                        SkinExtensionType skinExt, ToolBar toolbar2,ActionTool actiontool2) {
1607
                        extension = skinExt;
1608
                        toolbar = toolbar2;
1609
                        actiontool=actiontool2;
1610
                        this.loader = loader;
1611
                }
1612
                        public SortableToolBar(PluginClassLoader loader,
1613
                                SkinExtensionType skinExt, ToolBar toolbar2,SelectableTool selectabletool2) {
1614
                                extension = skinExt;
1615
                                toolbar = toolbar2;
1616
                                selectabletool=selectabletool2;
1617
                                this.loader = loader;
1618
                        }
1619
        }
1620
}