Statistics
| Revision:

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

History | View | Annotate | Download (60.8 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.Authenticator;
65
import java.net.MalformedURLException;
66
import java.net.PasswordAuthentication;
67
import java.net.URL;
68
import java.net.URLConnection;
69
import java.security.AllPermission;
70
import java.security.CodeSource;
71
import java.security.PermissionCollection;
72
import java.security.Permissions;
73
import java.security.Policy;
74
import java.util.ArrayList;
75
import java.util.Comparator;
76
import java.util.Date;
77
import java.util.HashMap;
78
import java.util.HashSet;
79
import java.util.Iterator;
80
import java.util.Locale;
81
import java.util.Properties;
82
import java.util.TreeMap;
83
import java.util.prefs.Preferences;
84

    
85
import javax.jnlp.BasicService;
86
import javax.jnlp.ServiceManager;
87
import javax.jnlp.UnavailableServiceException;
88
import javax.swing.ImageIcon;
89
import javax.swing.JButton;
90
import javax.swing.JComponent;
91
import javax.swing.JOptionPane;
92
import javax.swing.JPopupMenu;
93
import javax.swing.SwingUtilities;
94
import javax.swing.UIManager;
95

    
96
import org.apache.log4j.Logger;
97
import org.apache.log4j.PatternLayout;
98
import org.apache.log4j.PropertyConfigurator;
99
import org.apache.log4j.RollingFileAppender;
100
import org.exolab.castor.xml.MarshalException;
101
import org.exolab.castor.xml.ValidationException;
102

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

    
135

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

    
157
    private static ArrayList pluginsOrdered = new ArrayList();
158
    private static ArrayList extensions=new ArrayList();
159
    private static String appHomeDir = null;
160
    
161
    private static final class ProxyAuth extends Authenticator {
162
                private PasswordAuthentication auth;
163

    
164
                private ProxyAuth(String user, String pass) {
165
                        auth = new PasswordAuthentication(user, pass.toCharArray());
166
                }
167

    
168
                protected PasswordAuthentication getPasswordAuthentication() {
169
                        return auth;
170
                }
171
        }
172
    
173
        /**
174
         * DOCUMENT ME!
175
         *
176
         * @param args DOCUMENT ME!
177
         * @throws Exception
178
         *
179
         * @throws InterruptedException
180
         * @throws InvocationTargetException
181
         * @throws ConfigurationException
182
         * @throws MDIManagerLoadException
183
         * @throws IOException
184
         */
185
    public static void main(String[] args) throws Exception {
186
            try{
187

    
188
                    if (!validJVM()){
189
                            System.exit(-1);
190
                    }
191

    
192
                    if (args.length < 1) {
193
                            System.err.println("Uso: Launcher appName plugins-directory [language=locale]");
194
                    }
195

    
196
                    //  Clean temporal files
197
                    Utilities.cleanUpTempFiles();
198

    
199
                    appName = args[0];
200

    
201
                    //Se crea el directorio de configuraci?n de la aplicaci?n
202
                    appHomeDir = System.getProperty(args[0]+".home");
203
                    if (appHomeDir == null)
204
                            appHomeDir = System.getProperty("user.home");
205
                    //System.err.println("LWS: "+args[0]+".home"+"="+appHomeDir);
206
                    appHomeDir += File.separator + args[0] + File.separator;
207
                    File parent = new File( appHomeDir );
208
                    parent.mkdirs();
209

    
210
                    andamiConfigPath = appHomeDir + "andami-config.xml";
211
                    pluginsPersistencePath = appHomeDir +
212
                    "plugins-persistence.xml";
213

    
214
                    // Configurar el log4j
215
                    PropertyConfigurator.configure(Launcher.class.getClassLoader()
216
                                    .getResource("log4j.properties"));
217

    
218
                    PatternLayout l = new PatternLayout("%p %t %C - %m%n");
219
                    RollingFileAppender fa = new RollingFileAppender(l,
220
                                    appHomeDir + args[0] + ".log", false);
221
                    fa.setMaxFileSize("512KB");
222
                    fa.setMaxBackupIndex(3);
223
                    Logger.getRootLogger().addAppender(fa);
224

    
225
                    // Leer el fichero de configuraci?n de andami (andami-config.xsd)
226
                    // locale
227
                    // Buscar actualizaci?nes al comenzar
228
                    //  Andami
229
                    //  Plugins
230
                    // Directorio de las extensiones
231
                    andamiConfigFromXML(andamiConfigPath);
232
                    andamiConfig.setPluginsDirectory(args[1]);
233

    
234
                    // Hacemos visibles los argumentos como una propiedad est?tica
235
                    // de plugin services para quien lo quiera usar (por ejemplo, para
236
                    // cargar un proyecto por l?nea de comandos)
237
                    PluginServices.setArguments(args);
238

    
239
                    configureLocales(args);
240

    
241
                    //Se pone el lookAndFeel
242
                    try {
243
                            String lookAndFeel = getAndamiConfig().getLookAndFeel();
244
                            if (lookAndFeel == null)
245
                                    lookAndFeel = getDefaultLookAndFeel();
246
                            UIManager.setLookAndFeel(lookAndFeel);
247
                    } catch (Exception e) {
248
                            logger.warn(Messages.getString("Launcher.look_and_feel"), e);
249
                    }
250
                // Solucionamos el problema de permisos que se produc?a con Java Web Start con este c?digo.
251
                // System.setSecurityManager(null);
252
             Policy.setPolicy(new Policy() {
253
             public PermissionCollection getPermissions(CodeSource codesource) {
254
                      Permissions perms = new Permissions();
255
                      perms.add(new AllPermission());
256
                      return (perms);
257
             }
258
             public void
259
                         refresh() {}
260
             });
261

    
262
                    validate();
263
                    // Mostrar la ventana de inicio
264
                    Frame f=new Frame();
265
                    splashWindow=new MultiSplashWindow(f);
266
                    validate();
267
                    
268
                    // Ponemos los datos del proxy
269
                    String host = prefs.get("firewall.http.host", "");
270
                        String port = prefs.get("firewall.http.port", "");
271

    
272
                        System.getProperties().put("http.proxyHost", host);
273
                        System.getProperties().put("http.proxyPort", port);
274

    
275
                    // Ponemos el usuario y clave del proxy, si existe                    
276
                    String proxyUser = prefs.get("firewall.http.user",null);
277
                    String proxyPassword = prefs.get("firewall.http.password", null);
278
                        if (proxyUser != null )
279
                        {
280
                                System.getProperties().put("http.proxyUserName", proxyUser);
281
                                System.getProperties().put("http.proxyPassword", proxyPassword);
282

    
283
                                Authenticator.setDefault(new ProxyAuth(proxyUser,
284
                                                                proxyPassword));
285
                        } else {
286
                                Authenticator.setDefault(new ProxyAuth("", ""));
287
                        }
288
                    // TODO Buscar actualizaciones de los plugins
289
                    downloadExtensions(andamiConfig.getPluginsDirectory());
290

    
291
                    // Se leen los config.xml de los plugins -----++++
292
                    loadPlugins(andamiConfig.getPluginsDirectory());
293

    
294
                    // Se configura el classloader del plugin
295
                    pluginsClassLoaders();
296

    
297
                    // Se carga un Skin si alguno de los plugins trae informaci?n para ello
298
                    skinPlugin();
299

    
300
                    //Se configura la cola de eventos
301
                    EventQueue waitQueue = new AndamiEventQueue();
302
                    Toolkit.getDefaultToolkit().getSystemEventQueue().push(waitQueue);
303

    
304
                    // Se configura la mensajer?a del plugin
305
                    pluginsMessages();
306

    
307
                    // Se modifica el andami-config con los plugins nuevos
308
                    updateAndamiConfig();
309

    
310
                    // Se prepara el MainFrame para albergar las extensiones
311
                    JPopupMenu.setDefaultLightWeightPopupEnabled(false);
312
                    frame = new MDIFrame();
313

    
314
                    // Se configura el nombre e icono de la aplicaci?n
315
                    frameIcon();
316

    
317
                    SwingUtilities.invokeAndWait(new Runnable() {
318
                            public void run() {
319
                                    frame.init();
320
                            }
321
                    });
322

    
323
                    // Se instalan los controles de las extensiones de los plugins
324
                    SwingUtilities.invokeAndWait(new Runnable() {
325
                            public void run() {
326
                                    installPluginsControls();
327
                                    installPluginsMenus();
328
                                    installPluginsLabels();
329
                            }
330
                    });
331

    
332
                    // Leer el fichero de persistencia
333
                    //  info de los plugins
334
                    //  bookmarks de los plugins
335
                    loadPluginsPersistence();
336

    
337
                    // Se instalan los controles del skin
338
                    // Se inicializan todas las extensiones de todos los plugins
339
                    SwingUtilities.invokeAndWait(new Runnable() {
340
                            public void run() {
341
                                    initializeExtensions();
342
                                    postInitializeExtensions();
343
                            }
344
                    });
345
                    frame.setClassesExtensions(classesExtensions);
346

    
347
                    // Se instalan los bookmarks de los plugins
348

    
349
                    //Se muestra el frame principal
350
                    frame.show();
351

    
352
                    // Definimos un KeyEventDispatcher global para que las extensiones
353
                    // puedan registrar sus "teclas r?pidas".
354
                    GlobalKeyEventDispatcher keyDispatcher = GlobalKeyEventDispatcher.getInstance();
355
                    KeyboardFocusManager.getCurrentKeyboardFocusManager().addKeyEventDispatcher(keyDispatcher);
356

    
357
                    SwingUtilities.invokeAndWait(new Runnable() {
358
                            public void run() {
359
                                    frame.enableControls();
360
                            }
361
                    });
362
                    splashWindow.close();
363
            }catch(Exception e){
364
                    logger.error("excepci?n al arrancar", e);
365
                    System.exit(-1);
366
            }
367

    
368
    }
369

    
370
        /**
371
         * Recupera la geometr?a (tama?o, posici?n y estado) de la ventana principal de Andami.
372
         * TODO Pendiente de ver como se asigna un pluginServices para el launcher.
373
         * @author LWS
374
         */
375
        private static void restoreMDIStatus(XMLEntity xml) {
376
                //System.err.println("Launcher: restoreMDIStatus()");
377
                if (xml == null) xml = new XMLEntity();
378
                //  restore frame size
379
                Dimension sz = new Dimension(700,580);
380
                if (xml.contains("MDIFrameSize")) {
381
                        int [] wh = xml.getIntArrayProperty("MDIFrameSize");
382
                        sz = new Dimension(wh[0], wh[1]);
383
                }
384
                frame.setSize(sz);
385
                //  restore frame location
386
                Point pos = new Point(10,10);
387
                if (xml.contains("MDIFramePos")) {
388
                        int [] xy = xml.getIntArrayProperty("MDIFramePos");
389
                        pos = new Point(xy[0], xy[1]);
390
                }
391
                frame.setLocation(pos);
392

    
393
                //  restore frame status (Maximized, minimized, etc);
394
                int state = java.awt.Frame.MAXIMIZED_BOTH;
395
                if (xml.contains("MDIFrameState")) {
396
                        state = xml.getIntProperty("MDIFrameState");
397
                }
398
                frame.setExtendedState(state);
399
        }
400

    
401
        private static XMLEntity saveMDIStatus() {
402
                XMLEntity xml = new XMLEntity();
403
                // save frame size
404
                int [] wh = new int[2];
405
                wh[0] = frame.getWidth();
406
                wh[1] = frame.getHeight();
407
                xml.putProperty("MDIFrameSize", wh);
408
                // save frame location
409
                int [] xy = new int[2];
410
                xy[0] = frame.getX();
411
                xy[1] = frame.getY();
412
                xml.putProperty("MDIFramePos", xy);
413
                // save frame status
414
                xml.putProperty("MDIFrameState", frame.getExtendedState());
415
                return xml;
416
        }
417

    
418
        /**
419
     * @return
420
     */
421
    private static boolean validJVM() {
422
        char thirdCharacter = System.getProperty("java.version").charAt(2);
423
        if (thirdCharacter < '4'){
424
            return false;
425
            }else{
426
                return true;
427
            }
428
    }
429

    
430
    /**
431
         * DOCUMENT ME!
432
         *
433
         * @throws ConfigurationException
434
         */
435
        private static void loadPluginsPersistence() throws ConfigurationException {
436
                XMLEntity entity = persistenceFromXML();
437

    
438
                //System.err.println("loadPluginPersistence()");
439
                for (int i = 0; i < entity.getChildrenCount(); i++) {
440
                        XMLEntity plugin = entity.getChild(i);
441
                        String pName = plugin.getStringProperty(
442
                                        "com.iver.andami.pluginName");
443
                        //System.err.println("--> "+pName);
444
                        if (pluginsServices.get(pName)!= null){
445
                                ((PluginServices) pluginsServices.get(pName)).setPersistentXML(plugin);
446
                        } else {
447
                                if (pName.startsWith("Andami.Launcher"))
448
                                        restoreMDIStatus(plugin);
449
                        }
450
                }
451
        }
452

    
453
        /**
454
         * Salva la persistencia de los plugins.
455
         * @author LWS
456
         */
457
        private static void savePluginPersistence() {
458
                Iterator i = pluginsConfig.keySet().iterator();
459

    
460
                XMLEntity entity = new XMLEntity();
461

    
462
                while (i.hasNext()) {
463
                        String pName = (String) i.next();
464
                        PluginServices ps = (PluginServices) pluginsServices.get(pName);
465
                        XMLEntity ent = ps.getPersistentXML();
466

    
467
                        if (ent != null) {
468
                                ent.putProperty("com.iver.andami.pluginName", pName);
469
                                entity.addChild(ent);
470
                        }
471
                }
472
                XMLEntity ent = saveMDIStatus();
473
                if (ent != null) {
474
                        ent.putProperty("com.iver.andami.pluginName", "Andami.Launcher");
475
                        entity.addChild(ent);
476
                }
477
                try {
478
                        persistenceToXML(entity);
479
                } catch (ConfigurationException e1) {
480
                        logger.error(Messages.getString(
481
                                        "Launcher.Se_produjo_un_error_guardando_la_configuracion_de_los_plugins"),
482
                                e1);
483
                }
484
        }
485

    
486
        /**
487
         * DOCUMENT ME!
488
         */
489
        private static void installPluginsLabels() {
490
                Iterator i = pluginsConfig.keySet().iterator();
491

    
492
                while (i.hasNext()) {
493
                        String name = (String) i.next();
494
                        PluginConfig pc = (PluginConfig) pluginsConfig.get(name);
495
                        PluginServices ps = (PluginServices) pluginsServices.get(name);
496

    
497
                        LabelSet[] ls = pc.getLabelSet();
498

    
499
                        for (int j = 0; j < ls.length; j++) {
500
                                PluginClassLoader loader = ps.getClassLoader();
501

    
502
                                try {
503
                                        Class clase = loader.loadClass(ls[j].getClassName());
504
                                        frame.setLabels(clase, ls[j].getLabel());
505
                                } catch (ClassNotFoundException e) {
506
                                        logger.error(Messages.getString("Launcher.labelset_class"),
507
                                                e);
508
                                }
509
                        }
510
                }
511
        }
512

    
513
        /**
514
         * DOCUMENT ME!
515
         *
516
         * @throws MDIManagerLoadException
517
         */
518
        private static void skinPlugin() throws MDIManagerLoadException {
519
                Iterator i = pluginsConfig.keySet().iterator();
520

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

    
526
                        if (pc.getExtensions().getSkinExtension() != null) {
527
                                if (MDIManagerFactory.getSkinExtension() != null) {
528
                                        logger.warn(Messages.getString(
529
                                                        "Launcher.Dos_skin_extension"));
530
                                }
531

    
532
                                SkinExtension se = pc.getExtensions().getSkinExtension();
533

    
534
                                MDIManagerFactory.setSkinExtension(se, ps.getClassLoader());
535

    
536
                                Class skinClass;
537

    
538
                                try {
539
                                        skinClass = ps.getClassLoader().loadClass(se.getClassName());
540

    
541
                                        com.iver.andami.plugins.IExtension skinInstance = (com.iver.andami.plugins.IExtension) skinClass.newInstance();
542
                                        // classesExtensions.put(skinClass, skinInstance);
543
                                        // jaume
544
                                        ExtensionDecorator newExtensionDecorator = new ExtensionDecorator(skinInstance, ExtensionDecorator.INACTIVE);
545
                                        classesExtensions.put(skinClass, newExtensionDecorator);
546
                                } catch (ClassNotFoundException e) {
547
                                        logger.error(Messages.getString(
548
                                                        "Launcher.No_se_encontro_la_clase_mdi_manager"), e);
549
                                        throw new MDIManagerLoadException(e);
550
                                } catch (InstantiationException e) {
551
                                        logger.error(Messages.getString(
552
                                                        "Launcher.No_se_pudo_instanciar_la_clase_mdi_manager"),
553
                                                e);
554
                                        throw new MDIManagerLoadException(e);
555
                                } catch (IllegalAccessException e) {
556
                                        logger.error(Messages.getString(
557
                                                        "Launcher.No_se_pudo_acceder_a_la_clase_mdi_manager"),
558
                                                e);
559
                                        throw new MDIManagerLoadException(e);
560
                                }
561
                        }
562
                }
563
        }
