Statistics
| Revision:

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

History | View | Annotate | Download (61.7 KB)

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

    
43
import java.awt.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.SwingUtilities;
93
import javax.swing.UIManager;
94

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

    
102
import com.iver.andami.authentication.IAuthentication;
103
import com.iver.andami.config.generate.Andami;
104
import com.iver.andami.config.generate.AndamiConfig;
105
import com.iver.andami.config.generate.Plugin;
106
import com.iver.andami.messages.Messages;
107
import com.iver.andami.messages.NotificationManager;
108
import com.iver.andami.plugins.ExtensionDecorator;
109
import com.iver.andami.plugins.PluginClassLoader;
110
import com.iver.andami.plugins.config.generate.ActionTool;
111
import com.iver.andami.plugins.config.generate.ComboButton;
112
import com.iver.andami.plugins.config.generate.ComboButtonElement;
113
import com.iver.andami.plugins.config.generate.ComboScale;
114
import com.iver.andami.plugins.config.generate.Depends;
115
import com.iver.andami.plugins.config.generate.Extension;
116
import com.iver.andami.plugins.config.generate.Extensions;
117
import com.iver.andami.plugins.config.generate.LabelSet;
118
import com.iver.andami.plugins.config.generate.Menu;
119
import com.iver.andami.plugins.config.generate.PluginConfig;
120
import com.iver.andami.plugins.config.generate.PopupMenu;
121
import com.iver.andami.plugins.config.generate.PopupMenus;
122
import com.iver.andami.plugins.config.generate.SelectableTool;
123
import com.iver.andami.plugins.config.generate.SkinExtension;
124
import com.iver.andami.plugins.config.generate.SkinExtensionType;
125
import com.iver.andami.plugins.config.generate.ToolBar;
126
import com.iver.andami.ui.AndamiEventQueue;
127
import com.iver.andami.ui.MDIManagerLoadException;
128
import com.iver.andami.ui.mdiFrame.MDIFrame;
129
import com.iver.andami.ui.mdiManager.MDIManagerFactory;
130
import com.iver.andami.ui.splash.MultiSplashWindow;
131
import com.iver.andami.ui.theme.Theme;
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: 8970 $
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

    
264
                    // Obtener la personalizaci?n de la aplicaci?n.
265
                        Theme theme=getTheme();
266

    
267
                        // Mostrar la ventana de inicio
268
                    Frame f=new Frame();
269
                    splashWindow=new MultiSplashWindow(f,theme);
270

    
271
                    // Ponemos los datos del proxy
272
                    configureProxy();
273

    
274
                    // TODO Buscar actualizaciones de los plugins
275
                    downloadExtensions(andamiConfig.getPluginsDirectory());
276

    
277
                    // Se leen los config.xml de los plugins -----++++
278
                    loadPlugins(andamiConfig.getPluginsDirectory());
279

    
280
                    // Se configura el classloader del plugin
281
                    pluginsClassLoaders();
282

    
283
                    // Se carga un Skin si alguno de los plugins trae informaci?n para ello
284
                    skinPlugin();
285

    
286
                    //Se configura la cola de eventos
287
                    EventQueue waitQueue = new AndamiEventQueue();
288
                    Toolkit.getDefaultToolkit().getSystemEventQueue().push(waitQueue);
289

    
290
                    // Se configura la mensajer?a del plugin
291
                    pluginsMessages();
292

    
293
                    // Se modifica el andami-config con los plugins nuevos
294
                    updateAndamiConfig();
295

    
296
                    // Se prepara el MainFrame para albergar las extensiones
297
                    frame = new MDIFrame();
298

    
299
                    // Se configura el nombre e icono de la aplicaci?n
300
                    frameIcon(theme);
301

    
302
                    SwingUtilities.invokeAndWait(new Runnable() {
303
                            public void run() {
304
                                    frame.init();
305
                            }
306
                    });
307

    
308
                    // Se instalan los controles de las extensiones de los plugins
309
                    SwingUtilities.invokeAndWait(new Runnable() {
310
                            public void run() {
311
                                    installPluginsControls();
312
                                    installPluginsMenus();
313
                                    installPluginsLabels();
314
                            }
315
                    });
316

    
317
                    // Leer el fichero de persistencia
318
                    //  info de los plugins
319
                    //  bookmarks de los plugins
320
                    loadPluginsPersistence();
321

    
322
                    // Se instalan los controles del skin
323
                    // Se inicializan todas las extensiones de todos los plugins
324
                    SwingUtilities.invokeAndWait(new Runnable() {
325
                            public void run() {
326
                                    initializeExtensions();
327
                                    postInitializeExtensions();
328
                            }
329
                    });
330
                    frame.setClassesExtensions(classesExtensions);
331

    
332
                    // Se instalan los bookmarks de los plugins
333

    
334
                    //Se muestra el frame principal
335
                    frame.show();
336

    
337
                    // Definimos un KeyEventDispatcher global para que las extensiones
338
                    // puedan registrar sus "teclas r?pidas".
339
                    GlobalKeyEventDispatcher keyDispatcher = GlobalKeyEventDispatcher.getInstance();
340
                    KeyboardFocusManager.getCurrentKeyboardFocusManager().addKeyEventDispatcher(keyDispatcher);
341

    
342
                    SwingUtilities.invokeAndWait(new Runnable() {
343
                            public void run() {
344
                                    frame.enableControls();
345
                            }
346
                    });
347
                    splashWindow.close();
348
            }catch(Exception e){
349
                    logger.error("excepci?n al arrancar", e);
350
                    System.exit(-1);
351
            }
352

    
353
    }
354

    
355
    /**
356
     * Obtiene la personalizaci?n de los iconos, splash, fondo y el nombre de
357
     * la aplicaci?n.
358
     *
359
     * @return Theme
360
     */
361
    private static Theme getTheme() {
362
            Theme theme=new Theme();
363
                File file=new File("theme/andami-theme.xml");
364
                if (file.exists()) {
365
                        theme.readTheme(file);
366
                }
367
                return theme;
368
        }
369
        /**
370
     *Establece los datos que ten?amos guardados respecto de la configuraci?n
371
     *del proxy.
372
     */
373
        private static void configureProxy() {
374
                String host = prefs.get("firewall.http.host", "");
375
                String port = prefs.get("firewall.http.port", "");
376

    
377
                System.getProperties().put("http.proxyHost", host);
378
                System.getProperties().put("http.proxyPort", port);
379

    
380
                // Ponemos el usuario y clave del proxy, si existe
381
                String proxyUser = prefs.get("firewall.http.user",null);
382
                String proxyPassword = prefs.get("firewall.http.password", null);
383
                if (proxyUser != null )
384
                {
385
                        System.getProperties().put("http.proxyUserName", proxyUser);
386
                        System.getProperties().put("http.proxyPassword", proxyPassword);
387

    
388
                        Authenticator.setDefault(new ProxyAuth(proxyUser,
389
                                                        proxyPassword));
390
                } else {
391
                        Authenticator.setDefault(new ProxyAuth("", ""));
392
                }
393
        }
394

    
395
        /**
396
         * Recupera la geometr?a (tama?o, posici?n y estado) de la ventana principal de Andami.
397
         * TODO Pendiente de ver como se asigna un pluginServices para el launcher.
398
         * @author LWS
399
         */
400
        private static void restoreMDIStatus(XMLEntity xml) {
401
                //System.err.println("Launcher: restoreMDIStatus()");
402
                if (xml == null) xml = new XMLEntity();
403
                //  restore frame size
404
                Dimension sz = new Dimension(700,580);
405
                if (xml.contains("MDIFrameSize")) {
406
                        int [] wh = xml.getIntArrayProperty("MDIFrameSize");
407
                        sz = new Dimension(wh[0], wh[1]);
408
                }
409
                frame.setSize(sz);
410
                //  restore frame location
411
                Point pos = new Point(10,10);
412
                if (xml.contains("MDIFramePos")) {
413
                        int [] xy = xml.getIntArrayProperty("MDIFramePos");
414
                        pos = new Point(xy[0], xy[1]);
415
                }
416
                frame.setLocation(pos);
417

    
418
                //  restore frame status (Maximized, minimized, etc);
419
                int state = java.awt.Frame.MAXIMIZED_BOTH;
420
                if (xml.contains("MDIFrameState")) {
421
                        state = xml.getIntProperty("MDIFrameState");
422
                }
423
                frame.setExtendedState(state);
424
        }
425

    
426
        private static XMLEntity saveMDIStatus() {
427
                XMLEntity xml = new XMLEntity();
428
                // save frame size
429
                int [] wh = new int[2];
430
                wh[0] = frame.getWidth();
431
                wh[1] = frame.getHeight();
432
                xml.putProperty("MDIFrameSize", wh);
433
                // save frame location
434
                int [] xy = new int[2];
435
                xy[0] = frame.getX();
436
                xy[1] = frame.getY();
437
                xml.putProperty("MDIFramePos", xy);
438
                // save frame status
439
                xml.putProperty("MDIFrameState", frame.getExtendedState());
440
                return xml;
441
        }
442

    
443
        /**
444
     * @return
445
     */
446
    private static boolean validJVM() {
447
        char thirdCharacter = System.getProperty("java.version").charAt(2);
448
        if (thirdCharacter < '4'){
449
            return false;
450
            }else{
451
                return true;
452
            }
453
    }
454

    
455
    /**
456
         * DOCUMENT ME!
457
         *
458
         * @throws ConfigurationException
459
         */
