Statistics
| Revision:

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

History | View | Annotate | Download (59.5 KB)

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

    
43
import java.awt.Component;
44
import java.awt.Dimension;
45
import java.awt.EventQueue;
46
import java.awt.Frame;
47
import java.awt.KeyboardFocusManager;
48
import java.awt.Point;
49
import java.awt.Toolkit;
50
import java.io.BufferedReader;
51
import java.io.File;
52
import java.io.FileFilter;
53
import java.io.FileInputStream;
54
import java.io.FileNotFoundException;
55
import java.io.FileOutputStream;
56
import java.io.FileReader;
57
import java.io.FileWriter;
58
import java.io.FilenameFilter;
59
import java.io.IOException;
60
import java.io.InputStream;
61
import java.io.InputStreamReader;
62
import java.io.Reader;
63
import java.lang.reflect.InvocationTargetException;
64
import java.net.MalformedURLException;
65
import java.net.URL;
66
import java.net.URLConnection;
67
import java.security.AllPermission;
68
import java.security.CodeSource;
69
import java.security.PermissionCollection;
70
import java.security.Permissions;
71
import java.security.Policy;
72
import java.util.ArrayList;
73
import java.util.Comparator;
74
import java.util.Date;
75
import java.util.HashMap;
76
import java.util.HashSet;
77
import java.util.Iterator;
78
import java.util.Locale;
79
import java.util.Properties;
80
import java.util.Set;
81
import java.util.TreeMap;
82

    
83
import javax.jnlp.BasicService;
84
import javax.jnlp.ServiceManager;
85
import javax.jnlp.UnavailableServiceException;
86
import javax.swing.ImageIcon;
87
import javax.swing.JButton;
88
import javax.swing.JComponent;
89
import javax.swing.JOptionPane;
90
import javax.swing.SwingUtilities;
91
import javax.swing.UIManager;
92

    
93
import org.apache.log4j.Logger;
94
import org.apache.log4j.PatternLayout;
95
import org.apache.log4j.PropertyConfigurator;
96
import org.apache.log4j.RollingFileAppender;
97
import org.exolab.castor.xml.MarshalException;
98
import org.exolab.castor.xml.ValidationException;
99

    
100
import com.iver.andami.authentication.IAuthentication;
101
import com.iver.andami.config.generate.Andami;
102
import com.iver.andami.config.generate.AndamiConfig;
103
import com.iver.andami.config.generate.Plugin;
104
import com.iver.andami.messages.Messages;
105
import com.iver.andami.messages.NotificationManager;
106
import com.iver.andami.plugins.ExtensionDecorator;
107
import com.iver.andami.plugins.PluginClassLoader;
108
import com.iver.andami.plugins.config.generate.ActionTool;
109
import com.iver.andami.plugins.config.generate.ComboButton;
110
import com.iver.andami.plugins.config.generate.ComboButtonElement;
111
import com.iver.andami.plugins.config.generate.ComboScale;
112
import com.iver.andami.plugins.config.generate.Depends;
113
import com.iver.andami.plugins.config.generate.Extension;
114
import com.iver.andami.plugins.config.generate.Extensions;
115
import com.iver.andami.plugins.config.generate.LabelSet;
116
import com.iver.andami.plugins.config.generate.Menu;
117
import com.iver.andami.plugins.config.generate.PluginConfig;
118
import com.iver.andami.plugins.config.generate.PopupMenu;
119
import com.iver.andami.plugins.config.generate.PopupMenus;
120
import com.iver.andami.plugins.config.generate.SelectableTool;
121
import com.iver.andami.plugins.config.generate.SkinExtension;
122
import com.iver.andami.plugins.config.generate.SkinExtensionType;
123
import com.iver.andami.plugins.config.generate.ToolBar;
124
import com.iver.andami.ui.AndamiEventQueue;
125
import com.iver.andami.ui.MDIManagerLoadException;
126
import com.iver.andami.ui.mdiFrame.MDIFrame;
127
import com.iver.andami.ui.mdiManager.MDIManagerFactory;
128
import com.iver.andami.ui.splash.MultiSplashWindow;
129
import com.iver.utiles.XMLEntity;
130
import com.iver.utiles.xmlEntity.generate.XmlTag;
131

    
132

    
133
/**
134
 * DOCUMENT ME!
135
 *
136
 * @author $author$
137
 * @version $Revision: 8752 $
138
 */