564

    
565
        /**
566
         *
567
         */
568
        private static void frameIcon() {
569
                Iterator i = pluginsConfig.keySet().iterator();
570

    
571
                while (i.hasNext()) {
572
                        String pName = (String) i.next();
573
                        PluginConfig pc = (PluginConfig) pluginsConfig.get(pName);
574
                        PluginServices ps = (PluginServices) pluginsServices.get(pName);
575

    
576
                        if (pc.getIcon() != null) {
577
                                ImageIcon icon = new ImageIcon(ps.getClassLoader().getResource(pc.getIcon()
578
                                                                                                                                                                 .getSrc()));
579
                                frame.setIconImage(icon.getImage());
580
                                frame.setTitlePrefix(pc.getIcon().getText());
581
                        }
582
                }
583
        }
584

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

    
591
                while (i.hasNext()) {
592
                        String pName = (String) i.next();
593
            logger.debug("Initializing extensions from " + pName);
594
                        PluginConfig pc = (PluginConfig) pluginsConfig.get(pName);
595
                        PluginServices ps = (PluginServices) pluginsServices.get(pName);
596

    
597
                        Extension[] exts = pc.getExtensions().getExtension();
598

    
599
                        TreeMap orderedExtensions = new TreeMap(new ExtensionComparator());
600

    
601
                        for (int j = 0; j < exts.length; j++) {
602
                                if (!exts[j].getActive()) {
603
                                        continue;
604
                                }
605

    
606
                                if (orderedExtensions.containsKey(exts[j])) {
607
                                        logger.warn(Messages.getString(
608
                                                        "Launcher.Two_extensions_with_the_same_priority") +
609
                                                exts[j].getClassName());
610
                                }
611

    
612
                                orderedExtensions.put(exts[j], null);
613
                        }
614

    
615
                        Iterator e = orderedExtensions.keySet().iterator();
616

    
617
                        while (e.hasNext()) {
618
                                Extension extension = (Extension) e.next();
619
                                com.iver.andami.plugins.IExtension extensionInstance;
620

    
621
                                try {
622
                                        Class extensionClass = ps.getClassLoader().loadClass(extension.getClassName());
623
                                        extensionInstance = (com.iver.andami.plugins.IExtension) extensionClass.newInstance();
624

    
625
                                        // CON DECORATOR
626
                                        // ANTES: classesExtensions.put(extensionClass, extensionInstance);
627
                                        // AHORA: CREAMOS UNA ExtensionDecorator y asignamos esta instancia para
628
                                        // poder ampliar con nuevas propiedades (AlwaysVisible, por ejemplo)
629
                                        // Para crear la nueva clase ExtensionDecorator, le pasamos como par?metro
630
                                        // la extensi?n original que acabamos de crear
631
                                        // 0-> Inactivo, controla la extension
632
                                        // 1-> Siempre visible
633
                                        // 2-> Invisible
634
                                        ExtensionDecorator newExtensionDecorator = new ExtensionDecorator(extensionInstance, ExtensionDecorator.INACTIVE);
635
                                        classesExtensions.put(extensionClass, newExtensionDecorator);
636
                                        System.err.println("Loading "+extension.getClassName()+"...");
637
                    // logger.debug("Initializing " + extension.getClassName());
638
                    extensionInstance.initialize();
639
                    extensions.add(extensionInstance);
640
                    // logger.debug(extension.getClassName() + " initialized.");
641

    
642
                                } catch (InstantiationException e1) {
643
                                        logger.error(Messages.getString(
644
                                                        "Launcher.Error_instanciando_la_extension") +
645
                                                extension.getClassName(), e1);
646
                                } catch (IllegalAccessException e1) {
647
                                        logger.error(Messages.getString(
648
                                                        "Launcher.Error_instanciando_la_extension") +
649
                                                extension.getClassName(), e1);
650
                                } catch (ClassNotFoundException e1) {
651
                                        logger.error(Messages.getString(
652
                                                        "Launcher.No_se_encontro_la_clase_de_la_extension") +
653
                                                extension.getClassName(), e1);
654
                                } catch (NoClassDefFoundError e1) {
655
                                        logger.error(Messages.getString(
656
                                                        "Launcher.Error_localizando_la_clase_de_la_extension") +
657
                                                extension.getClassName(), e1);
658
                                }
659
                        }
660
                }
