Statistics
| Revision:

svn-gvsig-desktop / tags / Root_v06 / frameworks / _fwAndami / src / com / iver / andami / Launcher.java @ 4811

History | View | Annotate | Download (46.1 KB)

1
/* gvSIG. Sistema de Informaci?n Geogr?fica de la Generalitat Valenciana
2
 *
3
 * Copyright (C) 2004 IVER T.I. and Generalitat Valenciana.
4
 *
5
 * This program is free software; you can redistribute it and/or
6
 * modify it under the terms of the GNU General Public License
7
 * as published by the Free Software Foundation; either version 2
8
 * of the License, or (at your option) any later version.
9
 *
10
 * This program is distributed in the hope that it will be useful,
11
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13
 * GNU General Public License for more details.
14
 *
15
 * You should have received a copy of the GNU General Public License
16
 * along with this program; if not, write to the Free Software
17
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307,USA.
18
 *
19
 * For more information, contact:
20
 *
21
 *  Generalitat Valenciana
22
 *   Conselleria d'Infraestructures i Transport
23
 *   Av. Blasco Ib??ez, 50
24
 *   46010 VALENCIA
25
 *   SPAIN
26
 *
27
 *      +34 963862235
28
 *   gvsig@gva.es
29
 *      www.gvsig.gva.es
30
 *
31
 *    or
32
 *
33
 *   IVER T.I. S.A
34
 *   Salamanca 50
35
 *   46005 Valencia
36
 *   Spain
37
 *
38
 *   +34 963163400
39
 *   dac@iver.es
40
 */
41
package com.iver.andami;
42

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

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

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

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

    
116

    
117
/**
118
 * DOCUMENT ME!
119
 *
120
 * @author $author$
121
 * @version $Revision: 4811 $
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
            locale = getLocale(localeStr,
216
                    andamiConfig.getLocaleCountry(),
217
                    andamiConfig.getLocaleVariant());
218
            Messages.init(locale);
219
        }
220

    
221
                Locale.setDefault(locale);
222
                JComponent.setDefaultLocale(locale);        
223
                
224

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

    
232
                // Mostrar la ventana de inicio
233
                splashWindow = new SplashWindow(null);
234

    
235
                // TODO Buscar actualizaciones de los plugins
236
                downloadExtensions(andamiConfig.getPluginsDirectory());
237

    
238
                // Se leen los config.xml de los plugins -----++++
239
                loadPlugins(andamiConfig.getPluginsDirectory());
240

    
241
                // Se configura el classloader del plugin
242
                pluginsClassLoaders();
243

    
244
                // Se carga un Skin si alguno de los plugins trae informaci?n para ello
245
                skinPlugin();
246

    
247
                //Se configura la cola de eventos
248
                EventQueue waitQueue = new AndamiEventQueue();
249
                Toolkit.getDefaultToolkit().getSystemEventQueue().push(waitQueue);
250

    
251
                // Se configura la mensajer?a del plugin
252
                pluginsMessages();
253

    
254
                // Se modifica el andami-config con los plugins nuevos
255
                updateAndamiConfig();
256

    
257
                // Se prepara el MainFrame para albergar las extensiones
258
                frame = new MDIFrame();
259

    
260
                // Se configura el nombre e icono de la aplicaci?n
261
                frameIcon();
262

    
263
                SwingUtilities.invokeAndWait(new Runnable() {
264
                                public void run() {
265
                                        frame.init();
266
                                }
267
                        });
268

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

    
278
                // Leer el fichero de persistencia
279
                //  info de los plugins
280
                //  bookmarks de los plugins
281
                loadPluginsPersistence();
282

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

    
292
                // Se instalan los bookmarks de los plugins
293
                splashWindow.close();
294

    
295
                //Se muestra el frame principal
296
                frame.show();
297

    
298
                SwingUtilities.invokeAndWait(new Runnable() {
299
                                public void run() {
300
                                        frame.enableControls();
301
                                }
302
                        });
303
            }catch(Exception e){
304
                logger.error("excepci?n al arrancar", e);
305
                System.exit(-1);
306
            }
307
            
308
            //  Clean temporal files
309
                Utilities.cleanUpTempFiles();
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
         * Recupera la geometr?a (tama?o, posici?n y estado) de la ventana principal de Andami.
327
         * @author LWS
328
         */
329
        private static void restoreMDIStatus(XMLEntity xml) {
330
                //System.err.println("Launcher: restoreMDIStatus()");
331
                if (xml == null) xml = new XMLEntity();
332
                //  restore frame size
333
                Dimension sz = new Dimension(700,580);
334
                if (xml.contains("MDIFrameSize")) {
335
                        int [] wh = xml.getIntArrayProperty("MDIFrameSize");
336
                        sz = new Dimension(wh[0], wh[1]);
337
                }
338
                frame.setSize(sz);
339
                //  restore frame location
340
                Point pos = new Point(10,10);
341
                if (xml.contains("MDIFramePos")) {
342
                        int [] xy = xml.getIntArrayProperty("MDIFramePos");
343
                        pos = new Point(xy[0], xy[1]);
344
                }
345
                frame.setLocation(pos);
346
                
347
                //  restore frame status (Maximized, minimized, etc);
348
                int state = java.awt.Frame.MAXIMIZED_BOTH;
349
                if (xml.contains("MDIFrameState")) {
350
                        state = xml.getIntProperty("MDIFrameState");
351
                }
352
                frame.setExtendedState(state);
353
        }
354
        
355
        private static XMLEntity saveMDIStatus() {
356
                XMLEntity xml = new XMLEntity();
357
                // save frame size
358
                int [] wh = new int[2];
359
                wh[0] = frame.getWidth();
360
                wh[1] = frame.getHeight();
361
                xml.putProperty("MDIFrameSize", wh);
362
                // save frame location
363
                int [] xy = new int[2];
364
                xy[0] = frame.getX();
365
                xy[1] = frame.getY();
366
                xml.putProperty("MDIFramePos", xy);
367
                // save frame status
368
                xml.putProperty("MDIFrameState", frame.getExtendedState());
369
                return xml;
370
        }
371

    
372
        /**
373
         * DOCUMENT ME!
374
         *
375
         * @throws ConfigurationException
376
         */