139
public class Launcher {
140
        private static Logger logger = Logger.getLogger(Launcher.class.getName());
141
        private static AndamiConfig andamiConfig;
142
        private static MultiSplashWindow splashWindow;
143
        private static String appName;
144
        private static Locale locale;
145
        private static HashMap pluginsConfig = new HashMap();
146
        private static HashMap pluginsServices = new HashMap();
147
        private static MDIFrame frame;
148
        private static HashMap classesExtensions = new HashMap();
149
        private static String andamiConfigPath;
150
        private static String pluginsPersistencePath;
151
        private static final String nonWinDefaultLookAndFeel =  "com.jgoodies.looks.plastic.PlasticXPLookAndFeel";
152

    
153
    private static ArrayList pluginsOrdered = new ArrayList();
154
    private static ArrayList extensions=new ArrayList();
155
    private static String appHomeDir = null;
156
        /**
157
         * DOCUMENT ME!
158
         *
159
         * @param args DOCUMENT ME!
160
         * @throws Exception
161
         *
162
         * @throws InterruptedException
163
         * @throws InvocationTargetException
164
         * @throws ConfigurationException
165
         * @throws MDIManagerLoadException
166
         * @throws IOException
167
         */
168
    public static void main(String[] args) throws Exception {
169
            try{
170

    
171
                    if (!validJVM()){
172
                            System.exit(-1);
173
                    }
174

    
175
                    if (args.length < 1) {
176
                            System.err.println("Uso: Launcher appName plugins-directory [language=locale]");
177
                    }
178

    
179
                    //  Clean temporal files
180
                    Utilities.cleanUpTempFiles();
181

    
182
                    appName = args[0];
183

    
184
                    //Se crea el directorio de configuraci?n de la aplicaci?n
185
                    appHomeDir = System.getProperty(args[0]+".home");
186
                    if (appHomeDir == null)
187
                            appHomeDir = System.getProperty("user.home");
188
                    //System.err.println("LWS: "+args[0]+".home"+"="+appHomeDir);
189
                    appHomeDir += File.separator + args[0] + File.separator;
190
                    File parent = new File( appHomeDir );
191
                    parent.mkdirs();
192

    
193
                    andamiConfigPath = appHomeDir + "andami-config.xml";
194
                    pluginsPersistencePath = appHomeDir +
195
                    "plugins-persistence.xml";
196

    
197
                    // Configurar el log4j
198
                    PropertyConfigurator.configure(Launcher.class.getClassLoader()
199
                                    .getResource("log4j.properties"));
200

    
201
                    PatternLayout l = new PatternLayout("%p %t %C - %m%n");
202
                    RollingFileAppender fa = new RollingFileAppender(l,
203
                                    appHomeDir + args[0] + ".log", false);
204
                    fa.setMaxFileSize("512KB");
205
                    fa.setMaxBackupIndex(3);
206
                    Logger.getRootLogger().addAppender(fa);
207

    
208
                    // Leer el fichero de configuraci?n de andami (andami-config.xsd)
209
                    // locale
210
                    // Buscar actualizaci?nes al comenzar
211
                    //  Andami
212
                    //  Plugins
213
                    // Directorio de las extensiones
214
                    andamiConfigFromXML(andamiConfigPath);
215
                    andamiConfig.setPluginsDirectory(args[1]);
216

    
217
                    // Hacemos visibles los argumentos como una propiedad est?tica
218
                    // de plugin services para quien lo quiera usar (por ejemplo, para
219
                    // cargar un proyecto por l?nea de comandos)
220
                    PluginServices.setArguments(args);
221

    
222
                    configureLocales(args);
223

    
224
                    //Se pone el lookAndFeel
225
                    try {
226
                            String lookAndFeel = getAndamiConfig().getLookAndFeel();
227
                            if (lookAndFeel == null)
228
                                    lookAndFeel = getDefaultLookAndFeel();
229
                            UIManager.setLookAndFeel(lookAndFeel);
230
                    } catch (Exception e) {
231
                            logger.warn(Messages.getString("Launcher.look_and_feel"), e);
232
                    }
233
                // Solucionamos el problema de permisos que se produc?a con Java Web Start con este c?digo.
234
                // System.setSecurityManager(null);
235
             Policy.setPolicy(new Policy() {
236
             public PermissionCollection getPermissions(CodeSource codesource) {
237
                      Permissions perms = new Permissions();
238
                      perms.add(new AllPermission());
239
                      return (perms);
240
             }
241
             public void
242
                         refresh() {}
243
             });
244

    
245
                    validate();
246
                    // Mostrar la ventana de inicio
247
                    Frame f=new Frame();
248
                    splashWindow=new MultiSplashWindow(f);
249

    
250
                    // TODO Buscar actualizaciones de los plugins
251
                    downloadExtensions(andamiConfig.getPluginsDirectory());
252

    
253
                    // Se leen los config.xml de los plugins -----++++
254
                    loadPlugins(andamiConfig.getPluginsDirectory());
255

    
256
                    // Se configura el classloader del plugin
257
                    pluginsClassLoaders();
258

    
259
                    // Se carga un Skin si alguno de los plugins trae informaci?n para ello
260
                    skinPlugin();
261

    
262
                    //Se configura la cola de eventos
263
                    EventQueue waitQueue = new AndamiEventQueue();
264
                    Toolkit.getDefaultToolkit().getSystemEventQueue().push(waitQueue);
265

    
266
                    // Se configura la mensajer?a del plugin
267
                    pluginsMessages();
268

    
269
                    // Se modifica el andami-config con los plugins nuevos
270
                    updateAndamiConfig();
271

    
272
                    // Se prepara el MainFrame para albergar las extensiones
273
                    frame = new MDIFrame();
274

    
275
                    // Se configura el nombre e icono de la aplicaci?n
276
                    frameIcon();
277

    
278
                    SwingUtilities.invokeAndWait(new Runnable() {
279
                            public void run() {
280
                                    frame.init();
281
                            }
282
                    });
283

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

    
293
                    // Leer el fichero de persistencia
294
                    //  info de los plugins
295
                    //  bookmarks de los plugins
296
                    loadPluginsPersistence();
297

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

    
308
                    // Se instalan los bookmarks de los plugins
309

    
310
                    //Se muestra el frame principal
311
                    frame.show();
312

    
313
                    // Definimos un KeyEventDispatcher global para que las extensiones
314
                    // puedan registrar sus "teclas r?pidas".
315
                    GlobalKeyEventDispatcher keyDispatcher = GlobalKeyEventDispatcher.getInstance();
316
                    KeyboardFocusManager.getCurrentKeyboardFocusManager().addKeyEventDispatcher(keyDispatcher);
317

    
318
                    SwingUtilities.invokeAndWait(new Runnable() {
319
                            public void run() {
320
                                    frame.enableControls();
321
                            }
322
                    });
323
                    splashWindow.close();
324
            }catch(Exception e){
325
                    logger.error("excepci?n al arrancar", e);
326
                    System.exit(-1);
327
            }
328

    
329
    }
330

    
331
        /**
332
         * Recupera la geometr?a (tama?o, posici?n y estado) de la ventana principal de Andami.
333
         * TODO Pendiente de ver como se asigna un pluginServices para el launcher.
334
         * @author LWS
335
         */
336
        private static void restoreMDIStatus(XMLEntity xml) {
337
                //System.err.println("Launcher: restoreMDIStatus()");
338
                if (xml == null) xml = new XMLEntity();
339
                //  restore frame size
340
                Dimension sz = new Dimension(700,580);
341
                if (xml.contains("MDIFrameSize")) {
342
                        int [] wh = xml.getIntArrayProperty("MDIFrameSize");
343
                        sz = new Dimension(wh[0], wh[1]);
344
                }
345
                frame.setSize(sz);
346
                //  restore frame location
347
                Point pos = new Point(10,10);
348
                if (xml.contains("MDIFramePos")) {
349
                        int [] xy = xml.getIntArrayProperty("MDIFramePos");
350
                        pos = new Point(xy[0], xy[1]);
351
                }
352
                frame.setLocation(pos);
353

    
354
                //  restore frame status (Maximized, minimized, etc);
355
                int state = java.awt.Frame.MAXIMIZED_BOTH;
356
                if (xml.contains("MDIFrameState")) {
357
                        state = xml.getIntProperty("MDIFrameState");
358
                }
359
                frame.setExtendedState(state);
360
        }
361

    
362
        private static XMLEntity saveMDIStatus() {
363
                XMLEntity xml = new XMLEntity();
364
                // save frame size
365
                int [] wh = new int[2];
366
                wh[0] = frame.getWidth();
367
                wh[1] = frame.getHeight();
368
                xml.putProperty("MDIFrameSize", wh);
369
                // save frame location
370
                int [] xy = new int[2];
371
                xy[0] = frame.getX();
372
                xy[1] = frame.getY();
373
                xml.putProperty("MDIFramePos", xy);
374
                // save frame status
375
                xml.putProperty("MDIFrameState", frame.getExtendedState());
376
                return xml;
377
        }
378

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

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

    
399
                //System.err.println("loadPluginPersistence()");
400
                for (int i = 0; i < entity.getChildrenCount(); i++) {
401
                        XMLEntity plugin = entity.getChild(i);
402
                        String pName = plugin.getStringProperty(
403
                                        "com.iver.andami.pluginName");
404
                        //System.err.println("--> "+pName);
405
                        if (pluginsServices.get(pName)!= null){
406
                                ((PluginServices) pluginsServices.get(pName)).setPersistentXML(plugin);
407
                        } else {
408
                                if (pName.startsWith("Andami.Launcher"))
409
                                        restoreMDIStatus(plugin);
410
                        }
411
                }
412
        }
413

    
414
        /**
415
         * Salva la persistencia de los plugins.
416
         * @author LWS
417
         */