661
        }
662

    
663
        private static void postInitializeExtensions() {
664
                for (int i=0;i<extensions.size();i++) {
665
                        com.iver.andami.plugins.IExtension extensionInstance=(com.iver.andami.plugins.IExtension)extensions.get(i);
666
                        extensionInstance.postInitialize();
667
                }
668
        }
669
        /**
670
         * DOCUMENT ME!
671
         */
672
        private static void installPluginsMenus() {
673
                TreeMap orderedMenus = new TreeMap(new MenuComparator());
674

    
675
                Iterator i = pluginsConfig.keySet().iterator();
676

    
677
                while (i.hasNext()) {
678
                        String pName = (String) i.next();
679
                        PluginServices ps = (PluginServices) pluginsServices.get(pName);
680
                        PluginConfig pc = (PluginConfig) pluginsConfig.get(pName);
681

    
682
                        Extension[] exts = pc.getExtensions().getExtension();
683

    
684
                        for (int j = 0; j < exts.length; j++) {
685
                                if (!exts[j].getActive()) {
686
                                        continue;
687
                                }
688

    
689
                                Menu[] menus = exts[j].getMenu();
690

    
691
                                for (int k = 0; k < menus.length; k++) {
692
                                        SortableMenu sm = new SortableMenu(ps.getClassLoader(),
693
                                                        exts[j], menus[k]);
694

    
695
                                        if (orderedMenus.containsKey(sm)) {
696
                                                logger.error(Messages.getString(
697
                                                                "Launcher.Two_menus_with_the_same_position") + " - " +
698
                                                        menus[k].getText()+ " - " + exts[j].getClassName());
699
                                        }
700

    
701
                                        orderedMenus.put(sm, null);
702
                                }
703
                        }
704

    
705
                        // Se instalan las extensiones de MDI
706
                        SkinExtension skinExt = pc.getExtensions().getSkinExtension();
707

    
708
                        if (skinExt != null) {
709
                                Menu[] menu = skinExt.getMenu();
710

    
711
                                for (int k = 0; k < menu.length; k++) {
712
                                        SortableMenu sm = new SortableMenu(ps.getClassLoader(),
713
                                                        skinExt, menu[k]);
714

    
715
                                        if (orderedMenus.containsKey(sm)) {
716
                                                logger.error(Messages.getString(
717
                                                                "Launcher.Two_menus_with_the_same_position") +
718
                                                        skinExt.getClassName());
719
                                        }
720

    
721
                                        orderedMenus.put(sm, null);
722
                                }
723
                        }
724
                }
725

    
726
                //Se itera por los menus ordenados
727
                Iterator e = orderedMenus.keySet().iterator();
728

    
729
                // Se ordenan los menues
730
                while (e.hasNext()) {
731
                        try {
732
                                SortableMenu sm = (SortableMenu) e.next();
733

    
734
                                frame.addMenu(sm.loader, sm.extension, sm.menu);
735
                        } catch (ClassNotFoundException ex) {
736
                                logger.error(Messages.getString(
737
                                                "Launcher.No_se_encontro_la_clase_de_la_extension"), ex);
738
                        }
739
                }
740
        }
741

    
742
        /**
743
         * Installs the menus, toolbars, actiontools, selectable toolbars and combos.
744
         * The order in which they are shown is determined here.
745
         */