377
        private static void loadPluginsPersistence() throws ConfigurationException {
378
                XMLEntity entity = persistenceFromXML();
379

    
380
                for (int i = 0; i < entity.getNumChild(); i++) {
381
                        XMLEntity plugin = entity.getChild(i);
382
                        String pName = plugin.getStringProperty(
383
                                        "com.iver.andami.pluginName");
384
                        if (pluginsServices.get(pName)!= null){
385
                                ((PluginServices) pluginsServices.get(pName)).setPersistentXML(plugin);
386
                        } else {
387
                                if (pName.startsWith("Andami.Launcher"))
388
                                        restoreMDIStatus(plugin);
389
                        }
390
                }
391
        }
392

    
393
        /**
394
         * DOCUMENT ME!
395
         */
396
        private static void installPluginsLabels() {
397
                Iterator i = pluginsConfig.keySet().iterator();
398

    
399
                while (i.hasNext()) {
400
                        String name = (String) i.next();
401
                        PluginConfig pc = (PluginConfig) pluginsConfig.get(name);
402
                        PluginServices ps = (PluginServices) pluginsServices.get(name);
403

    
404
                        LabelSet[] ls = pc.getLabelSet();
405

    
406
                        for (int j = 0; j < ls.length; j++) {
407
                                PluginClassLoader loader = ps.getClassLoader();
408

    
409
                                try {
410
                                        Class clase = loader.loadClass(ls[j].getClassName());
411
                                        frame.setLabels(clase, ls[j].getLabel());
412
                                } catch (ClassNotFoundException e) {
413
                                        logger.error(Messages.getString("Launcher.labelset_class"),
414
                                                e);
415
                                }
416
                        }
417
                }
418
        }
419

    
420
        /**
421
         * Salva la persistencia de los plugins.
422
         * @author LWS
423
         */
424
        private static void savePluginPersistence() {
425
                Iterator i = pluginsConfig.keySet().iterator();
426

    
427
                XMLEntity entity = new XMLEntity();
428

    
429
                while (i.hasNext()) {
430
                        String pName = (String) i.next();
431
                        PluginServices ps = (PluginServices) pluginsServices.get(pName);
432
                        XMLEntity ent = ps.getPersistentXML();
433

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

    
453
        /**
454
         * DOCUMENT ME!
455
         *
456
         * @throws MDIManagerLoadException
457
         */
458
        private static void skinPlugin() throws MDIManagerLoadException {
459
                Iterator i = pluginsConfig.keySet().iterator();
460

    
461
                while (i.hasNext()) {
462
                        String name = (String) i.next();
463
                        PluginConfig pc = (PluginConfig) pluginsConfig.get(name);
464
                        PluginServices ps = (PluginServices) pluginsServices.get(name);
465

    
466
                        if (pc.getExtensions().getSkinExtension() != null) {
467
                                if (MDIManagerFactory.getSkinExtension() != null) {
468
                                        logger.warn(Messages.getString(
469
                                                        "Launcher.Dos_skin_extension"));
470
                                }
471

    
472
                                SkinExtension se = pc.getExtensions().getSkinExtension();
473

    
474
                                MDIManagerFactory.setSkinExtension(se, ps.getClassLoader());
475

    
476
                                Class skinClass;
477

    
478
                                try {
479
                                        skinClass = ps.getClassLoader().loadClass(se.getClassName());
480

    
481
                                        com.iver.andami.plugins.Extension skinInstance = (com.iver.andami.plugins.Extension) skinClass.newInstance();
482
                                        // classesExtensions.put(skinClass, skinInstance);
483
                                        // jaume
484
                                        ExtensionDecorator newExtensionDecorator = new ExtensionDecorator(skinInstance, ExtensionDecorator.INACTIVE);
485
                                        classesExtensions.put(skinClass, newExtensionDecorator);
486
                                } catch (ClassNotFoundException e) {
487
                                        logger.error(Messages.getString(
488
                                                        "Launcher.No_se_encontro_la_clase_mdi_manager"), e);
489
                                        throw new MDIManagerLoadException(e);
490
                                } catch (InstantiationException e) {
491
                                        logger.error(Messages.getString(
492
                                                        "Launcher.No_se_pudo_instanciar_la_clase_mdi_manager"),
493
                                                e);
494
                                        throw new MDIManagerLoadException(e);
495
                                } catch (IllegalAccessException e) {
496
                                        logger.error(Messages.getString(
497
                                                        "Launcher.No_se_pudo_acceder_a_la_clase_mdi_manager"),
498
                                                e);
499
                                        throw new MDIManagerLoadException(e);
500
                                }
501
                        }
502
                }
503
        }
504

    
505
        /**
506
         *
507
         */
508
        private static void frameIcon() {
509
                Iterator i = pluginsConfig.keySet().iterator();
510

    
511
                while (i.hasNext()) {
512
                        String pName = (String) i.next();
513
                        PluginConfig pc = (PluginConfig) pluginsConfig.get(pName);
514
                        PluginServices ps = (PluginServices) pluginsServices.get(pName);
515

    
516
                        if (pc.getIcon() != null) {
517
                                ImageIcon icon = new ImageIcon(ps.getClassLoader().getResource(pc.getIcon()
518
                                                                                                                                                                 .getSrc()));
519
                                frame.setIconImage(icon.getImage());
520
                                frame.setTitlePrefix(pc.getIcon().getText());
521
                        }
522
                }
523
        }
524

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

    
531
                while (i.hasNext()) {
532
                        String pName = (String) i.next();
533
            logger.debug("Initializing extensions from " + pName);
534
                        PluginConfig pc = (PluginConfig) pluginsConfig.get(pName);
535
                        PluginServices ps = (PluginServices) pluginsServices.get(pName);
536

    
537
                        Extension[] exts = pc.getExtensions().getExtension();
538

    
539
                        TreeMap orderedExtensions = new TreeMap(new ExtensionComparator());
540

    
541
                        for (int j = 0; j < exts.length; j++) {
542
                                if (!exts[j].getActive()) {
543
                                        continue;
544
                                }
545

    
546
                                if (orderedExtensions.containsKey(exts[j])) {
547
                                        logger.warn(Messages.getString(
548
                                                        "Launcher.Two_extensions_with_the_same_priority") +
549
                                                exts[j].getClassName());
550
                                }
551

    
552
                                orderedExtensions.put(exts[j], null);
553
                        }
554

    
555
                        Iterator e = orderedExtensions.keySet().iterator();
556

    
557
                        while (e.hasNext()) {
558
                                Extension extension = (Extension) e.next();
559
                                com.iver.andami.plugins.Extension extensionInstance;
560

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

    
581
                                } catch (InstantiationException e1) {
582
                                        logger.error(Messages.getString(
583
                                                        "Launcher.Error_instanciando_la_extension") +
584
                                                extension.getClassName(), e1);
585
                                } catch (IllegalAccessException e1) {
586
                                        logger.error(Messages.getString(
587
                                                        "Launcher.Error_instanciando_la_extension") +
588
                                                extension.getClassName(), e1);
589
                                } catch (ClassNotFoundException e1) {
590
                                        logger.error(Messages.getString(
591
                                                        "Launcher.No_se_encontro_la_clase_de_la_extension") +
592
                                                extension.getClassName(), e1);
593
                                } catch (NoClassDefFoundError e1) {
594
                                        logger.error(Messages.getString(
595
                                                        "Launcher.Error_localizando_la_clase_de_la_extension") +
596
                                                extension.getClassName(), e1);
597
                                }
598
                        }
599
                }
600
        }