460
        private static void loadPluginsPersistence() throws ConfigurationException {
461
                XMLEntity entity = persistenceFromXML();
462

    
463
                //System.err.println("loadPluginPersistence()");
464
                for (int i = 0; i < entity.getChildrenCount(); i++) {
465
                        XMLEntity plugin = entity.getChild(i);
466
                        String pName = plugin.getStringProperty(
467
                                        "com.iver.andami.pluginName");
468
                        //System.err.println("--> "+pName);
469
                        if (pluginsServices.get(pName)!= null){
470
                                ((PluginServices) pluginsServices.get(pName)).setPersistentXML(plugin);
471
                        } else {
472
                                if (pName.startsWith("Andami.Launcher"))
473
                                        restoreMDIStatus(plugin);
474
                        }
475
                }
476
        }
477

    
478
        /**
479
         * Salva la persistencia de los plugins.
480
         * @author LWS
481
         */
482
        private static void savePluginPersistence() {
483
                Iterator i = pluginsConfig.keySet().iterator();
484

    
485
                XMLEntity entity = new XMLEntity();
486

    
487
                while (i.hasNext()) {
488
                        String pName = (String) i.next();
489
                        PluginServices ps = (PluginServices) pluginsServices.get(pName);
490
                        XMLEntity ent = ps.getPersistentXML();
491

    
492
                        if (ent != null) {
493
                                ent.putProperty("com.iver.andami.pluginName", pName);
494
                                entity.addChild(ent);
495
                        }
496
                }
497
                XMLEntity ent = saveMDIStatus();
498
                if (ent != null) {
499
                        ent.putProperty("com.iver.andami.pluginName", "Andami.Launcher");
500
                        entity.addChild(ent);
501
                }
502
                try {
503
                        persistenceToXML(entity);
504
                } catch (ConfigurationException e1) {
505
                        logger.error(Messages.getString(
506
                                        "Launcher.Se_produjo_un_error_guardando_la_configuracion_de_los_plugins"),
507
                                e1);
508
                }
509
        }
510

    
511
        /**
512
         * DOCUMENT ME!
513
         */
514
        private static void installPluginsLabels() {
515
                Iterator i = pluginsConfig.keySet().iterator();
516

    
517
                while (i.hasNext()) {
518
                        String name = (String) i.next();
519
                        PluginConfig pc = (PluginConfig) pluginsConfig.get(name);
520
                        PluginServices ps = (PluginServices) pluginsServices.get(name);
521

    
522
                        LabelSet[] ls = pc.getLabelSet();
523

    
524
                        for (int j = 0; j < ls.length; j++) {
525
                                PluginClassLoader loader = ps.getClassLoader();
526

    
527
                                try {
528
                                        Class clase = loader.loadClass(ls[j].getClassName());
529
                                        frame.setLabels(clase, ls[j].getLabel());
530
                                } catch (ClassNotFoundException e) {
531
                                        logger.error(Messages.getString("Launcher.labelset_class"),
532
                                                e);
533
                                }
534
                        }
535
                }
536
        }
537

    
538
        /**
539
         * DOCUMENT ME!
540
         *
541
         * @throws MDIManagerLoadException
542
         */
543
        private static void skinPlugin() throws MDIManagerLoadException {
544
                Iterator i = pluginsConfig.keySet().iterator();
545

    
546
                while (i.hasNext()) {
547
                        String name = (String) i.next();
548
                        PluginConfig pc = (PluginConfig) pluginsConfig.get(name);
549
                        PluginServices ps = (PluginServices) pluginsServices.get(name);
550

    
551
                        if (pc.getExtensions().getSkinExtension() != null) {
552
                                if (MDIManagerFactory.getSkinExtension() != null) {
553
                                        logger.warn(Messages.getString(
554
                                                        "Launcher.Dos_skin_extension"));
555
                                }
556

    
557
                                SkinExtension se = pc.getExtensions().getSkinExtension();
558

    
559
                                MDIManagerFactory.setSkinExtension(se, ps.getClassLoader());
560

    
561
                                Class skinClass;
562

    
563
                                try {
564
                                        skinClass = ps.getClassLoader().loadClass(se.getClassName());
565

    
566
                                        com.iver.andami.plugins.IExtension skinInstance = (com.iver.andami.plugins.IExtension) skinClass.newInstance();
567
                                        // classesExtensions.put(skinClass, skinInstance);
568
                                        // jaume
569
                                        ExtensionDecorator newExtensionDecorator = new ExtensionDecorator(skinInstance, ExtensionDecorator.INACTIVE);
570
                                        classesExtensions.put(skinClass, newExtensionDecorator);
571
                                } catch (ClassNotFoundException e) {
572
                                        logger.error(Messages.getString(
573
                                                        "Launcher.No_se_encontro_la_clase_mdi_manager"), e);
574
                                        throw new MDIManagerLoadException(e);
575
                                } catch (InstantiationException e) {
576
                                        logger.error(Messages.getString(
577
                                                        "Launcher.No_se_pudo_instanciar_la_clase_mdi_manager"),
578
                                                e);
579
                                        throw new MDIManagerLoadException(e);
580
                                } catch (IllegalAccessException e) {
581
                                        logger.error(Messages.getString(
582
                                                        "Launcher.No_se_pudo_acceder_a_la_clase_mdi_manager"),
583
                                                e);
584
                                        throw new MDIManagerLoadException(e);
585
                                }
586
                        }
587
                }
588
        }
589

    
590
        /**
591
         * @param theme
592
         *
593
         */
594
        private static void frameIcon(Theme theme) {
595
                Iterator i = pluginsConfig.keySet().iterator();
596

    
597
                while (i.hasNext()) {
598
                        String pName = (String) i.next();
599
                        PluginConfig pc = (PluginConfig) pluginsConfig.get(pName);
600
                        PluginServices ps = (PluginServices) pluginsServices.get(pName);
601
                        if (pc.getIcon() != null) {
602
                                if (theme.getIcon() != null) {
603
                                        frame.setIconImage(theme.getIcon().getImage());
604
                                } else {
605

    
606
                                        ImageIcon icon = new ImageIcon(ps.getClassLoader()
607
                                                        .getResource(pc.getIcon().getSrc()));
608
                                        frame.setIconImage(icon.getImage());
609

    
610
                                }
611
                                if (theme.getName() != null) {
612
                                        frame.setTitlePrefix(theme.getName());
613
                                } else {
614
                                        frame.setTitlePrefix(pc.getIcon().getText());
615
                                }
616
                                if (theme.getBackgroundImage() != null) {
617

    
618
                                        PluginServices.getMDIManager().setBackgroundImage(theme.getBackgroundImage(),theme.getTypeDesktop());
619
                                        //frame.setBackgroundImage(theme.getBackgroundImage());
620
                                }
621
                        }
622
                }
623
        }
624

    
625
        /**
626
         *
627
         */
628
        private static void initializeExtensions() {
629
                Iterator i = pluginsOrdered.iterator();
630

    
631
                while (i.hasNext()) {
632
                        String pName = (String) i.next();
633
            logger.debug("Initializing extensions from " + pName);
634
                        PluginConfig pc = (PluginConfig) pluginsConfig.get(pName);
635
                        PluginServices ps = (PluginServices) pluginsServices.get(pName);
636

    
637
                        Extension[] exts = pc.getExtensions().getExtension();
638

    
639
                        TreeMap orderedExtensions = new TreeMap(new ExtensionComparator());
640

    
641
                        for (int j = 0; j < exts.length; j++) {
642
                                if (!exts[j].getActive()) {
643
                                        continue;
644
                                }
645

    
646
                                if (orderedExtensions.containsKey(exts[j])) {
647
                                        logger.warn(Messages.getString(
648
                                                        "Launcher.Two_extensions_with_the_same_priority") +
649
                                                exts[j].getClassName());
650
                                }
651

    
652
                                orderedExtensions.put(exts[j], null);
653
                        }
654

    
655
                        Iterator e = orderedExtensions.keySet().iterator();
656

    
657
                        while (e.hasNext()) {
658
                                Extension extension = (Extension) e.next();
659
                                com.iver.andami.plugins.IExtension extensionInstance;
660

    
661
                                try {
662
                                        Class extensionClass = ps.getClassLoader().loadClass(extension.getClassName());
663
                                        extensionInstance = (com.iver.andami.plugins.IExtension) extensionClass.newInstance();
664

    
665
                                        // CON DECORATOR
666
                                        // ANTES: classesExtensions.put(extensionClass, extensionInstance);
667
                                        // AHORA: CREAMOS UNA ExtensionDecorator y asignamos esta instancia para
668
                                        // poder ampliar con nuevas propiedades (AlwaysVisible, por ejemplo)
669
                                        // Para crear la nueva clase ExtensionDecorator, le pasamos como par?metro
670
                                        // la extensi?n original que acabamos de crear
671
                                        // 0-> Inactivo, controla la extension
672
                                        // 1-> Siempre visible
673
                                        // 2-> Invisible
674
                                        ExtensionDecorator newExtensionDecorator = new ExtensionDecorator(extensionInstance, ExtensionDecorator.INACTIVE);
675
                                        classesExtensions.put(extensionClass, newExtensionDecorator);
676
                                        System.err.println("Loading "+extension.getClassName()+"...");
677
                    // logger.debug("Initializing " + extension.getClassName());
678
                    extensionInstance.initialize();
679
                    extensions.add(extensionInstance);
680
                    // logger.debug(extension.getClassName() + " initialized.");
681

    
682
                                } catch (InstantiationException e1) {
683
                                        logger.error(Messages.getString(
684
                                                        "Launcher.Error_instanciando_la_extension") +
685
                                                extension.getClassName(), e1);
686
                                } catch (IllegalAccessException e1) {
687
                                        logger.error(Messages.getString(
688
                                                        "Launcher.Error_instanciando_la_extension") +
689
                                                extension.getClassName(), e1);
690
                                } catch (ClassNotFoundException e1) {
691
                                        logger.error(Messages.getString(
692
                                                        "Launcher.No_se_encontro_la_clase_de_la_extension") +
693
                                                extension.getClassName(), e1);
694
                                } catch (NoClassDefFoundError e1) {
695
                                        logger.error(Messages.getString(
696
                                                        "Launcher.Error_localizando_la_clase_de_la_extension") +
697
                                                extension.getClassName(), e1);
698
                                }
699
                        }
700
                }
701
        }