746
        private static void installPluginsControls() {
747
                Iterator i = pluginsConfig.keySet().iterator();
748

    
749
                HashMap extensionPluginServices = new HashMap();
750
                HashMap extensionPluginConfig = new HashMap();
751
                TreeMap orderedExtensions = new TreeMap(new ExtensionComparator());
752

    
753
                // First of all, sort the extensions.
754
                // We need to iterate on the plugins, and iterate on each plugin's extensions
755
                // (each plugin may contain one or more extensions)
756
                while (i.hasNext()) { // iterate on the plugins
757
                        String pName = (String) i.next();
758
                        PluginConfig pc = (PluginConfig) pluginsConfig.get(pName);
759
                        PluginServices ps = (PluginServices) pluginsServices.get(pName);
760

    
761
                        Extension[] exts = pc.getExtensions().getExtension();
762

    
763
                        for (int j = 0; j < exts.length; j++) { // iterate on the extensions
764
                                if (exts[j].getActive()) {
765
                                        if (orderedExtensions.containsKey(exts[j])) {
766
                                                logger.error(Messages.getString(
767
                                                "Launcher.Two_extensions_with_the_same_priority") +
768
                                                exts[j].getClassName());
769
                                        }
770

    
771
                                        orderedExtensions.put(exts[j], null);
772
                                        extensionPluginServices.put(exts[j], ps);
773
                                        extensionPluginConfig.put(exts[j], pc);
774
                                }
775
                        }
776
                }
777

    
778
                TreeMap orderedTools = new TreeMap(new ToolComparator());
779
                Iterator e = orderedExtensions.keySet().iterator();
780

    
781
                // sort the toolbars and tools from 'normal' extensions (actiontools, selectabletools)
782
                // and load the  combo-scales and combo-buttons for the status bar
783
                while (e.hasNext()) {
784
                        Extension ext = (Extension) e.next();
785

    
786
                        ToolBar[] toolbars = ext.getToolBar();
787

    
788
                        // get tools from toolbars
789
                        for (int k = 0; k < toolbars.length; k++) {
790
                                ActionTool[] tools = toolbars[k].getActionTool();
791

    
792
                                for (int t = 0; t < tools.length; t++) {
793
                                        SortableTool sm = new SortableTool(((PluginServices)extensionPluginServices.get(ext)).getClassLoader(), ext,
794
                                                        toolbars[k], tools[t]);
795
                                        orderedTools.put(sm, null);
796
                                }
797

    
798
                                SelectableTool[] sTools = toolbars[k].getSelectableTool();
799

    
800
                                for (int t = 0; t < sTools.length; t++) {
801
                                        SortableTool sm=new SortableTool(((PluginServices)extensionPluginServices.get(ext)).getClassLoader(), ext,
802
                                                        toolbars[k], sTools[t]);
803
                                        orderedTools.put(sm, null);
804
                                }
805
                        }
806

    
807
                        // get controls for statusBar
808
                        PluginServices ps = (PluginServices) extensionPluginServices.get(ext);
809
                        PluginClassLoader loader = ps.getClassLoader();
810

    
811
                        //ArrayList componentList = new ArrayList();
812
                        ComboScale[] comboScaleArray = ext.getComboScale();
813
                        for (int k=0; k < comboScaleArray.length; k++) {
814
                                org.gvsig.gui.beans.controls.comboscale.ComboScale combo = new org.gvsig.gui.beans.controls.comboscale.ComboScale();
815
                                String label = comboScaleArray[k].getLabel();
816
                                if (label!=null)
817
                                        combo.setLabel(label);
818
                                String name = comboScaleArray[k].getName();
819
                                if (name!=null)
820
                                        combo.setName(name);
821
                                String[] elementsString = ((String)comboScaleArray[k].getElements()).split(";");
822
                                long[] elements = new long[elementsString.length];
823
                                for (int currentElem=0; currentElem<elementsString.length; currentElem++) {
824
                                        try {
825
                                                elements[currentElem] = Long.parseLong(elementsString[currentElem]);
826
                                        }
827
                                        catch (NumberFormatException nfex1) {
828
                                                logger.error(ext.getClassName()+" -- "+Messages.getString( "error_parsing_comboscale_elements"));
829
                                                elements[currentElem] = 0;
830
                                        }
831
                                }
832
                                combo.setItems(elements);
833
                                try {
834
                                        long value = Long.parseLong((String)comboScaleArray[k].getValue());
835
                                        combo.setScale(value);
836
                                }
837
                                catch (NumberFormatException nfex2) {
838
                                        logger.error(ext.getClassName()+" -- "+Messages.getString( "error_parsing_comboscale_value"));
839
                                }
840
                                try {
841
                                        frame.addStatusBarControl(loader.loadClass(ext.getClassName()),combo);
842
                                } catch (ClassNotFoundException e1) {
843
                                        logger.error(Messages.getString("Launcher.error_getting_class_loader_for_status_bar_control"), e1);
844
                                }
845
                        }
846

    
847
                        ComboButton[] comboButtonArray = ext.getComboButton();
848
                        for (int k=0; k < comboButtonArray.length; k++) {
849
                                ComboButtonElement[] elementList = comboButtonArray[k].getComboButtonElement();
850
                                org.gvsig.gui.beans.controls.combobutton.ComboButton combo = new org.gvsig.gui.beans.controls.combobutton.ComboButton();
851
                                String name = comboButtonArray[k].getName();
852
                                if (name!=null)
853
                                        combo.setName(name);
854
                                for (int currentElement=0; currentElement<elementList.length; currentElement++) {
855
                                        ComboButtonElement element = elementList[currentElement];
856
                                        ImageIcon icon;
857
                                        URL iconLocation = loader.getResource(element.getIcon());
858
                                        if (iconLocation==null)
859
                                                logger.error(Messages.getString("Icon_not_found_")+element.getIcon());
860
                                        else {
861
                                                icon = new ImageIcon(iconLocation);
862
                                                JButton button = new JButton(icon);
863
                                                combo.addButton(button);
864
                                                button.setActionCommand(element.getActionCommand());
865
                                        }
866
                                }
867
                                try {
868
                                        frame.addStatusBarControl(loader.loadClass(ext.getClassName()), combo);
869
                                } catch (ClassNotFoundException e1) {
870
                                        logger.error(Messages.getString("Launcher.error_getting_class_loader_for_status_bar_control"), e1);
871
                                }
872
                        }
873
                }
874

    
875
                // Add the tools from MDI extensions to the ordered tool-list, so that we get a sorted list containing all the tools
876
                i = pluginsConfig.keySet().iterator();
877
                while (i.hasNext()) {
878
                        String pName = (String) i.next();
879
                        PluginConfig pc = (PluginConfig) pluginsConfig.get(pName);
880
                        PluginServices ps = (PluginServices) pluginsServices.get(pName);
881

    
882
                        SkinExtension skinExt = pc.getExtensions().getSkinExtension();
883

    
884
                        if (skinExt != null) {
885
                                ToolBar[] toolbars = skinExt.getToolBar();
886

    
887
                                for (int k = 0; k < toolbars.length; k++) {
888
                                        ActionTool[] tools = toolbars[k].getActionTool();
889

    
890
                                        for (int t = 0; t < tools.length; t++) {
891
                                                SortableTool stb=new SortableTool(ps.getClassLoader(), skinExt,
892
                                                                toolbars[k], tools[t]);
893
                                                orderedTools.put(stb,null);
894
                                        }
895

    
896
                                        SelectableTool[] sTools = toolbars[k].getSelectableTool();
897

    
898
                                        for (int t = 0; t < sTools.length; t++) {
899
                                                SortableTool stb=new SortableTool(ps.getClassLoader(), skinExt,
900
                                                                toolbars[k], sTools[t]);
901
                                                orderedTools.put(stb,null);
902
                                        }
903
                                }
904
                        }
905
                        // Install popup menus
906
                        PopupMenus pus = pc.getPopupMenus();
907

    
908
                        if (pus != null) {
909
                                PopupMenu[] menus = pus.getPopupMenu();
910

    
911
                                for (int j = 0; j < menus.length; j++) {
912
                                        frame.addPopupMenu(ps.getClassLoader(), menus[j]);
913
                                }
914
                        }
915
                }
916

    
917
                // loop on the ordered extension list, to add them to the interface in an ordered way
918
                Iterator t = orderedTools.keySet().iterator();
919
                while (t.hasNext()) {
920
                        try {
921
                                SortableTool stb = (SortableTool) t.next();
922
                                if (stb.actiontool!=null)
923
                                        frame.addTool(stb.loader, stb.extension,stb.toolbar, stb.actiontool);
924
                                else
925
                                        frame.addTool(stb.loader, stb.extension,stb.toolbar, stb.selectabletool);
926
                        } catch (ClassNotFoundException ex) {
927
                                logger.error(Messages.getString(
928
                                "Launcher.No_se_encontro_la_clase_de_la_extension"), ex);
929
                        }
930
                }
931
        }
932

    
933
        /**
934
         * Adds new plugins to the the andami-config file.
935
         */
936
        private static void updateAndamiConfig() {
937
                HashSet olds = new HashSet();
938

    
939
                Plugin[] plugins = andamiConfig.getPlugin();
940

    
941
                for (int i = 0; i < plugins.length; i++) {
942
                        olds.add(plugins[i].getName());
943
                }
944

    
945
                Iterator i = pluginsServices.values().iterator();
946

    
947
                while (i.hasNext()) {
948
                        PluginServices ps = (PluginServices) i.next();
949

    
950
                        if (!olds.contains(ps.getPluginName())) {
951
                                Plugin p = new Plugin();
952
                                p.setName(ps.getPluginName());
953
                                p.setUpdate(false);
954

    
955
                                andamiConfig.addPlugin(p);
956
                        }
957
                }
958
        }
959

    
960
        /**
961
         * DOCUMENT ME!
962
         */
963
        private static void pluginsClassLoaders() {
964
                HashSet instalados = new HashSet();
965

    
966
                // Se itera hasta que est?n todos instalados
967
                while (instalados.size() != pluginsConfig.size()) {
968
                        boolean circle = true;
969

    
970
                        //Hacemos una pasada por todos los plugins
971
                        Iterator i = pluginsConfig.keySet().iterator();
972

    
973
                        while (i.hasNext()) {
974
                                String pluginName = (String) i.next();
975
                                PluginConfig config = (PluginConfig) pluginsConfig.get(pluginName);
976

    
977
                                if (instalados.contains(pluginName)) {
978
                                        continue;
979
                                }
980

    
981
                                //Se obtienen las dependencias y sus class loaders
982
                                boolean ready = true;
983
                                Depends[] dependencies = config.getDepends();
984
                                PluginClassLoader[] loaders = new PluginClassLoader[dependencies.length];
985

    
986
                                for (int j = 0; j < dependencies.length; j++) {
987
                                        if (pluginsConfig.get(dependencies[j].getPluginName()) == null) {
988
                                                logger.error(Messages.getString(
989
                                                                "Launcher.Dependencia_no_resuelta_en_plugin") +
990
                                                        pluginName + ": " +
991
                                                        dependencies[j].getPluginName());
992

    
993
                                                continue;
994
                                        }
995

    
996
                                        if (!instalados.contains(dependencies[j].getPluginName())) {
997
                                                ready = false;
998
                                        } else {
999
                                                loaders[j] = ((PluginServices) pluginsServices.get(dependencies[j].getPluginName())).getClassLoader();
1000
                                        }
1001
                                }
1002

    
1003
                                //Si no est?n sus dependencias satisfechas se aborta la instalaci?n
1004
                                if (!ready) {
1005
                                        continue;
1006
                                }
1007

    
1008
                                //Se genera el class loader
1009
                                String jardir = config.getLibraries().getLibraryDir();
1010
                                File jarDir = new File(andamiConfig.getPluginsDirectory() +
1011
                                                File.separator + pluginName + File.separator + jardir);
1012
                                File[] jarFiles = jarDir.listFiles(new FileFilter() {
1013
                                                        public boolean accept(File pathname) {
1014
                                                                return (pathname.getName().toUpperCase()
1015
                                                                                                .endsWith(".JAR")) ||
1016
                                                                (pathname.getName().toUpperCase().endsWith(".ZIP"));
1017
                                                        }
1018
                                                });
1019

    
1020
                                URL[] urls = new URL[jarFiles.length];
1021

    
1022
                                for (int j = 0; j < jarFiles.length; j++) {
1023
                                        try {
1024
                                                urls[j] = new URL("file:" + jarFiles[j]);
1025
                                        } catch (MalformedURLException e) {
1026
                                                logger.error(Messages.getString(
1027
                                                                "Launcher.No_se_puede_acceder_a") +
1028
                                                        jarFiles[j]);
1029
                                        }
1030
                                }
1031

    
1032
                                PluginClassLoader loader;
1033

    
1034
                                try {
1035
                                        loader = new PluginClassLoader(urls,
1036
                                                        andamiConfig.getPluginsDirectory() +
1037
                                                        File.separator + pluginName,
1038
                                                        Launcher.class.getClassLoader(), loaders);
1039

    
1040
                                        PluginServices ps = new PluginServices(loader);
1041

    
1042
                                        pluginsServices.put(ps.getPluginName(), ps);
1043

    
1044
                                        instalados.add(pluginName);
1045
                    // FJP: Los metemos ordenados para luego no cargar uno que necesita de otro antes de tiempo. Esto lo usaremos al
1046
                    // inicializar los plugins
1047
                    pluginsOrdered.add(pluginName);
1048

    
1049
                                        circle = false;
1050
                                } catch (IOException e) {
1051
                                        logger.error(Messages.getString(
1052
                                                        "Launcher.Error_con_las_librerias_del_plugin"), e);
1053
                                        pluginsConfig.remove(pluginName);
1054
                                        i = pluginsConfig.keySet().iterator();
1055
                                }
1056
                        }
1057

    
1058
                        if (circle) {
1059
                                logger.error(Messages.getString(
1060
                                                "Launcher.Hay_dependencias_circulares"));
1061

    
1062
                                break;
1063
                        }
1064
                }
1065

    
1066
                //Se eliminan los plugins que no fueron instalados
1067
                Iterator i = pluginsConfig.keySet().iterator();
1068

    
1069
                while (i.hasNext()) {
1070
                        String pluginName = (String) i.next();
1071
                        PluginConfig config = (PluginConfig) pluginsConfig.get(pluginName);
1072
                        PluginServices ps = (PluginServices) pluginsServices.get(pluginName);
1073

    
1074
                        if (ps == null) {
1075
                                pluginsConfig.remove(pluginName);
1076
                                i = pluginsConfig.keySet().iterator();
1077
                        }
1078
                }
1079
        }
