Statistics
| Revision:

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

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

    
72
import javax.jnlp.BasicService;
73
import javax.jnlp.ServiceManager;
74
import javax.jnlp.UnavailableServiceException;
75
import javax.swing.ImageIcon;
76
import javax.swing.JComponent;
77
import javax.swing.JDialog;
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: 3281 $
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) || (args.length > 3)) {
159
                        System.err.println("Uso: Launcher appName plugins-directory [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
                // Configurar el locale
197
        String localeStr = "";
198
                if (args.length == 3) {
199
            localeStr = args[2];
200
            
201
                } else {
202
            localeStr = andamiConfig.getLocaleLanguage();
203
                        /* locale = getLocale(localeStr,
204
                                        andamiConfig.getLocaleCountry(),
205
                                        andamiConfig.getLocaleVariant()); */
206
                }
207
        if (localeStr.compareTo("va")==0)
208
        {
209
            locale = new Locale("ca");
210
            Messages.init("va");
211
        }
212
        else
213
        {
214
            locale = Locale.getDefault();
215
            Messages.init(locale);
216
        }
217

    
218
                Locale.setDefault(locale);
219
                JComponent.setDefaultLocale(locale);        
220
                
221

    
222
                //Se pone el lookAndFeel
223
                try {
224
                        UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
225
                } catch (Exception e) {
226
                        logger.warn(Messages.getString("Launcher.look_and_feel"), e);
227
                }
228

    
229
                // Mostrar la ventana de inicio
230
                splashWindow = new SplashWindow(null);
231

    
232
                // TODO Buscar actualizaciones de los plugins
233
                downloadExtensions(andamiConfig.getPluginsDirectory());
234

    
235
                // Se leen los config.xml de los plugins -----++++
236
                loadPlugins(andamiConfig.getPluginsDirectory());
237

    
238
                // Se configura el classloader del plugin
239
                pluginsClassLoaders();
240

    
241
                // Se carga un Skin si alguno de los plugins trae informaci?n para ello
242
                skinPlugin();
243

    
244
                //Se configura la cola de eventos
245
                EventQueue waitQueue = new AndamiEventQueue();
246
                Toolkit.getDefaultToolkit().getSystemEventQueue().push(waitQueue);
247

    
248
                // Se configura la mensajer?a del plugin
249
                pluginsMessages();
250

    
251
                // Se modifica el andami-config con los plugins nuevos
252
                updateAndamiConfig();
253

    
254
                // Se prepara el MainFrame para albergar las extensiones
255
                frame = new MDIFrame();
256

    
257
                // Se configura el nombre e icono de la aplicaci?n
258
                frameIcon();
259

    
260
                SwingUtilities.invokeAndWait(new Runnable() {
261
                                public void run() {
262
                                        frame.init();
263
                                }
264
                        });
265

    
266
                // Se instalan los controles de las extensiones de los plugins
267
                SwingUtilities.invokeAndWait(new Runnable() {
268
                                public void run() {
269
                                        installPluginsControls();
270
                                        installPluginsMenus();
271
                                        installPluginsLabels();
272
                                }
273
                        });
274

    
275
                // Leer el fichero de persistencia
276
                //  info de los plugins
277
                //  bookmarks de los plugins
278
                loadPluginsPersistence();
279

    
280
                // Se instalan los controles del skin
281
                // Se inicializan todas las extensiones de todos los plugins
282
                SwingUtilities.invokeAndWait(new Runnable() {
283
                                public void run() {
284
                                        initializeExtensions();
285
                                }
286
                        });
287
                frame.setClassesExtensions(classesExtensions);
288

    
289
                // Se instalan los bookmarks de los plugins
290
                splashWindow.close();
291

    
292
                //Se muestra el frame principal
293
                frame.show();
294

    
295
                SwingUtilities.invokeAndWait(new Runnable() {
296
                                public void run() {
297
                                        frame.enableControls();
298
                                }
299
                        });
300
            }catch(Exception e){
301
                logger.error("excepci?n al arrancar", e);
302
                System.exit(-1);
303
            }
304
        }
305

    
306
        /**
307
     * @return
308
     */
309
    private static boolean validJVM() {
310
        char thirdCharacter = System.getProperty("java.version").charAt(2);
311
        if (thirdCharacter < '4'){
312
            return false;
313
            }else{
314
                return true;
315
            }
316
    }
317

    
318
    /**
319
         * DOCUMENT ME!
320
         *
321
         * @throws ConfigurationException
322
         */
323
        private static void loadPluginsPersistence() throws ConfigurationException {
324
                XMLEntity entity = persistenceFromXML();
325

    
326
                for (int i = 0; i < entity.getNumChild(); i++) {
327
                        XMLEntity plugin = entity.getChild(i);
328
                        String pName = plugin.getStringProperty(
329
                                        "com.iver.andami.pluginName");
330
                        if (pluginsServices.get(pName)!= null){
331
                                ((PluginServices) pluginsServices.get(pName)).setPersistentXML(plugin);
332
                        }
333
                }
334
        }
335

    
336
        /**
337
         * DOCUMENT ME!
338
         */
339
        private static void installPluginsLabels() {
340
                Iterator i = pluginsConfig.keySet().iterator();
341

    
342
                while (i.hasNext()) {
343
                        String name = (String) i.next();
344
                        PluginConfig pc = (PluginConfig) pluginsConfig.get(name);
345
                        PluginServices ps = (PluginServices) pluginsServices.get(name);
346

    
347
                        LabelSet[] ls = pc.getLabelSet();
348

    
349
                        for (int j = 0; j < ls.length; j++) {
350
                                PluginClassLoader loader = ps.getClassLoader();
351

    
352
                                try {
353
                                        Class clase = loader.loadClass(ls[j].getClassName());
354
                                        frame.setLabels(clase, ls[j].getLabel());
355
                                } catch (ClassNotFoundException e) {
356
                                        logger.error(Messages.getString("Launcher.labelset_class"),
357
                                                e);
358
                                }
359
                        }
360
                }
361
        }