702

    
703
        private static void postInitializeExtensions() {
704
                for (int i=0;i<extensions.size();i++) {
705
                        com.iver.andami.plugins.IExtension extensionInstance=(com.iver.andami.plugins.IExtension)extensions.get(i);
706
                        extensionInstance.postInitialize();
707
                }
708
        }
709
        /**
710
         * DOCUMENT ME!
711
         */
712
        private static void installPluginsMenus() {
713
                TreeMap orderedMenus = new TreeMap(new MenuComparator());
714

    
715
                Iterator i = pluginsConfig.keySet().iterator();
716

    
717
                while (i.hasNext()) {
718
                        String pName = (String) i.next();
719
                        PluginServices ps = (PluginServices) pluginsServices.get(pName);
720
                        PluginConfig pc = (PluginConfig) pluginsConfig.get(pName);
721

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

    
724
                        for (int j = 0; j < exts.length; j++) {
725
                                if (!exts[j].getActive()) {
726
                                        continue;
727
                                }
728

    
729
                                Menu[] menus = exts[j].getMenu();
730

    
731
                                for (int k = 0; k < menus.length; k++) {
732
                                        SortableMenu sm = new SortableMenu(ps.getClassLoader(),
733
                                                        exts[j], menus[k]);
734

    
735
                                        if (orderedMenus.containsKey(sm)) {
736
                                                logger.error(Messages.getString(
737
                                                                "Launcher.Two_menus_with_the_same_position") + " - " +
738
                                                        menus[k].getText()+ " - " + exts[j].getClassName());
739
                                        }
740

    
741
                                        orderedMenus.put(sm, null);
742
                                }
743
                        }
744

    
745
                        // Se instalan las extensiones de MDI
746
                        SkinExtension skinExt = pc.getExtensions().getSkinExtension();
747

    
748
                        if (skinExt != null) {
749
                                Menu[] menu = skinExt.getMenu();
750

    
751
                                for (int k = 0; k < menu.length; k++) {
752
                                        SortableMenu sm = new SortableMenu(ps.getClassLoader(),
753
                                                        skinExt, menu[k]);
754

    
755
                                        if (orderedMenus.containsKey(sm)) {
756
                                                logger.error(Messages.getString(
757
                                                                "Launcher.Two_menus_with_the_same_position") +
758
                                                        skinExt.getClassName());
759
                                        }
760

    
761
                                        orderedMenus.put(sm, null);
762
                                }
763
                        }
764
                }
765

    
766
                //Se itera por los menus ordenados
767
                Iterator e = orderedMenus.keySet().iterator();
768

    
769
                // Se ordenan los menues
770
                while (e.hasNext()) {
771
                        try {
772
                                SortableMenu sm = (SortableMenu) e.next();
773

    
774
                                frame.addMenu(sm.loader, sm.extension, sm.menu);
775
                        } catch (ClassNotFoundException ex) {
776
                                logger.error(Messages.getString(
777
                                                "Launcher.No_se_encontro_la_clase_de_la_extension"), ex);
778
                        }
779
                }
780
        }
781

    
782
        /**
783
         * Installs the menus, toolbars, actiontools, selectable toolbars and combos.
784
         * The order in which they are shown is determined here.
785
         */
786
        private static void installPluginsControls() {
787
                Iterator i = pluginsConfig.keySet().iterator();
788

    
789
                HashMap extensionPluginServices = new HashMap();
790
                HashMap extensionPluginConfig = new HashMap();
791
                TreeMap orderedExtensions = new TreeMap(new ExtensionComparator());
792

    
793
                // First of all, sort the extensions.
794
                // We need to iterate on the plugins, and iterate on each plugin's extensions
795
                // (each plugin may contain one or more extensions)
796
                while (i.hasNext()) { // iterate on the plugins
797
                        String pName = (String) i.next();
798
                        PluginConfig pc = (PluginConfig) pluginsConfig.get(pName);
799
                        PluginServices ps = (PluginServices) pluginsServices.get(pName);
800

    
801
                        Extension[] exts = pc.getExtensions().getExtension();
802

    
803
                        for (int j = 0; j < exts.length; j++) { // iterate on the extensions
804
                                if (exts[j].getActive()) {
805
                                        if (orderedExtensions.containsKey(exts[j])) {
806
                                                logger.error(Messages.getString(
807
                                                "Launcher.Two_extensions_with_the_same_priority") +
808
                                                exts[j].getClassName());
809
                                        }
810

    
811
                                        orderedExtensions.put(exts[j], null);
812
                                        extensionPluginServices.put(exts[j], ps);
813
                                        extensionPluginConfig.put(exts[j], pc);
814
                                }
815
                        }
816
                }
817

    
818
                TreeMap orderedTools = new TreeMap(new ToolComparator());
819
                Iterator e = orderedExtensions.keySet().iterator();
820

    
821
                // sort the toolbars and tools from 'normal' extensions (actiontools, selectabletools)
822
                // and load the  combo-scales and combo-buttons for the status bar
823
                while (e.hasNext()) {
824
                        Extension ext = (Extension) e.next();
825

    
826
                        ToolBar[] toolbars = ext.getToolBar();
827

    
828
                        // get tools from toolbars
829
                        for (int k = 0; k < toolbars.length; k++) {
830
                                ActionTool[] tools = toolbars[k].getActionTool();
831

    
832
                                for (int t = 0; t < tools.length; t++) {
833
                                        SortableTool sm = new SortableTool(((PluginServices)extensionPluginServices.get(ext)).getClassLoader(), ext,
834
                                                        toolbars[k], tools[t]);
835
                                        orderedTools.put(sm, null);
836
                                }
837

    
838
                                SelectableTool[] sTools = toolbars[k].getSelectableTool();
839

    
840
                                for (int t = 0; t < sTools.length; t++) {
841
                                        SortableTool sm=new SortableTool(((PluginServices)extensionPluginServices.get(ext)).getClassLoader(), ext,
842
                                                        toolbars[k], sTools[t]);
843
                                        orderedTools.put(sm, null);
844
                                }
845
                        }
846

    
847
                        // get controls for statusBar
848
                        PluginServices ps = (PluginServices) extensionPluginServices.get(ext);
849
                        PluginClassLoader loader = ps.getClassLoader();
850

    
851
                        //ArrayList componentList = new ArrayList();
852
                        ComboScale[] comboScaleArray = ext.getComboScale();
853
                        for (int k=0; k < comboScaleArray.length; k++) {
854
                                org.gvsig.gui.beans.controls.comboscale.ComboScale combo = new org.gvsig.gui.beans.controls.comboscale.ComboScale();
855
                                String label = comboScaleArray[k].getLabel();
856
                                if (label!=null)
857
                                        combo.setLabel(label);
858
                                String name = comboScaleArray[k].getName();
859
                                if (name!=null)
860
                                        combo.setName(name);
861
                                String[] elementsString = ((String)comboScaleArray[k].getElements()).split(";");
862
                                long[] elements = new long[elementsString.length];
863
                                for (int currentElem=0; currentElem<elementsString.length; currentElem++) {
864
                                        try {
865
                                                elements[currentElem] = Long.parseLong(elementsString[currentElem]);
866
                                        }
867
                                        catch (NumberFormatException nfex1) {
868
                                                logger.error(ext.getClassName()+" -- "+Messages.getString( "error_parsing_comboscale_elements"));
869
                                                elements[currentElem] = 0;
870
                                        }
871
                                }
872
                                combo.setItems(elements);
873
                                try {
874
                                        long value = Long.parseLong((String)comboScaleArray[k].getValue());
875
                                        combo.setScale(value);
876
                                }
877
                                catch (NumberFormatException nfex2) {
878
                                        logger.error(ext.getClassName()+" -- "+Messages.getString( "error_parsing_comboscale_value"));
879
                                }
880
                                try {
881
                                        frame.addStatusBarControl(loader.loadClass(ext.getClassName()),combo);
882
                                } catch (ClassNotFoundException e1) {
883
                                        logger.error(Messages.getString("Launcher.error_getting_class_loader_for_status_bar_control"), e1);
884
                                }
885
                        }
886

    
887
                        ComboButton[] comboButtonArray = ext.getComboButton();
888
                        for (int k=0; k < comboButtonArray.length; k++) {
889
                                ComboButtonElement[] elementList = comboButtonArray[k].getComboButtonElement();
890
                                org.gvsig.gui.beans.controls.combobutton.ComboButton combo = new org.gvsig.gui.beans.controls.combobutton.ComboButton();
891
                                String name = comboButtonArray[k].getName();
892
                                if (name!=null)
893
                                        combo.setName(name);
894
                                for (int currentElement=0; currentElement<elementList.length; currentElement++) {
895
                                        ComboButtonElement element = elementList[currentElement];
896
                                        ImageIcon icon;
897
                                        URL iconLocation = loader.getResource(element.getIcon());
898
                                        if (iconLocation==null)
899
                                                logger.error(Messages.getString("Icon_not_found_")+element.getIcon());
900
                                        else {
901
                                                icon = new ImageIcon(iconLocation);
902
                                                JButton button = new JButton(icon);
903
                                                combo.addButton(button);
904
                                                button.setActionCommand(element.getActionCommand());
905
                                        }
906
                                }
907
                                try {
908
                                        frame.addStatusBarControl(loader.loadClass(ext.getClassName()), combo);
909
                                } catch (ClassNotFoundException e1) {
910
                                        logger.error(Messages.getString("Launcher.error_getting_class_loader_for_status_bar_control"), e1);
911
                                }
912
                        }
913
                }
914

    
915
                // Add the tools from MDI extensions to the ordered tool-list, so that we get a sorted list containing all the tools
916
                i = pluginsConfig.keySet().iterator();
917
                while (i.hasNext()) {
918
                        String pName = (String) i.next();
919
                        PluginConfig pc = (PluginConfig) pluginsConfig.get(pName);
920
                        PluginServices ps = (PluginServices) pluginsServices.get(pName);
921

    
922
                        SkinExtension skinExt = pc.getExtensions().getSkinExtension();
923

    
924
                        if (skinExt != null) {
925
                                ToolBar[] toolbars = skinExt.getToolBar();
926

    
927
                                for (int k = 0; k < toolbars.length; k++) {
928
                                        ActionTool[] tools = toolbars[k].getActionTool();
929

    
930
                                        for (int t = 0; t < tools.length; t++) {
931
                                                SortableTool stb=new SortableTool(ps.getClassLoader(), skinExt,
932
                                                                toolbars[k], tools[t]);
933
                                                orderedTools.put(stb,null);
934
                                        }
935

    
936
                                        SelectableTool[] sTools = toolbars[k].getSelectableTool();
937

    
938
                                        for (int t = 0; t < sTools.length; t++) {
939
                                                SortableTool stb=new SortableTool(ps.getClassLoader(), skinExt,
940
                                                                toolbars[k], sTools[t]);
941
                                                orderedTools.put(stb,null);
942
                                        }
943
                                }
944
                        }
945
                        // Install popup menus
946
                        PopupMenus pus = pc.getPopupMenus();
947

    
948
                        if (pus != null) {
949
                                PopupMenu[] menus = pus.getPopupMenu();
950

    
951
                                for (int j = 0; j < menus.length; j++) {
952
                                        frame.addPopupMenu(ps.getClassLoader(), menus[j]);
953
                                }
954
                        }
955
                }
956

    
957
                // loop on the ordered extension list, to add them to the interface in an ordered way
958
                Iterator t = orderedTools.keySet().iterator();
959
                while (t.hasNext()) {
960
                        try {
961
                                SortableTool stb = (SortableTool) t.next();
962
                                if (stb.actiontool!=null)
963
                                        frame.addTool(stb.loader, stb.extension,stb.toolbar, stb.actiontool);
964
                                else
965
                                        frame.addTool(stb.loader, stb.extension,stb.toolbar, stb.selectabletool);
966
                        } catch (ClassNotFoundException ex) {
967
                                logger.error(Messages.getString(
968
                                "Launcher.No_se_encontro_la_clase_de_la_extension"), ex);
969
                        }
970
                }
971
        }