1080

    
1081
        /**
1082
         * DOCUMENT ME!
1083
         */
1084
        private static void pluginsMessages() {
1085
                /* add gvsig translations first. This should be done using a generic "appPlugin" variable, instead
1086
                 * of using "com.iver.cit.gvsig" directly, but I'll do it when we use the new appgvSIG launcher.
1087
                 * I keep this workaround for the moment.
1088
                 */
1089
                PluginConfig config = (PluginConfig) pluginsConfig.get("com.iver.cit.gvsig");
1090
                PluginServices ps = (PluginServices) pluginsServices.get("com.iver.cit.gvsig");
1091
                if (config.getResourceBundle() != null) {
1092
                        org.gvsig.i18n.Messages.addResourceFamily(config.getResourceBundle().getName(), ps.getClassLoader(), "com.iver.cit.gvsig");
1093
                }
1094

    
1095
                //Iteramos por todos los plugins
1096
                Iterator i = pluginsConfig.keySet().iterator();
1097

    
1098
                while (i.hasNext()) {
1099
                        String pluginName = (String) i.next();
1100
                        if (!pluginName.equals("com.iver.cit.gvsig")) { // we've already loaded com.iver.cit.gvsig
1101
                                config = (PluginConfig) pluginsConfig.get(pluginName);
1102
                                ps = (PluginServices) pluginsServices.get(pluginName);
1103

    
1104
                                if (config.getResourceBundle() != null && !config.getResourceBundle().getName().equals("")) {
1105
                                        // add the locale files associated with the plugin
1106
                                        org.gvsig.i18n.Messages.addResourceFamily(config.getResourceBundle().getName(), ps.getClassLoader(), pluginName);
1107
                                }
1108
                        }
1109
                }
1110
        }
1111

    
1112
        /**
1113
         * DOCUMENT ME!
1114
         *
1115
         * @param name DOCUMENT ME!
1116
         *
1117
         * @return DOCUMENT ME!
1118
         */
1119
        static PluginServices getPluginServices(String name) {
1120
                return (PluginServices) pluginsServices.get(name);
1121
        }
1122

    
1123
        /**
1124
         * DOCUMENT ME!
1125
         *
1126
         * @return DOCUMENT ME!
1127
         */
1128
        static String getPluginsDir() {
1129
                return andamiConfig.getPluginsDirectory();
1130
        }
1131

    
1132
        /**
1133
         * DOCUMENT ME!
1134
         *
1135
         * @param s DOCUMENT ME!
1136
         */
1137
        static void setPluginsDir(String s) {
1138
                andamiConfig.setPluginsDirectory(s);
1139
        }
1140

    
1141
        /**
1142
         * DOCUMENT ME!
1143
         *
1144
         * @return DOCUMENT ME!
1145
         */
1146
        static MDIFrame getMDIFrame() {
1147
                return frame;
1148
        }
1149

    
1150
        /**
1151
         * DOCUMENT ME!
1152
         *
1153
         * @param pluginsDirectory
1154
         */
1155
        private static void loadPlugins(String pluginsDirectory) {
1156
                File pDir = new File(pluginsDirectory);
1157

    
1158
                if (!pDir.exists()) {
1159
                        return;
1160
                }
1161

    
1162
                File[] pluginDirs = pDir.listFiles();
1163

    
1164
                for (int i = 0; i < pluginDirs.length; i++) {
1165
                        if (pluginDirs[i].isDirectory()) {
1166
                                File configXml = new File(pluginDirs[i].getAbsolutePath() +
1167
                                                File.separator + "config.xml");
1168

    
1169
                                try {
1170
                                        FileInputStream is = new FileInputStream(configXml);
1171
                                        Reader xml = com.iver.utiles.xml.XMLEncodingUtils.getReader(is);
1172
                                        if (xml==null) {
1173
                                                // the encoding was not correctly detected, use system default
1174
                                                xml = new FileReader(configXml);
1175
                                        }
1176
                                        else {
1177
                                                // use a buffered reader to improve performance
1178
                                                xml = new BufferedReader(xml);
1179
                                        }
1180
                                        PluginConfig pConfig = (PluginConfig) PluginConfig.unmarshal(xml);
1181
                                        pluginsConfig.put(pluginDirs[i].getName(), pConfig);
1182
                                } catch (FileNotFoundException e) {
1183
                                        logger.info(Messages.getString(
1184
                                                        "Launcher.Ignorando_el_directorio") +
1185
                                                pluginDirs[i].getAbsolutePath() +
1186
                                                Messages.getString("Launcher.config_no_encontrado"));
1187
                                } catch (MarshalException e) {
1188
                                        logger.info(Messages.getString(
1189
                                                        "Launcher.Ignorando_el_directorio") +
1190
                                                pluginDirs[i].getAbsolutePath() +
1191
                                                Messages.getString("Launcher.config_mal_formado"), e);
1192
                                } catch (ValidationException e) {
1193
                                        logger.info(Messages.getString(
1194
                                                        "Launcher.Ignorando_el_directorio") +
1195
                                                pluginDirs[i].getAbsolutePath() +
1196
                                                Messages.getString("Launcher.config_mal_formado"), e);
1197
                                }
1198
                        }
1199
                }
1200
        }
1201

    
1202
        /**
1203
         * DOCUMENT ME!
1204
         *
1205
         * @param language
1206
         * @param country
1207
         * @param variant
1208
         *
1209
         * @return DOCUMENT ME!
1210
         */
1211
        private static Locale getLocale(String language, String country,
1212
                String variant) {
1213
                if (variant != null) {
1214
                        return new Locale(language, country, variant);
1215
                } else if (country != null) {
1216
                        return new Locale(language, country);
1217
                } else if (language != null) {
1218
                        return new Locale(language);
1219
                } else {
1220
                        return new Locale("es");
1221
                }
1222
        }
1223

    
1224
        /**
1225
         * DOCUMENT ME!
1226
         *
1227
         * @param file DOCUMENT ME!
1228
         *
1229
         * @throws IOException DOCUMENT ME!
1230
         * @throws MarshalException DOCUMENT ME!
1231
         * @throws ValidationException DOCUMENT ME!
1232
         */
1233
        private static void andamiConfigToXML(String file)
1234
                throws IOException, MarshalException, ValidationException {
1235
                File xml = new File(file);
1236
                File parent = xml.getParentFile();
1237
                parent.mkdirs();
1238

    
1239
                FileWriter writer = new FileWriter(xml);
1240
                andamiConfig.marshal(writer);
1241
        }
1242

    
1243
        /**
1244
         * DOCUMENT ME!
1245
         *
1246
         * @param file DOCUMENT ME!
1247
         *
1248
         * @throws ConfigurationException DOCUMENT ME!
1249
         */
1250
        private static void andamiConfigFromXML(String file)
1251
                throws ConfigurationException {
1252
                File xml = new File(file);
1253

    
1254
                //Si no existe se ponen los valores por defecto
1255
                if (!xml.exists()) {
1256
                        andamiConfig = new AndamiConfig();
1257

    
1258
                        Andami andami = new Andami();
1259
                        andami.setUpdate(true);
1260
                        andamiConfig.setAndami(andami);
1261
                        andamiConfig.setLocaleCountry(Locale.getDefault().getCountry());
1262
                        andamiConfig.setLocaleLanguage(Locale.getDefault().getLanguage());
1263
                        andamiConfig.setLocaleVariant(Locale.getDefault().getVariant());
1264

    
1265
                        if (System.getProperty("javawebstart.version") != null) // Es java web start)
1266
                         {
1267
                                andamiConfig.setPluginsDirectory(new File(appHomeDir
1268
                                                + "extensiones").getAbsolutePath());
1269
                        } else {
1270
                                andamiConfig.setPluginsDirectory(new File(appName +
1271
                                                File.separator + "extensiones").getAbsolutePath());
1272
                        }
1273

    
1274
                        andamiConfig.setPlugin(new Plugin[0]);
1275
                } else {
1276
                        //Se lee la configuraci?n
1277
                        FileReader reader;
1278

    
1279
                        try {
1280
                                reader = new FileReader(xml);
1281
                                andamiConfig = (AndamiConfig) AndamiConfig.unmarshal(reader);
1282
                        } catch (FileNotFoundException e) {
1283
                                throw new ConfigurationException(e);
1284
                        } catch (MarshalException e) {
1285
                                throw new ConfigurationException(e);
1286
                        } catch (ValidationException e) {
1287
                                throw new ConfigurationException(e);
1288
                        }
1289
                }
1290
        }
1291

    
1292
        /**
1293
         * DOCUMENT ME!
1294
         *
1295
         * @return DOCUMENT ME!
1296
         *
1297
         * @throws ConfigurationException DOCUMENT ME!
1298
         */
1299
        private static XMLEntity persistenceFromXML() throws ConfigurationException {
1300
                File xml = new File(pluginsPersistencePath);
1301

    
1302
                if (xml.exists()) {
1303
                        FileReader reader;
1304

    
1305
                        try {
1306
                                reader = new FileReader(xml);
1307

    
1308
                                XmlTag tag = (XmlTag) XmlTag.unmarshal(reader);
1309

    
1310
                                return new XMLEntity(tag);
1311
                        } catch (FileNotFoundException e) {
1312
                                throw new ConfigurationException(e);
1313
                        } catch (MarshalException e) {
1314
                                throw new ConfigurationException(e);
1315
                        } catch (ValidationException e) {
1316
                                throw new ConfigurationException(e);
1317
                        }
1318
                } else {
1319
                        return new XMLEntity();
1320
                }
1321
        }