601

    
602
        /**
603
         * DOCUMENT ME!
604
         */
605
        private static void installPluginsMenus() {
606
                TreeMap orderedMenus = new TreeMap(new MenuComparator());
607

    
608
                Iterator i = pluginsConfig.keySet().iterator();
609

    
610
                while (i.hasNext()) {
611
                        String pName = (String) i.next();
612
                        PluginServices ps = (PluginServices) pluginsServices.get(pName);
613
                        PluginConfig pc = (PluginConfig) pluginsConfig.get(pName);
614

    
615
                        Extension[] exts = pc.getExtensions().getExtension();
616

    
617
                        for (int j = 0; j < exts.length; j++) {
618
                                if (!exts[j].getActive()) {
619
                                        continue;
620
                                }
621

    
622
                                Menu[] menus = exts[j].getMenu();
623

    
624
                                for (int k = 0; k < menus.length; k++) {
625
                                        SortableMenu sm = new SortableMenu(ps.getClassLoader(),
626
                                                        exts[j], menus[k]);
627

    
628
                                        if (orderedMenus.containsKey(sm)) {
629
                                                logger.error(Messages.getString(
630
                                                                "Launcher.Two_menus_with_the_same_position") +
631
                                                        exts[j].getClassName());
632
                                        }
633

    
634
                                        orderedMenus.put(sm, null);
635
                                }
636
                        }
637

    
638
                        // Se instalan las extensiones de MDI
639
                        SkinExtension skinExt = pc.getExtensions().getSkinExtension();
640

    
641
                        if (skinExt != null) {
642
                                Menu[] menu = skinExt.getMenu();
643

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

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

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

    
659
                //Se itera por los menus ordenados
660
                Iterator e = orderedMenus.keySet().iterator();
661

    
662
                // Se ordenan los menues
663
                while (e.hasNext()) {
664
                        try {
665
                                SortableMenu sm = (SortableMenu) e.next();
666

    
667
                                frame.addMenu(sm.loader, sm.extension, sm.menu);
668
                        } catch (ClassNotFoundException ex) {
669
                                logger.error(Messages.getString(
670
                                                "Launcher.No_se_encontro_la_clase_de_la_extension"), ex);
671
                        }
672
                }
673
        }
674

    
675
        /**
676
         *
677
         */
678
        private static void installPluginsControls() {
679
                Iterator i = pluginsConfig.keySet().iterator();
680

    
681
                HashMap extensionPluginServices = new HashMap();
682
                HashMap extensionPluginConfig = new HashMap();
683
                TreeMap orderedExtensions = new TreeMap(new ExtensionComparator());
684
                while (i.hasNext()) {
685
                                String pName = (String) i.next();
686
                                PluginConfig pc = (PluginConfig) pluginsConfig.get(pName);
687
                                PluginServices ps = (PluginServices) pluginsServices.get(pName);
688

    
689
                                Extension[] exts = pc.getExtensions().getExtension();
690

    
691
                                for (int j = 0; j < exts.length; j++) {
692
                                        if (exts[j].getActive()) {
693
                                                if (orderedExtensions.containsKey(exts[j])) {
694
                                                        logger.error(Messages.getString(
695
                                                                        "Launcher.Two_extensions_with_the_same_priority") +
696
                                                                exts[j].getClassName());
697
                                                }
698

    
699
                                                orderedExtensions.put(exts[j], null);
700
                                                extensionPluginServices.put(exts[j], ps);
701
                                                extensionPluginConfig.put(exts[j], pc);
702
                                        }
703
                                }
704
                }
705

    
706
                ///try {
707
                        TreeMap orderedToolBars = new TreeMap(new ToolBarComparator());
708
                        Iterator e = orderedExtensions.keySet().iterator();
709

    
710
                        // Se instalan las extensiones
711
                        while (e.hasNext()) {
712
                                Extension ext = (Extension) e.next();
713

    
714
                                ToolBar[] toolbars = ext.getToolBar();
715

    
716
                                for (int k = 0; k < toolbars.length; k++) {
717
                                        ActionTool[] tools = toolbars[k].getActionTool();
718

    
719
                                        for (int t = 0; t < tools.length; t++) {
720
                                                SortableToolBar sm = new SortableToolBar(((PluginServices)extensionPluginServices.get(ext)).getClassLoader(), ext,
721
                                                                toolbars[k], tools[t]);
722
                                                orderedToolBars.put(sm, null);
723
                                                ///frame.addTool(((PluginServices)extensionPluginServices.get(ext)).getClassLoader(), ext,
724
                                                ///        toolbars[k], tools[t]);
725
                                        }
726

    
727
                                        SelectableTool[] sTools = toolbars[k].getSelectableTool();
728

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

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

    
782
                                if (pus != null) {
783
                                        PopupMenu[] menus = pus.getPopupMenu();
784

    
785
                                        for (int j = 0; j < menus.length; j++) {
786
                                                frame.addPopupMenu(ps.getClassLoader(), menus[j]);
787
                                        }
788
                                }
789
                        }
790
//                        Se itera por los menus ordenados
791
                        Iterator t = orderedToolBars.keySet().iterator();
792

    
793
                        // Se ordenan los menues
794
                        while (t.hasNext()) {
795
                                try {
796
                                        SortableToolBar stb = (SortableToolBar) t.next();
797
                                        if (stb.actiontool!=null)
798
                                                frame.addTool(stb.loader, stb.extension,stb.toolbar, stb.actiontool);
799
                                        else
800
                                                frame.addTool(stb.loader, stb.extension,stb.toolbar, stb.selectabletool);
801
                                } catch (ClassNotFoundException ex) {
802
                                        logger.error(Messages.getString(
803
                                                        "Launcher.No_se_encontro_la_clase_de_la_extension"), ex);
804
                                }
805
                        }
806
                ///} catch (ClassNotFoundException e) {
807
                ///        logger.error(Messages.getString(
808
                ///                        "Launcher.No_se_encontro_la_clase_de_la_extension"), e);
809
                ///}
810
        }
811

    
812
        /**
813
         *
814
         */
815
        private static void updateAndamiConfig() {
816
                HashSet olds = new HashSet();
817

    
818
                Plugin[] plugins = andamiConfig.getPlugin();
819

    
820
                for (int i = 0; i < plugins.length; i++) {
821
                        olds.add(plugins[i].getName());
822
                }
823

    
824
                Iterator i = pluginsServices.values().iterator();
825

    
826
                while (i.hasNext()) {
827
                        PluginServices ps = (PluginServices) i.next();
828

    
829
                        if (!olds.contains(ps.getPluginName())) {
830
                                Plugin p = new Plugin();
831
                                p.setName(ps.getPluginName());
832
                                p.setUpdate(false);
833

    
834
                                andamiConfig.addPlugin(p);
835
                        }
836
                }
837
        }
838

    
839
        /**
840
         * DOCUMENT ME!
841
         */
842
        private static void pluginsClassLoaders() {
843
                HashSet instalados = new HashSet();
844

    
845
                // Se itera hasta que est?n todos instalados
846
                while (instalados.size() != pluginsConfig.size()) {
847
                        boolean circle = true;
848

    
849
                        //Hacemos una pasada por todos los plugins
850
                        Iterator i = pluginsConfig.keySet().iterator();
851

    
852
                        while (i.hasNext()) {
853
                                String pluginName = (String) i.next();
854
                                PluginConfig config = (PluginConfig) pluginsConfig.get(pluginName);
855

    
856
                                if (instalados.contains(pluginName)) {
857
                                        continue;
858
                                }
859

    
860
                                //Se obtienen las dependencias y sus class loaders
861
                                boolean ready = true;
862
                                Depends[] dependencies = config.getDepends();
863
                                PluginClassLoader[] loaders = new PluginClassLoader[dependencies.length];
864

    
865
                                for (int j = 0; j < dependencies.length; j++) {
866
                                        if (pluginsConfig.get(dependencies[j].getPluginName()) == null) {
867
                                                logger.error(Messages.getString(
868
                                                                "Launcher.Dependencia_no_resuelta_en_plugin") +
869
                                                        pluginName + ": " +
870
                                                        dependencies[j].getPluginName());
871

    
872
                                                continue;
873
                                        }
874

    
875
                                        if (!instalados.contains(dependencies[j].getPluginName())) {
876
                                                ready = false;
877
                                        } else {
878
                                                loaders[j] = ((PluginServices) pluginsServices.get(dependencies[j].getPluginName())).getClassLoader();
879
                                        }
880
                                }
881

    
882
                                //Si no est?n sus dependencias satisfechas se aborta la instalaci?n
883
                                if (!ready) {
884
                                        continue;
885
                                }
886

    
887
                                //Se genera el class loader
888
                                String jardir = config.getLibraries().getLibraryDir();
889
                                File jarDir = new File(andamiConfig.getPluginsDirectory() +
890
                                                File.separator + pluginName + File.separator + jardir);
891
                                File[] jarFiles = jarDir.listFiles(new FileFilter() {
892
                                                        public boolean accept(File pathname) {
893
                                                                return (pathname.getName().toUpperCase()
894
                                                                                                .endsWith(".JAR")) ||
895
                                                                (pathname.getName().toUpperCase().endsWith(".ZIP"));
896
                                                        }
897
                                                });
898

    
899
                                URL[] urls = new URL[jarFiles.length];
900

    
901
                                for (int j = 0; j < jarFiles.length; j++) {
902
                                        try {
903
                                                urls[j] = new URL("file:" + jarFiles[j]);
904
                                        } catch (MalformedURLException e) {
905
                                                logger.error(Messages.getString(
906
                                                                "Launcher.No_se_puede_acceder_a") +
907
                                                        jarFiles[j]);
908
                                        }
909
                                }
910

    
911
                                PluginClassLoader loader;
912

    
913
                                try {
914
                                        loader = new PluginClassLoader(urls,
915
                                                        andamiConfig.getPluginsDirectory() +
916
                                                        File.separator + pluginName,
917
                                                        Launcher.class.getClassLoader(), loaders);
918

    
919
                                        PluginServices ps = new PluginServices(loader);
920

    
921
                                        pluginsServices.put(ps.getPluginName(), ps);
922

    
923
                                        instalados.add(pluginName);
924
                    // FJP: Los metemos ordenados para luego no cargar uno que necesita de otro antes de tiempo. Esto lo usaremos al 
925
                    // inicializar los plugins
926
                    pluginsOrdered.add(pluginName);
927

    
928
                                        circle = false;
929
                                } catch (IOException e) {
930
                                        logger.error(Messages.getString(
931
                                                        "Launcher.Error_con_las_librerias_del_plugin"), e);
932
                                        pluginsConfig.remove(pluginName);
933
                                        i = pluginsConfig.keySet().iterator();
934
                                }
935
                        }
936

    
937
                        if (circle) {
938
                                logger.error(Messages.getString(
939
                                                "Launcher.Hay_dependencias_circulares"));
940

    
941
                                break;
942
                        }
943
                }
944

    
945
                //Se eliminan los plugins que no fueron instalados
946
                Iterator i = pluginsConfig.keySet().iterator();
947

    
948
                while (i.hasNext()) {
949
                        String pluginName = (String) i.next();
950
                        PluginConfig config = (PluginConfig) pluginsConfig.get(pluginName);
951
                        PluginServices ps = (PluginServices) pluginsServices.get(pluginName);
952

    
953
                        if (ps == null) {
954
                                pluginsConfig.remove(pluginName);
955
                                i = pluginsConfig.keySet().iterator();
956
                        }
957
                } 
958
        }
959

    
960
        /**
961
         * DOCUMENT ME!
962
         */
963
        private static void pluginsMessages() {
964
                //Iteramos por todos los plugins
965
                Iterator i = pluginsConfig.keySet().iterator();
966

    
967
                while (i.hasNext()) {
968
                        String pluginName = (String) i.next();
969
                        PluginConfig config = (PluginConfig) pluginsConfig.get(pluginName);
970

    
971
                        PluginServices ps = (PluginServices) pluginsServices.get(pluginName);
972

    
973
                        if (config.getResourceBundle() != null) {
974
                                ps.setResourceBundle(config.getResourceBundle().getName(),
975
                                        locale);
976
                        }
977
                }
978
        }
979

    
980
        /**
981
         * DOCUMENT ME!
982
         *
983
         * @param name DOCUMENT ME!
984
         *
985
         * @return DOCUMENT ME!
986
         */
987
        static PluginServices getPluginServices(String name) {
988
                return (PluginServices) pluginsServices.get(name);
989
        }
990

    
991
        /**
992
         * DOCUMENT ME!
993
         *
994
         * @return DOCUMENT ME!
995
         */
996
        static String getPluginsDir() {
997
                return andamiConfig.getPluginsDirectory();
998
        }
999

    
1000
        /**
1001
         * DOCUMENT ME!
1002
         *
1003
         * @param s DOCUMENT ME!
1004
         */
1005
        static void setPluginsDir(String s) {
1006
                andamiConfig.setPluginsDirectory(s);
1007
        }
1008

    
1009
        /**
1010
         * DOCUMENT ME!
1011
         *
1012
         * @return DOCUMENT ME!
1013
         */
1014
        static MDIFrame getMDIFrame() {
1015
                return frame;
1016
        }
1017

    
1018
        /**
1019
         * DOCUMENT ME!
1020
         *
1021
         * @param pluginsDirectory
1022
         */
1023
        private static void loadPlugins(String pluginsDirectory) {
1024
                File pDir = new File(pluginsDirectory);
1025

    
1026
                if (!pDir.exists()) {
1027
                        return;
1028
                }
1029

    
1030
                File[] pluginDirs = pDir.listFiles();
1031

    
1032
                for (int i = 0; i < pluginDirs.length; i++) {
1033
                        if (pluginDirs[i].isDirectory()) {
1034
                                File configXml = new File(pluginDirs[i].getAbsolutePath() +
1035
                                                File.separator + "config.xml");
1036

    
1037
                                try {
1038
                                        FileReader xml = new FileReader(configXml);
1039
                                        PluginConfig pConfig = (PluginConfig) PluginConfig.unmarshal(xml);
1040
                                        pluginsConfig.put(pluginDirs[i].getName(), pConfig);
1041
                                } catch (FileNotFoundException e) {
1042
                                        logger.info(Messages.getString(
1043
                                                        "Launcher.Ignorando_el_directorio") +
1044
                                                pluginDirs[i].getAbsolutePath() +
1045
                                                Messages.getString("Launcher.config_no_encontrado"));
1046
                                } catch (MarshalException e) {
1047
                                        logger.info(Messages.getString(
1048
                                                        "Launcher.Ignorando_el_directorio") +
1049
                                                pluginDirs[i].getAbsolutePath() +
1050
                                                Messages.getString("Launcher.config_mal_formado"), e);
1051
                                } catch (ValidationException e) {
1052
                                        logger.info(Messages.getString(
1053
                                                        "Launcher.Ignorando_el_directorio") +
1054
                                                pluginDirs[i].getAbsolutePath() +
1055
                                                Messages.getString("Launcher.config_mal_formado"), e);
1056
                                }
1057
                        }
1058
                }
1059
        }
1060

    
1061
        /**
1062
         * DOCUMENT ME!
1063
         *
1064
         * @param language
1065
         * @param country
1066
         * @param variant
1067
         *
1068
         * @return DOCUMENT ME!
1069
         */
1070
        private static Locale getLocale(String language, String country,
1071
                String variant) {
1072
                if (variant != null) {
1073
                        return new Locale(language, country, variant);
1074
                } else if (country != null) {
1075
                        return new Locale(language, country);
1076
                } else if (language != null) {
1077
                        return new Locale(language);
1078
                } else {
1079
                        return new Locale("es");
1080
                }
1081
        }
1082

    
1083
        /**
1084
         * DOCUMENT ME!
1085
         *
1086
         * @param file DOCUMENT ME!
1087
         *
1088
         * @throws IOException DOCUMENT ME!
1089
         * @throws MarshalException DOCUMENT ME!
1090
         * @throws ValidationException DOCUMENT ME!
1091
         */
1092
        private static void andamiConfigToXML(String file)
1093
                throws IOException, MarshalException, ValidationException {
1094
                File xml = new File(file);
1095
                File parent = xml.getParentFile();
1096
                parent.mkdirs();
1097

    
1098
                FileWriter writer = new FileWriter(xml);
1099
                andamiConfig.marshal(writer);
1100
        }
1101

    
1102
        /**
1103
         * DOCUMENT ME!
1104
         *
1105
         * @param file DOCUMENT ME!
1106
         *
1107
         * @throws ConfigurationException DOCUMENT ME!
1108
         */
1109
        private static void andamiConfigFromXML(String file)
1110
                throws ConfigurationException {
1111
                File xml = new File(file);
1112

    
1113
                //Si no existe se ponen los valores por defecto
1114
                if (!xml.exists()) {
1115
                        andamiConfig = new AndamiConfig();
1116

    
1117
                        Andami andami = new Andami();
1118
                        andami.setUpdate(true);
1119
                        andamiConfig.setAndami(andami);
1120
                        andamiConfig.setLocaleCountry(Locale.getDefault().getCountry());
1121
                        andamiConfig.setLocaleLanguage(Locale.getDefault().getLanguage());
1122
                        andamiConfig.setLocaleVariant(Locale.getDefault().getVariant());
1123

    
1124
                        if (System.getProperty("javawebstart.version") != null) // Es java web start)
1125
                         {
1126
                                andamiConfig.setPluginsDirectory(new File(System.getProperty(
1127
                                                        "user.home") + File.separator + appName +
1128
                                                File.separator + "extensiones").getAbsolutePath());
1129
                        } else {
1130
                                andamiConfig.setPluginsDirectory(new File(appName +
1131
                                                File.separator + "extensiones").getAbsolutePath());
1132
                        }
1133

    
1134
                        andamiConfig.setPlugin(new Plugin[0]);
1135
                } else {
1136
                        //Se lee la configuraci?n
1137
                        FileReader reader;
1138

    
1139
                        try {
1140
                                reader = new FileReader(xml);
1141
                                andamiConfig = (AndamiConfig) AndamiConfig.unmarshal(reader);
1142
                        } catch (FileNotFoundException e) {
1143
                                throw new ConfigurationException(e);
1144
                        } catch (MarshalException e) {
1145
                                throw new ConfigurationException(e);
1146
                        } catch (ValidationException e) {
1147
                                throw new ConfigurationException(e);
1148
                        }
1149
                }
1150
        }
1151

    
1152
        /**
1153
         * DOCUMENT ME!
1154
         *
1155
         * @return DOCUMENT ME!
1156
         *
1157
         * @throws ConfigurationException DOCUMENT ME!
1158
         */
1159
        private static XMLEntity persistenceFromXML() throws ConfigurationException {
1160
                File xml = new File(pluginsPersistencePath);
1161

    
1162
                if (xml.exists()) {
1163
                        FileReader reader;
1164

    
1165
                        try {
1166
                                reader = new FileReader(xml);
1167

    
1168
                                XmlTag tag = (XmlTag) XmlTag.unmarshal(reader);
1169

    
1170
                                return new XMLEntity(tag);
1171
                        } catch (FileNotFoundException e) {
1172
                                throw new ConfigurationException(e);
1173
                        } catch (MarshalException e) {
1174
                                throw new ConfigurationException(e);
1175
                        } catch (ValidationException e) {
1176
                                throw new ConfigurationException(e);
1177
                        }
1178
                } else {
1179
                        return new XMLEntity();
1180
                }
1181
        }
1182

    
1183
        /**
1184
         * DOCUMENT ME!
1185
         *
1186
         * @param entity DOCUMENT ME!
1187
         *
1188
         * @throws ConfigurationException DOCUMENT ME!
1189
         */
1190
        private static void persistenceToXML(XMLEntity entity)
1191
                throws ConfigurationException {
1192
                File xml = new File(pluginsPersistencePath);
1193

    
1194
                FileWriter writer;
1195

    
1196
                try {
1197
                        writer = new FileWriter(xml);
1198
                        entity.getXmlTag().marshal(writer);
1199
                } catch (FileNotFoundException e) {
1200
                        throw new ConfigurationException(e);
1201
                } catch (MarshalException e) {
1202
                        throw new ConfigurationException(e);
1203
                } catch (ValidationException e) {
1204
                        throw new ConfigurationException(e);
1205
                } catch (IOException e) {
1206
                        throw new ConfigurationException(e);
1207
                }
1208
        }
1209

    
1210
        /**
1211
         * Devuelve un array con los directorios de los plugins
1212
         *
1213
         * @param dirExt Directorio de las extensiones a partir del cual cuelgan
1214
         *                   todos los directorios de los plugins
1215
         *
1216
         * @return ArrayList con los directorios
1217
         */
1218
        private String[] getLocales(File dirExt) {
1219
                ArrayList types = new ArrayList();
1220
                File[] files = dirExt.listFiles();
1221

    
1222
                for (int i = 0; i < files.length; i++) {
1223
                        if (files[i].isDirectory()) {
1224
                                File[] textFile = files[i].listFiles(new FilenameFilter() {
1225
                                                        public boolean accept(File dir, String fileName) {
1226
                                                                return fileName.toLowerCase().startsWith("text_"); //$NON-NLS-1$
1227
                                                        }
1228
                                                });
1229

    
1230
                                for (int j = 0; j < textFile.length; j++) {
1231
                                        String s = (textFile[j]).getName().replaceAll("text_", "");
1232
                                        s = s.replaceAll(".properties", "");
1233
                                        s = s.trim();
1234

    
1235
                                        if (!types.contains(s)) {
1236
                                                types.add(s);
1237
                                        }
1238
                                }
1239
                        }
1240
                }
1241

    
1242
                return (String[]) types.toArray(new String[0]);
1243
        }
1244

    
1245
        /**
1246
         * DOCUMENT ME!
1247
         *
1248
         * @return Returns the frame.
1249
         */
1250
        static MDIFrame getFrame() {
1251
                return frame;
1252
        }
1253

    
1254
        /**
1255
         * Secuencia de cerrado de Andami
1256
         */
1257
        public static void closeApplication() {
1258
                //Configuraci?n de Andami
1259
                try {
1260
                        andamiConfigToXML(andamiConfigPath);
1261
                } catch (MarshalException e) {
1262
                        logger.error(Messages.getString(
1263
                                        "Launcher.No_se_pudo_guardar_la_configuracion_de_andami"), e);
1264
                } catch (ValidationException e) {
1265
                        logger.error(Messages.getString(
1266
                                        "Launcher.No_se_pudo_guardar_la_configuracion_de_andami"), e);
1267
                } catch (IOException e) {
1268
                        logger.error(Messages.getString(
1269
                                        "Launcher.No_se_pudo_guardar_la_configuracion_de_andami"), e);
1270
                }
1271

    
1272
                //Persistencia de los plugins
1273
                savePluginPersistence();
1274

    
1275
                // Clean any temp data created
1276
                Utilities.cleanUpTempFiles();
1277
                
1278
                //Para la depuraci?n de memory leaks
1279
                System.gc();
1280

    
1281
        System.exit(0);
1282
        }
1283

    
1284
        /**
1285
         * DOCUMENT ME!
1286
         *
1287
         * @return DOCUMENT ME!
1288
         */
1289
        static HashMap getClassesExtensions() {
1290
                return classesExtensions;
1291
        }
1292

    
1293
        /**
1294
         * DOCUMENT ME!
1295
         *
1296
         * @param extDir DOCUMENT ME!
1297
         */
1298
        private static void downloadExtensions(String extDir) {
1299
                java.util.Date fechaActual = null;
1300

    
1301
                try {
1302
                        if (System.getProperty("javawebstart.version") != null) {
1303
                                //Obtenemos la URL del servidor
1304
                                BasicService bs = (BasicService) ServiceManager.lookup(
1305
                                                "javax.jnlp.BasicService");
1306
                                URL baseURL = bs.getCodeBase();
1307

    
1308
                                //Se descargan las extensiones
1309
                                SplashWindow.process(5,
1310
                                        "Descargando las extensiones desde " + baseURL + " a " +
1311
                                        extDir);
1312

    
1313
                                URL url = new URL(baseURL + "extensiones.zip");
1314
                                URLConnection connection = url.openConnection();
1315

    
1316
                                System.out.println(url.toExternalForm() + ":");
1317
                                System.out.println("  Content Type: " +
1318
                                        connection.getContentType());
1319
                                System.out.println("  Content Length: " +
1320
                                        connection.getContentLength());
1321
                                System.out.println("  Last Modified: " +
1322
                                        new Date(connection.getLastModified()));
1323
                                System.out.println("  Expiration: " +
1324
                                        connection.getExpiration());
1325
                                System.out.println("  Content Encoding: " +
1326
                                        connection.getContentEncoding());
1327

    
1328
                                // Guardamos la fecha del fichero de extensiones que nos hemos bajado, y
1329
                                // comprobamos el ?ltimo que se ha bajado. Si no son
1330
                                // iguales, nos bajamos el nuevo. Si son iguales, no
1331
                                // nos bajamos nada.
1332
                                Long miliSecondsInWeb = new Long(connection.getLastModified());
1333

    
1334
                                // PluginServices ps = PluginServices.getPluginServices("com.iver.core");
1335
                                // if (ps.getPersistentXML().getStringProperty("timestamp") != null)
1336
                                File destDir = new File(extDir);
1337

    
1338
                                if (!destDir.exists()) {
1339
                                        // Creamos gvSIG
1340
                                        destDir.getParentFile().mkdir();
1341

    
1342
                                        if (!destDir.mkdir()) {
1343
                                                System.err.println("Imposible crear el directorio " +
1344
                                                        destDir.getAbsolutePath());
1345
                                        }
1346
                                }
1347

    
1348
                                File timeFile = new File(destDir.getParent() + File.separator +
1349
                                                "timeStamp.properties");
1350

    
1351
                                if (!timeFile.exists()) {
1352
                                        timeFile.createNewFile();
1353
                                }
1354

    
1355
                                FileInputStream inAux = new FileInputStream(timeFile);
1356
                                Properties prop = new Properties();
1357
                                prop.load(inAux);
1358
                                inAux.close();
1359

    
1360
                                if (prop.getProperty("timestamp") != null) {
1361
                                        Long lastMiliSeconds = (Long) new Long(prop.getProperty(
1362
                                                                "timestamp"));
1363

    
1364
                                        if (lastMiliSeconds.longValue() == miliSecondsInWeb.longValue()) {
1365
                                                System.out.println("No hay nueva actualizaci?n");
1366

    
1367
                                                return;
1368
                                        }
1369

    
1370
                                        System.out.println("timeStampWeb= " + miliSecondsInWeb);
1371
                                        System.out.println("timeStampLocal= " + lastMiliSeconds);
1372
                                } else {
1373
                                        System.out.println("El timeStamp no est? escrito en " +
1374
                                                timeFile.getAbsolutePath());
1375
                                }
1376

    
1377
                                InputStream stream = connection.getInputStream();
1378
                                File temp = File.createTempFile("gvsig", ".zip");
1379
                                temp.deleteOnExit();
1380

    
1381
                                FileOutputStream file = new FileOutputStream(temp);
1382
                                BufferedInputStream in = new BufferedInputStream(stream);
1383
                                BufferedOutputStream out = new BufferedOutputStream(file);
1384

    
1385
                                int i;
1386
                                int pct;
1387
                                int desde;
1388
                                int hasta;
1389

    
1390
                                hasta = connection.getContentLength() / 1024;
1391
                                desde = 0;
1392

    
1393
                                while ((i = in.read()) != -1) {
1394
                                        pct = ((desde / 1024) * 100) / hasta;
1395

    
1396
                                        if (((desde % 10240) == 0) && (pct > 10) &&
1397
                                                        ((pct % 10) == 0)) {
1398
                                                SplashWindow.process(pct,
1399
                                                        (desde / 1024) + "Kb de " + hasta +
1400
                                                        "Kb descargados...");
1401
                                        }
1402

    
1403
                                        out.write(i);
1404
                                        desde++;
1405
                                }
1406

    
1407
                                out.flush();
1408
                                out.close();
1409
                                in.close();
1410

    
1411
                                //Se extrae el zip
1412
                                SplashWindow.process(5, "Extensiones descargadas.");
1413

    
1414
                                System.out.println("Extrayendo a " + destDir.getAbsolutePath());
1415

    
1416
                                Date fechaDir = new Date(destDir.lastModified());
1417
                                System.out.println("Fecha del directorio " + extDir + " = " +
1418
                                        fechaDir.toString());
1419
                                Utilities.extractTo(temp, new File(extDir), splashWindow);
1420

    
1421
                                // Si todo ha ido bien, guardamos el timestamp.
1422
                                ///  App.instance.getPc().addProperties("timestamp", miliSecondsInWeb);
1423
                                // XMLEntity xml=ps.getPersistentXML();
1424
                                fechaActual = new java.util.Date();
1425

    
1426
                                FileOutputStream outAux = new FileOutputStream(timeFile);
1427
                                prop.setProperty("timestamp", miliSecondsInWeb.toString());
1428
                                prop.store(outAux, "last download");
1429
                                outAux.close();
1430
                                System.out.println("Fecha actual guardada: " +
1431
                                        fechaActual.toGMTString());
1432

    
1433
                                /* xml.putProperty("timestamp",fechaActual.toGMTString());
1434
                                   ps.setPresistentXML(xml); */
1435
                        }
1436
                } catch (IOException e) {
1437
                        NotificationManager.addError("", e);
1438
                } catch (UnavailableServiceException e) {
1439
                        NotificationManager.addError("", e);
1440
                } catch (SecurityException e) {
1441
                        System.err.println("No se puede escribir el timeStamp " +
1442
                                fechaActual.toGMTString());
1443
                        NotificationManager.addError("", e);
1444
                }
1445
        }
1446

    
1447
        /**
1448
         * DOCUMENT ME!
1449
         *
1450
         * @return DOCUMENT ME!
1451
         */
1452
        private static Extensions[] getExtensions() {
1453
                ArrayList array = new ArrayList();
1454
                Iterator iter = pluginsConfig.values().iterator();
1455

    
1456
                while (iter.hasNext()) {
1457
                        array.add(((PluginConfig) iter.next()).getExtensions());
1458
                }
1459

    
1460
                return (Extensions[]) array.toArray(new Extensions[0]);
1461
        }
1462

    
1463
        /**
1464
         * DOCUMENT ME!
1465
         *
1466
         * @return DOCUMENT ME!
1467
         */
1468
        public static HashMap getPluginConfig() {
1469
                return pluginsConfig;
1470
        }
1471

    
1472
        /**
1473
         * DOCUMENT ME!
1474
         *
1475
         * @param s DOCUMENT ME!
1476
         *
1477
         * @return DOCUMENT ME!
1478
         */
1479
        public static Extension getExtension(String s) {
1480
                Extensions[] exts = getExtensions();
1481

    
1482
                for (int i = 0; i < exts.length; i++) {
1483
                        for (int j = 0; j < exts[i].getExtensionCount(); j++) {
1484
                                if (exts[i].getExtension(j).getClassName().equals(s)) {
1485
                                        return exts[i].getExtension(j);
1486
                                }
1487
                        }
1488
                }
1489

    
1490
                return null;
1491
        }
1492

    
1493
        /**
1494
         * DOCUMENT ME!
1495
         *
1496
         * @return DOCUMENT ME!
1497
         */
1498
        public static AndamiConfig getAndamiConfig() {
1499
                return andamiConfig;
1500
        }
1501

    
1502
        /**
1503
         * DOCUMENT ME!
1504
         *
1505
         * @author $author$
1506
         * @version $Revision: 4811 $
1507
         */
1508
        private static class ExtensionComparator implements Comparator {
1509
                /**
1510
                 * DOCUMENT ME!
1511
                 *
1512
                 * @param o1 DOCUMENT ME!
1513
                 * @param o2 DOCUMENT ME!
1514
                 *
1515
                 * @return DOCUMENT ME!
1516
                 */
1517
                public int compare(Object o1, Object o2) {
1518
                        Extension e1 = (Extension) o1;
1519
                        Extension e2 = (Extension) o2;
1520

    
1521
                        if (!e1.hasPriority() && !e2.hasPriority()) {
1522
                                return -1;
1523
                        }
1524

    
1525
                        if (e1.hasPriority() && !e2.hasPriority()) {
1526
                                return -Integer.MAX_VALUE;
1527
                        }
1528

    
1529
                        if (e2.hasPriority() && !e1.hasPriority()) {
1530
                                return Integer.MAX_VALUE;
1531
                        }
1532

    
1533
                        if (e1.getPriority() != e2.getPriority()){
1534
                                return e2.getPriority() - e1.getPriority();
1535
                        }else{
1536
                                return (e2.toString().compareTo(e1.toString()));
1537
                        }
1538
                }
1539
        }
1540

    
1541
        /**
1542
         * DOCUMENT ME!
1543
         */
1544
        private static class MenuComparator 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
                        SortableMenu e1 = (SortableMenu) o1;
1557
                        SortableMenu e2 = (SortableMenu) o2;
1558

    
1559
                        if (!e1.menu.hasPosition() && !e2.menu.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.menu.hasPosition() && !e2.menu.hasPosition()) {
1570
                                return -Integer.MAX_VALUE;
1571
                        }
1572

    
1573
                        if (e2.menu.hasPosition() && !e1.menu.hasPosition()) {
1574
                                return Integer.MAX_VALUE;
1575
                        }
1576

    
1577
                        return e1.menu.getPosition() - e2.menu.getPosition();
1578
                }
1579
        }
1580

    
1581
        /**
1582
         * DOCUMENT ME!
1583
         *
1584
         * @author $author$
1585
         * @version $Revision: 4811 $
1586
         */
1587
        private static class SortableMenu {
1588
                public PluginClassLoader loader;
1589
                public Menu menu;
1590
                public SkinExtensionType extension;
1591

    
1592
                /**
1593
                 * DOCUMENT ME!
1594
                 *
1595
                 * @param loader DOCUMENT ME!
1596
                 * @param skinExt
1597
                 * @param menu2
1598
                 */
1599
                public SortableMenu(PluginClassLoader loader,
1600
                        SkinExtensionType skinExt, Menu menu2) {
1601
                        extension = skinExt;
1602
                        menu = menu2;
1603
                        this.loader = loader;
1604
                }
1605
        }
1606
        /**
1607
         * DOCUMENT ME!
1608
         */
1609
        private static class ToolBarComparator implements Comparator {
1610
                private static ExtensionComparator extComp = new ExtensionComparator();
1611

    
1612
                /**
1613
                 * DOCUMENT ME!
1614
                 *
1615
                 * @param o1 DOCUMENT ME!
1616
                 * @param o2 DOCUMENT ME!
1617
                 *
1618
                 * @return DOCUMENT ME!
1619
                 */
1620
                public int compare(Object o1, Object o2) {
1621
                        SortableToolBar e1 = (SortableToolBar) o1;
1622
                        SortableToolBar e2 = (SortableToolBar) o2;
1623

    
1624
                        if (!e1.toolbar.hasPosition() && !e2.toolbar.hasPosition()) {
1625
                                if (e1.extension instanceof SkinExtensionType) {
1626
                                        return 1;
1627
                                } else if (e2.extension instanceof SkinExtensionType) {
1628
                                        return -1;
1629
                                } else {
1630
                                        return extComp.compare(e1.extension, e2.extension);
1631
                                }
1632
                        }
1633

    
1634
                        if (e1.toolbar.hasPosition() && !e2.toolbar.hasPosition()) {
1635
                                return -Integer.MAX_VALUE;
1636
                        }
1637

    
1638
                        if (e2.toolbar.hasPosition() && !e1.toolbar.hasPosition()) {
1639
                                return Integer.MAX_VALUE;
1640
                        }
1641
                        if (e1.toolbar.getPosition() != e2.toolbar.getPosition())
1642
                        return e1.toolbar.getPosition() - e2.toolbar.getPosition();
1643
                        
1644
                        if (e1.toolbar.getActionTool().equals(e2.toolbar.getActionTool()) && e1.toolbar.getSelectableTool().equals(e2.toolbar.getSelectableTool())){
1645
                                return 0;
1646
                        }
1647
                        return 1; 
1648
                }
1649
        }
1650
        /**
1651
         * DOCUMENT ME!
1652
         *
1653
         * @author $author$
1654
         * @version $Revision: 4811 $
1655
         */
1656
        private static class SortableToolBar {
1657
                public PluginClassLoader loader;
1658
                public ToolBar toolbar;
1659
                public ActionTool actiontool;
1660
                public SelectableTool selectabletool;
1661
                public SkinExtensionType extension;
1662

    
1663
                /**
1664
                 * DOCUMENT ME!
1665
                 *
1666
                 * @param loader DOCUMENT ME!
1667
                 * @param skinExt
1668
                 * @param menu2
1669
                 */
1670
                public SortableToolBar(PluginClassLoader loader,
1671
                        SkinExtensionType skinExt, ToolBar toolbar2,ActionTool actiontool2) {
1672
                        extension = skinExt;
1673
                        toolbar = toolbar2;
1674
                        actiontool=actiontool2;
1675
                        this.loader = loader;
1676
                }
1677
                        public SortableToolBar(PluginClassLoader loader,
1678
                                SkinExtensionType skinExt, ToolBar toolbar2,SelectableTool selectabletool2) {
1679
                                extension = skinExt;
1680
                                toolbar = toolbar2;
1681
                                selectabletool=selectabletool2;
1682
                                this.loader = loader;
1683
                        }
1684
        }
1685
}