972

    
973
        /**
974
         * Adds new plugins to the the andami-config file.
975
         */
976
        private static void updateAndamiConfig() {
977
                HashSet olds = new HashSet();
978

    
979
                Plugin[] plugins = andamiConfig.getPlugin();
980

    
981
                for (int i = 0; i < plugins.length; i++) {
982
                        olds.add(plugins[i].getName());
983
                }
984

    
985
                Iterator i = pluginsServices.values().iterator();
986

    
987
                while (i.hasNext()) {
988
                        PluginServices ps = (PluginServices) i.next();
989

    
990
                        if (!olds.contains(ps.getPluginName())) {
991
                                Plugin p = new Plugin();
992
                                p.setName(ps.getPluginName());
993
                                p.setUpdate(false);
994

    
995
                                andamiConfig.addPlugin(p);
996
                        }
997
                }
998
        }
999

    
1000
        /**
1001
         * DOCUMENT ME!
1002
         */
1003
        private static void pluginsClassLoaders() {
1004
                HashSet instalados = new HashSet();
1005

    
1006
                // Se itera hasta que est?n todos instalados
1007
                while (instalados.size() != pluginsConfig.size()) {
1008
                        boolean circle = true;
1009

    
1010
                        //Hacemos una pasada por todos los plugins
1011
                        Iterator i = pluginsConfig.keySet().iterator();
1012

    
1013
                        while (i.hasNext()) {
1014
                                String pluginName = (String) i.next();
1015
                                PluginConfig config = (PluginConfig) pluginsConfig.get(pluginName);
1016

    
1017
                                if (instalados.contains(pluginName)) {
1018
                                        continue;
1019
                                }
1020

    
1021
                                //Se obtienen las dependencias y sus class loaders
1022
                                boolean ready = true;
1023
                                Depends[] dependencies = config.getDepends();
1024
                                PluginClassLoader[] loaders = new PluginClassLoader[dependencies.length];
1025

    
1026
                                for (int j = 0; j < dependencies.length; j++) {
1027
                                        if (pluginsConfig.get(dependencies[j].getPluginName()) == null) {
1028
                                                logger.error(Messages.getString(
1029
                                                                "Launcher.Dependencia_no_resuelta_en_plugin") +
1030
                                                        pluginName + ": " +
1031
                                                        dependencies[j].getPluginName());
1032

    
1033
                                                continue;
1034
                                        }
1035

    
1036
                                        if (!instalados.contains(dependencies[j].getPluginName())) {
1037
                                                ready = false;
1038
                                        } else {
1039
                                                loaders[j] = ((PluginServices) pluginsServices.get(dependencies[j].getPluginName())).getClassLoader();
1040
                                        }
1041
                                }
1042

    
1043
                                //Si no est?n sus dependencias satisfechas se aborta la instalaci?n
1044
                                if (!ready) {
1045
                                        continue;
1046
                                }
1047

    
1048
                                //Se genera el class loader
1049
                                String jardir = config.getLibraries().getLibraryDir();
1050
                                File jarDir = new File(andamiConfig.getPluginsDirectory() +
1051
                                                File.separator + pluginName + File.separator + jardir);
1052
                                File[] jarFiles = jarDir.listFiles(new FileFilter() {
1053
                                                        public boolean accept(File pathname) {
1054
                                                                return (pathname.getName().toUpperCase()
1055
                                                                                                .endsWith(".JAR")) ||
1056
                                                                (pathname.getName().toUpperCase().endsWith(".ZIP"));
1057
                                                        }
1058
                                                });
1059

    
1060
                                URL[] urls = new URL[jarFiles.length];
1061

    
1062
                                for (int j = 0; j < jarFiles.length; j++) {
1063
                                        try {
1064
                                                urls[j] = new URL("file:" + jarFiles[j]);
1065
                                        } catch (MalformedURLException e) {
1066
                                                logger.error(Messages.getString(
1067
                                                                "Launcher.No_se_puede_acceder_a") +
1068
                                                        jarFiles[j]);
1069
                                        }
1070
                                }
1071

    
1072
                                PluginClassLoader loader;
1073

    
1074
                                try {
1075
                                        loader = new PluginClassLoader(urls,
1076
                                                        andamiConfig.getPluginsDirectory() +
1077
                                                        File.separator + pluginName,
1078
                                                        Launcher.class.getClassLoader(), loaders);
1079

    
1080
                                        PluginServices ps = new PluginServices(loader);
1081

    
1082
                                        pluginsServices.put(ps.getPluginName(), ps);
1083

    
1084
                                        instalados.add(pluginName);
1085
                    // FJP: Los metemos ordenados para luego no cargar uno que necesita de otro antes de tiempo. Esto lo usaremos al
1086
                    // inicializar los plugins
1087
                    pluginsOrdered.add(pluginName);
1088

    
1089
                                        circle = false;
1090
                                } catch (IOException e) {
1091
                                        logger.error(Messages.getString(
1092
                                                        "Launcher.Error_con_las_librerias_del_plugin"), e);
1093
                                        pluginsConfig.remove(pluginName);
1094
                                        i = pluginsConfig.keySet().iterator();
1095
                                }
1096
                        }
1097

    
1098
                        if (circle) {
1099
                                logger.error(Messages.getString(
1100
                                                "Launcher.Hay_dependencias_circulares"));
1101

    
1102
                                break;
1103
                        }
1104
                }
1105

    
1106
                //Se eliminan los plugins que no fueron instalados
1107
                Iterator i = pluginsConfig.keySet().iterator();
1108

    
1109
                while (i.hasNext()) {
1110
                        String pluginName = (String) i.next();
1111
                        PluginConfig config = (PluginConfig) pluginsConfig.get(pluginName);
1112
                        PluginServices ps = (PluginServices) pluginsServices.get(pluginName);
1113

    
1114
                        if (ps == null) {
1115
                                pluginsConfig.remove(pluginName);
1116
                                i = pluginsConfig.keySet().iterator();
1117
                        }
1118
                }
1119
        }
1120

    
1121
        /**
1122
         * DOCUMENT ME!
1123
         */
