Statistics
| Revision:

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

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: 8921 $
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
                                        PluginServices.getMDIManager().setBackgroundImage(theme.getBackgroundImage().getImage());
618
                                        //frame.setBackgroundImage(theme.getBackgroundImage());
619
                                }
620
                        }
621
                }
622
        }
623

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
1032
                                                continue;
1033
                                        }
1034

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

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

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

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

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

    
1071
                                PluginClassLoader loader;
1072

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

    
1079
                                        PluginServices ps = new PluginServices(loader);
1080

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

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

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

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

    
1101
                                break;
1102
                        }
1103
                }
1104

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
1373
                FileWriter writer;
1374

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

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

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

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

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

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

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

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

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

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

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

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

    
1463
        System.exit(0);
1464
        }
1465

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

    
1478

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
1565
                                                return;
1566
                                        }
1567

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

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

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

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

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

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

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

    
1593
                System.gc();
1594

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

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

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

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

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

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

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

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

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

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

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

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

    
1675
                return null;
1676
        }
1677

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
1948

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

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

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

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

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

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

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

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

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

    
2084
        }
2085

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

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