1322

    
1323
        /**
1324
         * DOCUMENT ME!
1325
         *
1326
         * @param entity DOCUMENT ME!
1327
         *
1328
         * @throws ConfigurationException DOCUMENT ME!
1329
         */
1330
        private static void persistenceToXML(XMLEntity entity)
1331
                throws ConfigurationException {
1332
                File xml = new File(pluginsPersistencePath);
1333

    
1334
                FileWriter writer;
1335

    
1336
                try {
1337
                        writer = new FileWriter(xml);
1338
                        entity.getXmlTag().marshal(writer);
1339
                } catch (FileNotFoundException e) {
1340
                        throw new ConfigurationException(e);
1341
                } catch (MarshalException e) {
1342
                        throw new ConfigurationException(e);
1343
                } catch (ValidationException e) {
1344
                        throw new ConfigurationException(e);
1345
                } catch (IOException e) {
1346
                        throw new ConfigurationException(e);
1347
                }
1348
        }
1349

    
1350
        /**
1351
         * Devuelve un array con los directorios de los plugins
1352
         *
1353
         * @param dirExt Directorio de las extensiones a partir del cual cuelgan
1354
         *                   todos los directorios de los plugins
1355
         *
1356
         * @return ArrayList con los directorios
1357
         */
1358
        private String[] getLocales(File dirExt) {
1359
                ArrayList types = new ArrayList();
1360
                File[] files = dirExt.listFiles();
1361

    
1362
                for (int i = 0; i < files.length; i++) {
1363
                        if (files[i].isDirectory()) {
1364
                                File[] textFile = files[i].listFiles(new FilenameFilter() {
1365
                                                        public boolean accept(File dir, String fileName) {
1366
                                                                return fileName.toLowerCase().startsWith("text_"); //$NON-NLS-1$
1367
                                                        }
1368
                                                });
1369

    
1370
                                for (int j = 0; j < textFile.length; j++) {
1371
                                        String s = (textFile[j]).getName().replaceAll("text_", "");
1372
                                        s = s.replaceAll(".properties", "");
1373
                                        s = s.trim();
1374

    
1375
                                        if (!types.contains(s)) {
1376
                                                types.add(s);
1377
                                        }
1378
                                }
1379
                        }
1380
                }
1381

    
1382
                return (String[]) types.toArray(new String[0]);
1383
        }
1384

    
1385
        /**
1386
         * DOCUMENT ME!
1387
         *
1388
         * @return Returns the frame.
1389
         */
1390
        static MDIFrame getFrame() {
1391
                return frame;
1392
        }
1393

    
1394
        /**
1395
         * Secuencia de cerrado de Andami
1396
         */
1397
        public static void closeApplication() {
1398
                //Configuraci?n de Andami
1399
                try {
1400
                        andamiConfigToXML(andamiConfigPath);
1401
                } catch (MarshalException e) {
1402
                        logger.error(Messages.getString(
1403
                                        "Launcher.No_se_pudo_guardar_la_configuracion_de_andami"), e);
1404
                } catch (ValidationException e) {
1405
                        logger.error(Messages.getString(
1406
                                        "Launcher.No_se_pudo_guardar_la_configuracion_de_andami"), e);
1407
                } catch (IOException e) {
1408
                        logger.error(Messages.getString(
1409
                                        "Launcher.No_se_pudo_guardar_la_configuracion_de_andami"), e);
1410
                }
1411

    
1412
                //Persistencia de los plugins
1413
                savePluginPersistence();
1414

    
1415
                //Finalize all the extensions
1416
                finalizeExtensions();
1417

    
1418
                // Clean any temp data created
1419
                Utilities.cleanUpTempFiles();
1420

    
1421
                //Para la depuraci?n de memory leaks
1422
                System.gc();
1423

    
1424
        System.exit(0);
1425
        }
1426

    
1427
        /**
1428
         * Exectutes the terminate method for all the extensions, in the reverse
1429
         * order they were initialized
1430
         *
1431
         */
1432
        private static void finalizeExtensions() {
1433
                for (int i=extensions.size()-1; i>=0; i--) {
1434
                        com.iver.andami.plugins.IExtension extensionInstance=(com.iver.andami.plugins.IExtension)extensions.get(i);
1435
                        extensionInstance.terminate();
1436
                }
1437
        }
1438

    
1439

    
1440
        /**
1441
         * DOCUMENT ME!
1442
         *
1443
         * @return DOCUMENT ME!
1444
         */
1445
        static HashMap getClassesExtensions() {
1446
                return classesExtensions;
1447
        }
1448

    
1449
        /**
1450
         * DOCUMENT ME!
1451
         *
1452
         * @param extDir DOCUMENT ME!
1453
         */
1454
        private static void downloadExtensions(String extDir) {
1455
                java.util.Date fechaActual = null;
1456

    
1457
                try {
1458
                        if (System.getProperty("javawebstart.version") != null) {
1459
                                //Obtenemos la URL del servidor
1460
                                BasicService bs = (BasicService) ServiceManager.lookup(
1461
                                                "javax.jnlp.BasicService");
1462
                                URL baseURL = bs.getCodeBase();
1463

    
1464
                                //Se descargan las extensiones
1465
                                MultiSplashWindow.process(5,
1466
                                        "Descargando las extensiones desde " + baseURL + " a " +
1467
                                        extDir);
1468

    
1469
                                URL url = new URL(baseURL + "extensiones.zip");
1470
                                URLConnection connection = url.openConnection();
1471

    
1472
                                System.out.println(url.toExternalForm() + ":");
1473
                                System.out.println("  Content Type: " +
1474
                                        connection.getContentType());
1475
                                System.out.println("  Content Length: " +
1476
                                        connection.getContentLength());
1477
                                System.out.println("  Last Modified: " +
1478
                                        new Date(connection.getLastModified()));
1479
                                System.out.println("  Expiration: " +
1480
                                        connection.getExpiration());
1481
                                System.out.println("  Content Encoding: " +
1482
                                        connection.getContentEncoding());
1483

    
1484
                                // Guardamos la fecha del fichero de extensiones que nos hemos bajado, y
1485
                                // comprobamos el ?ltimo que se ha bajado. Si no son
1486
                                // iguales, nos bajamos el nuevo. Si son iguales, no
1487
                                // nos bajamos nada.
1488
                                Long miliSecondsInWeb = new Long(connection.getLastModified());
1489

    
1490
                                // PluginServices ps = PluginServices.getPluginServices("com.iver.core");
1491
                                // if (ps.getPersistentXML().getStringProperty("timestamp") != null)
1492
                                File destDir = new File(extDir);
1493

    
1494
                                if (!destDir.exists()) {
1495
                                        // Creamos gvSIG
1496
                                        destDir.getParentFile().mkdir();
1497

    
1498
                                        if (!destDir.mkdir()) {
1499
                                                System.err.println("Imposible crear el directorio " +
1500
                                                        destDir.getAbsolutePath());
1501
                                        }
1502
                                }
1503

    
1504
                                File timeFile = new File(destDir.getParent() + File.separator +
1505
                                                "timeStamp.properties");
1506

    
1507
                                if (!timeFile.exists()) {
1508
                                        timeFile.createNewFile();
1509
                                }
1510

    
1511
                                FileInputStream inAux = new FileInputStream(timeFile);
1512
                                Properties prop = new Properties();
1513
                                prop.load(inAux);
1514
                                inAux.close();
1515

    
1516
                                if (prop.getProperty("timestamp") != null) {
1517
                                        Long lastMiliSeconds = (Long) new Long(prop.getProperty(
1518
                                                                "timestamp"));
1519

    
1520
                                        if (lastMiliSeconds.longValue() == miliSecondsInWeb.longValue()) {
1521
                                                System.out.println("No hay nueva actualizaci?n");
1522
                        logger.debug("No hay nueva actualizaci?n -> Return");
1523
                        logger.debug("timeStampWeb= " + miliSecondsInWeb);
1524
                        logger.debug("timeStampLocal= " + lastMiliSeconds);
1525

    
1526
                                                return;
1527
                                        }
1528

    
1529
                                        System.out.println("timeStampWeb= " + miliSecondsInWeb);
1530
                                        System.out.println("timeStampLocal= " + lastMiliSeconds);
1531
                                } else {
1532
                                        System.out.println("El timeStamp no est? escrito en " +
1533
                                                timeFile.getAbsolutePath());
1534
                                }
1535

    
1536
                                InputStream stream = url.openStream();
1537
                File temp = File.createTempFile("gvsig", ".zip");
1538

    
1539
                logger.debug(temp.getAbsolutePath());
1540

    
1541
                temp.deleteOnExit();
1542
                FileOutputStream file = new FileOutputStream(temp);
1543

    
1544
                byte[] lt_read = new byte[1];
1545

    
1546
                while (stream.read(lt_read) > 0)
1547
                  file.write(lt_read);
1548

    
1549
                                stream.close();
1550
                stream = null;
1551
                file.close();
1552
                file = null;
1553

    
1554
                System.gc();
1555

    
1556
                logger.debug("Ha creado el fichero ZIP");
1557
                                //Se extrae el zip
1558
                                MultiSplashWindow.process(5, "Extensiones descargadas.");
1559

    
1560
                                System.out.println("Extrayendo a " + destDir.getAbsolutePath());
1561

    
1562
                                Date fechaDir = new Date(destDir.lastModified());
1563
                                System.out.println("Fecha del directorio " + extDir + " = " +
1564
                                        fechaDir.toString());
1565
                                Utilities.extractTo(temp, new File(extDir), splashWindow);
1566

    
1567
                                // Si todo ha ido bien, guardamos el timestamp.
1568
                                ///  App.instance.getPc().addProperties("timestamp", miliSecondsInWeb);
1569
                                // XMLEntity xml=ps.getPersistentXML();
1570
                                fechaActual = new java.util.Date();
1571

    
1572
                                FileOutputStream outAux = new FileOutputStream(timeFile);
1573
                                prop.setProperty("timestamp", miliSecondsInWeb.toString());
1574
                                prop.store(outAux, "last download");
1575
                                outAux.close();
1576
                                System.out.println("Fecha actual guardada: " +
1577
                                        fechaActual.toGMTString());
1578

    
1579
                                /* xml.putProperty("timestamp",fechaActual.toGMTString());
1580
                                   ps.setPresistentXML(xml); */
1581
                        }
1582
                } catch (IOException e) {
1583
                        NotificationManager.addError("", e);
1584
                } catch (UnavailableServiceException e) {
1585
                        NotificationManager.addError("", e);
1586
                } catch (SecurityException e) {
1587
                        System.err.println("No se puede escribir el timeStamp " +
1588
                                fechaActual.toGMTString());
1589
                        NotificationManager.addError("", e);
1590
                }
1591
        }