1124
        private static void pluginsMessages() {
1125
                /* add gvsig translations first. This should be done using a generic "appPlugin" variable, instead
1126
                 * of using "com.iver.cit.gvsig" directly, but I'll do it when we use the new appgvSIG launcher.
1127
                 * I keep this workaround for the moment.
1128
                 */
1129
                PluginConfig config = (PluginConfig) pluginsConfig.get("com.iver.cit.gvsig");
1130
                PluginServices ps = (PluginServices) pluginsServices.get("com.iver.cit.gvsig");
1131
                if (config.getResourceBundle() != null) {
1132
                        org.gvsig.i18n.Messages.addResourceFamily(config.getResourceBundle().getName(), ps.getClassLoader(), "com.iver.cit.gvsig");
1133
                }
1134

    
1135
                //Iteramos por todos los plugins
1136
                Iterator i = pluginsConfig.keySet().iterator();
1137

    
1138
                while (i.hasNext()) {
1139
                        String pluginName = (String) i.next();
1140
                        if (!pluginName.equals("com.iver.cit.gvsig")) { // we've already loaded com.iver.cit.gvsig
1141
                                config = (PluginConfig) pluginsConfig.get(pluginName);
1142
                                ps = (PluginServices) pluginsServices.get(pluginName);
1143

    
1144
                                if (config.getResourceBundle() != null && !config.getResourceBundle().getName().equals("")) {
1145
                                        // add the locale files associated with the plugin
1146
                                        org.gvsig.i18n.Messages.addResourceFamily(config.getResourceBundle().getName(), ps.getClassLoader(), pluginName);
1147
                                }
1148
                        }
1149
                }
1150
        }
1151

    
1152
        /**
1153
         * DOCUMENT ME!
1154
         *
1155
         * @param name DOCUMENT ME!
1156
         *
1157
         * @return DOCUMENT ME!
1158
         */
1159
        static PluginServices getPluginServices(String name) {
1160
                return (PluginServices) pluginsServices.get(name);
1161
        }
1162

    
1163
        /**
1164
         * DOCUMENT ME!
1165
         *
1166
         * @return DOCUMENT ME!
1167
         */
1168
        static String getPluginsDir() {
1169
                return andamiConfig.getPluginsDirectory();
1170
        }
1171

    
1172
        /**
1173
         * DOCUMENT ME!
1174
         *
1175
         * @param s DOCUMENT ME!
1176
         */
1177
        static void setPluginsDir(String s) {
1178
                andamiConfig.setPluginsDirectory(s);
1179
        }
1180

    
1181
        /**
1182
         * DOCUMENT ME!
1183
         *
1184
         * @return DOCUMENT ME!
1185
         */
1186
        static MDIFrame getMDIFrame() {
1187
                return frame;
1188
        }
1189

    
1190
        /**
1191
         * DOCUMENT ME!
1192
         *
1193
         * @param pluginsDirectory
1194
         */
1195
        private static void loadPlugins(String pluginsDirectory) {
1196
                File pDir = new File(pluginsDirectory);
1197

    
1198
                if (!pDir.exists()) {
1199
                        return;
1200
                }
1201

    
1202
                File[] pluginDirs = pDir.listFiles();
1203

    
1204
                for (int i = 0; i < pluginDirs.length; i++) {
1205
                        if (pluginDirs[i].isDirectory()) {
1206
                                File configXml = new File(pluginDirs[i].getAbsolutePath() +
1207
                                                File.separator + "config.xml");
1208

    
1209
                                try {
1210
                                        FileInputStream is = new FileInputStream(configXml);
1211
                                        Reader xml = com.iver.utiles.xml.XMLEncodingUtils.getReader(is);
1212
                                        if (xml==null) {
1213
                                                // the encoding was not correctly detected, use system default
1214
                                                xml = new FileReader(configXml);
1215
                                        }
1216
                                        else {
1217
                                                // use a buffered reader to improve performance
1218
                                                xml = new BufferedReader(xml);
1219
                                        }
1220
                                        PluginConfig pConfig = (PluginConfig) PluginConfig.unmarshal(xml);
1221
                                        pluginsConfig.put(pluginDirs[i].getName(), pConfig);
1222
                                } catch (FileNotFoundException e) {
1223
                                        logger.info(Messages.getString(
1224
                                                        "Launcher.Ignorando_el_directorio") +
1225
                                                pluginDirs[i].getAbsolutePath() +
1226
                                                Messages.getString("Launcher.config_no_encontrado"));
1227
                                } catch (MarshalException e) {
1228
                                        logger.info(Messages.getString(
1229
                                                        "Launcher.Ignorando_el_directorio") +
1230
                                                pluginDirs[i].getAbsolutePath() +
1231
                                                Messages.getString("Launcher.config_mal_formado"), e);
1232
                                } catch (ValidationException e) {
1233
                                        logger.info(Messages.getString(
1234
                                                        "Launcher.Ignorando_el_directorio") +
1235
                                                pluginDirs[i].getAbsolutePath() +
1236
                                                Messages.getString("Launcher.config_mal_formado"), e);
1237
                                }
1238
                        }
1239
                }
1240
        }
1241

    
1242
        /**
1243
         * DOCUMENT ME!
1244
         *
1245
         * @param language
1246
         * @param country
1247
         * @param variant
1248
         *
1249
         * @return DOCUMENT ME!
1250
         */
1251
        private static Locale getLocale(String language, String country,
1252
                String variant) {
1253
                if (variant != null) {
1254
                        return new Locale(language, country, variant);
1255
                } else if (country != null) {
1256
                        return new Locale(language, country);
1257
                } else if (language != null) {
1258
                        return new Locale(language);
1259
                } else {
1260
                        return new Locale("es");
1261
                }
1262
        }
1263

    
1264
        /**
1265
         * DOCUMENT ME!
1266
         *
1267
         * @param file DOCUMENT ME!
1268
         *
1269
         * @throws IOException DOCUMENT ME!
1270
         * @throws MarshalException DOCUMENT ME!
1271
         * @throws ValidationException DOCUMENT ME!
1272
         */
1273
        private static void andamiConfigToXML(String file)
1274
                throws IOException, MarshalException, ValidationException {
1275
                File xml = new File(file);
1276
                File parent = xml.getParentFile();
1277
                parent.mkdirs();
1278

    
1279
                FileWriter writer = new FileWriter(xml);
1280
                andamiConfig.marshal(writer);
1281
        }
1282

    
1283
        /**
1284
         * DOCUMENT ME!
1285
         *
1286
         * @param file DOCUMENT ME!
1287
         *
1288
         * @throws ConfigurationException DOCUMENT ME!
1289
         */
1290
        private static void andamiConfigFromXML(String file)
1291
                throws ConfigurationException {
1292
                File xml = new File(file);
1293

    
1294
                //Si no existe se ponen los valores por defecto
1295
                if (!xml.exists()) {
1296
                        andamiConfig = new AndamiConfig();
1297

    
1298
                        Andami andami = new Andami();
1299
                        andami.setUpdate(true);
1300
                        andamiConfig.setAndami(andami);
1301
                        andamiConfig.setLocaleCountry(Locale.getDefault().getCountry());
1302
                        andamiConfig.setLocaleLanguage(Locale.getDefault().getLanguage());
1303
                        andamiConfig.setLocaleVariant(Locale.getDefault().getVariant());
1304

    
1305
                        if (System.getProperty("javawebstart.version") != null) // Es java web start)
1306
                         {
1307
                                andamiConfig.setPluginsDirectory(new File(appHomeDir
1308
                                                + "extensiones").getAbsolutePath());
1309
                        } else {
1310
                                andamiConfig.setPluginsDirectory(new File(appName +
1311
                                                File.separator + "extensiones").getAbsolutePath());
1312
                        }
1313

    
1314
                        andamiConfig.setPlugin(new Plugin[0]);
1315
                } else {
1316
                        //Se lee la configuraci?n
1317
                        FileReader reader;
1318

    
1319
                        try {
1320
                                reader = new FileReader(xml);
1321
                                andamiConfig = (AndamiConfig) AndamiConfig.unmarshal(reader);
1322
                        } catch (FileNotFoundException e) {
1323
                                throw new ConfigurationException(e);
1324
                        } catch (MarshalException e) {
1325
                                throw new ConfigurationException(e);
1326
                        } catch (ValidationException e) {
1327
                                throw new ConfigurationException(e);
1328
                        }
1329
                }
1330
        }
1331

    
1332
        /**
1333
         * DOCUMENT ME!
1334
         *
1335
         * @return DOCUMENT ME!
1336
         *
1337
         * @throws ConfigurationException DOCUMENT ME!
1338
         */
1339
        private static XMLEntity persistenceFromXML() throws ConfigurationException {
1340
                File xml = new File(pluginsPersistencePath);
1341

    
1342
                if (xml.exists()) {
1343
                        FileReader reader;
1344

    
1345
                        try {
1346
                                reader = new FileReader(xml);
1347

    
1348
                                XmlTag tag = (XmlTag) XmlTag.unmarshal(reader);
1349

    
1350
                                return new XMLEntity(tag);
1351
                        } catch (FileNotFoundException e) {
1352
                                throw new ConfigurationException(e);
1353
                        } catch (MarshalException e) {
1354
                                throw new ConfigurationException(e);
1355
                        } catch (ValidationException e) {
1356
                                throw new ConfigurationException(e);
1357
                        }
1358
                } else {
1359
                        return new XMLEntity();
1360
                }
1361
        }
1362

    
1363
        /**
1364
         * DOCUMENT ME!
1365
         *
1366
         * @param entity DOCUMENT ME!
1367
         *
1368
         * @throws ConfigurationException DOCUMENT ME!
1369
         */
1370
        private static void persistenceToXML(XMLEntity entity)