362

    
363
        /**
364
         * DOCUMENT ME!
365
         *
366
         * @throws MDIManagerLoadException
367
         */
368
        private static void skinPlugin() throws MDIManagerLoadException {
369
                Iterator i = pluginsConfig.keySet().iterator();
370

    
371
                while (i.hasNext()) {
372
                        String name = (String) i.next();
373
                        PluginConfig pc = (PluginConfig) pluginsConfig.get(name);
374
                        PluginServices ps = (PluginServices) pluginsServices.get(name);
375

    
376
                        if (pc.getExtensions().getSkinExtension() != null) {
377
                                if (MDIManagerFactory.getSkinExtension() != null) {
378
                                        logger.warn(Messages.getString(
379
                                                        "Launcher.Dos_skin_extension"));
380
                                }
381

    
382
                                SkinExtension se = pc.getExtensions().getSkinExtension();
383

    
384
                                MDIManagerFactory.setSkinExtension(se, ps.getClassLoader());
385

    
386
                                Class skinClass;
387

    
388
                                try {
389
                                        skinClass = ps.getClassLoader().loadClass(se.getClassName());
390

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

    
415
        /**
416
         *
417
         */
418
        private static void frameIcon() {
419
                Iterator i = pluginsConfig.keySet().iterator();
420

    
421
                while (i.hasNext()) {
422
                        String pName = (String) i.next();
423
                        PluginConfig pc = (PluginConfig) pluginsConfig.get(pName);
424
                        PluginServices ps = (PluginServices) pluginsServices.get(pName);
425

    
426
                        if (pc.getIcon() != null) {
427
                                ImageIcon icon = new ImageIcon(ps.getClassLoader().getResource(pc.getIcon()
428
                                                                                                                                                                 .getSrc()));
429
                                frame.setIconImage(icon.getImage());
430
                                frame.setTitlePrefix(pc.getIcon().getText());
431
                        }
432
                }
433
        }
434

    
435
        /**
436
         *
437
         */
438
        private static void initializeExtensions() {
439
                Iterator i = pluginsOrdered.iterator();
440

    
441
                while (i.hasNext()) {
442
                        String pName = (String) i.next();
443
            logger.debug("Initializing extensions from " + pName);
444
                        PluginConfig pc = (PluginConfig) pluginsConfig.get(pName);
445
                        PluginServices ps = (PluginServices) pluginsServices.get(pName);
446

    
447
                        Extension[] exts = pc.getExtensions().getExtension();
448

    
449
                        TreeMap orderedExtensions = new TreeMap(new ExtensionComparator());
450

    
451
                        for (int j = 0; j < exts.length; j++) {
452
                                if (!exts[j].getActive()) {
453
                                        continue;
454
                                }
455

    
456
                                if (orderedExtensions.containsKey(exts[j])) {
457
                                        logger.warn(Messages.getString(
458
                                                        "Launcher.Two_extensions_with_the_same_priority") +
459
                                                exts[j].getClassName());
460
                                }
461

    
462
                                orderedExtensions.put(exts[j], null);
463
                        }
464

    
465
                        Iterator e = orderedExtensions.keySet().iterator();
466

    
467
                        while (e.hasNext()) {
468
                                Extension extension = (Extension) e.next();
469
                                com.iver.andami.plugins.Extension extensionInstance;
470

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

    
491
                                } catch (InstantiationException e1) {
492
                                        logger.error(Messages.getString(
493
                                                        "Launcher.Error_instanciando_la_extension") +
494
                                                extension.getClassName(), e1);
495
                                } catch (IllegalAccessException e1) {
496
                                        logger.error(Messages.getString(
497
                                                        "Launcher.Error_instanciando_la_extension") +
498
                                                extension.getClassName(), e1);
499
                                } catch (ClassNotFoundException e1) {
500
                                        logger.error(Messages.getString(
501
                                                        "Launcher.No_se_encontro_la_clase_de_la_extension") +
502
                                                extension.getClassName(), e1);
503
                                } catch (NoClassDefFoundError e1) {
504
                                        logger.error(Messages.getString(
505
                                                        "Launcher.Error_localizando_la_clase_de_la_extension") +
506
                                                extension.getClassName(), e1);
507
                                }
508
                        }
509
                }
510
        }
511

    
512
        /**
513
         * DOCUMENT ME!
514
         */
515
        private static void installPluginsMenus() {
516
                TreeMap orderedMenus = new TreeMap(new MenuComparator());
517

    
518
                Iterator i = pluginsConfig.keySet().iterator();
519

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

    
525
                        Extension[] exts = pc.getExtensions().getExtension();
526

    
527
                        for (int j = 0; j < exts.length; j++) {
528
                                if (!exts[j].getActive()) {
529
                                        continue;
530
                                }
531

    
532
                                Menu[] menu = exts[j].getMenu();
533

    
534
                                for (int k = 0; k < menu.length; k++) {
535
                                        SortableMenu sm = new SortableMenu(ps.getClassLoader(),
536
                                                        exts[j], menu[k]);
537

    
538
                                        if (orderedMenus.containsKey(sm)) {
539
                                                logger.error(Messages.getString(
540
                                                                "Launcher.Two_menus_with_the_same_position") +
541
                                                        exts[j].getClassName());
542
                                        }
543

    
544
                                        orderedMenus.put(sm, null);
545
                                }
546
                        }
547

    
548
                        // Se instalan las extensiones de MDI
549
                        SkinExtension skinExt = pc.getExtensions().getSkinExtension();
550

    
551
                        if (skinExt != null) {
552
                                Menu[] menu = skinExt.getMenu();
553

    
554
                                for (int k = 0; k < menu.length; k++) {
555
                                        SortableMenu sm = new SortableMenu(ps.getClassLoader(),
556
                                                        skinExt, menu[k]);
557

    
558
                                        if (orderedMenus.containsKey(sm)) {
559
                                                logger.error(Messages.getString(
560
                                                                "Launcher.Two_menus_with_the_same_position") +
561
                                                        skinExt.getClassName());
562
                                        }
563

    
564
                                        orderedMenus.put(sm, null);
565
                                }
566
                        }
567
                }
568

    
569
                //Se itera por los menus ordenados
570
                Iterator e = orderedMenus.keySet().iterator();
571

    
572
                // Se ordenan los menues
573
                while (e.hasNext()) {
574
                        try {
575
                                SortableMenu sm = (SortableMenu) e.next();
576

    
577
                                frame.addMenu(sm.loader, sm.extension, sm.menu);
578
                        } catch (ClassNotFoundException ex) {
579
                                logger.error(Messages.getString(
580
                                                "Launcher.No_se_encontro_la_clase_de_la_extension"), ex);
581
                        }
582
                }
583
        }
584

    
585
        /**
586
         *
587
         */
588
        private static void installPluginsControls() {
589
                Iterator i = pluginsConfig.keySet().iterator();
590

    
591
                HashMap extensionPluginServices = new HashMap();
592
                HashMap extensionPluginConfig = new HashMap();
593
                TreeMap orderedExtensions = new TreeMap(new ExtensionComparator());
594
                while (i.hasNext()) {
595
                                String pName = (String) i.next();
596
                                PluginConfig pc = (PluginConfig) pluginsConfig.get(pName);
597
                                PluginServices ps = (PluginServices) pluginsServices.get(pName);
598

    
599
                                Extension[] exts = pc.getExtensions().getExtension();
600

    
601
                                for (int j = 0; j < exts.length; j++) {
602
                                        if (exts[j].getActive()) {
603
                                                if (orderedExtensions.containsKey(exts[j])) {
604
                                                        logger.error(Messages.getString(
605
                                                                        "Launcher.Two_extensions_with_the_same_priority") +
606
                                                                exts[j].getClassName());
607
                                                }
608

    
609
                                                orderedExtensions.put(exts[j], null);
610
                                                extensionPluginServices.put(exts[j], ps);
611
                                                extensionPluginConfig.put(exts[j], pc);
612
                                        }
613
                                }
614
                }
615

    
616
                try {
617
                        Iterator e = orderedExtensions.keySet().iterator();
618

    
619
                        // Se instalan las extensiones
620
                        while (e.hasNext()) {
621
                                Extension ext = (Extension) e.next();
622

    
623
                                ToolBar[] toolbars = ext.getToolBar();
624

    
625
                                for (int k = 0; k < toolbars.length; k++) {
626
                                        ActionTool[] tools = toolbars[k].getActionTool();
627

    
628
                                        for (int t = 0; t < tools.length; t++) {
629
                                                frame.addTool(((PluginServices)extensionPluginServices.get(ext)).getClassLoader(), ext,
630
                                                        toolbars[k], tools[t]);
631
                                        }
632

    
633
                                        SelectableTool[] sTools = toolbars[k].getSelectableTool();
634

    
635
                                        for (int t = 0; t < sTools.length; t++) {
636
                                                frame.addTool(((PluginServices)extensionPluginServices.get(ext)).getClassLoader(), ext,
637
                                                        toolbars[k], sTools[t]);
638
                                        }
639
                                }
640
                        }
641

    
642
                        i = pluginsConfig.keySet().iterator();
643
                        while (i.hasNext()) {
644
                                String pName = (String) i.next();
645
                                PluginConfig pc = (PluginConfig) pluginsConfig.get(pName);
646
                                PluginServices ps = (PluginServices) pluginsServices.get(pName);
647
                                // Se instalan las extensiones de MDI
648
                                SkinExtension skinExt = pc.getExtensions().getSkinExtension();
649
        
650
                                if (skinExt != null) {
651
                                        ToolBar[] toolbars = skinExt.getToolBar();
652
        
653
                                        for (int k = 0; k < toolbars.length; k++) {
654
                                                ActionTool[] tools = toolbars[k].getActionTool();
655
        
656
                                                for (int t = 0; t < tools.length; t++) {
657
                                                        frame.addTool(ps.getClassLoader(), skinExt,
658
                                                                toolbars[k], tools[t]);
659
                                                }
660
        
661
                                                SelectableTool[] sTools = toolbars[k].getSelectableTool();
662
        
663
                                                for (int t = 0; t < sTools.length; t++) {
664
                                                        frame.addTool(ps.getClassLoader(), skinExt,
665
                                                                toolbars[k], sTools[t]);
666
                                                }
667
                                        }
668
        
669
                                        /*
670
                                           Menu[] menu = skinExt.getMenu();
671
                                           for (int k = 0; k < menu.length; k++) {
672
                                               frame.addMenu(ps.getClassLoader(), skinExt, menu[k]);
673
                                           }
674
                                         */
675
                                }
676
                                //Se instalan los popup menus
677
                                PopupMenus pus = pc.getPopupMenus();
678

    
679
                                if (pus != null) {
680
                                        PopupMenu[] menus = pus.getPopupMenu();
681

    
682
                                        for (int j = 0; j < menus.length; j++) {
683
                                                frame.addPopupMenu(ps.getClassLoader(), menus[j]);
684
                                        }
685
                                }
686
                        }
687
                } catch (ClassNotFoundException e) {
688
                        logger.error(Messages.getString(
689
                                        "Launcher.No_se_encontro_la_clase_de_la_extension"), e);
690
                }
691
        }
692

    
693
        /**
694
         *
695
         */
696
        private static void updateAndamiConfig() {
697
                HashSet olds = new HashSet();
698

    
699
                Plugin[] plugins = andamiConfig.getPlugin();
700

    
701
                for (int i = 0; i < plugins.length; i++) {
702
                        olds.add(plugins[i].getName());
703
                }
704

    
705
                Iterator i = pluginsServices.values().iterator();
706

    
707
                while (i.hasNext()) {
708
                        PluginServices ps = (PluginServices) i.next();
709

    
710
                        if (!olds.contains(ps.getPluginName())) {
711
                                Plugin p = new Plugin();
712
                                p.setName(ps.getPluginName());
713
                                p.setUpdate(false);
714

    
715
                                andamiConfig.addPlugin(p);
716
                        }
717
                }
718
        }
719

    
720
        /**
721
         * DOCUMENT ME!
722
         */
723
        private static void pluginsClassLoaders() {
724
                HashSet instalados = new HashSet();
725

    
726
                // Se itera hasta que est?n todos instalados
727
                while (instalados.size() != pluginsConfig.size()) {
728
                        boolean circle = true;
729

    
730
                        //Hacemos una pasada por todos los plugins
731
                        Iterator i = pluginsConfig.keySet().iterator();
732

    
733
                        while (i.hasNext()) {
734
                                String pluginName = (String) i.next();
735
                                PluginConfig config = (PluginConfig) pluginsConfig.get(pluginName);
736

    
737
                                if (instalados.contains(pluginName)) {
738
                                        continue;
739
                                }
740

    
741
                                //Se obtienen las dependencias y sus class loaders
742
                                boolean ready = true;
743
                                Depends[] dependencies = config.getDepends();
744
                                PluginClassLoader[] loaders = new PluginClassLoader[dependencies.length];
745

    
746
                                for (int j = 0; j < dependencies.length; j++) {
747
                                        if (pluginsConfig.get(dependencies[j].getPluginName()) == null) {
748
                                                logger.error(Messages.getString(
749
                                                                "Launcher.Dependencia_no_resuelta_en_plugin") +
750
                                                        pluginName + ": " +
751
                                                        dependencies[j].getPluginName());
752

    
753
                                                continue;
754
                                        }
755

    
756
                                        if (!instalados.contains(dependencies[j].getPluginName())) {
757
                                                ready = false;
758
                                        } else {
759
                                                loaders[j] = ((PluginServices) pluginsServices.get(dependencies[j].getPluginName())).getClassLoader();
760
                                        }
761
                                }
762

    
763
                                //Si no est?n sus dependencias satisfechas se aborta la instalaci?n
764
                                if (!ready) {
765
                                        continue;
766
                                }
767

    
768
                                //Se genera el class loader
769
                                String jardir = config.getLibraries().getLibraryDir();
770
                                File jarDir = new File(andamiConfig.getPluginsDirectory() +
771
                                                File.separator + pluginName + File.separator + jardir);
772
                                File[] jarFiles = jarDir.listFiles(new FileFilter() {
773
                                                        public boolean accept(File pathname) {
774
                                                                return (pathname.getName().toUpperCase()
775
                                                                                                .endsWith(".JAR")) ||
776
                                                                (pathname.getName().toUpperCase().endsWith(".ZIP"));
777
                                                        }
778
                                                });
779

    
780
                                URL[] urls = new URL[jarFiles.length];
781

    
782
                                for (int j = 0; j < jarFiles.length; j++) {
783
                                        try {
784
                                                urls[j] = new URL("file:" + jarFiles[j]);
785
                                        } catch (MalformedURLException e) {
786
                                                logger.error(Messages.getString(
787
                                                                "Launcher.No_se_puede_acceder_a") +
788
                                                        jarFiles[j]);
789
                                        }
790
                                }
791

    
792
                                PluginClassLoader loader;
793

    
794
                                try {
795
                                        loader = new PluginClassLoader(urls,
796
                                                        andamiConfig.getPluginsDirectory() +
797
                                                        File.separator + pluginName,
798
                                                        Launcher.class.getClassLoader(), loaders);
799

    
800
                                        PluginServices ps = new PluginServices(loader);
801

    
802
                                        pluginsServices.put(ps.getPluginName(), ps);
803

    
804
                                        instalados.add(pluginName);
805
                    // FJP: Los metemos ordenados para luego no cargar uno que necesita de otro antes de tiempo. Esto lo usaremos al 
806
                    // inicializar los plugins
807
                    pluginsOrdered.add(pluginName);
808

    
809
                                        circle = false;
810
                                } catch (IOException e) {
811
                                        logger.error(Messages.getString(
812
                                                        "Launcher.Error_con_las_librerias_del_plugin"), e);
813
                                        pluginsConfig.remove(pluginName);
814
                                        i = pluginsConfig.keySet().iterator();
815
                                }
816
                        }
817

    
818
                        if (circle) {
819
                                logger.error(Messages.getString(
820
                                                "Launcher.Hay_dependencias_circulares"));
821

    
822
                                break;
823
                        }
824
                }
825

    
826
                //Se eliminan los plugins que no fueron instalados
827
                Iterator i = pluginsConfig.keySet().iterator();
828

    
829
                while (i.hasNext()) {
830
                        String pluginName = (String) i.next();
831
                        PluginConfig config = (PluginConfig) pluginsConfig.get(pluginName);
832
                        PluginServices ps = (PluginServices) pluginsServices.get(pluginName);
833

    
834
                        if (ps == null) {
835
                                pluginsConfig.remove(pluginName);
836
                                i = pluginsConfig.keySet().iterator();
837
                        }
838
                } 
839
        }
840

    
841
        /**
842
         * DOCUMENT ME!
843
         */
844
        private static void pluginsMessages() {
845
                //Iteramos por todos los plugins
846
                Iterator i = pluginsConfig.keySet().iterator();
847

    
848
                while (i.hasNext()) {
849
                        String pluginName = (String) i.next();
850
                        PluginConfig config = (PluginConfig) pluginsConfig.get(pluginName);
851

    
852
                        PluginServices ps = (PluginServices) pluginsServices.get(pluginName);
853

    
854
                        if (config.getResourceBundle() != null) {
855
                                ps.setResourceBundle(config.getResourceBundle().getName(),
856
                                        locale);
857
                        }
858
                }
859
        }
860

    
861
        /**
862
         * DOCUMENT ME!
863
         *
864
         * @param name DOCUMENT ME!
865
         *
866
         * @return DOCUMENT ME!
867
         */
868
        static PluginServices getPluginServices(String name) {
869
                return (PluginServices) pluginsServices.get(name);
870
        }
871

    
872
        /**
873
         * DOCUMENT ME!
874
         *
875
         * @return DOCUMENT ME!
876
         */
877
        static String getPluginsDir() {
878
                return andamiConfig.getPluginsDirectory();
879
        }
880

    
881
        /**
882
         * DOCUMENT ME!
883
         *
884
         * @param s DOCUMENT ME!
885
         */
886
        static void setPluginsDir(String s) {
887
                andamiConfig.setPluginsDirectory(s);
888
        }
889

    
890
        /**
891
         * DOCUMENT ME!
892
         *
893
         * @return DOCUMENT ME!
894
         */
895
        static MDIFrame getMDIFrame() {
896
                return frame;
897
        }
898

    
899
        /**
900
         * DOCUMENT ME!
901
         *
902
         * @param pluginsDirectory
903
         */
904
        private static void loadPlugins(String pluginsDirectory) {
905
                File pDir = new File(pluginsDirectory);
906

    
907
                if (!pDir.exists()) {
908
                        return;
909
                }
910

    
911
                File[] pluginDirs = pDir.listFiles();
912

    
913
                for (int i = 0; i < pluginDirs.length; i++) {
914
                        if (pluginDirs[i].isDirectory()) {
915
                                File configXml = new File(pluginDirs[i].getAbsolutePath() +
916
                                                File.separator + "config.xml");
917

    
918
                                try {
919
                                        FileReader xml = new FileReader(configXml);
920
                                        PluginConfig pConfig = (PluginConfig) PluginConfig.unmarshal(xml);
921
                                        pluginsConfig.put(pluginDirs[i].getName(), pConfig);
922
                                } catch (FileNotFoundException e) {
923
                                        logger.info(Messages.getString(
924
                                                        "Launcher.Ignorando_el_directorio") +
925
                                                pluginDirs[i].getAbsolutePath() +
926
                                                Messages.getString("Launcher.config_no_encontrado"));
927
                                } catch (MarshalException e) {
928
                                        logger.info(Messages.getString(
929
                                                        "Launcher.Ignorando_el_directorio") +
930
                                                pluginDirs[i].getAbsolutePath() +
931
                                                Messages.getString("Launcher.config_mal_formado"), e);
932
                                } catch (ValidationException e) {
933
                                        logger.info(Messages.getString(
934
                                                        "Launcher.Ignorando_el_directorio") +
935
                                                pluginDirs[i].getAbsolutePath() +
936
                                                Messages.getString("Launcher.config_mal_formado"), e);
937
                                }
938
                        }
939
                }
940
        }
941

    
942
        /**
943
         * DOCUMENT ME!
944
         *
945
         * @param language
946
         * @param country
947
         * @param variant
948
         *
949
         * @return DOCUMENT ME!
950
         */
951
        private static Locale getLocale(String language, String country,
952
                String variant) {
953
                if (variant != null) {
954
                        return new Locale(language, country, variant);
955
                } else if (country != null) {
956
                        return new Locale(language, country);
957
                } else if (language != null) {
958
                        return new Locale(language);
959
                } else {
960
                        return new Locale("es");
961
                }
962
        }
963

    
964
        /**
965
         * DOCUMENT ME!
966
         *
967
         * @param file DOCUMENT ME!
968
         *
969
         * @throws IOException DOCUMENT ME!
970
         * @throws MarshalException DOCUMENT ME!
971
         * @throws ValidationException DOCUMENT ME!
972
         */
973
        private static void andamiConfigToXML(String file)
974
                throws IOException, MarshalException, ValidationException {
975
                File xml = new File(file);
976
                File parent = xml.getParentFile();
977
                parent.mkdirs();
978

    
979
                FileWriter writer = new FileWriter(xml);
980
                andamiConfig.marshal(writer);
981
        }
982

    
983
        /**
984
         * DOCUMENT ME!
985
         *
986
         * @param file DOCUMENT ME!
987
         *
988
         * @throws ConfigurationException DOCUMENT ME!
989
         */
990
        private static void andamiConfigFromXML(String file)
991
                throws ConfigurationException {
992
                File xml = new File(file);
993

    
994
                //Si no existe se ponen los valores por defecto
995
                if (!xml.exists()) {
996
                        andamiConfig = new AndamiConfig();
997

    
998
                        Andami andami = new Andami();
999
                        andami.setUpdate(true);
1000
                        andamiConfig.setAndami(andami);
1001
                        andamiConfig.setLocaleCountry(Locale.getDefault().getCountry());
1002
                        andamiConfig.setLocaleLanguage(Locale.getDefault().getLanguage());
1003
                        andamiConfig.setLocaleVariant(Locale.getDefault().getVariant());
1004

    
1005
                        if (System.getProperty("javawebstart.version") != null) // Es java web start)
1006
                         {
1007
                                andamiConfig.setPluginsDirectory(new File(System.getProperty(
1008
                                                        "user.home") + File.separator + appName +
1009
                                                File.separator + "extensiones").getAbsolutePath());
1010
                        } else {
1011
                                andamiConfig.setPluginsDirectory(new File(appName +
1012
                                                File.separator + "extensiones").getAbsolutePath());
1013
                        }
1014

    
1015
                        andamiConfig.setPlugin(new Plugin[0]);
1016
                } else {
1017
                        //Se lee la configuraci?n
1018
                        FileReader reader;
1019

    
1020
                        try {
1021
                                reader = new FileReader(xml);
1022
                                andamiConfig = (AndamiConfig) AndamiConfig.unmarshal(reader);
1023
                        } catch (FileNotFoundException e) {
1024
                                throw new ConfigurationException(e);
1025
                        } catch (MarshalException e) {
1026
                                throw new ConfigurationException(e);
1027
                        } catch (ValidationException e) {
1028
                                throw new ConfigurationException(e);
1029
                        }
1030
                }
1031
        }
1032

    
1033
        /**
1034
         * DOCUMENT ME!
1035
         *
1036
         * @return DOCUMENT ME!
1037
         *
1038
         * @throws ConfigurationException DOCUMENT ME!
1039
         */
1040
        private static XMLEntity persistenceFromXML() throws ConfigurationException {
1041
                File xml = new File(pluginsPersistencePath);
1042

    
1043
                if (xml.exists()) {
1044
                        FileReader reader;
1045

    
1046
                        try {
1047
                                reader = new FileReader(xml);
1048

    
1049
                                XmlTag tag = (XmlTag) XmlTag.unmarshal(reader);
1050

    
1051
                                return new XMLEntity(tag);
1052
                        } catch (FileNotFoundException e) {
1053
                                throw new ConfigurationException(e);
1054
                        } catch (MarshalException e) {
1055
                                throw new ConfigurationException(e);
1056
                        } catch (ValidationException e) {
1057
                                throw new ConfigurationException(e);
1058
                        }
1059
                } else {
1060
                        return new XMLEntity();
1061
                }
1062
        }
1063

    
1064
        /**
1065
         * DOCUMENT ME!
1066
         *
1067
         * @param entity DOCUMENT ME!
1068
         *
1069
         * @throws ConfigurationException DOCUMENT ME!
1070
         */
1071
        private static void persistenceToXML(XMLEntity entity)
1072
                throws ConfigurationException {
1073
                File xml = new File(pluginsPersistencePath);
1074

    
1075
                FileWriter writer;
1076

    
1077
                try {
1078
                        writer = new FileWriter(xml);
1079
                        entity.getXmlTag().marshal(writer);
1080
                } catch (FileNotFoundException e) {
1081
                        throw new ConfigurationException(e);
1082
                } catch (MarshalException e) {
1083
                        throw new ConfigurationException(e);
1084
                } catch (ValidationException e) {
1085
                        throw new ConfigurationException(e);
1086
                } catch (IOException e) {
1087
                        throw new ConfigurationException(e);
1088
                }
1089
        }
1090

    
1091
        /**
1092
         * Devuelve un array con los directorios de los plugins
1093
         *
1094
         * @param dirExt Directorio de las extensiones a partir del cual cuelgan
1095
         *                   todos los directorios de los plugins
1096
         *
1097
         * @return ArrayList con los directorios
1098
         */
1099
        private String[] getLocales(File dirExt) {
1100
                ArrayList types = new ArrayList();
1101
                File[] files = dirExt.listFiles();
1102

    
1103
                for (int i = 0; i < files.length; i++) {
1104
                        if (files[i].isDirectory()) {
1105
                                File[] textFile = files[i].listFiles(new FilenameFilter() {
1106
                                                        public boolean accept(File dir, String fileName) {
1107
                                                                return fileName.toLowerCase().startsWith("text_"); //$NON-NLS-1$
1108
                                                        }
1109
                                                });
1110

    
1111
                                for (int j = 0; j < textFile.length; j++) {
1112
                                        String s = (textFile[j]).getName().replaceAll("text_", "");
1113
                                        s = s.replaceAll(".properties", "");
1114
                                        s = s.trim();
1115

    
1116
                                        if (!types.contains(s)) {
1117
                                                types.add(s);
1118
                                        }
1119
                                }
1120
                        }
1121
                }
1122

    
1123
                return (String[]) types.toArray(new String[0]);
1124
        }
1125

    
1126
        /**
1127
         * DOCUMENT ME!
1128
         *
1129
         * @return Returns the frame.
1130
         */
1131
        static MDIFrame getFrame() {
1132
                return frame;
1133
        }
1134

    
1135
        /**
1136
         * Secuencia de cerrado de Andami
1137
         */
1138
        public static void closeApplication() {
1139
                //Configuraci?n de Andami
1140
                try {
1141
                        andamiConfigToXML(andamiConfigPath);
1142
                } catch (MarshalException e) {
1143
                        logger.error(Messages.getString(
1144
                                        "Launcher.No_se_pudo_guardar_la_configuracion_de_andami"), e);
1145
                } catch (ValidationException e) {
1146
                        logger.error(Messages.getString(
1147
                                        "Launcher.No_se_pudo_guardar_la_configuracion_de_andami"), e);
1148
                } catch (IOException e) {
1149
                        logger.error(Messages.getString(
1150
                                        "Launcher.No_se_pudo_guardar_la_configuracion_de_andami"), e);
1151
                }
1152

    
1153
                //Persistencia de los plugins
1154
                Iterator i = pluginsConfig.keySet().iterator();
1155

    
1156
                XMLEntity entity = new XMLEntity();
1157

    
1158
                while (i.hasNext()) {
1159
                        String pName = (String) i.next();
1160
                        PluginServices ps = (PluginServices) pluginsServices.get(pName);
1161
                        XMLEntity ent = ps.getPersistentXML();
1162

    
1163
                        if (ent != null) {
1164
                                ent.putProperty("com.iver.andami.pluginName", pName);
1165
                                entity.addChild(ent);
1166
                        }
1167
                }
1168

    
1169
                try {
1170
                        persistenceToXML(entity);
1171
                } catch (ConfigurationException e1) {
1172
                        logger.error(Messages.getString(
1173
                                        "Launcher.Se_produjo_un_error_guardando_la_configuracion_de_los_plugins"),
1174
                                e1);
1175
                }
1176

    
1177
                //Para la depuraci?n de memory leaks
1178
                System.gc();
1179

    
1180
        System.exit(0);
1181
        }
1182

    
1183
        /**
1184
         * DOCUMENT ME!
1185
         *
1186
         * @return DOCUMENT ME!
1187
         */
1188
        static HashMap getClassesExtensions() {
1189
                return classesExtensions;
1190
        }
1191

    
1192
        /**
1193
         * DOCUMENT ME!
1194
         *
1195
         * @param extDir DOCUMENT ME!
1196
         */
1197
        private static void downloadExtensions(String extDir) {
1198
                java.util.Date fechaActual = null;
1199

    
1200
                try {
1201
                        if (System.getProperty("javawebstart.version") != null) {
1202
                                //Obtenemos la URL del servidor
1203
                                BasicService bs = (BasicService) ServiceManager.lookup(
1204
                                                "javax.jnlp.BasicService");
1205
                                URL baseURL = bs.getCodeBase();
1206

    
1207
                                //Se descargan las extensiones
1208
                                SplashWindow.process(5,
1209
                                        "Descargando las extensiones desde " + baseURL + " a " +
1210
                                        extDir);
1211

    
1212
                                URL url = new URL(baseURL + "extensiones.zip");
1213
                                URLConnection connection = url.openConnection();
1214

    
1215
                                System.out.println(url.toExternalForm() + ":");
1216
                                System.out.println("  Content Type: " +
1217
                                        connection.getContentType());
1218
                                System.out.println("  Content Length: " +
1219
                                        connection.getContentLength());
1220
                                System.out.println("  Last Modified: " +
1221
                                        new Date(connection.getLastModified()));
1222
                                System.out.println("  Expiration: " +
1223
                                        connection.getExpiration());
1224
                                System.out.println("  Content Encoding: " +
1225
                                        connection.getContentEncoding());
1226

    
1227
                                // Guardamos la fecha del fichero de extensiones que nos hemos bajado, y
1228
                                // comprobamos el ?ltimo que se ha bajado. Si no son
1229
                                // iguales, nos bajamos el nuevo. Si son iguales, no
1230
                                // nos bajamos nada.
1231
                                Long miliSecondsInWeb = new Long(connection.getLastModified());
1232

    
1233
                                // PluginServices ps = PluginServices.getPluginServices("com.iver.core");
1234
                                // if (ps.getPersistentXML().getStringProperty("timestamp") != null)
1235
                                File destDir = new File(extDir);
1236

    
1237
                                if (!destDir.exists()) {
1238
                                        // Creamos gvSIG
1239
                                        destDir.getParentFile().mkdir();
1240

    
1241
                                        if (!destDir.mkdir()) {
1242
                                                System.err.println("Imposible crear el directorio " +
1243
                                                        destDir.getAbsolutePath());
1244
                                        }
1245
                                }
1246

    
1247
                                File timeFile = new File(destDir.getParent() + File.separator +
1248
                                                "timeStamp.properties");
1249

    
1250
                                if (!timeFile.exists()) {
1251
                                        timeFile.createNewFile();
1252
                                }
1253

    
1254
                                FileInputStream inAux = new FileInputStream(timeFile);
1255
                                Properties prop = new Properties();
1256
                                prop.load(inAux);
1257
                                inAux.close();
1258

    
1259
                                if (prop.getProperty("timestamp") != null) {
1260
                                        Long lastMiliSeconds = (Long) new Long(prop.getProperty(
1261
                                                                "timestamp"));
1262

    
1263
                                        if (lastMiliSeconds.longValue() == miliSecondsInWeb.longValue()) {
1264
                                                System.out.println("No hay nueva actualizaci?n");
1265

    
1266
                                                return;
1267
                                        }
1268

    
1269
                                        System.out.println("timeStampWeb= " + miliSecondsInWeb);
1270
                                        System.out.println("timeStampLocal= " + lastMiliSeconds);
1271
                                } else {
1272
                                        System.out.println("El timeStamp no est? escrito en " +
1273
                                                timeFile.getAbsolutePath());
1274
                                }
1275

    
1276
                                InputStream stream = connection.getInputStream();
1277
                                File temp = File.createTempFile("gvsig", ".zip");
1278
                                temp.deleteOnExit();
1279

    
1280
                                FileOutputStream file = new FileOutputStream(temp);
1281
                                BufferedInputStream in = new BufferedInputStream(stream);
1282
                                BufferedOutputStream out = new BufferedOutputStream(file);
1283

    
1284
                                int i;
1285
                                int pct;
1286
                                int desde;
1287
                                int hasta;
1288

    
1289
                                hasta = connection.getContentLength() / 1024;
1290
                                desde = 0;
1291

    
1292
                                while ((i = in.read()) != -1) {
1293
                                        pct = ((desde / 1024) * 100) / hasta;
1294

    
1295
                                        if (((desde % 10240) == 0) && (pct > 10) &&
1296
                                                        ((pct % 10) == 0)) {
1297
                                                SplashWindow.process(pct,
1298
                                                        (desde / 1024) + "Kb de " + hasta +
1299
                                                        "Kb descargados...");
1300
                                        }
1301

    
1302
                                        out.write(i);
1303
                                        desde++;
1304
                                }
1305

    
1306
                                out.flush();
1307
                                out.close();
1308
                                in.close();
1309

    
1310
                                //Se extrae el zip
1311
                                SplashWindow.process(5, "Extensiones descargadas.");
1312

    
1313
                                System.out.println("Extrayendo a " + destDir.getAbsolutePath());
1314

    
1315
                                Date fechaDir = new Date(destDir.lastModified());
1316
                                System.out.println("Fecha del directorio " + extDir + " = " +
1317
                                        fechaDir.toString());
1318
                                Utilities.extractTo(temp, new File(extDir), splashWindow);
1319

    
1320
                                // Si todo ha ido bien, guardamos el timestamp.
1321
                                ///  App.instance.getPc().addProperties("timestamp", miliSecondsInWeb);
1322
                                // XMLEntity xml=ps.getPersistentXML();
1323
                                fechaActual = new java.util.Date();
1324

    
1325
                                FileOutputStream outAux = new FileOutputStream(timeFile);
1326
                                prop.setProperty("timestamp", miliSecondsInWeb.toString());
1327
                                prop.store(outAux, "last download");
1328
                                outAux.close();
1329
                                System.out.println("Fecha actual guardada: " +
1330
                                        fechaActual.toGMTString());
1331

    
1332
                                /* xml.putProperty("timestamp",fechaActual.toGMTString());
1333
                                   ps.setPresistentXML(xml); */
1334
                        }
1335
                } catch (IOException e) {
1336
                        NotificationManager.addError("", e);
1337
                } catch (UnavailableServiceException e) {
1338
                        NotificationManager.addError("", e);
1339
                } catch (SecurityException e) {
1340
                        System.err.println("No se puede escribir el timeStamp " +
1341
                                fechaActual.toGMTString());
1342
                        NotificationManager.addError("", e);
1343
                }
1344
        }
1345

    
1346
        /**
1347
         * DOCUMENT ME!
1348
         *
1349
         * @return DOCUMENT ME!
1350
         */
1351
        private static Extensions[] getExtensions() {
1352
                ArrayList array = new ArrayList();
1353
                Iterator iter = pluginsConfig.values().iterator();
1354

    
1355
                while (iter.hasNext()) {
1356
                        array.add(((PluginConfig) iter.next()).getExtensions());
1357
                }
1358

    
1359
                return (Extensions[]) array.toArray(new Extensions[0]);
1360
        }
1361

    
1362
        /**
1363
         * DOCUMENT ME!
1364
         *
1365
         * @return DOCUMENT ME!
1366
         */
1367
        public static HashMap getPluginConfig() {
1368
                return pluginsConfig;
1369
        }
1370

    
1371
        /**
1372
         * DOCUMENT ME!
1373
         *
1374
         * @param s DOCUMENT ME!
1375
         *
1376
         * @return DOCUMENT ME!
1377
         */
1378
        public static Extension getExtension(String s) {
1379
                Extensions[] exts = getExtensions();
1380

    
1381
                for (int i = 0; i < exts.length; i++) {
1382
                        for (int j = 0; j < exts[i].getExtensionCount(); j++) {
1383
                                if (exts[i].getExtension(j).getClassName().equals(s)) {
1384
                                        return exts[i].getExtension(j);
1385
                                }
1386
                        }
1387
                }
1388

    
1389
                return null;
1390
        }
1391

    
1392
        /**
1393
         * DOCUMENT ME!
1394
         *
1395
         * @return DOCUMENT ME!
1396
         */
1397
        public static AndamiConfig getAndamiConfig() {
1398
                return andamiConfig;
1399
        }
1400

    
1401
        /**
1402
         * DOCUMENT ME!
1403
         *
1404
         * @author $author$
1405
         * @version $Revision: 3281 $
1406
         */
1407
        private static class ExtensionComparator implements Comparator {
1408
                /**
1409
                 * DOCUMENT ME!
1410
                 *
1411
                 * @param o1 DOCUMENT ME!
1412
                 * @param o2 DOCUMENT ME!
1413
                 *
1414
                 * @return DOCUMENT ME!
1415
                 */
1416
                public int compare(Object o1, Object o2) {
1417
                        Extension e1 = (Extension) o1;
1418
                        Extension e2 = (Extension) o2;
1419

    
1420
                        if (!e1.hasPriority() && !e2.hasPriority()) {
1421
                                return -1;
1422
                        }
1423

    
1424
                        if (e1.hasPriority() && !e2.hasPriority()) {
1425
                                return -Integer.MAX_VALUE;
1426
                        }
1427

    
1428
                        if (e2.hasPriority() && !e1.hasPriority()) {
1429
                                return Integer.MAX_VALUE;
1430
                        }
1431

    
1432
                        if (e1.getPriority() != e2.getPriority()){
1433
                                return e2.getPriority() - e1.getPriority();
1434
                        }else{
1435
                                return (e2.toString().compareTo(e1.toString()));
1436
                        }
1437
                }
1438
        }
1439

    
1440
        /**
1441
         * DOCUMENT ME!
1442
         */
1443
        private static class MenuComparator implements Comparator {
1444
                private static ExtensionComparator extComp = new ExtensionComparator();
1445

    
1446
                /**
1447
                 * DOCUMENT ME!
1448
                 *
1449
                 * @param o1 DOCUMENT ME!
1450
                 * @param o2 DOCUMENT ME!
1451
                 *
1452
                 * @return DOCUMENT ME!
1453
                 */
1454
                public int compare(Object o1, Object o2) {
1455
                        SortableMenu e1 = (SortableMenu) o1;
1456
                        SortableMenu e2 = (SortableMenu) o2;
1457

    
1458
                        if (!e1.menu.hasPosition() && !e2.menu.hasPosition()) {
1459
                                if (e1.extension instanceof SkinExtensionType) {
1460
                                        return 1;
1461
                                } else if (e2.extension instanceof SkinExtensionType) {
1462
                                        return -1;
1463
                                } else {
1464
                                        return extComp.compare(e1.extension, e2.extension);
1465
                                }
1466
                        }
1467

    
1468
                        if (e1.menu.hasPosition() && !e2.menu.hasPosition()) {
1469
                                return -Integer.MAX_VALUE;
1470
                        }
1471

    
1472
                        if (e2.menu.hasPosition() && !e1.menu.hasPosition()) {
1473
                                return Integer.MAX_VALUE;
1474
                        }
1475

    
1476
                        return e1.menu.getPosition() - e2.menu.getPosition();
1477
                }
1478
        }
1479

    
1480
        /**
1481
         * DOCUMENT ME!
1482
         *
1483
         * @author $author$
1484
         * @version $Revision: 3281 $
1485
         */
1486
        private static class SortableMenu {
1487
                public PluginClassLoader loader;
1488
                public Menu menu;
1489
                public SkinExtensionType extension;
1490

    
1491
                /**
1492
                 * DOCUMENT ME!
1493
                 *
1494
                 * @param loader DOCUMENT ME!
1495
                 * @param skinExt
1496
                 * @param menu2
1497
                 */
1498
                public SortableMenu(PluginClassLoader loader,
1499
                        SkinExtensionType skinExt, Menu menu2) {
1500
                        extension = skinExt;
1501
                        menu = menu2;
1502
                        this.loader = loader;
1503
                }
1504
        }
1505
}