1592

    
1593
        /**
1594
         * DOCUMENT ME!
1595
         *
1596
         * @return DOCUMENT ME!
1597
         */
1598
        private static Extensions[] getExtensions() {
1599
                ArrayList array = new ArrayList();
1600
                Iterator iter = pluginsConfig.values().iterator();
1601

    
1602
                while (iter.hasNext()) {
1603
                        array.add(((PluginConfig) iter.next()).getExtensions());
1604
                }
1605

    
1606
                return (Extensions[]) array.toArray(new Extensions[0]);
1607
        }
1608

    
1609
        /**
1610
         * DOCUMENT ME!
1611
         *
1612
         * @return DOCUMENT ME!
1613
         */
1614
        public static HashMap getPluginConfig() {
1615
                return pluginsConfig;
1616
        }
1617

    
1618
        /**
1619
         * DOCUMENT ME!
1620
         *
1621
         * @param s DOCUMENT ME!
1622
         *
1623
         * @return DOCUMENT ME!
1624
         */
1625
        public static Extension getExtension(String s) {
1626
                Extensions[] exts = getExtensions();
1627

    
1628
                for (int i = 0; i < exts.length; i++) {
1629
                        for (int j = 0; j < exts[i].getExtensionCount(); j++) {
1630
                                if (exts[i].getExtension(j).getClassName().equals(s)) {
1631
                                        return exts[i].getExtension(j);
1632
                                }
1633
                        }
1634
                }
1635

    
1636
                return null;
1637
        }
1638

    
1639
        /**
1640
         * DOCUMENT ME!
1641
         *
1642
         * @return DOCUMENT ME!
1643
         */
1644
        public static AndamiConfig getAndamiConfig() {
1645
                return andamiConfig;
1646
        }
1647

    
1648
        /**
1649
         * DOCUMENT ME!
1650
         *
1651
         * @author $author$
1652
         * @version $Revision: 9167 $
1653
         */
1654
        private static class ExtensionComparator implements Comparator {
1655
                /**
1656
                 * DOCUMENT ME!
1657
                 *
1658
                 * @param o1 DOCUMENT ME!
1659
                 * @param o2 DOCUMENT ME!
1660
                 *
1661
                 * @return DOCUMENT ME!
1662
                 */
1663
                public int compare(Object o1, Object o2) {
1664
                        Extension e1 = (Extension) o1;
1665
                        Extension e2 = (Extension) o2;
1666

    
1667
                        if (!e1.hasPriority() && !e2.hasPriority()) {
1668
                                return -1;
1669
                        }
1670

    
1671
                        if (e1.hasPriority() && !e2.hasPriority()) {
1672
                                return Integer.MIN_VALUE;
1673
                        }
1674

    
1675
                        if (e2.hasPriority() && !e1.hasPriority()) {
1676
                                return Integer.MAX_VALUE;
1677
                        }
1678

    
1679
                        if (e1.getPriority() != e2.getPriority()){
1680
                                return e2.getPriority() - e1.getPriority();
1681
                        }else{
1682
                                return (e2.toString().compareTo(e1.toString()));
1683
                        }
1684
                }
1685
        }
1686

    
1687
        /**
1688
         * DOCUMENT ME!
1689
         */
1690
        private static class MenuComparator implements Comparator {
1691
                private static ExtensionComparator extComp = new ExtensionComparator();
1692

    
1693
                /**
1694
                 * DOCUMENT ME!
1695
                 *
1696
                 * @param o1 DOCUMENT ME!
1697
                 * @param o2 DOCUMENT ME!
1698
                 *
1699
                 * @return DOCUMENT ME!
1700
                 */
1701
                public int compare(Object o1, Object o2) {
1702
                        SortableMenu e1 = (SortableMenu) o1;
1703
                        SortableMenu e2 = (SortableMenu) o2;
1704

    
1705
                        if (!e1.menu.hasPosition() && !e2.menu.hasPosition()) {
1706
                                if (e1.extension instanceof SkinExtensionType) {
1707
                                        return 1;
1708
                                } else if (e2.extension instanceof SkinExtensionType) {
1709
                                        return -1;
1710
                                } else {
1711
                                        return extComp.compare(e1.extension, e2.extension);
1712
                                }
1713
                        }
1714

    
1715
                        if (e1.menu.hasPosition() && !e2.menu.hasPosition()) {
1716
                                return Integer.MIN_VALUE;
1717
                        }
1718

    
1719
                        if (e2.menu.hasPosition() && !e1.menu.hasPosition()) {
1720
                                return Integer.MAX_VALUE;
1721
                        }
1722
                        if (e1.menu.getPosition() != e2.menu.getPosition()){
1723
                                //we don't return 0 unless both objects are the same, otherwise the objects get overwritten in the treemap
1724
                                return e1.menu.getPosition() - e2.menu.getPosition();
1725
                        }else{
1726
                                return (e1.toString().compareTo(e2.toString()));
1727
                        }
1728
                }
1729
        }
1730

    
1731
        /**
1732
         * DOCUMENT ME!
1733
         *
1734
         * @author $author$
1735
         * @version $Revision: 9167 $
1736
         */
1737
        private static class SortableMenu {
1738
                public PluginClassLoader loader;
1739
                public Menu menu;
1740
                public SkinExtensionType extension;
1741

    
1742
                /**
1743
                 * DOCUMENT ME!
1744
                 *
1745
                 * @param loader DOCUMENT ME!
1746
                 * @param skinExt
1747
                 * @param menu2
1748
                 */
1749
                public SortableMenu(PluginClassLoader loader,
1750
                        SkinExtensionType skinExt, Menu menu2) {
1751
                        extension = skinExt;
1752
                        menu = menu2;
1753
                        this.loader = loader;
1754
                }
1755
        }
1756
        /**
1757
         * DOCUMENT ME!
1758
         */
1759
        private static class SortableTool {
1760
                public PluginClassLoader loader;
1761
                public ToolBar toolbar;
1762
                public ActionTool actiontool;
1763
                public SelectableTool selectabletool;
1764
                public SkinExtensionType extension;
1765

    
1766
                /**
1767
                 * DOCUMENT ME!
1768
                 *
1769
                 * @param loader DOCUMENT ME!
1770
                 * @param skinExt
1771
                 * @param menu2
1772
                 */
1773
                public SortableTool(PluginClassLoader loader,
1774
                        SkinExtensionType skinExt, ToolBar toolbar2,ActionTool actiontool2) {
1775
                        extension = skinExt;
1776
                        toolbar = toolbar2;
1777
                        actiontool=actiontool2;
1778
                        this.loader = loader;
1779
                }
1780
                public SortableTool(PluginClassLoader loader,
1781
                                SkinExtensionType skinExt, ToolBar toolbar2,SelectableTool selectabletool2) {
1782
                        extension = skinExt;
1783
                        toolbar = toolbar2;
1784
                        selectabletool=selectabletool2;
1785
                        this.loader = loader;
1786
                }
1787
        }
1788
        /**
1789
         * DOCUMENT ME!
1790
         */
1791
        private static class ToolBarComparator implements Comparator {
1792
                private static ExtensionComparator extComp = new ExtensionComparator();
1793

    
1794
                /**
1795
                 * DOCUMENT ME!
1796
                 *
1797
                 * @param o1 DOCUMENT ME!
1798
                 * @param o2 DOCUMENT ME!
1799
                 *
1800
                 * @return DOCUMENT ME!
1801
                 */
1802
                public int compare(Object o1, Object o2) {
1803
                        SortableTool e1 = (SortableTool) o1;
1804
                        SortableTool e2 = (SortableTool) o2;
1805

    
1806
                        // if the toolbars have the same name, they are considered to be
1807
                        // the same toolbar, so we don't need to do further comparing
1808
                        if (e1.toolbar.getName().equals(e2.toolbar.getName()))
1809
                                return 0;
1810

    
1811
                        if (!e1.toolbar.hasPosition() && !e2.toolbar.hasPosition()) {
1812
                                if (e1.extension instanceof SkinExtensionType) {
1813
                                        return 1;
1814
                                } else if (e2.extension instanceof SkinExtensionType) {
1815
                                        return -1;
1816
                                } else {
1817
                                        return extComp.compare(e1.extension, e2.extension);
1818
                                }
1819
                        }
1820

    
1821
                        if (e1.toolbar.hasPosition() && !e2.toolbar.hasPosition()) {
1822
                                return Integer.MIN_VALUE;
1823
                        }
1824

    
1825
                        if (e2.toolbar.hasPosition() && !e1.toolbar.hasPosition()) {
1826
                                return Integer.MAX_VALUE;
1827
                        }
1828
                        if (e1.toolbar.getPosition() != e2.toolbar.getPosition())
1829
                                return e1.toolbar.getPosition() - e2.toolbar.getPosition();
1830

    
1831
                        if (e1.toolbar.getActionTool().equals(e2.toolbar.getActionTool()) && e1.toolbar.getSelectableTool().equals(e2.toolbar.getSelectableTool())){
1832
                                return 0;
1833
                        }
1834
                        return (e1.toolbar.toString().compareTo(e2.toolbar.toString()));
1835
                }
1836
        }