1371
                throws ConfigurationException {
1372
                File xml = new File(pluginsPersistencePath);
1373

    
1374
                FileWriter writer;
1375

    
1376
                try {
1377
                        writer = new FileWriter(xml);
1378
                        entity.getXmlTag().marshal(writer);
1379
                } catch (FileNotFoundException e) {
1380
                        throw new ConfigurationException(e);
1381
                } catch (MarshalException e) {
1382
                        throw new ConfigurationException(e);
1383
                } catch (ValidationException e) {
1384
                        throw new ConfigurationException(e);
1385
                } catch (IOException e) {
1386
                        throw new ConfigurationException(e);
1387
                }
1388
        }
1389

    
1390
        /**
1391
         * Devuelve un array con los directorios de los plugins
1392
         *
1393
         * @param dirExt Directorio de las extensiones a partir del cual cuelgan
1394
         *                   todos los directorios de los plugins
1395
         *
1396
         * @return ArrayList con los directorios
1397
         */
1398
        private String[] getLocales(File dirExt) {
1399
                ArrayList types = new ArrayList();
1400
                File[] files = dirExt.listFiles();
1401

    
1402
                for (int i = 0; i < files.length; i++) {
1403
                        if (files[i].isDirectory()) {
1404
                                File[] textFile = files[i].listFiles(new FilenameFilter() {
1405
                                                        public boolean accept(File dir, String fileName) {
1406
                                                                return fileName.toLowerCase().startsWith("text_"); //$NON-NLS-1$
1407
                                                        }
1408
                                                });
1409

    
1410
                                for (int j = 0; j < textFile.length; j++) {
1411
                                        String s = (textFile[j]).getName().replaceAll("text_", "");
1412
                                        s = s.replaceAll(".properties", "");
1413
                                        s = s.trim();
1414

    
1415
                                        if (!types.contains(s)) {
1416
                                                types.add(s);
1417
                                        }
1418
                                }
1419
                        }
1420
                }
1421

    
1422
                return (String[]) types.toArray(new String[0]);
1423
        }
1424

    
1425
        /**
1426
         * DOCUMENT ME!
1427
         *
1428
         * @return Returns the frame.
1429
         */
1430
        static MDIFrame getFrame() {
1431
                return frame;
1432
        }
1433

    
1434
        /**
1435
         * Secuencia de cerrado de Andami
1436
         */
1437
        public static void closeApplication() {
1438
                //Configuraci?n de Andami
1439
                try {
1440
                        andamiConfigToXML(andamiConfigPath);
1441
                } catch (MarshalException e) {
1442
                        logger.error(Messages.getString(
1443
                                        "Launcher.No_se_pudo_guardar_la_configuracion_de_andami"), e);
1444
                } catch (ValidationException e) {
1445
                        logger.error(Messages.getString(
1446
                                        "Launcher.No_se_pudo_guardar_la_configuracion_de_andami"), e);
1447
                } catch (IOException e) {
1448
                        logger.error(Messages.getString(
1449
                                        "Launcher.No_se_pudo_guardar_la_configuracion_de_andami"), e);
1450
                }
1451

    
1452
                //Persistencia de los plugins
1453
                savePluginPersistence();
1454

    
1455
                //Finalize all the extensions
1456
                finalizeExtensions();
1457

    
1458
                // Clean any temp data created
1459
                Utilities.cleanUpTempFiles();
1460

    
1461
                //Para la depuraci?n de memory leaks
1462
                System.gc();
1463

    
1464
        System.exit(0);
1465
        }
1466

    
1467
        /**
1468
         * Exectutes the terminate method for all the extensions, in the reverse
1469
         * order they were initialized
1470
         *
1471
         */
1472
        private static void finalizeExtensions() {
1473
                for (int i=extensions.size()-1; i>=0; i--) {
1474
                        com.iver.andami.plugins.IExtension extensionInstance=(com.iver.andami.plugins.IExtension)extensions.get(i);
1475
                        extensionInstance.terminate();
1476
                }
1477
        }
1478

    
1479

    
1480
        /**
1481
         * DOCUMENT ME!
1482
         *
1483
         * @return DOCUMENT ME!
1484
         */
1485
        static HashMap getClassesExtensions() {
1486
                return classesExtensions;
1487
        }
1488

    
1489
        /**
1490
         * DOCUMENT ME!
1491
         *
1492
         * @param extDir DOCUMENT ME!
1493
         */
1494
        private static void downloadExtensions(String extDir) {
1495
                java.util.Date fechaActual = null;
1496

    
1497
                try {
1498
                        if (System.getProperty("javawebstart.version") != null) {
1499
                                //Obtenemos la URL del servidor
1500
                                BasicService bs = (BasicService) ServiceManager.lookup(
1501
                                                "javax.jnlp.BasicService");
1502
                                URL baseURL = bs.getCodeBase();
1503

    
1504
                                //Se descargan las extensiones
1505
                                MultiSplashWindow.process(5,
1506
                                        "Descargando las extensiones desde " + baseURL + " a " +
1507
                                        extDir);
1508

    
1509
                                URL url = new URL(baseURL + "extensiones.zip");
1510
                                URLConnection connection = url.openConnection();
1511

    
1512
                                System.out.println(url.toExternalForm() + ":");
1513
                                System.out.println("  Content Type: " +
1514
                                        connection.getContentType());
1515
                                System.out.println("  Content Length: " +
1516
                                        connection.getContentLength());
1517
                                System.out.println("  Last Modified: " +
1518
                                        new Date(connection.getLastModified()));
1519
                                System.out.println("  Expiration: " +
1520
                                        connection.getExpiration());
1521
                                System.out.println("  Content Encoding: " +
1522
                                        connection.getContentEncoding());
1523

    
1524
                                // Guardamos la fecha del fichero de extensiones que nos hemos bajado, y
1525
                                // comprobamos el ?ltimo que se ha bajado. Si no son
1526
                                // iguales, nos bajamos el nuevo. Si son iguales, no
1527
                                // nos bajamos nada.
1528
                                Long miliSecondsInWeb = new Long(connection.getLastModified());
1529

    
1530
                                // PluginServices ps = PluginServices.getPluginServices("com.iver.core");
1531
                                // if (ps.getPersistentXML().getStringProperty("timestamp") != null)
1532
                                File destDir = new File(extDir);
1533

    
1534
                                if (!destDir.exists()) {
1535
                                        // Creamos gvSIG
1536
                                        destDir.getParentFile().mkdir();
1537

    
1538
                                        if (!destDir.mkdir()) {
1539
                                                System.err.println("Imposible crear el directorio " +
1540
                                                        destDir.getAbsolutePath());
1541
                                        }
1542
                                }
1543

    
1544
                                File timeFile = new File(destDir.getParent() + File.separator +
1545
                                                "timeStamp.properties");
1546

    
1547
                                if (!timeFile.exists()) {
1548
                                        timeFile.createNewFile();
1549
                                }
1550

    
1551
                                FileInputStream inAux = new FileInputStream(timeFile);
1552
                                Properties prop = new Properties();
1553
                                prop.load(inAux);
1554
                                inAux.close();
1555

    
1556
                                if (prop.getProperty("timestamp") != null) {
1557
                                        Long lastMiliSeconds = (Long) new Long(prop.getProperty(
1558
                                                                "timestamp"));
1559

    
1560
                                        if (lastMiliSeconds.longValue() == miliSecondsInWeb.longValue()) {
1561
                                                System.out.println("No hay nueva actualizaci?n");
1562
                        logger.debug("No hay nueva actualizaci?n -> Return");
1563
                        logger.debug("timeStampWeb= " + miliSecondsInWeb);
1564
                        logger.debug("timeStampLocal= " + lastMiliSeconds);
1565

    
1566
                                                return;
1567
                                        }
1568

    
1569
                                        System.out.println("timeStampWeb= " + miliSecondsInWeb);
1570
                                        System.out.println("timeStampLocal= " + lastMiliSeconds);
1571
                                } else {
1572
                                        System.out.println("El timeStamp no est? escrito en " +
1573
                                                timeFile.getAbsolutePath());
1574
                                }
1575

    
1576
                                InputStream stream = url.openStream();
1577
                File temp = File.createTempFile("gvsig", ".zip");
1578

    
1579
                logger.debug(temp.getAbsolutePath());
1580

    
1581
                temp.deleteOnExit();
1582
                FileOutputStream file = new FileOutputStream(temp);
1583

    
1584
                byte[] lt_read = new byte[1];
1585

    
1586
                while (stream.read(lt_read) > 0)
1587
                  file.write(lt_read);
1588

    
1589
                                stream.close();
1590
                stream = null;
1591
                file.close();
1592
                file = null;
1593

    
1594
                System.gc();
1595

    
1596
                logger.debug("Ha creado el fichero ZIP");
1597
                                //Se extrae el zip
1598
                                MultiSplashWindow.process(5, "Extensiones descargadas.");
1599

    
1600
                                System.out.println("Extrayendo a " + destDir.getAbsolutePath());
1601

    
1602
                                Date fechaDir = new Date(destDir.lastModified());
1603
                                System.out.println("Fecha del directorio " + extDir + " = " +
1604
                                        fechaDir.toString());
1605
                                Utilities.extractTo(temp, new File(extDir), splashWindow);
1606

    
1607
                                // Si todo ha ido bien, guardamos el timestamp.
1608
                                ///  App.instance.getPc().addProperties("timestamp", miliSecondsInWeb);
1609
                                // XMLEntity xml=ps.getPersistentXML();
1610
                                fechaActual = new java.util.Date();
1611

    
1612
                                FileOutputStream outAux = new FileOutputStream(timeFile);
1613
                                prop.setProperty("timestamp", miliSecondsInWeb.toString());
1614
                                prop.store(outAux, "last download");
1615
                                outAux.close();
1616
                                System.out.println("Fecha actual guardada: " +
1617
                                        fechaActual.toGMTString());
1618

    
1619
                                /* xml.putProperty("timestamp",fechaActual.toGMTString());
1620
                                   ps.setPresistentXML(xml); */
1621
                        }
1622
                } catch (IOException e) {
1623
                        NotificationManager.addError("", e);
1624
                } catch (UnavailableServiceException e) {
1625
                        NotificationManager.addError("", e);
1626
                } catch (SecurityException e) {
1627
                        System.err.println("No se puede escribir el timeStamp " +
1628
                                fechaActual.toGMTString());
1629
                        NotificationManager.addError("", e);
1630
                }
1631
        }