418
        private static void savePluginPersistence() {
419
                Iterator i = pluginsConfig.keySet().iterator();
420

    
421
                XMLEntity entity = new XMLEntity();
422

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

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

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

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

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

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

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

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

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

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

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

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

    
497
                                Class skinClass;
498

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
582
                                try {
583
                                        Class extensionClass = ps.getClassLoader().loadClass(extension.getClassName());
584
                                        extensionInstance = (com.iver.andami.plugins.IExtension) extensionClass.newInstance();
585

    
586
                                        // CON DECORATOR
587
                                        // ANTES: classesExtensions.put(extensionClass, extensionInstance);
588
                                        // AHORA: CREAMOS UNA ExtensionDecorator y asignamos esta instancia para
589
                                        // poder ampliar con nuevas propiedades (AlwaysVisible, por ejemplo)
590
                                        // Para crear la nueva clase ExtensionDecorator, le pasamos como par?metro
591
                                        // la extensi?n original que acabamos de crear
592
                                        // 0-> Inactivo, controla la extension
593
                                        // 1-> Siempre visible
594
                                        // 2-> Invisible
595
                                        ExtensionDecorator newExtensionDecorator = new ExtensionDecorator(extensionInstance, ExtensionDecorator.INACTIVE);
596
                                        classesExtensions.put(extensionClass, newExtensionDecorator);
597
                                        System.err.println("Loading "+extension.getClassName()+"...");
598
                    // logger.debug("Initializing " + extension.getClassName());
599
                    extensionInstance.initialize();
600
                    extensions.add(extensionInstance);
601
                    // logger.debug(extension.getClassName() + " initialized.");
602

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

    
624
        private static void postInitializeExtensions() {
625
                for (int i=0;i<extensions.size();i++) {
626
                        com.iver.andami.plugins.IExtension extensionInstance=(com.iver.andami.plugins.IExtension)extensions.get(i);
627
                        extensionInstance.postInitialize();
628
                }
629
        }
630
        /**
631
         * DOCUMENT ME!
632
         */
633
        private static void installPluginsMenus() {
634
                TreeMap orderedMenus = new TreeMap(new MenuComparator());
635

    
636
                Iterator i = pluginsConfig.keySet().iterator();
637

    
638
                while (i.hasNext()) {
639
                        String pName = (String) i.next();
640
                        PluginServices ps = (PluginServices) pluginsServices.get(pName);
641
                        PluginConfig pc = (PluginConfig) pluginsConfig.get(pName);
642

    
643
                        Extension[] exts = pc.getExtensions().getExtension();
644

    
645
                        for (int j = 0; j < exts.length; j++) {
646
                                if (!exts[j].getActive()) {
647
                                        continue;
648
                                }
649

    
650
                                Menu[] menus = exts[j].getMenu();
651

    
652
                                for (int k = 0; k < menus.length; k++) {
653
                                        SortableMenu sm = new SortableMenu(ps.getClassLoader(),
654
                                                        exts[j], menus[k]);
655

    
656
                                        if (orderedMenus.containsKey(sm)) {
657
                                                logger.error(Messages.getString(
658
                                                                "Launcher.Two_menus_with_the_same_position") + " - " +
659
                                                        menus[k].getText()+ " - " + exts[j].getClassName());
660
                                        }
661

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

    
666
                        // Se instalan las extensiones de MDI
667
                        SkinExtension skinExt = pc.getExtensions().getSkinExtension();
668

    
669
                        if (skinExt != null) {
670
                                Menu[] menu = skinExt.getMenu();
671

    
672
                                for (int k = 0; k < menu.length; k++) {
673
                                        SortableMenu sm = new SortableMenu(ps.getClassLoader(),
674
                                                        skinExt, menu[k]);
675

    
676
                                        if (orderedMenus.containsKey(sm)) {
677
                                                logger.error(Messages.getString(
678
                                                                "Launcher.Two_menus_with_the_same_position") +
679
                                                        skinExt.getClassName());
680
                                        }
681

    
682
                                        orderedMenus.put(sm, null);
683
                                }
684
                        }
685
                }
686

    
687
                //Se itera por los menus ordenados
688
                Iterator e = orderedMenus.keySet().iterator();
689

    
690
                // Se ordenan los menues
691
                while (e.hasNext()) {
692
                        try {
693
                                SortableMenu sm = (SortableMenu) e.next();
694

    
695
                                frame.addMenu(sm.loader, sm.extension, sm.menu);
696
                        } catch (ClassNotFoundException ex) {
697
                                logger.error(Messages.getString(
698
                                                "Launcher.No_se_encontro_la_clase_de_la_extension"), ex);
699
                        }
700
                }
701
        }
702

    
703
        /**
704
         * Installs the menus, toolbars, actiontools, selectable toolbars and combos.
705
         * The order in which they are shown is determined here.
706
         */
707
        private static void installPluginsControls() {
708
                Iterator i = pluginsConfig.keySet().iterator();
709

    
710
                HashMap extensionPluginServices = new HashMap();
711
                HashMap extensionPluginConfig = new HashMap();
712
                TreeMap orderedExtensions = new TreeMap(new ExtensionComparator());
713

    
714
                // First of all, sort the extensions.
715
                // We need to iterate on the plugins, and iterate on each plugin's extensions
716
                // (each plugin may contain one or more extensions)
717
                while (i.hasNext()) { // iterate on the plugins
718
                        String pName = (String) i.next();
719
                        PluginConfig pc = (PluginConfig) pluginsConfig.get(pName);
720
                        PluginServices ps = (PluginServices) pluginsServices.get(pName);
721

    
722
                        Extension[] exts = pc.getExtensions().getExtension();
723

    
724
                        for (int j = 0; j < exts.length; j++) { // iterate on the extensions
725
                                if (exts[j].getActive()) {
726
                                        if (orderedExtensions.containsKey(exts[j])) {
727
                                                logger.error(Messages.getString(
728
                                                "Launcher.Two_extensions_with_the_same_priority") +
729
                                                exts[j].getClassName());
730
                                        }
731

    
732
                                        orderedExtensions.put(exts[j], null);
733
                                        extensionPluginServices.put(exts[j], ps);
734
                                        extensionPluginConfig.put(exts[j], pc);
735
                                }
736
                        }
737
                }
738

    
739
                TreeMap orderedTools = new TreeMap(new ToolComparator());
740
                Iterator e = orderedExtensions.keySet().iterator();
741

    
742
                // sort the toolbars and tools from 'normal' extensions (actiontools, selectabletools)
743
                // and load the  combo-scales and combo-buttons for the status bar
744
                while (e.hasNext()) {
745
                        Extension ext = (Extension) e.next();
746

    
747
                        ToolBar[] toolbars = ext.getToolBar();
748

    
749
                        // get tools from toolbars
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
                                        SortableTool sm = new SortableTool(((PluginServices)extensionPluginServices.get(ext)).getClassLoader(), ext,
755
                                                        toolbars[k], tools[t]);
756
                                        orderedTools.put(sm, null);
757
                                }
758

    
759
                                SelectableTool[] sTools = toolbars[k].getSelectableTool();
760

    
761
                                for (int t = 0; t < sTools.length; t++) {
762
                                        SortableTool sm=new SortableTool(((PluginServices)extensionPluginServices.get(ext)).getClassLoader(), ext,
763
                                                        toolbars[k], sTools[t]);
764
                                        orderedTools.put(sm, null);
765
                                }
766
                        }
767

    
768
                        // get controls for statusBar
769
                        PluginServices ps = (PluginServices) extensionPluginServices.get(ext);
770
                        PluginClassLoader loader = ps.getClassLoader();
771

    
772
                        //ArrayList componentList = new ArrayList();
773
                        ComboScale[] comboScaleArray = ext.getComboScale();
774
                        for (int k=0; k < comboScaleArray.length; k++) {
775
                                org.gvsig.gui.beans.controls.comboscale.ComboScale combo = new org.gvsig.gui.beans.controls.comboscale.ComboScale();
776
                                String label = comboScaleArray[k].getLabel();
777
                                if (label!=null)
778
                                        combo.setLabel(label);
779
                                String name = comboScaleArray[k].getName();
780
                                if (name!=null)
781
                                        combo.setName(name);
782
                                String[] elementsString = ((String)comboScaleArray[k].getElements()).split(";");
783
                                long[] elements = new long[elementsString.length];
784
                                for (int currentElem=0; currentElem<elementsString.length; currentElem++) {
785
                                        try {
786
                                                elements[currentElem] = Long.parseLong(elementsString[currentElem]);
787
                                        }
788
                                        catch (NumberFormatException nfex1) {
789
                                                logger.error(ext.getClassName()+" -- "+Messages.getString( "error_parsing_comboscale_elements"));
790
                                                elements[currentElem] = 0;
791
                                        }
792
                                }
793
                                combo.setItems(elements);
794
                                try {
795
                                        long value = Long.parseLong((String)comboScaleArray[k].getValue());
796
                                        combo.setScale(value);
797
                                }
798
                                catch (NumberFormatException nfex2) {
799
                                        logger.error(ext.getClassName()+" -- "+Messages.getString( "error_parsing_comboscale_value"));
800
                                }
801
                                try {
802
                                        frame.addStatusBarControl(loader.loadClass(ext.getClassName()),combo);
803
                                } catch (ClassNotFoundException e1) {
804
                                        logger.error(Messages.getString("Launcher.error_getting_class_loader_for_status_bar_control"), e1);
805
                                }
806
                        }
807

    
808
                        ComboButton[] comboButtonArray = ext.getComboButton();
809
                        for (int k=0; k < comboButtonArray.length; k++) {
810
                                ComboButtonElement[] elementList = comboButtonArray[k].getComboButtonElement();
811
                                org.gvsig.gui.beans.controls.combobutton.ComboButton combo = new org.gvsig.gui.beans.controls.combobutton.ComboButton();
812
                                String name = comboButtonArray[k].getName();
813
                                if (name!=null)
814
                                        combo.setName(name);
815
                                for (int currentElement=0; currentElement<elementList.length; currentElement++) {
816
                                        ComboButtonElement element = elementList[currentElement];
817
                                        ImageIcon icon;
818
                                        URL iconLocation = loader.getResource(element.getIcon());
819
                                        if (iconLocation==null)
820
                                                logger.error(Messages.getString("Icon_not_found_")+element.getIcon());
821
                                        else {
822
                                                icon = new ImageIcon(iconLocation);
823
                                                JButton button = new JButton(icon);
824
                                                combo.addButton(button);
825
                                                button.setActionCommand(element.getActionCommand());
826
                                        }
827
                                }
828
                                try {
829
                                        frame.addStatusBarControl(loader.loadClass(ext.getClassName()), combo);
830
                                } catch (ClassNotFoundException e1) {
831
                                        logger.error(Messages.getString("Launcher.error_getting_class_loader_for_status_bar_control"), e1);
832
                                }
833
                        }
834
                }
835

    
836
                // Add the tools from MDI extensions to the ordered tool-list, so that we get a sorted list containing all the tools
837
                i = pluginsConfig.keySet().iterator();
838
                while (i.hasNext()) {
839
                        String pName = (String) i.next();
840
                        PluginConfig pc = (PluginConfig) pluginsConfig.get(pName);
841
                        PluginServices ps = (PluginServices) pluginsServices.get(pName);
842

    
843
                        SkinExtension skinExt = pc.getExtensions().getSkinExtension();
844

    
845
                        if (skinExt != null) {
846
                                ToolBar[] toolbars = skinExt.getToolBar();
847

    
848
                                for (int k = 0; k < toolbars.length; k++) {
849
                                        ActionTool[] tools = toolbars[k].getActionTool();
850

    
851
                                        for (int t = 0; t < tools.length; t++) {
852
                                                SortableTool stb=new SortableTool(ps.getClassLoader(), skinExt,
853
                                                                toolbars[k], tools[t]);
854
                                                orderedTools.put(stb,null);
855
                                        }
856

    
857
                                        SelectableTool[] sTools = toolbars[k].getSelectableTool();
858

    
859
                                        for (int t = 0; t < sTools.length; t++) {
860
                                                SortableTool stb=new SortableTool(ps.getClassLoader(), skinExt,
861
                                                                toolbars[k], sTools[t]);
862
                                                orderedTools.put(stb,null);
863
                                        }
864
                                }
865
                        }
866
                        // Install popup menus
867
                        PopupMenus pus = pc.getPopupMenus();
868

    
869
                        if (pus != null) {
870
                                PopupMenu[] menus = pus.getPopupMenu();
871

    
872
                                for (int j = 0; j < menus.length; j++) {
873
                                        frame.addPopupMenu(ps.getClassLoader(), menus[j]);
874
                                }
875
                        }
876
                }
877

    
878
                // loop on the ordered extension list, to add them to the interface in an ordered way
879
                Iterator t = orderedTools.keySet().iterator();
880
                while (t.hasNext()) {
881
                        try {
882
                                SortableTool stb = (SortableTool) t.next();
883
                                if (stb.actiontool!=null)
884
                                        frame.addTool(stb.loader, stb.extension,stb.toolbar, stb.actiontool);
885
                                else
886
                                        frame.addTool(stb.loader, stb.extension,stb.toolbar, stb.selectabletool);
887
                        } catch (ClassNotFoundException ex) {
888
                                logger.error(Messages.getString(
889
                                "Launcher.No_se_encontro_la_clase_de_la_extension"), ex);
890
                        }
891
                }
892
        }
893

    
894
        /**
895
         * Adds new plugins to the the andami-config file.
896
         */
897
        private static void updateAndamiConfig() {
898
                HashSet olds = new HashSet();
899

    
900
                Plugin[] plugins = andamiConfig.getPlugin();
901

    
902
                for (int i = 0; i < plugins.length; i++) {
903
                        olds.add(plugins[i].getName());
904
                }
905

    
906
                Iterator i = pluginsServices.values().iterator();
907

    
908
                while (i.hasNext()) {
909
                        PluginServices ps = (PluginServices) i.next();
910

    
911
                        if (!olds.contains(ps.getPluginName())) {
912
                                Plugin p = new Plugin();
913
                                p.setName(ps.getPluginName());
914
                                p.setUpdate(false);
915

    
916
                                andamiConfig.addPlugin(p);
917
                        }
918
                }
919
        }
920

    
921
        /**
922
         * DOCUMENT ME!
923
         */
924
        private static void pluginsClassLoaders() {
925
                HashSet instalados = new HashSet();
926

    
927
                // Se itera hasta que est?n todos instalados
928
                while (instalados.size() != pluginsConfig.size()) {
929
                        boolean circle = true;
930

    
931
                        //Hacemos una pasada por todos los plugins
932
                        Iterator i = pluginsConfig.keySet().iterator();
933

    
934
                        while (i.hasNext()) {
935
                                String pluginName = (String) i.next();
936
                                PluginConfig config = (PluginConfig) pluginsConfig.get(pluginName);
937

    
938
                                if (instalados.contains(pluginName)) {
939
                                        continue;
940
                                }
941

    
942
                                //Se obtienen las dependencias y sus class loaders
943
                                boolean ready = true;
944
                                Depends[] dependencies = config.getDepends();
945
                                PluginClassLoader[] loaders = new PluginClassLoader[dependencies.length];
946

    
947
                                for (int j = 0; j < dependencies.length; j++) {
948
                                        if (pluginsConfig.get(dependencies[j].getPluginName()) == null) {
949
                                                logger.error(Messages.getString(
950
                                                                "Launcher.Dependencia_no_resuelta_en_plugin") +
951
                                                        pluginName + ": " +
952
                                                        dependencies[j].getPluginName());
953

    
954
                                                continue;
955
                                        }
956

    
957
                                        if (!instalados.contains(dependencies[j].getPluginName())) {
958
                                                ready = false;
959
                                        } else {
960
                                                loaders[j] = ((PluginServices) pluginsServices.get(dependencies[j].getPluginName())).getClassLoader();
961
                                        }
962
                                }
963

    
964
                                //Si no est?n sus dependencias satisfechas se aborta la instalaci?n
965
                                if (!ready) {
966
                                        continue;
967
                                }
968

    
969
                                //Se genera el class loader
970
                                String jardir = config.getLibraries().getLibraryDir();
971
                                File jarDir = new File(andamiConfig.getPluginsDirectory() +
972
                                                File.separator + pluginName + File.separator + jardir);
973
                                File[] jarFiles = jarDir.listFiles(new FileFilter() {
974
                                                        public boolean accept(File pathname) {
975
                                                                return (pathname.getName().toUpperCase()
976
                                                                                                .endsWith(".JAR")) ||
977
                                                                (pathname.getName().toUpperCase().endsWith(".ZIP"));
978
                                                        }
979
                                                });
980

    
981
                                URL[] urls = new URL[jarFiles.length];
982

    
983
                                for (int j = 0; j < jarFiles.length; j++) {
984
                                        try {
985
                                                urls[j] = new URL("file:" + jarFiles[j]);
986
                                        } catch (MalformedURLException e) {
987
                                                logger.error(Messages.getString(
988
                                                                "Launcher.No_se_puede_acceder_a") +
989
                                                        jarFiles[j]);
990
                                        }
991
                                }
992

    
993
                                PluginClassLoader loader;
994

    
995
                                try {
996
                                        loader = new PluginClassLoader(urls,
997
                                                        andamiConfig.getPluginsDirectory() +
998
                                                        File.separator + pluginName,
999
                                                        Launcher.class.getClassLoader(), loaders);
1000

    
1001
                                        PluginServices ps = new PluginServices(loader);
1002

    
1003
                                        pluginsServices.put(ps.getPluginName(), ps);
1004

    
1005
                                        instalados.add(pluginName);
1006
                    // FJP: Los metemos ordenados para luego no cargar uno que necesita de otro antes de tiempo. Esto lo usaremos al
1007
                    // inicializar los plugins
1008
                    pluginsOrdered.add(pluginName);
1009

    
1010
                                        circle = false;
1011
                                } catch (IOException e) {
1012
                                        logger.error(Messages.getString(
1013
                                                        "Launcher.Error_con_las_librerias_del_plugin"), e);
1014
                                        pluginsConfig.remove(pluginName);
1015
                                        i = pluginsConfig.keySet().iterator();
1016
                                }
1017
                        }
1018

    
1019
                        if (circle) {
1020
                                logger.error(Messages.getString(
1021
                                                "Launcher.Hay_dependencias_circulares"));
1022

    
1023
                                break;
1024
                        }
1025
                }
1026

    
1027
                //Se eliminan los plugins que no fueron instalados
1028
                Iterator i = pluginsConfig.keySet().iterator();
1029

    
1030
                while (i.hasNext()) {
1031
                        String pluginName = (String) i.next();
1032
                        PluginConfig config = (PluginConfig) pluginsConfig.get(pluginName);
1033
                        PluginServices ps = (PluginServices) pluginsServices.get(pluginName);
1034

    
1035
                        if (ps == null) {
1036
                                pluginsConfig.remove(pluginName);
1037
                                i = pluginsConfig.keySet().iterator();
1038
                        }
1039
                }
1040
        }
1041

    
1042
        /**
1043
         * DOCUMENT ME!
1044
         */
1045
        private static void pluginsMessages() {
1046
                /* add gvsig translations first. This should be done using a generic "appPlugin" variable, instead
1047
                 * of using "com.iver.cit.gvsig" directly, but I'll do it when we use the new appgvSIG launcher.
1048
                 * I keep this workaround for the moment.
1049
                 */
1050
                PluginConfig config = (PluginConfig) pluginsConfig.get("com.iver.cit.gvsig");
1051
                PluginServices ps = (PluginServices) pluginsServices.get("com.iver.cit.gvsig");
1052
                if (config.getResourceBundle() != null) {
1053
                        org.gvsig.i18n.Messages.addResourceFamily(config.getResourceBundle().getName(), ps.getClassLoader(), "com.iver.cit.gvsig");
1054
                }
1055

    
1056
                //Iteramos por todos los plugins
1057
                Iterator i = pluginsConfig.keySet().iterator();
1058

    
1059
                while (i.hasNext()) {
1060
                        String pluginName = (String) i.next();
1061
                        if (!pluginName.equals("com.iver.cit.gvsig")) { // we've already loaded com.iver.cit.gvsig
1062
                                config = (PluginConfig) pluginsConfig.get(pluginName);
1063
                                ps = (PluginServices) pluginsServices.get(pluginName);
1064

    
1065
                                if (config.getResourceBundle() != null && !config.getResourceBundle().getName().equals("")) {
1066
                                        // add the locale files associated with the plugin
1067
                                        org.gvsig.i18n.Messages.addResourceFamily(config.getResourceBundle().getName(), ps.getClassLoader(), pluginName);
1068
                                }
1069
                        }
1070
                }
1071
        }
1072

    
1073
        /**
1074
         * DOCUMENT ME!
1075
         *
1076
         * @param name DOCUMENT ME!
1077
         *
1078
         * @return DOCUMENT ME!
1079
         */
1080
        static PluginServices getPluginServices(String name) {
1081
                return (PluginServices) pluginsServices.get(name);
1082
        }
1083

    
1084
        /**
1085
         * DOCUMENT ME!
1086
         *
1087
         * @return DOCUMENT ME!
1088
         */
1089
        static String getPluginsDir() {
1090
                return andamiConfig.getPluginsDirectory();
1091
        }
1092

    
1093
        /**
1094
         * DOCUMENT ME!
1095
         *
1096
         * @param s DOCUMENT ME!
1097
         */
1098
        static void setPluginsDir(String s) {
1099
                andamiConfig.setPluginsDirectory(s);
1100
        }
1101

    
1102
        /**
1103
         * DOCUMENT ME!
1104
         *
1105
         * @return DOCUMENT ME!
1106
         */
1107
        static MDIFrame getMDIFrame() {
1108
                return frame;
1109
        }
1110

    
1111
        /**
1112
         * DOCUMENT ME!
1113
         *
1114
         * @param pluginsDirectory
1115
         */
1116
        private static void loadPlugins(String pluginsDirectory) {
1117
                File pDir = new File(pluginsDirectory);
1118

    
1119
                if (!pDir.exists()) {
1120
                        return;
1121
                }
1122

    
1123
                File[] pluginDirs = pDir.listFiles();
1124

    
1125
                for (int i = 0; i < pluginDirs.length; i++) {
1126
                        if (pluginDirs[i].isDirectory()) {
1127
                                File configXml = new File(pluginDirs[i].getAbsolutePath() +
1128
                                                File.separator + "config.xml");
1129

    
1130
                                try {
1131
                                        FileInputStream is = new FileInputStream(configXml);
1132
                                        Reader xml = com.iver.utiles.xml.XMLEncodingUtils.getReader(is);
1133
                                        if (xml==null) {
1134
                                                // the encoding was not correctly detected, use system default
1135
                                                xml = new FileReader(configXml);
1136
                                        }
1137
                                        else {
1138
                                                // use a buffered reader to improve performance
1139
                                                xml = new BufferedReader(xml);
1140
                                        }
1141
                                        PluginConfig pConfig = (PluginConfig) PluginConfig.unmarshal(xml);
1142
                                        pluginsConfig.put(pluginDirs[i].getName(), pConfig);
1143
                                } catch (FileNotFoundException e) {
1144
                                        logger.info(Messages.getString(
1145
                                                        "Launcher.Ignorando_el_directorio") +
1146
                                                pluginDirs[i].getAbsolutePath() +
1147
                                                Messages.getString("Launcher.config_no_encontrado"));
1148
                                } catch (MarshalException e) {
1149
                                        logger.info(Messages.getString(
1150
                                                        "Launcher.Ignorando_el_directorio") +
1151
                                                pluginDirs[i].getAbsolutePath() +
1152
                                                Messages.getString("Launcher.config_mal_formado"), e);
1153
                                } catch (ValidationException e) {
1154
                                        logger.info(Messages.getString(
1155
                                                        "Launcher.Ignorando_el_directorio") +
1156
                                                pluginDirs[i].getAbsolutePath() +
1157
                                                Messages.getString("Launcher.config_mal_formado"), e);
1158
                                }
1159
                        }
1160
                }
1161
        }
1162

    
1163
        /**
1164
         * DOCUMENT ME!
1165
         *
1166
         * @param language
1167
         * @param country
1168
         * @param variant
1169
         *
1170
         * @return DOCUMENT ME!
1171
         */
1172
        private static Locale getLocale(String language, String country,
1173
                String variant) {
1174
                if (variant != null) {
1175
                        return new Locale(language, country, variant);
1176
                } else if (country != null) {
1177
                        return new Locale(language, country);
1178
                } else if (language != null) {
1179
                        return new Locale(language);
1180
                } else {
1181
                        return new Locale("es");
1182
                }
1183
        }
1184

    
1185
        /**
1186
         * DOCUMENT ME!
1187
         *
1188
         * @param file DOCUMENT ME!
1189
         *
1190
         * @throws IOException DOCUMENT ME!
1191
         * @throws MarshalException DOCUMENT ME!
1192
         * @throws ValidationException DOCUMENT ME!
1193
         */
1194
        private static void andamiConfigToXML(String file)
1195
                throws IOException, MarshalException, ValidationException {
1196
                File xml = new File(file);
1197
                File parent = xml.getParentFile();
1198
                parent.mkdirs();
1199

    
1200
                FileWriter writer = new FileWriter(xml);
1201
                andamiConfig.marshal(writer);
1202
        }
1203

    
1204
        /**
1205
         * DOCUMENT ME!
1206
         *
1207
         * @param file DOCUMENT ME!
1208
         *
1209
         * @throws ConfigurationException DOCUMENT ME!
1210
         */
1211
        private static void andamiConfigFromXML(String file)
1212
                throws ConfigurationException {
1213
                File xml = new File(file);
1214

    
1215
                //Si no existe se ponen los valores por defecto
1216
                if (!xml.exists()) {
1217
                        andamiConfig = new AndamiConfig();
1218

    
1219
                        Andami andami = new Andami();
1220
                        andami.setUpdate(true);
1221
                        andamiConfig.setAndami(andami);
1222
                        andamiConfig.setLocaleCountry(Locale.getDefault().getCountry());
1223
                        andamiConfig.setLocaleLanguage(Locale.getDefault().getLanguage());
1224
                        andamiConfig.setLocaleVariant(Locale.getDefault().getVariant());
1225

    
1226
                        if (System.getProperty("javawebstart.version") != null) // Es java web start)
1227
                         {
1228
                                andamiConfig.setPluginsDirectory(new File(appHomeDir
1229
                                                + "extensiones").getAbsolutePath());
1230
                        } else {
1231
                                andamiConfig.setPluginsDirectory(new File(appName +
1232
                                                File.separator + "extensiones").getAbsolutePath());
1233
                        }
1234

    
1235
                        andamiConfig.setPlugin(new Plugin[0]);
1236
                } else {
1237
                        //Se lee la configuraci?n
1238
                        FileReader reader;
1239

    
1240
                        try {
1241
                                reader = new FileReader(xml);
1242
                                andamiConfig = (AndamiConfig) AndamiConfig.unmarshal(reader);
1243
                        } catch (FileNotFoundException e) {
1244
                                throw new ConfigurationException(e);
1245
                        } catch (MarshalException e) {
1246
                                throw new ConfigurationException(e);
1247
                        } catch (ValidationException e) {
1248
                                throw new ConfigurationException(e);
1249
                        }
1250
                }
1251
        }
1252

    
1253
        /**
1254
         * DOCUMENT ME!
1255
         *
1256
         * @return DOCUMENT ME!
1257
         *
1258
         * @throws ConfigurationException DOCUMENT ME!
1259
         */
1260
        private static XMLEntity persistenceFromXML() throws ConfigurationException {
1261
                File xml = new File(pluginsPersistencePath);
1262

    
1263
                if (xml.exists()) {
1264
                        FileReader reader;
1265

    
1266
                        try {
1267
                                reader = new FileReader(xml);
1268

    
1269
                                XmlTag tag = (XmlTag) XmlTag.unmarshal(reader);
1270

    
1271
                                return new XMLEntity(tag);
1272
                        } catch (FileNotFoundException e) {
1273
                                throw new ConfigurationException(e);
1274
                        } catch (MarshalException e) {
1275
                                throw new ConfigurationException(e);
1276
                        } catch (ValidationException e) {
1277
                                throw new ConfigurationException(e);
1278
                        }
1279
                } else {
1280
                        return new XMLEntity();
1281
                }
1282
        }
1283

    
1284
        /**
1285
         * DOCUMENT ME!
1286
         *
1287
         * @param entity DOCUMENT ME!
1288
         *
1289
         * @throws ConfigurationException DOCUMENT ME!
1290
         */
1291
        private static void persistenceToXML(XMLEntity entity)
1292
                throws ConfigurationException {
1293
                File xml = new File(pluginsPersistencePath);
1294

    
1295
                FileWriter writer;
1296

    
1297
                try {
1298
                        writer = new FileWriter(xml);
1299
                        entity.getXmlTag().marshal(writer);
1300
                } catch (FileNotFoundException e) {
1301
                        throw new ConfigurationException(e);
1302
                } catch (MarshalException e) {
1303
                        throw new ConfigurationException(e);
1304
                } catch (ValidationException e) {
1305
                        throw new ConfigurationException(e);
1306
                } catch (IOException e) {
1307
                        throw new ConfigurationException(e);
1308
                }
1309
        }
1310

    
1311
        /**
1312
         * Devuelve un array con los directorios de los plugins
1313
         *
1314
         * @param dirExt Directorio de las extensiones a partir del cual cuelgan
1315
         *                   todos los directorios de los plugins
1316
         *
1317
         * @return ArrayList con los directorios
1318
         */
1319
        private String[] getLocales(File dirExt) {
1320
                ArrayList types = new ArrayList();
1321
                File[] files = dirExt.listFiles();
1322

    
1323
                for (int i = 0; i < files.length; i++) {
1324
                        if (files[i].isDirectory()) {
1325
                                File[] textFile = files[i].listFiles(new FilenameFilter() {
1326
                                                        public boolean accept(File dir, String fileName) {
1327
                                                                return fileName.toLowerCase().startsWith("text_"); //$NON-NLS-1$
1328
                                                        }
1329
                                                });
1330

    
1331
                                for (int j = 0; j < textFile.length; j++) {
1332
                                        String s = (textFile[j]).getName().replaceAll("text_", "");
1333
                                        s = s.replaceAll(".properties", "");
1334
                                        s = s.trim();
1335

    
1336
                                        if (!types.contains(s)) {
1337
                                                types.add(s);
1338
                                        }
1339
                                }
1340
                        }
1341
                }
1342

    
1343
                return (String[]) types.toArray(new String[0]);
1344
        }
1345

    
1346
        /**
1347
         * DOCUMENT ME!
1348
         *
1349
         * @return Returns the frame.
1350
         */
1351
        static MDIFrame getFrame() {
1352
                return frame;
1353
        }
1354

    
1355
        /**
1356
         * Secuencia de cerrado de Andami
1357
         */
1358
        public static void closeApplication() {
1359
                //Configuraci?n de Andami
1360
                try {
1361
                        andamiConfigToXML(andamiConfigPath);
1362
                } catch (MarshalException e) {
1363
                        logger.error(Messages.getString(
1364
                                        "Launcher.No_se_pudo_guardar_la_configuracion_de_andami"), e);
1365
                } catch (ValidationException e) {
1366
                        logger.error(Messages.getString(
1367
                                        "Launcher.No_se_pudo_guardar_la_configuracion_de_andami"), e);
1368
                } catch (IOException e) {
1369
                        logger.error(Messages.getString(
1370
                                        "Launcher.No_se_pudo_guardar_la_configuracion_de_andami"), e);
1371
                }
1372

    
1373
                //Persistencia de los plugins
1374
                savePluginPersistence();
1375

    
1376
                //Finalize all the extensions
1377
                finalizeExtensions();
1378

    
1379
                // Clean any temp data created
1380
                Utilities.cleanUpTempFiles();
1381

    
1382
                //Para la depuraci?n de memory leaks
1383
                System.gc();
1384

    
1385
        System.exit(0);
1386
        }
1387

    
1388
        /**
1389
         * Exectutes the finalize method for all the extensions
1390
         *
1391
         */
1392
        private static void finalizeExtensions() {
1393
                Set extensions = getClassesExtensions().keySet();
1394
                Object[] keys = extensions.toArray();
1395

    
1396
                for (int i=0 ; i<keys.length ; i++){
1397
                        ExtensionDecorator extensionDecorator =
1398
                                (ExtensionDecorator) getClassesExtensions().get(keys[i]);
1399
                        extensionDecorator.getExtension().terminate();
1400
                }
1401
        }
1402

    
1403

    
1404
        /**
1405
         * DOCUMENT ME!
1406
         *
1407
         * @return DOCUMENT ME!
1408
         */
1409
        static HashMap getClassesExtensions() {
1410
                return classesExtensions;
1411
        }
1412

    
1413
        /**
1414
         * DOCUMENT ME!
1415
         *
1416
         * @param extDir DOCUMENT ME!
1417
         */
1418
        private static void downloadExtensions(String extDir) {
1419
                java.util.Date fechaActual = null;
1420

    
1421
                try {
1422
                        if (System.getProperty("javawebstart.version") != null) {
1423
                                //Obtenemos la URL del servidor
1424
                                BasicService bs = (BasicService) ServiceManager.lookup(
1425
                                                "javax.jnlp.BasicService");
1426
                                URL baseURL = bs.getCodeBase();
1427

    
1428
                                //Se descargan las extensiones
1429
                                MultiSplashWindow.process(5,
1430
                                        "Descargando las extensiones desde " + baseURL + " a " +
1431
                                        extDir);
1432

    
1433
                                URL url = new URL(baseURL + "extensiones.zip");
1434
                                URLConnection connection = url.openConnection();
1435

    
1436
                                System.out.println(url.toExternalForm() + ":");
1437
                                System.out.println("  Content Type: " +
1438
                                        connection.getContentType());
1439
                                System.out.println("  Content Length: " +
1440
                                        connection.getContentLength());
1441
                                System.out.println("  Last Modified: " +
1442
                                        new Date(connection.getLastModified()));
1443
                                System.out.println("  Expiration: " +
1444
                                        connection.getExpiration());
1445
                                System.out.println("  Content Encoding: " +
1446
                                        connection.getContentEncoding());
1447

    
1448
                                // Guardamos la fecha del fichero de extensiones que nos hemos bajado, y
1449
                                // comprobamos el ?ltimo que se ha bajado. Si no son
1450
                                // iguales, nos bajamos el nuevo. Si son iguales, no
1451
                                // nos bajamos nada.
1452
                                Long miliSecondsInWeb = new Long(connection.getLastModified());
1453

    
1454
                                // PluginServices ps = PluginServices.getPluginServices("com.iver.core");
1455
                                // if (ps.getPersistentXML().getStringProperty("timestamp") != null)
1456
                                File destDir = new File(extDir);
1457

    
1458
                                if (!destDir.exists()) {
1459
                                        // Creamos gvSIG
1460
                                        destDir.getParentFile().mkdir();
1461

    
1462
                                        if (!destDir.mkdir()) {
1463
                                                System.err.println("Imposible crear el directorio " +
1464
                                                        destDir.getAbsolutePath());
1465
                                        }
1466
                                }
1467

    
1468
                                File timeFile = new File(destDir.getParent() + File.separator +
1469
                                                "timeStamp.properties");
1470

    
1471
                                if (!timeFile.exists()) {
1472
                                        timeFile.createNewFile();
1473
                                }
1474

    
1475
                                FileInputStream inAux = new FileInputStream(timeFile);
1476
                                Properties prop = new Properties();
1477
                                prop.load(inAux);
1478
                                inAux.close();
1479

    
1480
                                if (prop.getProperty("timestamp") != null) {
1481
                                        Long lastMiliSeconds = (Long) new Long(prop.getProperty(
1482
                                                                "timestamp"));
1483

    
1484
                                        if (lastMiliSeconds.longValue() == miliSecondsInWeb.longValue()) {
1485
                                                System.out.println("No hay nueva actualizaci?n");
1486
                        logger.debug("No hay nueva actualizaci?n -> Return");
1487
                        logger.debug("timeStampWeb= " + miliSecondsInWeb);
1488
                        logger.debug("timeStampLocal= " + lastMiliSeconds);
1489

    
1490
                                                return;
1491
                                        }
1492

    
1493
                                        System.out.println("timeStampWeb= " + miliSecondsInWeb);
1494
                                        System.out.println("timeStampLocal= " + lastMiliSeconds);
1495
                                } else {
1496
                                        System.out.println("El timeStamp no est? escrito en " +
1497
                                                timeFile.getAbsolutePath());
1498
                                }
1499

    
1500
                                InputStream stream = url.openStream();
1501
                File temp = File.createTempFile("gvsig", ".zip");
1502

    
1503
                logger.debug(temp.getAbsolutePath());
1504

    
1505
                temp.deleteOnExit();
1506
                FileOutputStream file = new FileOutputStream(temp);
1507

    
1508
                byte[] lt_read = new byte[1];
1509

    
1510
                while (stream.read(lt_read) > 0)
1511
                  file.write(lt_read);
1512

    
1513
                                stream.close();
1514
                stream = null;
1515
                file.close();
1516
                file = null;
1517

    
1518
                System.gc();
1519

    
1520
                logger.debug("Ha creado el fichero ZIP");
1521
                                //Se extrae el zip
1522
                                MultiSplashWindow.process(5, "Extensiones descargadas.");
1523

    
1524
                                System.out.println("Extrayendo a " + destDir.getAbsolutePath());
1525

    
1526
                                Date fechaDir = new Date(destDir.lastModified());
1527
                                System.out.println("Fecha del directorio " + extDir + " = " +
1528
                                        fechaDir.toString());
1529
                                Utilities.extractTo(temp, new File(extDir), splashWindow);
1530

    
1531
                                // Si todo ha ido bien, guardamos el timestamp.
1532
                                ///  App.instance.getPc().addProperties("timestamp", miliSecondsInWeb);
1533
                                // XMLEntity xml=ps.getPersistentXML();
1534
                                fechaActual = new java.util.Date();
1535

    
1536
                                FileOutputStream outAux = new FileOutputStream(timeFile);
1537
                                prop.setProperty("timestamp", miliSecondsInWeb.toString());
1538
                                prop.store(outAux, "last download");
1539
                                outAux.close();
1540
                                System.out.println("Fecha actual guardada: " +
1541
                                        fechaActual.toGMTString());
1542

    
1543
                                /* xml.putProperty("timestamp",fechaActual.toGMTString());
1544
                                   ps.setPresistentXML(xml); */
1545
                        }
1546
                } catch (IOException e) {
1547
                        NotificationManager.addError("", e);
1548
                } catch (UnavailableServiceException e) {
1549
                        NotificationManager.addError("", e);
1550
                } catch (SecurityException e) {
1551
                        System.err.println("No se puede escribir el timeStamp " +
1552
                                fechaActual.toGMTString());
1553
                        NotificationManager.addError("", e);
1554
                }
1555
        }
1556

    
1557
        /**
1558
         * DOCUMENT ME!
1559
         *
1560
         * @return DOCUMENT ME!
1561
         */
1562
        private static Extensions[] getExtensions() {
1563
                ArrayList array = new ArrayList();
1564
                Iterator iter = pluginsConfig.values().iterator();
1565

    
1566
                while (iter.hasNext()) {
1567
                        array.add(((PluginConfig) iter.next()).getExtensions());
1568
                }
1569

    
1570
                return (Extensions[]) array.toArray(new Extensions[0]);
1571
        }
1572

    
1573
        /**
1574
         * DOCUMENT ME!
1575
         *
1576
         * @return DOCUMENT ME!
1577
         */
1578
        public static HashMap getPluginConfig() {
1579
                return pluginsConfig;
1580
        }
1581

    
1582
        /**
1583
         * DOCUMENT ME!
1584
         *
1585
         * @param s DOCUMENT ME!
1586
         *
1587
         * @return DOCUMENT ME!
1588
         */
1589
        public static Extension getExtension(String s) {
1590
                Extensions[] exts = getExtensions();
1591

    
1592
                for (int i = 0; i < exts.length; i++) {
1593
                        for (int j = 0; j < exts[i].getExtensionCount(); j++) {
1594
                                if (exts[i].getExtension(j).getClassName().equals(s)) {
1595
                                        return exts[i].getExtension(j);
1596
                                }
1597
                        }
1598
                }
1599

    
1600
                return null;
1601
        }
1602

    
1603
        /**
1604
         * DOCUMENT ME!
1605
         *
1606
         * @return DOCUMENT ME!
1607
         */
1608
        public static AndamiConfig getAndamiConfig() {
1609
                return andamiConfig;
1610
        }
1611

    
1612
        /**
1613
         * DOCUMENT ME!
1614
         *
1615
         * @author $author$
1616
         * @version $Revision: 8752 $
1617
         */
1618
        private static class ExtensionComparator implements Comparator {
1619
                /**
1620
                 * DOCUMENT ME!
1621
                 *
1622
                 * @param o1 DOCUMENT ME!
1623
                 * @param o2 DOCUMENT ME!
1624
                 *
1625
                 * @return DOCUMENT ME!
1626
                 */
1627
                public int compare(Object o1, Object o2) {
1628
                        Extension e1 = (Extension) o1;
1629
                        Extension e2 = (Extension) o2;
1630

    
1631
                        if (!e1.hasPriority() && !e2.hasPriority()) {
1632
                                return -1;
1633
                        }
1634

    
1635
                        if (e1.hasPriority() && !e2.hasPriority()) {
1636
                                return Integer.MIN_VALUE;
1637
                        }
1638

    
1639
                        if (e2.hasPriority() && !e1.hasPriority()) {
1640
                                return Integer.MAX_VALUE;
1641
                        }
1642

    
1643
                        if (e1.getPriority() != e2.getPriority()){
1644
                                return e2.getPriority() - e1.getPriority();
1645
                        }else{
1646
                                return (e2.toString().compareTo(e1.toString()));
1647
                        }
1648
                }
1649
        }
1650

    
1651
        /**
1652
         * DOCUMENT ME!
1653
         */
1654
        private static class MenuComparator implements Comparator {
1655
                private static ExtensionComparator extComp = new ExtensionComparator();
1656

    
1657
                /**
1658
                 * DOCUMENT ME!
1659
                 *
1660
                 * @param o1 DOCUMENT ME!
1661
                 * @param o2 DOCUMENT ME!
1662
                 *
1663
                 * @return DOCUMENT ME!
1664
                 */
1665
                public int compare(Object o1, Object o2) {
1666
                        SortableMenu e1 = (SortableMenu) o1;
1667
                        SortableMenu e2 = (SortableMenu) o2;
1668

    
1669
                        if (!e1.menu.hasPosition() && !e2.menu.hasPosition()) {
1670
                                if (e1.extension instanceof SkinExtensionType) {
1671
                                        return 1;
1672
                                } else if (e2.extension instanceof SkinExtensionType) {
1673
                                        return -1;
1674
                                } else {
1675
                                        return extComp.compare(e1.extension, e2.extension);
1676
                                }
1677
                        }
1678

    
1679
                        if (e1.menu.hasPosition() && !e2.menu.hasPosition()) {
1680
                                return Integer.MIN_VALUE;
1681
                        }
1682

    
1683
                        if (e2.menu.hasPosition() && !e1.menu.hasPosition()) {
1684
                                return Integer.MAX_VALUE;
1685
                        }
1686
                        if (e1.menu.getPosition() != e2.menu.getPosition()){
1687
                                //we don't return 0 unless both objects are the same, otherwise the objects get overwritten in the treemap
1688
                                return e1.menu.getPosition() - e2.menu.getPosition();
1689
                        }else{
1690
                                return (e1.toString().compareTo(e2.toString()));
1691
                        }
1692
                }
1693
        }
1694

    
1695
        /**
1696
         * DOCUMENT ME!
1697
         *
1698
         * @author $author$
1699
         * @version $Revision: 8752 $
1700
         */
1701
        private static class SortableMenu {
1702
                public PluginClassLoader loader;
1703
                public Menu menu;
1704
                public SkinExtensionType extension;
1705

    
1706
                /**
1707
                 * DOCUMENT ME!
1708
                 *
1709
                 * @param loader DOCUMENT ME!
1710
                 * @param skinExt
1711
                 * @param menu2
1712
                 */
1713
                public SortableMenu(PluginClassLoader loader,
1714
                        SkinExtensionType skinExt, Menu menu2) {
1715
                        extension = skinExt;
1716
                        menu = menu2;
1717
                        this.loader = loader;
1718
                }
1719
        }
1720
        /**
1721
         * DOCUMENT ME!
1722
         */
1723
        private static class SortableTool {
1724
                public PluginClassLoader loader;
1725
                public ToolBar toolbar;
1726
                public ActionTool actiontool;
1727
                public SelectableTool selectabletool;
1728
                public SkinExtensionType extension;
1729

    
1730
                /**
1731
                 * DOCUMENT ME!
1732
                 *
1733
                 * @param loader DOCUMENT ME!
1734
                 * @param skinExt
1735
                 * @param menu2
1736
                 */
1737
                public SortableTool(PluginClassLoader loader,
1738
                        SkinExtensionType skinExt, ToolBar toolbar2,ActionTool actiontool2) {
1739
                        extension = skinExt;
1740
                        toolbar = toolbar2;
1741
                        actiontool=actiontool2;
1742
                        this.loader = loader;
1743
                }
1744
                public SortableTool(PluginClassLoader loader,
1745
                                SkinExtensionType skinExt, ToolBar toolbar2,SelectableTool selectabletool2) {
1746
                        extension = skinExt;
1747
                        toolbar = toolbar2;
1748
                        selectabletool=selectabletool2;
1749
                        this.loader = loader;
1750
                }
1751
        }
1752
        /**
1753
         * DOCUMENT ME!
1754
         */
1755
        private static class ToolBarComparator implements Comparator {
1756
                private static ExtensionComparator extComp = new ExtensionComparator();
1757

    
1758
                /**
1759
                 * DOCUMENT ME!
1760
                 *
1761
                 * @param o1 DOCUMENT ME!
1762
                 * @param o2 DOCUMENT ME!
1763
                 *
1764
                 * @return DOCUMENT ME!
1765
                 */
1766
                public int compare(Object o1, Object o2) {
1767
                        SortableTool e1 = (SortableTool) o1;
1768
                        SortableTool e2 = (SortableTool) o2;
1769

    
1770
                        // if the toolbars have the same name, they are considered to be
1771
                        // the same toolbar, so we don't need to do further comparing
1772
                        if (e1.toolbar.getName().equals(e2.toolbar.getName()))
1773
                                return 0;
1774

    
1775
                        if (!e1.toolbar.hasPosition() && !e2.toolbar.hasPosition()) {
1776
                                if (e1.extension instanceof SkinExtensionType) {
1777
                                        return 1;
1778
                                } else if (e2.extension instanceof SkinExtensionType) {
1779
                                        return -1;
1780
                                } else {
1781
                                        return extComp.compare(e1.extension, e2.extension);
1782
                                }
1783
                        }
1784

    
1785
                        if (e1.toolbar.hasPosition() && !e2.toolbar.hasPosition()) {
1786
                                return Integer.MIN_VALUE;
1787
                        }
1788

    
1789
                        if (e2.toolbar.hasPosition() && !e1.toolbar.hasPosition()) {
1790
                                return Integer.MAX_VALUE;
1791
                        }
1792
                        if (e1.toolbar.getPosition() != e2.toolbar.getPosition())
1793
                                return e1.toolbar.getPosition() - e2.toolbar.getPosition();
1794

    
1795
                        if (e1.toolbar.getActionTool().equals(e2.toolbar.getActionTool()) && e1.toolbar.getSelectableTool().equals(e2.toolbar.getSelectableTool())){
1796
                                return 0;
1797
                        }
1798
                        return (e1.toolbar.toString().compareTo(e2.toolbar.toString()));
1799
                }
1800
        }
1801

    
1802
        /**
1803
         * <p>This class is used to compare tools (selectabletool and actiontool),
1804
         * using the "position"
1805
         * attribute.</p>
1806
         * <p>The ordering criteria are:</p>
1807
         * <ul><li>If the tools are placed in different toolbars, they use the toolbars'
1808
         * order.
1809
         * (using the ToolBarComparator).</li>
1810
         * <li></li>
1811
         * <li>If any of the tools has not 'position' attribute, the tool which
1812
         * <strong>has</strong> the attribute will be placed first.</li>
1813
         * <li>If both tools have the same position (or they don't have a
1814
         * 'position' attribute), the priority of the extensions where the tool is defined.</li></ul>
1815
         *
1816
         * @author cesar
1817
         * @version $Revision: 8752 $
1818
         */
1819
        private static class ToolComparator implements Comparator {
1820
                private static ToolBarComparator toolBarComp = new ToolBarComparator();
1821
                /**
1822
                 * DOCUMENT ME!
1823
                 *
1824
                 * @param o1 DOCUMENT ME!
1825
                 * @param o2 DOCUMENT ME!
1826
                 *
1827
                 * @return DOCUMENT ME!
1828
                 */
1829
                public int compare(Object o1, Object o2) {
1830
                        // compare the toolbars which contain the tools
1831
                        int result = toolBarComp.compare(o1, o2);
1832
                        if (result != 0) { // if the toolbars are different, use their order
1833
                                return result;
1834
                        }
1835
                        // otherwise, compare the tools
1836
                        SortableTool e1 = (SortableTool) o1;
1837
                        SortableTool e2 = (SortableTool) o2;
1838
                        int e1Position=-1, e2Position=-1;
1839

    
1840
                        if (e1.actiontool!=null) {
1841
                                if (e1.actiontool.hasPosition())
1842
                                        e1Position = e1.actiontool.getPosition();
1843
                        }
1844
                        else if (e1.selectabletool!=null) {
1845
                                if (e1.selectabletool.hasPosition())
1846
                                        e1Position = e1.selectabletool.getPosition();
1847
                        }
1848

    
1849
                        if (e2.actiontool!=null) {
1850
                                if (e2.actiontool.hasPosition())
1851
                                        e2Position = e2.actiontool.getPosition();
1852
                        }
1853
                        else if (e2.selectabletool!=null){
1854
                                if (e2.selectabletool.hasPosition())
1855
                                        e2Position = e2.selectabletool.getPosition();
1856
                        }
1857

    
1858
                        if (e1Position==-1 && e2Position!=-1) {
1859
                                return 1;
1860
                        }
1861
                        if (e1Position!=-1 && e2Position==-1) {
1862
                                return -1;
1863
                        }
1864
                        if (e1Position!=-1 && e2Position!=-1) {
1865
                                result = e1Position - e2Position;
1866
                                // we don't return 0 unless both objects are the same, otherwise the objects get overwritten in the treemap
1867
                                if (result!=0) return result;
1868
                        }
1869
                        return e1.toString().compareTo(e2.toString());
1870
                }
1871
        }
1872

    
1873

    
1874
        /**
1875
         * validates the user before starting gvsig
1876
         *
1877
         */
1878
        private static void validate(){
1879

    
1880
                IAuthentication session =  null;
1881
                try {
1882
                        session = (IAuthentication)Class.forName("com.iver.andami.authentication.Session").newInstance();
1883

    
1884
                } catch (ClassNotFoundException e) {
1885
                        // TODO Auto-generated catch block
1886
                        //e.printStackTrace();
1887
                        return;
1888
                } catch (InstantiationException e) {
1889
                        // TODO Auto-generated catch block
1890
                        //e.printStackTrace();
1891
                        return;
1892
                } catch (IllegalAccessException e) {
1893
                        // TODO Auto-generated catch block
1894
                        //e.printStackTrace();
1895
                        return;
1896
                }
1897

    
1898
                session.setPluginDirectory( andamiConfig.getPluginsDirectory() );
1899
                if (session.validationRequired()){
1900
                        if(session.Login()){
1901
                                System.out.println("You are logged in");
1902
                        }
1903
                        else{
1904
                                JOptionPane.showMessageDialog((Component)PluginServices.getMainFrame(),
1905
                                                 "You are not logged in");
1906
                                //System.exit(0);
1907
                        }
1908
                        PluginServices.setAuthentication(session);
1909
                }
1910
        }
1911

    
1912
        public static String getDefaultLookAndFeel() {
1913
                String osName = (String) System.getProperty("os.name");
1914

    
1915
            if (osName.substring(0,3).toLowerCase().equals("win"))
1916
                    return UIManager.getSystemLookAndFeelClassName();
1917
        else
1918
                return nonWinDefaultLookAndFeel;
1919
        }
1920

    
1921
        /**
1922
         * Gets the ISO 839 two-characters-long language code matching the
1923
         * provided language code (which may be an ISO 839-2/T
1924
         * three-characters-long code or an ISO 839-1 two-characters-long
1925
         * code).
1926
         *
1927
         * If the provided parameter is already two characters long, it
1928
         * returns the parameter without any modification.
1929
         *
1930
         * @param langCode A language code representing either
1931
         *  an ISO 839-2/T language code or an ISO 839-1 code.
1932
         * @return A two-characters-long code specifying
1933
         *  an ISO 839 language code.
1934
         */
1935
        private static String normalizeLanguageCode(String langCode) {
1936
                final String fileName = "iso_639.tab";
1937
                if (langCode.length()==2)
1938
                        return langCode;
1939
                else if (langCode.length()==3) {
1940
                        if (langCode.equals("va") || langCode.equals("val")) { // special case for Valencian
1941
                                return "ca";
1942
                        }
1943
                        URL isoCodes = Launcher.class.getClassLoader().getResource(fileName);
1944
                        if (isoCodes!=null) {
1945
                                try {
1946
                                        BufferedReader reader =
1947
                                                new BufferedReader(new InputStreamReader(isoCodes.openStream(), "ISO-8859-1"));
1948
                                                String line;
1949

    
1950
                                                while ((line = reader.readLine()) != null) {
1951
                                                        String[] language = line.split("\t");
1952
                                                        if (language[0].equals(langCode)) // first column is the three characters code
1953
                                                                return language[2]; // third column i the two characters code
1954
                                                }
1955
                                }
1956
                                catch (IOException ex) {
1957
                                        logger.error(Messages.getString("Error_reading_isocodes_file"), ex);
1958
                                        return "es";
1959
                                }
1960
                        }
1961
                        else {
1962
                                logger.error(Messages.getString("Error_reading_isocodes_file"));
1963
                                return "es";
1964
                        }
1965
                }
1966
                return "es";
1967
        }
1968

    
1969
        /**
1970
         * Configures the locales (languages and local resources) to be used
1971
         * by the application.
1972
         *
1973
         * First it tries to get the locale from the command line parameters,
1974
         * then the andami-config file is checked.
1975
         *
1976
         * The locale name is normalized to get a two characters language code
1977
         * as defined by ISO-639-1 (although ISO-639-2/T three characters codes
1978
         * are also accepted from the command line or the configuration file).
1979
         *
1980
         * Finally, the gvsig-i18n library and the default locales for Java and
1981
         * Swing are configured.
1982
         *
1983
         */
1984
        private static void configureLocales(String[] args) {
1985
                //                 Configurar el locale
1986
        String localeStr = null;
1987
        for (int i=2; i < args.length; i++)
1988
        {
1989
                int index = args[i].indexOf("language=");
1990
                if (index != -1)
1991
                        localeStr = args[i].substring(index+9);
1992
        }
1993
                if (localeStr == null)
1994
                {
1995
            localeStr = andamiConfig.getLocaleLanguage();
1996
                }
1997
                localeStr = normalizeLanguageCode(localeStr);
1998
                locale = getLocale(localeStr,
1999
                andamiConfig.getLocaleCountry(),
2000
                andamiConfig.getLocaleVariant());
2001
                Locale.setDefault(locale);
2002
                JComponent.setDefaultLocale(locale);
2003
        org.gvsig.i18n.Messages.addLocale(locale);
2004
                // add english and spanish as fallback languages
2005
                org.gvsig.i18n.Messages.addLocale(new Locale("en"));
2006
                org.gvsig.i18n.Messages.addLocale(new Locale("es"));
2007
        org.gvsig.i18n.Messages.addResourceFamily("com.iver.andami.text", "com.iver.andami.text");
2008

    
2009
        }
2010

    
2011
        /**
2012
         * Gets Home Directory location of the application.
2013
         * May be set from outside the aplication by means of
2014
         * -DgvSIG.home=C:/data/gvSIG, where gvSIG its the name
2015
         * of the application
2016
         * @return
2017
         */
2018
        public static String getAppHomeDir() {
2019
                return appHomeDir;
2020
        }
2021

    
2022
        /**
2023
         * Sets Home Directory location of the application.
2024
         * May be set from outside the aplication by means of
2025
         * -DgvSIG.home=C:/data/gvSIG, where gvSIG its the name
2026
         * of the application
2027
         * @param appHomeDir
2028
         */
2029
        public static void setAppHomeDir(String appHomeDir) {
2030
                Launcher.appHomeDir = appHomeDir;
2031
        }
2032
}