1837

    
1838
        /**
1839
         * <p>This class is used to compare tools (selectabletool and actiontool),
1840
         * using the "position"
1841
         * attribute.</p>
1842
         * <p>The ordering criteria are:</p>
1843
         * <ul><li>If the tools are placed in different toolbars, they use the toolbars'
1844
         * order.
1845
         * (using the ToolBarComparator).</li>
1846
         * <li></li>
1847
         * <li>If any of the tools has not 'position' attribute, the tool which
1848
         * <strong>has</strong> the attribute will be placed first.</li>
1849
         * <li>If both tools have the same position (or they don't have a
1850
         * 'position' attribute), the priority of the extensions where the tool is defined.</li></ul>
1851
         *
1852
         * @author cesar
1853
         * @version $Revision: 9167 $
1854
         */
1855
        private static class ToolComparator implements Comparator {
1856
                private static ToolBarComparator toolBarComp = new ToolBarComparator();
1857
                /**
1858
                 * DOCUMENT ME!
1859
                 *
1860
                 * @param o1 DOCUMENT ME!
1861
                 * @param o2 DOCUMENT ME!
1862
                 *
1863
                 * @return DOCUMENT ME!
1864
                 */
1865
                public int compare(Object o1, Object o2) {
1866
                        // compare the toolbars which contain the tools
1867
                        int result = toolBarComp.compare(o1, o2);
1868
                        if (result != 0) { // if the toolbars are different, use their order
1869
                                return result;
1870
                        }
1871
                        // otherwise, compare the tools
1872
                        SortableTool e1 = (SortableTool) o1;
1873
                        SortableTool e2 = (SortableTool) o2;
1874
                        int e1Position=-1, e2Position=-1;
1875

    
1876
                        if (e1.actiontool!=null) {
1877
                                if (e1.actiontool.hasPosition())
1878
                                        e1Position = e1.actiontool.getPosition();
1879
                        }
1880
                        else if (e1.selectabletool!=null) {
1881
                                if (e1.selectabletool.hasPosition())
1882
                                        e1Position = e1.selectabletool.getPosition();
1883
                        }
1884

    
1885
                        if (e2.actiontool!=null) {
1886
                                if (e2.actiontool.hasPosition())
1887
                                        e2Position = e2.actiontool.getPosition();
1888
                        }
1889
                        else if (e2.selectabletool!=null){
1890
                                if (e2.selectabletool.hasPosition())
1891
                                        e2Position = e2.selectabletool.getPosition();
1892
                        }
1893

    
1894
                        if (e1Position==-1 && e2Position!=-1) {
1895
                                return 1;
1896
                        }
1897
                        if (e1Position!=-1 && e2Position==-1) {
1898
                                return -1;
1899
                        }
1900
                        if (e1Position!=-1 && e2Position!=-1) {
1901
                                result = e1Position - e2Position;
1902
                                // we don't return 0 unless both objects are the same, otherwise the objects get overwritten in the treemap
1903
                                if (result!=0) return result;
1904
                        }
1905
                        return e1.toString().compareTo(e2.toString());
1906
                }
1907
        }
1908

    
1909

    
1910
        /**
1911
         * validates the user before starting gvsig
1912
         *
1913
         */
1914
        private static void validate(){
1915

    
1916
                IAuthentication session =  null;
1917
                try {
1918
                        session = (IAuthentication)Class.forName("com.iver.andami.authentication.Session").newInstance();
1919

    
1920
                } catch (ClassNotFoundException e) {
1921
                        // TODO Auto-generated catch block
1922
                        //e.printStackTrace();
1923
                        return;
1924
                } catch (InstantiationException e) {
1925
                        // TODO Auto-generated catch block
1926
                        //e.printStackTrace();
1927
                        return;
1928
                } catch (IllegalAccessException e) {
1929
                        // TODO Auto-generated catch block
1930
                        //e.printStackTrace();
1931
                        return;
1932
                }
1933

    
1934
                session.setPluginDirectory( andamiConfig.getPluginsDirectory() );
1935
                if (session.validationRequired()){
1936
                        if(session.Login()){
1937
                                System.out.println("You are logged in");
1938
                        }
1939
                        else{
1940
                                JOptionPane.showMessageDialog((Component)PluginServices.getMainFrame(),
1941
                                                 "You are not logged in");
1942
                                //System.exit(0);
1943
                        }
1944
                        PluginServices.setAuthentication(session);
1945
                }
1946
        }
1947

    
1948
        public static String getDefaultLookAndFeel() {
1949
                String osName = (String) System.getProperty("os.name");
1950

    
1951
                if (osName.length() > 4 && osName.substring(0,5).toLowerCase().equals("linux"))
1952
                        return nonWinDefaultLookAndFeel;
1953
                   return UIManager.getSystemLookAndFeelClassName();
1954
        }
1955

    
1956
        /**
1957
         * Gets the ISO 839 two-characters-long language code matching the
1958
         * provided language code (which may be an ISO 839-2/T
1959
         * three-characters-long code or an ISO 839-1 two-characters-long
1960
         * code).
1961
         *
1962
         * If the provided parameter is already two characters long, it
1963
         * returns the parameter without any modification.
1964
         *
1965
         * @param langCode A language code representing either
1966
         *  an ISO 839-2/T language code or an ISO 839-1 code.
1967
         * @return A two-characters-long code specifying
1968
         *  an ISO 839 language code.
1969
         */
1970
        private static String normalizeLanguageCode(String langCode) {
1971
                final String fileName = "iso_639.tab";
1972
                if (langCode.length()==2)
1973
                        return langCode;
1974
                else if (langCode.length()==3) {
1975
                        if (langCode.equals("va") || langCode.equals("val")) { // special case for Valencian
1976
                                return "ca";
1977
                        }
1978
                        URL isoCodes = Launcher.class.getClassLoader().getResource(fileName);
1979
                        if (isoCodes!=null) {
1980
                                try {
1981
                                        BufferedReader reader =
1982
                                                new BufferedReader(new InputStreamReader(isoCodes.openStream(), "ISO-8859-1"));
1983
                                                String line;
1984

    
1985
                                                while ((line = reader.readLine()) != null) {
1986
                                                        String[] language = line.split("\t");
1987
                                                        if (language[0].equals(langCode)) // first column is the three characters code
1988
                                                                return language[2]; // third column i the two characters code
1989
                                                }
1990
                                }
1991
                                catch (IOException ex) {
1992
                                        logger.error(Messages.getString("Error_reading_isocodes_file"), ex);
1993
                                        return "es";
1994
                                }
1995
                        }
1996
                        else {
1997
                                logger.error(Messages.getString("Error_reading_isocodes_file"));
1998
                                return "es";
1999
                        }
2000
                }
2001
                return "es";
2002
        }
2003

    
2004
        /**
2005
         * Configures the locales (languages and local resources) to be used
2006
         * by the application.
2007
         *
2008
         * First it tries to get the locale from the command line parameters,
2009
         * then the andami-config file is checked.
2010
         *
2011
         * The locale name is normalized to get a two characters language code
2012
         * as defined by ISO-639-1 (although ISO-639-2/T three characters codes
2013
         * are also accepted from the command line or the configuration file).
2014
         *
2015
         * Finally, the gvsig-i18n library and the default locales for Java and
2016
         * Swing are configured.
2017
         *
2018
         */
2019
        private static void configureLocales(String[] args) {
2020
                //                 Configurar el locale
2021
        String localeStr = null;
2022
        for (int i=2; i < args.length; i++)
2023
        {
2024
                int index = args[i].indexOf("language=");
2025
                if (index != -1)
2026
                        localeStr = args[i].substring(index+9);
2027
        }
2028
                if (localeStr == null)
2029
                {
2030
            localeStr = andamiConfig.getLocaleLanguage();
2031
                }
2032
                localeStr = normalizeLanguageCode(localeStr);
2033
                locale = getLocale(localeStr,
2034
                andamiConfig.getLocaleCountry(),
2035
                andamiConfig.getLocaleVariant());
2036
                Locale.setDefault(locale);
2037
                JComponent.setDefaultLocale(locale);
2038
        org.gvsig.i18n.Messages.addLocale(locale);
2039
                // add english and spanish as fallback languages
2040
                org.gvsig.i18n.Messages.addLocale(new Locale("en"));
2041
                org.gvsig.i18n.Messages.addLocale(new Locale("es"));
2042
        org.gvsig.i18n.Messages.addResourceFamily("com.iver.andami.text", "com.iver.andami.text");
2043

    
2044
        }
2045

    
2046
        /**
2047
         * Gets Home Directory location of the application.
2048
         * May be set from outside the aplication by means of
2049
         * -DgvSIG.home=C:/data/gvSIG, where gvSIG its the name
2050
         * of the application
2051
         * @return
2052
         */
2053
        public static String getAppHomeDir() {
2054
                return appHomeDir;
2055
        }
2056

    
2057
        /**
2058
         * Sets Home Directory location of the application.
2059
         * May be set from outside the aplication by means of
2060
         * -DgvSIG.home=C:/data/gvSIG, where gvSIG its the name
2061
         * of the application
2062
         * @param appHomeDir
2063
         */
2064
        public static void setAppHomeDir(String appHomeDir) {
2065
                Launcher.appHomeDir = appHomeDir;
2066
        }
2067
}