1632

    
1633
        /**
1634
         * DOCUMENT ME!
1635
         *
1636
         * @return DOCUMENT ME!
1637
         */
1638
        private static Extensions[] getExtensions() {
1639
                ArrayList array = new ArrayList();
1640
                Iterator iter = pluginsConfig.values().iterator();
1641

    
1642
                while (iter.hasNext()) {
1643
                        array.add(((PluginConfig) iter.next()).getExtensions());
1644
                }
1645

    
1646
                return (Extensions[]) array.toArray(new Extensions[0]);
1647
        }
1648

    
1649
        /**
1650
         * DOCUMENT ME!
1651
         *
1652
         * @return DOCUMENT ME!
1653
         */
1654
        public static HashMap getPluginConfig() {
1655
                return pluginsConfig;
1656
        }
1657

    
1658
        /**
1659
         * DOCUMENT ME!
1660
         *
1661
         * @param s DOCUMENT ME!
1662
         *
1663
         * @return DOCUMENT ME!
1664
         */
1665
        public static Extension getExtension(String s) {
1666
                Extensions[] exts = getExtensions();
1667

    
1668
                for (int i = 0; i < exts.length; i++) {
1669
                        for (int j = 0; j < exts[i].getExtensionCount(); j++) {
1670
                                if (exts[i].getExtension(j).getClassName().equals(s)) {
1671
                                        return exts[i].getExtension(j);
1672
                                }
1673
                        }
1674
                }
1675

    
1676
                return null;
1677
        }
1678

    
1679
        /**
1680
         * DOCUMENT ME!
1681
         *
1682
         * @return DOCUMENT ME!
1683
         */
1684
        public static AndamiConfig getAndamiConfig() {
1685
                return andamiConfig;
1686
        }
1687

    
1688
        /**
1689
         * DOCUMENT ME!
1690
         *
1691
         * @author $author$
1692
         * @version $Revision: 8970 $
1693
         */
1694
        private static class ExtensionComparator implements Comparator {
1695
                /**
1696
                 * DOCUMENT ME!
1697
                 *
1698
                 * @param o1 DOCUMENT ME!
1699
                 * @param o2 DOCUMENT ME!
1700
                 *
1701
                 * @return DOCUMENT ME!
1702
                 */
1703
                public int compare(Object o1, Object o2) {
1704
                        Extension e1 = (Extension) o1;
1705
                        Extension e2 = (Extension) o2;
1706

    
1707
                        if (!e1.hasPriority() && !e2.hasPriority()) {
1708
                                return -1;
1709
                        }
1710

    
1711
                        if (e1.hasPriority() && !e2.hasPriority()) {
1712
                                return Integer.MIN_VALUE;
1713
                        }
1714

    
1715
                        if (e2.hasPriority() && !e1.hasPriority()) {
1716
                                return Integer.MAX_VALUE;
1717
                        }
1718

    
1719
                        if (e1.getPriority() != e2.getPriority()){
1720
                                return e2.getPriority() - e1.getPriority();
1721
                        }else{
1722
                                return (e2.toString().compareTo(e1.toString()));
1723
                        }
1724
                }
1725
        }
1726

    
1727
        /**
1728
         * DOCUMENT ME!
1729
         */
1730
        private static class MenuComparator implements Comparator {
1731
                private static ExtensionComparator extComp = new ExtensionComparator();
1732

    
1733
                /**
1734
                 * DOCUMENT ME!
1735
                 *
1736
                 * @param o1 DOCUMENT ME!
1737
                 * @param o2 DOCUMENT ME!
1738
                 *
1739
                 * @return DOCUMENT ME!
1740
                 */
1741
                public int compare(Object o1, Object o2) {
1742
                        SortableMenu e1 = (SortableMenu) o1;
1743
                        SortableMenu e2 = (SortableMenu) o2;
1744

    
1745
                        if (!e1.menu.hasPosition() && !e2.menu.hasPosition()) {
1746
                                if (e1.extension instanceof SkinExtensionType) {
1747
                                        return 1;
1748
                                } else if (e2.extension instanceof SkinExtensionType) {
1749
                                        return -1;
1750
                                } else {
1751
                                        return extComp.compare(e1.extension, e2.extension);
1752
                                }
1753
                        }
1754

    
1755
                        if (e1.menu.hasPosition() && !e2.menu.hasPosition()) {
1756
                                return Integer.MIN_VALUE;
1757
                        }
1758

    
1759
                        if (e2.menu.hasPosition() && !e1.menu.hasPosition()) {
1760
                                return Integer.MAX_VALUE;
1761
                        }
1762
                        if (e1.menu.getPosition() != e2.menu.getPosition()){
1763
                                //we don't return 0 unless both objects are the same, otherwise the objects get overwritten in the treemap
1764
                                return e1.menu.getPosition() - e2.menu.getPosition();
1765
                        }else{
1766
                                return (e1.toString().compareTo(e2.toString()));
1767
                        }
1768
                }
1769
        }
1770

    
1771
        /**
1772
         * DOCUMENT ME!
1773
         *
1774
         * @author $author$
1775
         * @version $Revision: 8970 $
1776
         */
1777
        private static class SortableMenu {
1778
                public PluginClassLoader loader;
1779
                public Menu menu;
1780
                public SkinExtensionType extension;
1781

    
1782
                /**
1783
                 * DOCUMENT ME!
1784
                 *
1785
                 * @param loader DOCUMENT ME!
1786
                 * @param skinExt
1787
                 * @param menu2
1788
                 */
1789
                public SortableMenu(PluginClassLoader loader,
1790
                        SkinExtensionType skinExt, Menu menu2) {
1791
                        extension = skinExt;
1792
                        menu = menu2;
1793
                        this.loader = loader;
1794
                }
1795
        }
1796
        /**
1797
         * DOCUMENT ME!
1798
         */
1799
        private static class SortableTool {
1800
                public PluginClassLoader loader;
1801
                public ToolBar toolbar;
1802
                public ActionTool actiontool;
1803
                public SelectableTool selectabletool;
1804
                public SkinExtensionType extension;
1805

    
1806
                /**
1807
                 * DOCUMENT ME!
1808
                 *
1809
                 * @param loader DOCUMENT ME!
1810
                 * @param skinExt
1811
                 * @param menu2
1812
                 */
1813
                public SortableTool(PluginClassLoader loader,
1814
                        SkinExtensionType skinExt, ToolBar toolbar2,ActionTool actiontool2) {
1815
                        extension = skinExt;
1816
                        toolbar = toolbar2;
1817
                        actiontool=actiontool2;
1818
                        this.loader = loader;
1819
                }
1820
                public SortableTool(PluginClassLoader loader,
1821
                                SkinExtensionType skinExt, ToolBar toolbar2,SelectableTool selectabletool2) {
1822
                        extension = skinExt;
1823
                        toolbar = toolbar2;
1824
                        selectabletool=selectabletool2;
1825
                        this.loader = loader;
1826
                }
1827
        }
1828
        /**
1829
         * DOCUMENT ME!
1830
         */
1831
        private static class ToolBarComparator implements Comparator {
1832
                private static ExtensionComparator extComp = new ExtensionComparator();
1833

    
1834
                /**
1835
                 * DOCUMENT ME!
1836
                 *
1837
                 * @param o1 DOCUMENT ME!
1838
                 * @param o2 DOCUMENT ME!
1839
                 *
1840
                 * @return DOCUMENT ME!
1841
                 */
1842
                public int compare(Object o1, Object o2) {
1843
                        SortableTool e1 = (SortableTool) o1;
1844
                        SortableTool e2 = (SortableTool) o2;
1845

    
1846
                        // if the toolbars have the same name, they are considered to be
1847
                        // the same toolbar, so we don't need to do further comparing
1848
                        if (e1.toolbar.getName().equals(e2.toolbar.getName()))
1849
                                return 0;
1850

    
1851
                        if (!e1.toolbar.hasPosition() && !e2.toolbar.hasPosition()) {
1852
                                if (e1.extension instanceof SkinExtensionType) {
1853
                                        return 1;
1854
                                } else if (e2.extension instanceof SkinExtensionType) {
1855
                                        return -1;
1856
                                } else {
1857
                                        return extComp.compare(e1.extension, e2.extension);
1858
                                }
1859
                        }
1860

    
1861
                        if (e1.toolbar.hasPosition() && !e2.toolbar.hasPosition()) {
1862
                                return Integer.MIN_VALUE;
1863
                        }
1864

    
1865
                        if (e2.toolbar.hasPosition() && !e1.toolbar.hasPosition()) {
1866
                                return Integer.MAX_VALUE;
1867
                        }
1868
                        if (e1.toolbar.getPosition() != e2.toolbar.getPosition())
1869
                                return e1.toolbar.getPosition() - e2.toolbar.getPosition();
1870

    
1871
                        if (e1.toolbar.getActionTool().equals(e2.toolbar.getActionTool()) && e1.toolbar.getSelectableTool().equals(e2.toolbar.getSelectableTool())){
1872
                                return 0;
1873
                        }
1874
                        return (e1.toolbar.toString().compareTo(e2.toolbar.toString()));
1875
                }
1876
        }
1877

    
1878
        /**
1879
         * <p>This class is used to compare tools (selectabletool and actiontool),
1880
         * using the "position"
1881
         * attribute.</p>
1882
         * <p>The ordering criteria are:</p>
1883
         * <ul><li>If the tools are placed in different toolbars, they use the toolbars'
1884
         * order.
1885
         * (using the ToolBarComparator).</li>
1886
         * <li></li>
1887
         * <li>If any of the tools has not 'position' attribute, the tool which
1888
         * <strong>has</strong> the attribute will be placed first.</li>
1889
         * <li>If both tools have the same position (or they don't have a
1890
         * 'position' attribute), the priority of the extensions where the tool is defined.</li></ul>
1891
         *
1892
         * @author cesar
1893
         * @version $Revision: 8970 $
1894
         */
1895
        private static class ToolComparator implements Comparator {
1896
                private static ToolBarComparator toolBarComp = new ToolBarComparator();
1897
                /**
1898
                 * DOCUMENT ME!
1899
                 *
1900
                 * @param o1 DOCUMENT ME!
1901
                 * @param o2 DOCUMENT ME!
1902
                 *
1903
                 * @return DOCUMENT ME!
1904
                 */
1905
                public int compare(Object o1, Object o2) {
1906
                        // compare the toolbars which contain the tools
1907
                        int result = toolBarComp.compare(o1, o2);
1908
                        if (result != 0) { // if the toolbars are different, use their order
1909
                                return result;
1910
                        }
1911
                        // otherwise, compare the tools
1912
                        SortableTool e1 = (SortableTool) o1;
1913
                        SortableTool e2 = (SortableTool) o2;
1914
                        int e1Position=-1, e2Position=-1;
1915

    
1916
                        if (e1.actiontool!=null) {
1917
                                if (e1.actiontool.hasPosition())
1918
                                        e1Position = e1.actiontool.getPosition();
1919
                        }
1920
                        else if (e1.selectabletool!=null) {
1921
                                if (e1.selectabletool.hasPosition())
1922
                                        e1Position = e1.selectabletool.getPosition();
1923
                        }
1924

    
1925
                        if (e2.actiontool!=null) {
1926
                                if (e2.actiontool.hasPosition())
1927
                                        e2Position = e2.actiontool.getPosition();
1928
                        }
1929
                        else if (e2.selectabletool!=null){
1930
                                if (e2.selectabletool.hasPosition())
1931
                                        e2Position = e2.selectabletool.getPosition();
1932
                        }
1933

    
1934
                        if (e1Position==-1 && e2Position!=-1) {
1935
                                return 1;
1936
                        }
1937
                        if (e1Position!=-1 && e2Position==-1) {
1938
                                return -1;
1939
                        }
1940
                        if (e1Position!=-1 && e2Position!=-1) {
1941
                                result = e1Position - e2Position;
1942
                                // we don't return 0 unless both objects are the same, otherwise the objects get overwritten in the treemap
1943
                                if (result!=0) return result;
1944
                        }
1945
                        return e1.toString().compareTo(e2.toString());
1946
                }
1947
        }
1948

    
1949

    
1950
        /**
1951
         * validates the user before starting gvsig
1952
         *
1953
         */
1954
        private static void validate(){
1955

    
1956
                IAuthentication session =  null;
1957
                try {
1958
                        session = (IAuthentication)Class.forName("com.iver.andami.authentication.Session").newInstance();
1959

    
1960
                } catch (ClassNotFoundException e) {
1961
                        // TODO Auto-generated catch block
1962
                        //e.printStackTrace();
1963
                        return;
1964
                } catch (InstantiationException e) {
1965
                        // TODO Auto-generated catch block
1966
                        //e.printStackTrace();
1967
                        return;
1968
                } catch (IllegalAccessException e) {
1969
                        // TODO Auto-generated catch block
1970
                        //e.printStackTrace();
1971
                        return;
1972
                }
1973

    
1974
                session.setPluginDirectory( andamiConfig.getPluginsDirectory() );
1975
                if (session.validationRequired()){
1976
                        if(session.Login()){
1977
                                System.out.println("You are logged in");
1978
                        }
1979
                        else{
1980
                                JOptionPane.showMessageDialog((Component)PluginServices.getMainFrame(),
1981
                                                 "You are not logged in");
1982
                                //System.exit(0);
1983
                        }
1984
                        PluginServices.setAuthentication(session);
1985
                }
1986
        }
1987

    
1988
        public static String getDefaultLookAndFeel() {
1989
                String osName = (String) System.getProperty("os.name");
1990

    
1991
            if (osName.substring(0,3).toLowerCase().equals("win"))
1992
                    return UIManager.getSystemLookAndFeelClassName();
1993
        else
1994
                return nonWinDefaultLookAndFeel;
1995
        }
1996

    
1997
        /**
1998
         * Gets the ISO 839 two-characters-long language code matching the
1999
         * provided language code (which may be an ISO 839-2/T
2000
         * three-characters-long code or an ISO 839-1 two-characters-long
2001
         * code).
2002
         *
2003
         * If the provided parameter is already two characters long, it
2004
         * returns the parameter without any modification.
2005
         *
2006
         * @param langCode A language code representing either
2007
         *  an ISO 839-2/T language code or an ISO 839-1 code.
2008
         * @return A two-characters-long code specifying
2009
         *  an ISO 839 language code.
2010
         */
2011
        private static String normalizeLanguageCode(String langCode) {
2012
                final String fileName = "iso_639.tab";
2013
                if (langCode.length()==2)
2014
                        return langCode;
2015
                else if (langCode.length()==3) {
2016
                        if (langCode.equals("va") || langCode.equals("val")) { // special case for Valencian
2017
                                return "ca";
2018
                        }
2019
                        URL isoCodes = Launcher.class.getClassLoader().getResource(fileName);
2020
                        if (isoCodes!=null) {
2021
                                try {
2022
                                        BufferedReader reader =
2023
                                                new BufferedReader(new InputStreamReader(isoCodes.openStream(), "ISO-8859-1"));
2024
                                                String line;
2025

    
2026
                                                while ((line = reader.readLine()) != null) {
2027
                                                        String[] language = line.split("\t");
2028
                                                        if (language[0].equals(langCode)) // first column is the three characters code
2029
                                                                return language[2]; // third column i the two characters code
2030
                                                }
2031
                                }
2032
                                catch (IOException ex) {
2033
                                        logger.error(Messages.getString("Error_reading_isocodes_file"), ex);
2034
                                        return "es";
2035
                                }
2036
                        }
2037
                        else {
2038
                                logger.error(Messages.getString("Error_reading_isocodes_file"));
2039
                                return "es";
2040
                        }
2041
                }
2042
                return "es";
2043
        }
2044

    
2045
        /**
2046
         * Configures the locales (languages and local resources) to be used
2047
         * by the application.
2048
         *
2049
         * First it tries to get the locale from the command line parameters,
2050
         * then the andami-config file is checked.
2051
         *
2052
         * The locale name is normalized to get a two characters language code
2053
         * as defined by ISO-639-1 (although ISO-639-2/T three characters codes
2054
         * are also accepted from the command line or the configuration file).
2055
         *
2056
         * Finally, the gvsig-i18n library and the default locales for Java and
2057
         * Swing are configured.
2058
         *
2059
         */
2060
        private static void configureLocales(String[] args) {
2061
                //                 Configurar el locale
2062
        String localeStr = null;
2063
        for (int i=2; i < args.length; i++)
2064
        {
2065
                int index = args[i].indexOf("language=");
2066
                if (index != -1)
2067
                        localeStr = args[i].substring(index+9);
2068
        }
2069
                if (localeStr == null)
2070
                {
2071
            localeStr = andamiConfig.getLocaleLanguage();
2072
                }
2073
                localeStr = normalizeLanguageCode(localeStr);
2074
                locale = getLocale(localeStr,
2075
                andamiConfig.getLocaleCountry(),
2076
                andamiConfig.getLocaleVariant());
2077
                Locale.setDefault(locale);
2078
                JComponent.setDefaultLocale(locale);
2079
        org.gvsig.i18n.Messages.addLocale(locale);
2080
                // add english and spanish as fallback languages
2081
                org.gvsig.i18n.Messages.addLocale(new Locale("en"));
2082
                org.gvsig.i18n.Messages.addLocale(new Locale("es"));
2083
        org.gvsig.i18n.Messages.addResourceFamily("com.iver.andami.text", "com.iver.andami.text");
2084

    
2085
        }
2086

    
2087
        /**
2088
         * Gets Home Directory location of the application.
2089
         * May be set from outside the aplication by means of
2090
         * -DgvSIG.home=C:/data/gvSIG, where gvSIG its the name
2091
         * of the application
2092
         * @return
2093
         */
2094
        public static String getAppHomeDir() {
2095
                return appHomeDir;
2096
        }
2097

    
2098
        /**
2099
         * Sets Home Directory location of the application.
2100
         * May be set from outside the aplication by means of
2101
         * -DgvSIG.home=C:/data/gvSIG, where gvSIG its the name
2102
         * of the application
2103
         * @param appHomeDir
2104
         */
2105
        public static void setAppHomeDir(String appHomeDir) {
2106
                Launcher.appHomeDir = appHomeDir;
2107
        }
2108
}