Statistics
| Revision:

svn-gvsig-desktop / trunk / frameworks / _fwAndami / src / com / iver / andami / Launcher.java @ 9400

History | View | Annotate | Download (63.5 KB)

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

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

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

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

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

    
138

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

    
160
    private static ArrayList pluginsOrdered = new ArrayList();
161
    private static ArrayList extensions=new ArrayList();
162
    private static String appHomeDir = null;
163

    
164
        private static final class ProxyAuth extends Authenticator {
165
                private PasswordAuthentication auth;
166

    
167
                private ProxyAuth(String user, String pass) {
168
                        auth = new PasswordAuthentication(user, pass.toCharArray());
169
                }
170

    
171
                protected PasswordAuthentication getPasswordAuthentication() {
172
                        return auth;
173
                }
174
        }
175

    
176
        /**
177
         * DOCUMENT ME!
178
         *
179
         * @param args DOCUMENT ME!
180
         * @throws Exception
181
         *
182
         * @throws InterruptedException
183
         * @throws InvocationTargetException
184
         * @throws ConfigurationException
185
         * @throws MDIManagerLoadException
186
         * @throws IOException
187
         */
188
    public static void main(String[] args) throws Exception {
189
            try{
190

    
191
                    if (!validJVM()){
192
                            System.exit(-1);
193
                    }
194

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

    
199
                    //  Clean temporal files
200
                    Utilities.cleanUpTempFiles();
201

    
202
                    appName = args[0];
203

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

    
213
                    andamiConfigPath = appHomeDir + "andami-config.xml";
214
                    pluginsPersistencePath = appHomeDir +
215
                    "plugins-persistence.xml";
216

    
217
                    // Configurar el log4j
218
                    PropertyConfigurator.configure(Launcher.class.getClassLoader()
219
                                    .getResource("log4j.properties"));
220

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

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

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

    
242
                    configureLocales(args);
243

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

    
266
                    validate();
267

    
268
                    // Obtener la personalizaci?n de la aplicaci?n.
269
                        Theme theme=getTheme();
270

    
271
                        // Mostrar la ventana de inicio
272
                    Frame f=new Frame();
273
                    splashWindow=new MultiSplashWindow(f,theme);
274

    
275
                    // Ponemos los datos del proxy
276
                    configureProxy();
277

    
278
                    // TODO Buscar actualizaciones de los plugins
279
                    downloadExtensions(andamiConfig.getPluginsDirectory());
280

    
281
                    // Se leen los config.xml de los plugins -----++++
282
                    loadPlugins(andamiConfig.getPluginsDirectory());
283

    
284
                    // Se configura el classloader del plugin
285
                    pluginsClassLoaders();
286

    
287
                    // Se carga un Skin si alguno de los plugins trae informaci?n para ello
288
                    skinPlugin();
289

    
290
                    //Se configura la cola de eventos
291
                    EventQueue waitQueue = new AndamiEventQueue();
292
                    Toolkit.getDefaultToolkit().getSystemEventQueue().push(waitQueue);
293

    
294
                    // Se configura la mensajer?a del plugin
295
                    pluginsMessages();
296

    
297
                    // Se modifica el andami-config con los plugins nuevos
298
                    updateAndamiConfig();
299

    
300
                    // Se prepara el MainFrame para albergar las extensiones
301
                    JPopupMenu.setDefaultLightWeightPopupEnabled(false);
302
                    frame = new MDIFrame();
303

    
304
                    // Se configura el nombre e icono de la aplicaci?n
305
                    frameIcon(theme);
306

    
307
                    SwingUtilities.invokeAndWait(new Runnable() {
308
                            public void run() {
309
                                    frame.init();
310
                            }
311
                    });
312

    
313
                    // Se instalan los controles de las extensiones de los plugins
314
                    SwingUtilities.invokeAndWait(new Runnable() {
315
                            public void run() {
316
                                    installPluginsControls();
317
                                    installPluginsMenus();
318
                                    installPluginsLabels();
319
                            }
320
                    });
321

    
322
                    // Leer el fichero de persistencia
323
                    //  info de los plugins
324
                    //  bookmarks de los plugins
325
                    loadPluginsPersistence();
326

    
327
                    // Se instalan los controles del skin
328
                    // Se inicializan todas las extensiones de todos los plugins
329
                    SwingUtilities.invokeAndWait(new Runnable() {
330
                            public void run() {
331
                                    initializeExtensions();
332
                                    initializeExclusiveUIExtension();
333
                                    postInitializeExtensions();
334
                            }
335
                    });
336
                    frame.setClassesExtensions(classesExtensions);
337

    
338
                    // Se instalan los bookmarks de los plugins
339

    
340
                    //Se muestra el frame principal
341
                    frame.show();
342

    
343
                    // Definimos un KeyEventDispatcher global para que las extensiones
344
                    // puedan registrar sus "teclas r?pidas".
345
                    GlobalKeyEventDispatcher keyDispatcher = GlobalKeyEventDispatcher.getInstance();
346
                    KeyboardFocusManager.getCurrentKeyboardFocusManager().addKeyEventDispatcher(keyDispatcher);
347

    
348
                    SwingUtilities.invokeAndWait(new Runnable() {
349
                            public void run() {
350
                                    frame.enableControls();
351
                            }
352
                    });
353
                    splashWindow.close();
354
            }catch(Exception e){
355
                    logger.error("excepci?n al arrancar", e);
356
                    System.exit(-1);
357
            }
358

    
359
    }
360

    
361
    /**
362
     * Obtiene la personalizaci?n de los iconos, splash, fondo y el nombre de
363
     * la aplicaci?n.
364
     *
365
     * @return Theme
366
     */
367
    private static Theme getTheme() {
368
            Theme theme=new Theme();
369
            String name=PluginServices.getArgumentByName("andamiTheme");
370
                //File file=new File("theme/andami-theme.xml");
371
            File file;
372
            if (name==null){
373
                    file=new File("theme/andami-theme.xml");                    
374
            }else{
375
                    file=new File(name);        
376
            }
377
                        
378
            if (file.exists()) {
379
                        theme.readTheme(file);
380
                }
381
                return theme;
382
        }
383
        /**
384
     *Establece los datos que ten?amos guardados respecto de la configuraci?n
385
     *del proxy.
386
     */
387
        private static void configureProxy() {
388
                String host = prefs.get("firewall.http.host", "");
389
                String port = prefs.get("firewall.http.port", "");
390

    
391
                System.getProperties().put("http.proxyHost", host);
392
                System.getProperties().put("http.proxyPort", port);
393

    
394
                // Ponemos el usuario y clave del proxy, si existe
395
                String proxyUser = prefs.get("firewall.http.user",null);
396
                String proxyPassword = prefs.get("firewall.http.password", null);
397
                if (proxyUser != null )
398
                {
399
                        System.getProperties().put("http.proxyUserName", proxyUser);
400
                        System.getProperties().put("http.proxyPassword", proxyPassword);
401

    
402
                        Authenticator.setDefault(new ProxyAuth(proxyUser,
403
                                                        proxyPassword));
404
                } else {
405
                        Authenticator.setDefault(new ProxyAuth("", ""));
406
                }
407
        }
408

    
409
        /**
410
         * Recupera la geometr?a (tama?o, posici?n y estado) de la ventana principal de Andami.
411
         * TODO Pendiente de ver como se asigna un pluginServices para el launcher.
412
         * @author LWS
413
         */
414
        private static void restoreMDIStatus(XMLEntity xml) {
415
                //System.err.println("Launcher: restoreMDIStatus()");
416
                if (xml == null) xml = new XMLEntity();
417
                //  restore frame size
418
                Dimension sz = new Dimension(700,580);
419
                if (xml.contains("MDIFrameSize")) {
420
                        int [] wh = xml.getIntArrayProperty("MDIFrameSize");
421
                        sz = new Dimension(wh[0], wh[1]);
422
                }
423
                frame.setSize(sz);
424
                //  restore frame location
425
                Point pos = new Point(10,10);
426
                if (xml.contains("MDIFramePos")) {
427
                        int [] xy = xml.getIntArrayProperty("MDIFramePos");
428
                        pos = new Point(xy[0], xy[1]);
429
                }
430
                frame.setLocation(pos);
431

    
432
                //  restore frame status (Maximized, minimized, etc);
433
                int state = java.awt.Frame.MAXIMIZED_BOTH;
434
                if (xml.contains("MDIFrameState")) {
435
                        state = xml.getIntProperty("MDIFrameState");
436
                }
437
                frame.setExtendedState(state);
438
        }
439

    
440
        private static XMLEntity saveMDIStatus() {
441
                XMLEntity xml = new XMLEntity();
442
                // save frame size
443
                int [] wh = new int[2];
444
                wh[0] = frame.getWidth();
445
                wh[1] = frame.getHeight();
446
                xml.putProperty("MDIFrameSize", wh);
447
                // save frame location
448
                int [] xy = new int[2];
449
                xy[0] = frame.getX();
450
                xy[1] = frame.getY();
451
                xml.putProperty("MDIFramePos", xy);
452
                // save frame status
453
                xml.putProperty("MDIFrameState", frame.getExtendedState());
454
                return xml;
455
        }
456

    
457
        /**
458
     * @return
459
     */
460
    private static boolean validJVM() {
461
        char thirdCharacter = System.getProperty("java.version").charAt(2);
462
        if (thirdCharacter < '4'){
463
            return false;
464
            }else{
465
                return true;
466
            }
467
    }
468

    
469
    /**
470
         * DOCUMENT ME!
471
         *
472
         * @throws ConfigurationException
473
         */
474
        private static void loadPluginsPersistence() throws ConfigurationException {
475
                XMLEntity entity = persistenceFromXML();
476

    
477
                //System.err.println("loadPluginPersistence()");
478
                for (int i = 0; i < entity.getChildrenCount(); i++) {
479
                        XMLEntity plugin = entity.getChild(i);
480
                        String pName = plugin.getStringProperty(
481
                                        "com.iver.andami.pluginName");
482
                        //System.err.println("--> "+pName);
483
                        if (pluginsServices.get(pName)!= null){
484
                                ((PluginServices) pluginsServices.get(pName)).setPersistentXML(plugin);
485
                        } else {
486
                                if (pName.startsWith("Andami.Launcher"))
487
                                        restoreMDIStatus(plugin);
488
                        }
489
                }
490
        }
491

    
492
        /**
493
         * Salva la persistencia de los plugins.
494
         * @author LWS
495
         */
496
        private static void savePluginPersistence() {
497
                Iterator i = pluginsConfig.keySet().iterator();
498

    
499
                XMLEntity entity = new XMLEntity();
500

    
501
                while (i.hasNext()) {
502
                        String pName = (String) i.next();
503
                        PluginServices ps = (PluginServices) pluginsServices.get(pName);
504
                        XMLEntity ent = ps.getPersistentXML();
505

    
506
                        if (ent != null) {
507
                                ent.putProperty("com.iver.andami.pluginName", pName);
508
                                entity.addChild(ent);
509
                        }
510
                }
511
                XMLEntity ent = saveMDIStatus();
512
                if (ent != null) {
513
                        ent.putProperty("com.iver.andami.pluginName", "Andami.Launcher");
514
                        entity.addChild(ent);
515
                }
516
                try {
517
                        persistenceToXML(entity);
518
                } catch (ConfigurationException e1) {
519
                        logger.error(Messages.getString(
520
                                        "Launcher.Se_produjo_un_error_guardando_la_configuracion_de_los_plugins"),
521
                                e1);
522
                }
523
        }
524

    
525
        /**
526
         * DOCUMENT ME!
527
         */
528
        private static void installPluginsLabels() {
529
                Iterator i = pluginsConfig.keySet().iterator();
530

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

    
536
                        LabelSet[] ls = pc.getLabelSet();
537

    
538
                        for (int j = 0; j < ls.length; j++) {
539
                                PluginClassLoader loader = ps.getClassLoader();
540

    
541
                                try {
542
                                        Class clase = loader.loadClass(ls[j].getClassName());
543
                                        frame.setLabels(clase, ls[j].getLabel());
544
                                } catch (ClassNotFoundException e) {
545
                                        logger.error(Messages.getString("Launcher.labelset_class"),
546
                                                e);
547
                                }
548
                        }
549
                }
550
        }
551

    
552
        /**
553
         * DOCUMENT ME!
554
         *
555
         * @throws MDIManagerLoadException
556
         */
557
        private static void skinPlugin() throws MDIManagerLoadException {
558
                Iterator i = pluginsConfig.keySet().iterator();
559

    
560
                while (i.hasNext()) {
561
                        String name = (String) i.next();
562
                        PluginConfig pc = (PluginConfig) pluginsConfig.get(name);
563
                        PluginServices ps = (PluginServices) pluginsServices.get(name);
564

    
565
                        if (pc.getExtensions().getSkinExtension() != null) {
566
                                if (MDIManagerFactory.getSkinExtension() != null) {
567
                                        logger.warn(Messages.getString(
568
                                                        "Launcher.Dos_skin_extension"));
569
                                }
570

    
571
                                SkinExtension se = pc.getExtensions().getSkinExtension();
572

    
573
                                MDIManagerFactory.setSkinExtension(se, ps.getClassLoader());
574

    
575
                                Class skinClass;
576

    
577
                                try {
578
                                        skinClass = ps.getClassLoader().loadClass(se.getClassName());
579

    
580
                                        com.iver.andami.plugins.IExtension skinInstance = (com.iver.andami.plugins.IExtension) skinClass.newInstance();
581
                                        // classesExtensions.put(skinClass, skinInstance);
582
                                        // jaume
583
                                        ExtensionDecorator newExtensionDecorator = new ExtensionDecorator(skinInstance, ExtensionDecorator.INACTIVE);
584
                                        classesExtensions.put(skinClass, newExtensionDecorator);
585
                                } catch (ClassNotFoundException e) {
586
                                        logger.error(Messages.getString(
587
                                                        "Launcher.No_se_encontro_la_clase_mdi_manager"), e);
588
                                        throw new MDIManagerLoadException(e);
589
                                } catch (InstantiationException e) {
590
                                        logger.error(Messages.getString(
591
                                                        "Launcher.No_se_pudo_instanciar_la_clase_mdi_manager"),
592
                                                e);
593
                                        throw new MDIManagerLoadException(e);
594
                                } catch (IllegalAccessException e) {
595
                                        logger.error(Messages.getString(
596
                                                        "Launcher.No_se_pudo_acceder_a_la_clase_mdi_manager"),
597
                                                e);
598
                                        throw new MDIManagerLoadException(e);
599
                                }
600
                        }
601
                }
602
        }
603

    
604
        /**
605
         * @param theme
606
         *
607
         */
608
        private static void frameIcon(Theme theme) {
609
                Iterator i = pluginsConfig.keySet().iterator();
610

    
611
                while (i.hasNext()) {
612
                        String pName = (String) i.next();
613
                        PluginConfig pc = (PluginConfig) pluginsConfig.get(pName);
614
                        PluginServices ps = (PluginServices) pluginsServices.get(pName);
615
                        if (pc.getIcon() != null) {
616
                                if (theme.getIcon() != null) {
617
                                        frame.setIconImage(theme.getIcon().getImage());
618
                                } else {
619

    
620
                                        ImageIcon icon = new ImageIcon(ps.getClassLoader()
621
                                                        .getResource(pc.getIcon().getSrc()));
622
                                        frame.setIconImage(icon.getImage());
623

    
624
                                }
625
                                if (theme.getName() != null) {
626
                                        frame.setTitlePrefix(theme.getName());
627
                                } else {
628
                                        frame.setTitlePrefix(pc.getIcon().getText());
629
                                }
630
                                if (theme.getBackgroundImage() != null) {
631

    
632
                                        PluginServices.getMDIManager().setBackgroundImage(theme.getBackgroundImage(),theme.getTypeDesktop());
633
                                }
634
                        }
635
                }
636
        }
637

    
638
        /**
639
         *
640
         */
641
        private static void initializeExtensions() {
642
                Iterator i = pluginsOrdered.iterator();
643

    
644
                while (i.hasNext()) {
645
                        String pName = (String) i.next();
646
            logger.debug("Initializing extensions from " + pName);
647
                        PluginConfig pc = (PluginConfig) pluginsConfig.get(pName);
648
                        PluginServices ps = (PluginServices) pluginsServices.get(pName);
649

    
650
                        Extension[] exts = pc.getExtensions().getExtension();
651

    
652
                        TreeMap orderedExtensions = new TreeMap(new ExtensionComparator());
653

    
654
                        for (int j = 0; j < exts.length; j++) {
655
                                if (!exts[j].getActive()) {
656
                                        continue;
657
                                }
658

    
659
                                if (orderedExtensions.containsKey(exts[j])) {
660
                                        logger.warn(Messages.getString(
661
                                                        "Launcher.Two_extensions_with_the_same_priority") +
662
                                                exts[j].getClassName());
663
                                }
664

    
665
                                orderedExtensions.put(exts[j], null);
666
                        }
667

    
668
                        Iterator e = orderedExtensions.keySet().iterator();
669

    
670
                        while (e.hasNext()) {
671
                                Extension extension = (Extension) e.next();
672
                                com.iver.andami.plugins.IExtension extensionInstance;
673

    
674
                                try {
675
                                        Class extensionClass = ps.getClassLoader().loadClass(extension.getClassName());
676
                                        extensionInstance = (com.iver.andami.plugins.IExtension) extensionClass.newInstance();
677

    
678
                                        // CON DECORATOR
679
                                        // ANTES: classesExtensions.put(extensionClass, extensionInstance);
680
                                        // AHORA: CREAMOS UNA ExtensionDecorator y asignamos esta instancia para
681
                                        // poder ampliar con nuevas propiedades (AlwaysVisible, por ejemplo)
682
                                        // Para crear la nueva clase ExtensionDecorator, le pasamos como par?metro
683
                                        // la extensi?n original que acabamos de crear
684
                                        // 0-> Inactivo, controla la extension
685
                                        // 1-> Siempre visible
686
                                        // 2-> Invisible
687
                                        ExtensionDecorator newExtensionDecorator = new ExtensionDecorator(extensionInstance, ExtensionDecorator.INACTIVE);
688
                                        classesExtensions.put(extensionClass, newExtensionDecorator);
689
                                        System.err.println("Loading "+extension.getClassName()+"...");
690
                    // logger.debug("Initializing " + extension.getClassName());
691
                    extensionInstance.initialize();
692
                    extensions.add(extensionInstance);
693
                    // logger.debug(extension.getClassName() + " initialized.");
694

    
695
                                } catch (InstantiationException e1) {
696
                                        logger.error(Messages.getString(
697
                                                        "Launcher.Error_instanciando_la_extension") +
698
                                                extension.getClassName(), e1);
699
                                } catch (IllegalAccessException e1) {
700
                                        logger.error(Messages.getString(
701
                                                        "Launcher.Error_instanciando_la_extension") +
702
                                                extension.getClassName(), e1);
703
                                } catch (ClassNotFoundException e1) {
704
                                        logger.error(Messages.getString(
705
                                                        "Launcher.No_se_encontro_la_clase_de_la_extension") +
706
                                                extension.getClassName(), e1);
707
                                } catch (NoClassDefFoundError e1) {
708
                                        logger.error(Messages.getString(
709
                                                        "Launcher.Error_localizando_la_clase_de_la_extension") +
710
                                                extension.getClassName(), e1);
711
                                }
712
                        }
713
                }
714
        }
715

    
716
        private static void postInitializeExtensions() {
717
                for (int i=0;i<extensions.size();i++) {
718
                        com.iver.andami.plugins.IExtension extensionInstance=(com.iver.andami.plugins.IExtension)extensions.get(i);
719
                        extensionInstance.postInitialize();
720
                }
721
        }
722
        /**
723
         * DOCUMENT ME!
724
         */
725
        private static void installPluginsMenus() {
726
                TreeMap orderedMenus = new TreeMap(new MenuComparator());
727

    
728
                Iterator i = pluginsConfig.keySet().iterator();
729

    
730
                while (i.hasNext()) {
731
                        String pName = (String) i.next();
732
                        PluginServices ps = (PluginServices) pluginsServices.get(pName);
733
                        PluginConfig pc = (PluginConfig) pluginsConfig.get(pName);
734

    
735
                        Extension[] exts = pc.getExtensions().getExtension();
736

    
737
                        for (int j = 0; j < exts.length; j++) {
738
                                if (!exts[j].getActive()) {
739
                                        continue;
740
                                }
741

    
742
                                Menu[] menus = exts[j].getMenu();
743

    
744
                                for (int k = 0; k < menus.length; k++) {
745
                                        SortableMenu sm = new SortableMenu(ps.getClassLoader(),
746
                                                        exts[j], menus[k]);
747

    
748
                                        if (orderedMenus.containsKey(sm)) {
749
                                                logger.error(Messages.getString(
750
                                                                "Launcher.Two_menus_with_the_same_position") + " - " +
751
                                                        menus[k].getText()+ " - " + exts[j].getClassName());
752
                                        }
753

    
754
                                        orderedMenus.put(sm, null);
755
                                }
756
                        }
757

    
758
                        // Se instalan las extensiones de MDI
759
                        SkinExtension skinExt = pc.getExtensions().getSkinExtension();
760

    
761
                        if (skinExt != null) {
762
                                Menu[] menu = skinExt.getMenu();
763

    
764
                                for (int k = 0; k < menu.length; k++) {
765
                                        SortableMenu sm = new SortableMenu(ps.getClassLoader(),
766
                                                        skinExt, menu[k]);
767

    
768
                                        if (orderedMenus.containsKey(sm)) {
769
                                                logger.error(Messages.getString(
770
                                                                "Launcher.Two_menus_with_the_same_position") +
771
                                                        skinExt.getClassName());
772
                                        }
773

    
774
                                        orderedMenus.put(sm, null);
775
                                }
776
                        }
777
                }
778

    
779
                //Se itera por los menus ordenados
780
                Iterator e = orderedMenus.keySet().iterator();
781

    
782
                // Se ordenan los menues
783
                while (e.hasNext()) {
784
                        try {
785
                                SortableMenu sm = (SortableMenu) e.next();
786

    
787
                                frame.addMenu(sm.loader, sm.extension, sm.menu);
788
                        } catch (ClassNotFoundException ex) {
789
                                logger.error(Messages.getString(
790
                                                "Launcher.No_se_encontro_la_clase_de_la_extension"), ex);
791
                        }
792
                }
793
        }
794

    
795
        /**
796
         * Installs the menus, toolbars, actiontools, selectable toolbars and combos.
797
         * The order in which they are shown is determined here.
798
         */
799
        private static void installPluginsControls() {
800
                Iterator i = pluginsConfig.keySet().iterator();
801

    
802
                HashMap extensionPluginServices = new HashMap();
803
                HashMap extensionPluginConfig = new HashMap();
804
                TreeMap orderedExtensions = new TreeMap(new ExtensionComparator());
805

    
806
                // First of all, sort the extensions.
807
                // We need to iterate on the plugins, and iterate on each plugin's extensions
808
                // (each plugin may contain one or more extensions)
809
                while (i.hasNext()) { // iterate on the plugins
810
                        String pName = (String) i.next();
811
                        PluginConfig pc = (PluginConfig) pluginsConfig.get(pName);
812
                        PluginServices ps = (PluginServices) pluginsServices.get(pName);
813

    
814
                        Extension[] exts = pc.getExtensions().getExtension();
815

    
816
                        for (int j = 0; j < exts.length; j++) { // iterate on the extensions
817
                                if (exts[j].getActive()) {
818
                                        if (orderedExtensions.containsKey(exts[j])) {
819
                                                logger.error(Messages.getString(
820
                                                "Launcher.Two_extensions_with_the_same_priority") +
821
                                                exts[j].getClassName());
822
                                        }
823

    
824
                                        orderedExtensions.put(exts[j], null);
825
                                        extensionPluginServices.put(exts[j], ps);
826
                                        extensionPluginConfig.put(exts[j], pc);
827
                                }
828
                        }
829
                }
830

    
831
                TreeMap orderedTools = new TreeMap(new ToolComparator());
832
                Iterator e = orderedExtensions.keySet().iterator();
833

    
834
                // sort the toolbars and tools from 'normal' extensions (actiontools, selectabletools)
835
                // and load the  combo-scales and combo-buttons for the status bar
836
                while (e.hasNext()) {
837
                        Extension ext = (Extension) e.next();
838

    
839
                        ToolBar[] toolbars = ext.getToolBar();
840

    
841
                        // get tools from toolbars
842
                        for (int k = 0; k < toolbars.length; k++) {
843
                                ActionTool[] tools = toolbars[k].getActionTool();
844

    
845
                                for (int t = 0; t < tools.length; t++) {
846
                                        SortableTool sm = new SortableTool(((PluginServices)extensionPluginServices.get(ext)).getClassLoader(), ext,
847
                                                        toolbars[k], tools[t]);
848
                                        orderedTools.put(sm, null);
849
                                }
850

    
851
                                SelectableTool[] sTools = toolbars[k].getSelectableTool();
852

    
853
                                for (int t = 0; t < sTools.length; t++) {
854
                                        SortableTool sm=new SortableTool(((PluginServices)extensionPluginServices.get(ext)).getClassLoader(), ext,
855
                                                        toolbars[k], sTools[t]);
856
                                        orderedTools.put(sm, null);
857
                                }
858
                        }
859

    
860
                        // get controls for statusBar
861
                        PluginServices ps = (PluginServices) extensionPluginServices.get(ext);
862
                        PluginClassLoader loader = ps.getClassLoader();
863

    
864
                        //ArrayList componentList = new ArrayList();
865
                        ComboScale[] comboScaleArray = ext.getComboScale();
866
                        for (int k=0; k < comboScaleArray.length; k++) {
867
                                org.gvsig.gui.beans.controls.comboscale.ComboScale combo = new org.gvsig.gui.beans.controls.comboscale.ComboScale();
868
                                String label = comboScaleArray[k].getLabel();
869
                                if (label!=null)
870
                                        combo.setLabel(label);
871
                                String name = comboScaleArray[k].getName();
872
                                if (name!=null)
873
                                        combo.setName(name);
874
                                String[] elementsString = ((String)comboScaleArray[k].getElements()).split(";");
875
                                long[] elements = new long[elementsString.length];
876
                                for (int currentElem=0; currentElem<elementsString.length; currentElem++) {
877
                                        try {
878
                                                elements[currentElem] = Long.parseLong(elementsString[currentElem]);
879
                                        }
880
                                        catch (NumberFormatException nfex1) {
881
                                                logger.error(ext.getClassName()+" -- "+Messages.getString( "error_parsing_comboscale_elements"));
882
                                                elements[currentElem] = 0;
883
                                        }
884
                                }
885
                                combo.setItems(elements);
886
                                try {
887
                                        long value = Long.parseLong((String)comboScaleArray[k].getValue());
888
                                        combo.setScale(value);
889
                                }
890
                                catch (NumberFormatException nfex2) {
891
                                        logger.error(ext.getClassName()+" -- "+Messages.getString( "error_parsing_comboscale_value"));
892
                                }
893
                                try {
894
                                        frame.addStatusBarControl(loader.loadClass(ext.getClassName()),combo);
895
                                } catch (ClassNotFoundException e1) {
896
                                        logger.error(Messages.getString("Launcher.error_getting_class_loader_for_status_bar_control"), e1);
897
                                }
898
                        }
899

    
900
                        ComboButton[] comboButtonArray = ext.getComboButton();
901
                        for (int k=0; k < comboButtonArray.length; k++) {
902
                                ComboButtonElement[] elementList = comboButtonArray[k].getComboButtonElement();
903
                                org.gvsig.gui.beans.controls.combobutton.ComboButton combo = new org.gvsig.gui.beans.controls.combobutton.ComboButton();
904
                                String name = comboButtonArray[k].getName();
905
                                if (name!=null)
906
                                        combo.setName(name);
907
                                for (int currentElement=0; currentElement<elementList.length; currentElement++) {
908
                                        ComboButtonElement element = elementList[currentElement];
909
                                        ImageIcon icon;
910
                                        URL iconLocation = loader.getResource(element.getIcon());
911
                                        if (iconLocation==null)
912
                                                logger.error(Messages.getString("Icon_not_found_")+element.getIcon());
913
                                        else {
914
                                                icon = new ImageIcon(iconLocation);
915
                                                JButton button = new JButton(icon);
916
                                                combo.addButton(button);
917
                                                button.setActionCommand(element.getActionCommand());
918
                                        }
919
                                }
920
                                try {
921
                                        frame.addStatusBarControl(loader.loadClass(ext.getClassName()), combo);
922
                                } catch (ClassNotFoundException e1) {
923
                                        logger.error(Messages.getString("Launcher.error_getting_class_loader_for_status_bar_control"), e1);
924
                                }
925
                        }
926
                }
927

    
928
                // Add the tools from MDI extensions to the ordered tool-list, so that we get a sorted list containing all the tools
929
                i = pluginsConfig.keySet().iterator();
930
                while (i.hasNext()) {
931
                        String pName = (String) i.next();
932
                        PluginConfig pc = (PluginConfig) pluginsConfig.get(pName);
933
                        PluginServices ps = (PluginServices) pluginsServices.get(pName);
934

    
935
                        SkinExtension skinExt = pc.getExtensions().getSkinExtension();
936

    
937
                        if (skinExt != null) {
938
                                ToolBar[] toolbars = skinExt.getToolBar();
939

    
940
                                for (int k = 0; k < toolbars.length; k++) {
941
                                        ActionTool[] tools = toolbars[k].getActionTool();
942

    
943
                                        for (int t = 0; t < tools.length; t++) {
944
                                                SortableTool stb=new SortableTool(ps.getClassLoader(), skinExt,
945
                                                                toolbars[k], tools[t]);
946
                                                orderedTools.put(stb,null);
947
                                        }
948

    
949
                                        SelectableTool[] sTools = toolbars[k].getSelectableTool();
950

    
951
                                        for (int t = 0; t < sTools.length; t++) {
952
                                                SortableTool stb=new SortableTool(ps.getClassLoader(), skinExt,
953
                                                                toolbars[k], sTools[t]);
954
                                                orderedTools.put(stb,null);
955
                                        }
956
                                }
957
                        }
958
                        // Install popup menus
959
                        PopupMenus pus = pc.getPopupMenus();
960

    
961
                        if (pus != null) {
962
                                PopupMenu[] menus = pus.getPopupMenu();
963

    
964
                                for (int j = 0; j < menus.length; j++) {
965
                                        frame.addPopupMenu(ps.getClassLoader(), menus[j]);
966
                                }
967
                        }
968
                }
969

    
970
                // loop on the ordered extension list, to add them to the interface in an ordered way
971
                Iterator t = orderedTools.keySet().iterator();
972
                while (t.hasNext()) {
973
                        try {
974
                                SortableTool stb = (SortableTool) t.next();
975
                                if (stb.actiontool!=null)
976
                                        frame.addTool(stb.loader, stb.extension,stb.toolbar, stb.actiontool);
977
                                else
978
                                        frame.addTool(stb.loader, stb.extension,stb.toolbar, stb.selectabletool);
979
                        } catch (ClassNotFoundException ex) {
980
                                logger.error(Messages.getString(
981
                                "Launcher.No_se_encontro_la_clase_de_la_extension"), ex);
982
                        }
983
                }
984
        }
985

    
986
        /**
987
         * Adds new plugins to the the andami-config file.
988
         */
989
        private static void updateAndamiConfig() {
990
                HashSet olds = new HashSet();
991

    
992
                Plugin[] plugins = andamiConfig.getPlugin();
993

    
994
                for (int i = 0; i < plugins.length; i++) {
995
                        olds.add(plugins[i].getName());
996
                }
997

    
998
                Iterator i = pluginsServices.values().iterator();
999

    
1000
                while (i.hasNext()) {
1001
                        PluginServices ps = (PluginServices) i.next();
1002

    
1003
                        if (!olds.contains(ps.getPluginName())) {
1004
                                Plugin p = new Plugin();
1005
                                p.setName(ps.getPluginName());
1006
                                p.setUpdate(false);
1007

    
1008
                                andamiConfig.addPlugin(p);
1009
                        }
1010
                }
1011
        }
1012

    
1013
        /**
1014
         * DOCUMENT ME!
1015
         */
1016
        private static void pluginsClassLoaders() {
1017
                HashSet instalados = new HashSet();
1018

    
1019
                // Se itera hasta que est?n todos instalados
1020
                while (instalados.size() != pluginsConfig.size()) {
1021
                        boolean circle = true;
1022

    
1023
                        //Hacemos una pasada por todos los plugins
1024
                        Iterator i = pluginsConfig.keySet().iterator();
1025

    
1026
                        while (i.hasNext()) {
1027
                                String pluginName = (String) i.next();
1028
                                PluginConfig config = (PluginConfig) pluginsConfig.get(pluginName);
1029

    
1030
                                if (instalados.contains(pluginName)) {
1031
                                        continue;
1032
                                }
1033

    
1034
                                //Se obtienen las dependencias y sus class loaders
1035
                                boolean ready = true;
1036
                                Depends[] dependencies = config.getDepends();
1037
                                PluginClassLoader[] loaders = new PluginClassLoader[dependencies.length];
1038

    
1039
                                for (int j = 0; j < dependencies.length; j++) {
1040
                                        if (pluginsConfig.get(dependencies[j].getPluginName()) == null) {
1041
                                                logger.error(Messages.getString(
1042
                                                                "Launcher.Dependencia_no_resuelta_en_plugin") +
1043
                                                        pluginName + ": " +
1044
                                                        dependencies[j].getPluginName());
1045

    
1046
                                                continue;
1047
                                        }
1048

    
1049
                                        if (!instalados.contains(dependencies[j].getPluginName())) {
1050
                                                ready = false;
1051
                                        } else {
1052
                                                loaders[j] = ((PluginServices) pluginsServices.get(dependencies[j].getPluginName())).getClassLoader();
1053
                                        }
1054
                                }
1055

    
1056
                                //Si no est?n sus dependencias satisfechas se aborta la instalaci?n
1057
                                if (!ready) {
1058
                                        continue;
1059
                                }
1060

    
1061
                                //Se genera el class loader
1062
                                String jardir = config.getLibraries().getLibraryDir();
1063
                                File jarDir = new File(andamiConfig.getPluginsDirectory() +
1064
                                                File.separator + pluginName + File.separator + jardir);
1065
                                File[] jarFiles = jarDir.listFiles(new FileFilter() {
1066
                                                        public boolean accept(File pathname) {
1067
                                                                return (pathname.getName().toUpperCase()
1068
                                                                                                .endsWith(".JAR")) ||
1069
                                                                (pathname.getName().toUpperCase().endsWith(".ZIP"));
1070
                                                        }
1071
                                                });
1072

    
1073
                                URL[] urls = new URL[jarFiles.length];
1074

    
1075
                                for (int j = 0; j < jarFiles.length; j++) {
1076
                                        try {
1077
                                                urls[j] = new URL("file:" + jarFiles[j]);
1078
                                        } catch (MalformedURLException e) {
1079
                                                logger.error(Messages.getString(
1080
                                                                "Launcher.No_se_puede_acceder_a") +
1081
                                                        jarFiles[j]);
1082
                                        }
1083
                                }
1084

    
1085
                                PluginClassLoader loader;
1086

    
1087
                                try {
1088
                                        loader = new PluginClassLoader(urls,
1089
                                                        andamiConfig.getPluginsDirectory() +
1090
                                                        File.separator + pluginName,
1091
                                                        Launcher.class.getClassLoader(), loaders);
1092

    
1093
                                        PluginServices ps = new PluginServices(loader);
1094

    
1095
                                        pluginsServices.put(ps.getPluginName(), ps);
1096

    
1097
                                        instalados.add(pluginName);
1098
                    // FJP: Los metemos ordenados para luego no cargar uno que necesita de otro antes de tiempo. Esto lo usaremos al
1099
                    // inicializar los plugins
1100
                    pluginsOrdered.add(pluginName);
1101

    
1102
                                        circle = false;
1103
                                } catch (IOException e) {
1104
                                        logger.error(Messages.getString(
1105
                                                        "Launcher.Error_con_las_librerias_del_plugin"), e);
1106
                                        pluginsConfig.remove(pluginName);
1107
                                        i = pluginsConfig.keySet().iterator();
1108
                                }
1109
                        }
1110

    
1111
                        if (circle) {
1112
                                logger.error(Messages.getString(
1113
                                                "Launcher.Hay_dependencias_circulares"));
1114

    
1115
                                break;
1116
                        }
1117
                }
1118

    
1119
                //Se eliminan los plugins que no fueron instalados
1120
                Iterator i = pluginsConfig.keySet().iterator();
1121

    
1122
                while (i.hasNext()) {
1123
                        String pluginName = (String) i.next();
1124
                        PluginConfig config = (PluginConfig) pluginsConfig.get(pluginName);
1125
                        PluginServices ps = (PluginServices) pluginsServices.get(pluginName);
1126

    
1127
                        if (ps == null) {
1128
                                pluginsConfig.remove(pluginName);
1129
                                i = pluginsConfig.keySet().iterator();
1130
                        }
1131
                }
1132
        }
1133

    
1134
        /**
1135
         * DOCUMENT ME!
1136
         */
1137
        private static void pluginsMessages() {
1138
                /* add gvsig translations first. This should be done using a generic "appPlugin" variable, instead
1139
                 * of using "com.iver.cit.gvsig" directly, but I'll do it when we use the new appgvSIG launcher.
1140
                 * I keep this workaround for the moment.
1141
                 */
1142
                PluginConfig config = (PluginConfig) pluginsConfig.get("com.iver.cit.gvsig");
1143
                PluginServices ps = (PluginServices) pluginsServices.get("com.iver.cit.gvsig");
1144
                if (config.getResourceBundle() != null) {
1145
                        org.gvsig.i18n.Messages.addResourceFamily(config.getResourceBundle().getName(), ps.getClassLoader(), "com.iver.cit.gvsig");
1146
                }
1147

    
1148
                //Iteramos por todos los plugins
1149
                Iterator i = pluginsConfig.keySet().iterator();
1150

    
1151
                while (i.hasNext()) {
1152
                        String pluginName = (String) i.next();
1153
                        if (!pluginName.equals("com.iver.cit.gvsig")) { // we've already loaded com.iver.cit.gvsig
1154
                                config = (PluginConfig) pluginsConfig.get(pluginName);
1155
                                ps = (PluginServices) pluginsServices.get(pluginName);
1156

    
1157
                                if (config.getResourceBundle() != null && !config.getResourceBundle().getName().equals("")) {
1158
                                        // add the locale files associated with the plugin
1159
                                        org.gvsig.i18n.Messages.addResourceFamily(config.getResourceBundle().getName(), ps.getClassLoader(), pluginName);
1160
                                }
1161
                        }
1162
                }
1163
        }
1164

    
1165
        /**
1166
         * DOCUMENT ME!
1167
         *
1168
         * @param name DOCUMENT ME!
1169
         *
1170
         * @return DOCUMENT ME!
1171
         */
1172
        static PluginServices getPluginServices(String name) {
1173
                return (PluginServices) pluginsServices.get(name);
1174
        }
1175

    
1176
        /**
1177
         * DOCUMENT ME!
1178
         *
1179
         * @return DOCUMENT ME!
1180
         */
1181
        static String getPluginsDir() {
1182
                return andamiConfig.getPluginsDirectory();
1183
        }
1184

    
1185
        /**
1186
         * DOCUMENT ME!
1187
         *
1188
         * @param s DOCUMENT ME!
1189
         */
1190
        static void setPluginsDir(String s) {
1191
                andamiConfig.setPluginsDirectory(s);
1192
        }
1193

    
1194
        /**
1195
         * DOCUMENT ME!
1196
         *
1197
         * @return DOCUMENT ME!
1198
         */
1199
        static MDIFrame getMDIFrame() {
1200
                return frame;
1201
        }
1202

    
1203
        /**
1204
         * DOCUMENT ME!
1205
         *
1206
         * @param pluginsDirectory
1207
         */
1208
        private static void loadPlugins(String pluginsDirectory) {
1209
                File pDir = new File(pluginsDirectory);
1210

    
1211
                if (!pDir.exists()) {
1212
                        return;
1213
                }
1214

    
1215
                File[] pluginDirs = pDir.listFiles();
1216

    
1217
                for (int i = 0; i < pluginDirs.length; i++) {
1218
                        if (pluginDirs[i].isDirectory()) {
1219
                                File configXml = new File(pluginDirs[i].getAbsolutePath() +
1220
                                                File.separator + "config.xml");
1221

    
1222
                                try {
1223
                                        FileInputStream is = new FileInputStream(configXml);
1224
                                        Reader xml = com.iver.utiles.xml.XMLEncodingUtils.getReader(is);
1225
                                        if (xml==null) {
1226
                                                // the encoding was not correctly detected, use system default
1227
                                                xml = new FileReader(configXml);
1228
                                        }
1229
                                        else {
1230
                                                // use a buffered reader to improve performance
1231
                                                xml = new BufferedReader(xml);
1232
                                        }
1233
                                        PluginConfig pConfig = (PluginConfig) PluginConfig.unmarshal(xml);
1234
                                        pluginsConfig.put(pluginDirs[i].getName(), pConfig);
1235
                                } catch (FileNotFoundException e) {
1236
                                        logger.info(Messages.getString(
1237
                                                        "Launcher.Ignorando_el_directorio") +
1238
                                                pluginDirs[i].getAbsolutePath() +
1239
                                                Messages.getString("Launcher.config_no_encontrado"));
1240
                                } catch (MarshalException e) {
1241
                                        logger.info(Messages.getString(
1242
                                                        "Launcher.Ignorando_el_directorio") +
1243
                                                pluginDirs[i].getAbsolutePath() +
1244
                                                Messages.getString("Launcher.config_mal_formado"), e);
1245
                                } catch (ValidationException e) {
1246
                                        logger.info(Messages.getString(
1247
                                                        "Launcher.Ignorando_el_directorio") +
1248
                                                pluginDirs[i].getAbsolutePath() +
1249
                                                Messages.getString("Launcher.config_mal_formado"), e);
1250
                                }
1251
                        }
1252
                }
1253
        }
1254

    
1255
        /**
1256
         * DOCUMENT ME!
1257
         *
1258
         * @param language
1259
         * @param country
1260
         * @param variant
1261
         *
1262
         * @return DOCUMENT ME!
1263
         */
1264
        private static Locale getLocale(String language, String country,
1265
                String variant) {
1266
                if (variant != null) {
1267
                        return new Locale(language, country, variant);
1268
                } else if (country != null) {
1269
                        return new Locale(language, country);
1270
                } else if (language != null) {
1271
                        return new Locale(language);
1272
                } else {
1273
                        return new Locale("es");
1274
                }
1275
        }
1276

    
1277
        /**
1278
         * DOCUMENT ME!
1279
         *
1280
         * @param file DOCUMENT ME!
1281
         *
1282
         * @throws IOException DOCUMENT ME!
1283
         * @throws MarshalException DOCUMENT ME!
1284
         * @throws ValidationException DOCUMENT ME!
1285
         */
1286
        private static void andamiConfigToXML(String file)
1287
                throws IOException, MarshalException, ValidationException {
1288
                File xml = new File(file);
1289
                File parent = xml.getParentFile();
1290
                parent.mkdirs();
1291

    
1292
                FileWriter writer = new FileWriter(xml);
1293
                andamiConfig.marshal(writer);
1294
        }
1295

    
1296
        /**
1297
         * DOCUMENT ME!
1298
         *
1299
         * @param file DOCUMENT ME!
1300
         *
1301
         * @throws ConfigurationException DOCUMENT ME!
1302
         */
1303
        private static void andamiConfigFromXML(String file)
1304
                throws ConfigurationException {
1305
                File xml = new File(file);
1306

    
1307
                //Si no existe se ponen los valores por defecto
1308
                if (!xml.exists()) {
1309
                        andamiConfig = new AndamiConfig();
1310

    
1311
                        Andami andami = new Andami();
1312
                        andami.setUpdate(true);
1313
                        andamiConfig.setAndami(andami);
1314
                        andamiConfig.setLocaleCountry(Locale.getDefault().getCountry());
1315
                        andamiConfig.setLocaleLanguage(Locale.getDefault().getLanguage());
1316
                        andamiConfig.setLocaleVariant(Locale.getDefault().getVariant());
1317

    
1318
                        if (System.getProperty("javawebstart.version") != null) // Es java web start)
1319
                         {
1320
                                andamiConfig.setPluginsDirectory(new File(appHomeDir
1321
                                                + "extensiones").getAbsolutePath());
1322
                        } else {
1323
                                andamiConfig.setPluginsDirectory(new File(appName +
1324
                                                File.separator + "extensiones").getAbsolutePath());
1325
                        }
1326

    
1327
                        andamiConfig.setPlugin(new Plugin[0]);
1328
                } else {
1329
                        //Se lee la configuraci?n
1330
                        FileReader reader;
1331

    
1332
                        try {
1333
                                reader = new FileReader(xml);
1334
                                andamiConfig = (AndamiConfig) AndamiConfig.unmarshal(reader);
1335
                        } catch (FileNotFoundException e) {
1336
                                throw new ConfigurationException(e);
1337
                        } catch (MarshalException e) {
1338
                                throw new ConfigurationException(e);
1339
                        } catch (ValidationException e) {
1340
                                throw new ConfigurationException(e);
1341
                        }
1342
                }
1343
        }
1344

    
1345
        /**
1346
         * DOCUMENT ME!
1347
         *
1348
         * @return DOCUMENT ME!
1349
         *
1350
         * @throws ConfigurationException DOCUMENT ME!
1351
         */
1352
        private static XMLEntity persistenceFromXML() throws ConfigurationException {
1353
                File xml = new File(pluginsPersistencePath);
1354

    
1355
                if (xml.exists()) {
1356
                        FileReader reader;
1357

    
1358
                        try {
1359
                                reader = new FileReader(xml);
1360

    
1361
                                XmlTag tag = (XmlTag) XmlTag.unmarshal(reader);
1362

    
1363
                                return new XMLEntity(tag);
1364
                        } catch (FileNotFoundException e) {
1365
                                throw new ConfigurationException(e);
1366
                        } catch (MarshalException e) {
1367
                                throw new ConfigurationException(e);
1368
                        } catch (ValidationException e) {
1369
                                throw new ConfigurationException(e);
1370
                        }
1371
                } else {
1372
                        return new XMLEntity();
1373
                }
1374
        }
1375

    
1376
        /**
1377
         * DOCUMENT ME!
1378
         *
1379
         * @param entity DOCUMENT ME!
1380
         *
1381
         * @throws ConfigurationException DOCUMENT ME!
1382
         */
1383
        private static void persistenceToXML(XMLEntity entity)
1384
                throws ConfigurationException {
1385
                File xml = new File(pluginsPersistencePath);
1386

    
1387
                FileWriter writer;
1388

    
1389
                try {
1390
                        writer = new FileWriter(xml);
1391
                        entity.getXmlTag().marshal(writer);
1392
                } catch (FileNotFoundException e) {
1393
                        throw new ConfigurationException(e);
1394
                } catch (MarshalException e) {
1395
                        throw new ConfigurationException(e);
1396
                } catch (ValidationException e) {
1397
                        throw new ConfigurationException(e);
1398
                } catch (IOException e) {
1399
                        throw new ConfigurationException(e);
1400
                }
1401
        }
1402

    
1403
        /**
1404
         * Devuelve un array con los directorios de los plugins
1405
         *
1406
         * @param dirExt Directorio de las extensiones a partir del cual cuelgan
1407
         *                   todos los directorios de los plugins
1408
         *
1409
         * @return ArrayList con los directorios
1410
         */
1411
        private String[] getLocales(File dirExt) {
1412
                ArrayList types = new ArrayList();
1413
                File[] files = dirExt.listFiles();
1414

    
1415
                for (int i = 0; i < files.length; i++) {
1416
                        if (files[i].isDirectory()) {
1417
                                File[] textFile = files[i].listFiles(new FilenameFilter() {
1418
                                                        public boolean accept(File dir, String fileName) {
1419
                                                                return fileName.toLowerCase().startsWith("text_"); //$NON-NLS-1$
1420
                                                        }
1421
                                                });
1422

    
1423
                                for (int j = 0; j < textFile.length; j++) {
1424
                                        String s = (textFile[j]).getName().replaceAll("text_", "");
1425
                                        s = s.replaceAll(".properties", "");
1426
                                        s = s.trim();
1427

    
1428
                                        if (!types.contains(s)) {
1429
                                                types.add(s);
1430
                                        }
1431
                                }
1432
                        }
1433
                }
1434

    
1435
                return (String[]) types.toArray(new String[0]);
1436
        }
1437

    
1438
        /**
1439
         * DOCUMENT ME!
1440
         *
1441
         * @return Returns the frame.
1442
         */
1443
        static MDIFrame getFrame() {
1444
                return frame;
1445
        }
1446

    
1447
        /**
1448
         * Secuencia de cerrado de Andami
1449
         */
1450
        public static void closeApplication() {
1451
                //Configuraci?n de Andami
1452
                try {
1453
                        andamiConfigToXML(andamiConfigPath);
1454
                } catch (MarshalException e) {
1455
                        logger.error(Messages.getString(
1456
                                        "Launcher.No_se_pudo_guardar_la_configuracion_de_andami"), e);
1457
                } catch (ValidationException e) {
1458
                        logger.error(Messages.getString(
1459
                                        "Launcher.No_se_pudo_guardar_la_configuracion_de_andami"), e);
1460
                } catch (IOException e) {
1461
                        logger.error(Messages.getString(
1462
                                        "Launcher.No_se_pudo_guardar_la_configuracion_de_andami"), e);
1463
                }
1464

    
1465
                //Persistencia de los plugins
1466
                savePluginPersistence();
1467

    
1468
                //Finalize all the extensions
1469
                finalizeExtensions();
1470

    
1471
                // Clean any temp data created
1472
                Utilities.cleanUpTempFiles();
1473

    
1474
                //Para la depuraci?n de memory leaks
1475
                System.gc();
1476

    
1477
        System.exit(0);
1478
        }
1479

    
1480
        /**
1481
         * Exectutes the terminate method for all the extensions, in the reverse
1482
         * order they were initialized
1483
         *
1484
         */
1485
        private static void finalizeExtensions() {
1486
                for (int i=extensions.size()-1; i>=0; i--) {
1487
                        com.iver.andami.plugins.IExtension extensionInstance=(com.iver.andami.plugins.IExtension)extensions.get(i);
1488
                        extensionInstance.terminate();
1489
                }
1490
        }
1491

    
1492

    
1493
        /**
1494
         * DOCUMENT ME!
1495
         *
1496
         * @return DOCUMENT ME!
1497
         */
1498
        static HashMap getClassesExtensions() {
1499
                return classesExtensions;
1500
        }
1501

    
1502
        /**
1503
         * DOCUMENT ME!
1504
         *
1505
         * @param extDir DOCUMENT ME!
1506
         */
1507
        private static void downloadExtensions(String extDir) {
1508
                java.util.Date fechaActual = null;
1509

    
1510
                try {
1511
                        if (System.getProperty("javawebstart.version") != null) {
1512
                                //Obtenemos la URL del servidor
1513
                                BasicService bs = (BasicService) ServiceManager.lookup(
1514
                                                "javax.jnlp.BasicService");
1515
                                URL baseURL = bs.getCodeBase();
1516

    
1517
                                //Se descargan las extensiones
1518
                                MultiSplashWindow.process(5,
1519
                                        "Descargando las extensiones desde " + baseURL + " a " +
1520
                                        extDir);
1521

    
1522
                                URL url = new URL(baseURL + "extensiones.zip");
1523
                                URLConnection connection = url.openConnection();
1524

    
1525
                                System.out.println(url.toExternalForm() + ":");
1526
                                System.out.println("  Content Type: " +
1527
                                        connection.getContentType());
1528
                                System.out.println("  Content Length: " +
1529
                                        connection.getContentLength());
1530
                                System.out.println("  Last Modified: " +
1531
                                        new Date(connection.getLastModified()));
1532
                                System.out.println("  Expiration: " +
1533
                                        connection.getExpiration());
1534
                                System.out.println("  Content Encoding: " +
1535
                                        connection.getContentEncoding());
1536

    
1537
                                // Guardamos la fecha del fichero de extensiones que nos hemos bajado, y
1538
                                // comprobamos el ?ltimo que se ha bajado. Si no son
1539
                                // iguales, nos bajamos el nuevo. Si son iguales, no
1540
                                // nos bajamos nada.
1541
                                Long miliSecondsInWeb = new Long(connection.getLastModified());
1542

    
1543
                                // PluginServices ps = PluginServices.getPluginServices("com.iver.core");
1544
                                // if (ps.getPersistentXML().getStringProperty("timestamp") != null)
1545
                                File destDir = new File(extDir);
1546

    
1547
                                if (!destDir.exists()) {
1548
                                        // Creamos gvSIG
1549
                                        destDir.getParentFile().mkdir();
1550

    
1551
                                        if (!destDir.mkdir()) {
1552
                                                System.err.println("Imposible crear el directorio " +
1553
                                                        destDir.getAbsolutePath());
1554
                                        }
1555
                                }
1556

    
1557
                                File timeFile = new File(destDir.getParent() + File.separator +
1558
                                                "timeStamp.properties");
1559

    
1560
                                if (!timeFile.exists()) {
1561
                                        timeFile.createNewFile();
1562
                                }
1563

    
1564
                                FileInputStream inAux = new FileInputStream(timeFile);
1565
                                Properties prop = new Properties();
1566
                                prop.load(inAux);
1567
                                inAux.close();
1568

    
1569
                                if (prop.getProperty("timestamp") != null) {
1570
                                        Long lastMiliSeconds = (Long) new Long(prop.getProperty(
1571
                                                                "timestamp"));
1572

    
1573
                                        if (lastMiliSeconds.longValue() == miliSecondsInWeb.longValue()) {
1574
                                                System.out.println("No hay nueva actualizaci?n");
1575
                        logger.debug("No hay nueva actualizaci?n -> Return");
1576
                        logger.debug("timeStampWeb= " + miliSecondsInWeb);
1577
                        logger.debug("timeStampLocal= " + lastMiliSeconds);
1578

    
1579
                                                return;
1580
                                        }
1581

    
1582
                                        System.out.println("timeStampWeb= " + miliSecondsInWeb);
1583
                                        System.out.println("timeStampLocal= " + lastMiliSeconds);
1584
                                } else {
1585
                                        System.out.println("El timeStamp no est? escrito en " +
1586
                                                timeFile.getAbsolutePath());
1587
                                }
1588

    
1589
                                InputStream stream = url.openStream();
1590
                File temp = File.createTempFile("gvsig", ".zip");
1591

    
1592
                logger.debug(temp.getAbsolutePath());
1593

    
1594
                temp.deleteOnExit();
1595
                FileOutputStream file = new FileOutputStream(temp);
1596

    
1597
                byte[] lt_read = new byte[1];
1598

    
1599
                while (stream.read(lt_read) > 0)
1600
                  file.write(lt_read);
1601

    
1602
                                stream.close();
1603
                stream = null;
1604
                file.close();
1605
                file = null;
1606

    
1607
                System.gc();
1608

    
1609
                logger.debug("Ha creado el fichero ZIP");
1610
                                //Se extrae el zip
1611
                                MultiSplashWindow.process(5, "Extensiones descargadas.");
1612

    
1613
                                System.out.println("Extrayendo a " + destDir.getAbsolutePath());
1614

    
1615
                                Date fechaDir = new Date(destDir.lastModified());
1616
                                System.out.println("Fecha del directorio " + extDir + " = " +
1617
                                        fechaDir.toString());
1618
                                Utilities.extractTo(temp, new File(extDir), splashWindow);
1619

    
1620
                                // Si todo ha ido bien, guardamos el timestamp.
1621
                                ///  App.instance.getPc().addProperties("timestamp", miliSecondsInWeb);
1622
                                // XMLEntity xml=ps.getPersistentXML();
1623
                                fechaActual = new java.util.Date();
1624

    
1625
                                FileOutputStream outAux = new FileOutputStream(timeFile);
1626
                                prop.setProperty("timestamp", miliSecondsInWeb.toString());
1627
                                prop.store(outAux, "last download");
1628
                                outAux.close();
1629
                                System.out.println("Fecha actual guardada: " +
1630
                                        fechaActual.toGMTString());
1631

    
1632
                                /* xml.putProperty("timestamp",fechaActual.toGMTString());
1633
                                   ps.setPresistentXML(xml); */
1634
                        }
1635
                } catch (IOException e) {
1636
                        NotificationManager.addError("", e);
1637
                } catch (UnavailableServiceException e) {
1638
                        NotificationManager.addError("", e);
1639
                } catch (SecurityException e) {
1640
                        System.err.println("No se puede escribir el timeStamp " +
1641
                                fechaActual.toGMTString());
1642
                        NotificationManager.addError("", e);
1643
                }
1644
        }
1645

    
1646
        /**
1647
         * DOCUMENT ME!
1648
         *
1649
         * @return DOCUMENT ME!
1650
         */
1651
        private static Extensions[] getExtensions() {
1652
                ArrayList array = new ArrayList();
1653
                Iterator iter = pluginsConfig.values().iterator();
1654

    
1655
                while (iter.hasNext()) {
1656
                        array.add(((PluginConfig) iter.next()).getExtensions());
1657
                }
1658

    
1659
                return (Extensions[]) array.toArray(new Extensions[0]);
1660
        }
1661

    
1662
        /**
1663
         * DOCUMENT ME!
1664
         *
1665
         * @return DOCUMENT ME!
1666
         */
1667
        public static HashMap getPluginConfig() {
1668
                return pluginsConfig;
1669
        }
1670

    
1671
        /**
1672
         * DOCUMENT ME!
1673
         *
1674
         * @param s DOCUMENT ME!
1675
         *
1676
         * @return DOCUMENT ME!
1677
         */
1678
        public static Extension getExtension(String s) {
1679
                Extensions[] exts = getExtensions();
1680

    
1681
                for (int i = 0; i < exts.length; i++) {
1682
                        for (int j = 0; j < exts[i].getExtensionCount(); j++) {
1683
                                if (exts[i].getExtension(j).getClassName().equals(s)) {
1684
                                        return exts[i].getExtension(j);
1685
                                }
1686
                        }
1687
                }
1688

    
1689
                return null;
1690
        }
1691

    
1692
        /**
1693
         * DOCUMENT ME!
1694
         *
1695
         * @return DOCUMENT ME!
1696
         */
1697
        public static AndamiConfig getAndamiConfig() {
1698
                return andamiConfig;
1699
        }
1700

    
1701
        /**
1702
         * DOCUMENT ME!
1703
         *
1704
         * @author $author$
1705
         * @version $Revision: 9400 $
1706
         */
1707
        private static class ExtensionComparator implements Comparator {
1708
                /**
1709
                 * DOCUMENT ME!
1710
                 *
1711
                 * @param o1 DOCUMENT ME!
1712
                 * @param o2 DOCUMENT ME!
1713
                 *
1714
                 * @return DOCUMENT ME!
1715
                 */
1716
                public int compare(Object o1, Object o2) {
1717
                        Extension e1 = (Extension) o1;
1718
                        Extension e2 = (Extension) o2;
1719

    
1720
                        if (!e1.hasPriority() && !e2.hasPriority()) {
1721
                                return -1;
1722
                        }
1723

    
1724
                        if (e1.hasPriority() && !e2.hasPriority()) {
1725
                                return Integer.MIN_VALUE;
1726
                        }
1727

    
1728
                        if (e2.hasPriority() && !e1.hasPriority()) {
1729
                                return Integer.MAX_VALUE;
1730
                        }
1731

    
1732
                        if (e1.getPriority() != e2.getPriority()){
1733
                                return e2.getPriority() - e1.getPriority();
1734
                        }else{
1735
                                return (e2.toString().compareTo(e1.toString()));
1736
                        }
1737
                }
1738
        }
1739

    
1740
        /**
1741
         * DOCUMENT ME!
1742
         */
1743
        private static class MenuComparator implements Comparator {
1744
                private static ExtensionComparator extComp = new ExtensionComparator();
1745

    
1746
                /**
1747
                 * DOCUMENT ME!
1748
                 *
1749
                 * @param o1 DOCUMENT ME!
1750
                 * @param o2 DOCUMENT ME!
1751
                 *
1752
                 * @return DOCUMENT ME!
1753
                 */
1754
                public int compare(Object o1, Object o2) {
1755
                        SortableMenu e1 = (SortableMenu) o1;
1756
                        SortableMenu e2 = (SortableMenu) o2;
1757

    
1758
                        if (!e1.menu.hasPosition() && !e2.menu.hasPosition()) {
1759
                                if (e1.extension instanceof SkinExtensionType) {
1760
                                        return 1;
1761
                                } else if (e2.extension instanceof SkinExtensionType) {
1762
                                        return -1;
1763
                                } else {
1764
                                        return extComp.compare(e1.extension, e2.extension);
1765
                                }
1766
                        }
1767

    
1768
                        if (e1.menu.hasPosition() && !e2.menu.hasPosition()) {
1769
                                return Integer.MIN_VALUE;
1770
                        }
1771

    
1772
                        if (e2.menu.hasPosition() && !e1.menu.hasPosition()) {
1773
                                return Integer.MAX_VALUE;
1774
                        }
1775
                        if (e1.menu.getPosition() != e2.menu.getPosition()){
1776
                                //we don't return 0 unless both objects are the same, otherwise the objects get overwritten in the treemap
1777
                                return e1.menu.getPosition() - e2.menu.getPosition();
1778
                        }else{
1779
                                return (e1.toString().compareTo(e2.toString()));
1780
                        }
1781
                }
1782
        }
1783

    
1784
        /**
1785
         * DOCUMENT ME!
1786
         *
1787
         * @author $author$
1788
         * @version $Revision: 9400 $
1789
         */
1790
        private static class SortableMenu {
1791
                public PluginClassLoader loader;
1792
                public Menu menu;
1793
                public SkinExtensionType extension;
1794

    
1795
                /**
1796
                 * DOCUMENT ME!
1797
                 *
1798
                 * @param loader DOCUMENT ME!
1799
                 * @param skinExt
1800
                 * @param menu2
1801
                 */
1802
                public SortableMenu(PluginClassLoader loader,
1803
                        SkinExtensionType skinExt, Menu menu2) {
1804
                        extension = skinExt;
1805
                        menu = menu2;
1806
                        this.loader = loader;
1807
                }
1808
        }
1809
        /**
1810
         * DOCUMENT ME!
1811
         */
1812
        private static class SortableTool {
1813
                public PluginClassLoader loader;
1814
                public ToolBar toolbar;
1815
                public ActionTool actiontool;
1816
                public SelectableTool selectabletool;
1817
                public SkinExtensionType extension;
1818

    
1819
                /**
1820
                 * DOCUMENT ME!
1821
                 *
1822
                 * @param loader DOCUMENT ME!
1823
                 * @param skinExt
1824
                 * @param menu2
1825
                 */
1826
                public SortableTool(PluginClassLoader loader,
1827
                        SkinExtensionType skinExt, ToolBar toolbar2,ActionTool actiontool2) {
1828
                        extension = skinExt;
1829
                        toolbar = toolbar2;
1830
                        actiontool=actiontool2;
1831
                        this.loader = loader;
1832
                }
1833
                public SortableTool(PluginClassLoader loader,
1834
                                SkinExtensionType skinExt, ToolBar toolbar2,SelectableTool selectabletool2) {
1835
                        extension = skinExt;
1836
                        toolbar = toolbar2;
1837
                        selectabletool=selectabletool2;
1838
                        this.loader = loader;
1839
                }
1840
        }
1841
        /**
1842
         * DOCUMENT ME!
1843
         */
1844
        private static class ToolBarComparator implements Comparator {
1845
                private static ExtensionComparator extComp = new ExtensionComparator();
1846

    
1847
                /**
1848
                 * DOCUMENT ME!
1849
                 *
1850
                 * @param o1 DOCUMENT ME!
1851
                 * @param o2 DOCUMENT ME!
1852
                 *
1853
                 * @return DOCUMENT ME!
1854
                 */
1855
                public int compare(Object o1, Object o2) {
1856
                        SortableTool e1 = (SortableTool) o1;
1857
                        SortableTool e2 = (SortableTool) o2;
1858

    
1859
                        // if the toolbars have the same name, they are considered to be
1860
                        // the same toolbar, so we don't need to do further comparing
1861
                        if (e1.toolbar.getName().equals(e2.toolbar.getName()))
1862
                                return 0;
1863

    
1864
                        if (!e1.toolbar.hasPosition() && !e2.toolbar.hasPosition()) {
1865
                                if (e1.extension instanceof SkinExtensionType) {
1866
                                        return 1;
1867
                                } else if (e2.extension instanceof SkinExtensionType) {
1868
                                        return -1;
1869
                                } else {
1870
                                        return extComp.compare(e1.extension, e2.extension);
1871
                                }
1872
                        }
1873

    
1874
                        if (e1.toolbar.hasPosition() && !e2.toolbar.hasPosition()) {
1875
                                return Integer.MIN_VALUE;
1876
                        }
1877

    
1878
                        if (e2.toolbar.hasPosition() && !e1.toolbar.hasPosition()) {
1879
                                return Integer.MAX_VALUE;
1880
                        }
1881
                        if (e1.toolbar.getPosition() != e2.toolbar.getPosition())
1882
                                return e1.toolbar.getPosition() - e2.toolbar.getPosition();
1883

    
1884
                        if (e1.toolbar.getActionTool().equals(e2.toolbar.getActionTool()) && e1.toolbar.getSelectableTool().equals(e2.toolbar.getSelectableTool())){
1885
                                return 0;
1886
                        }
1887
                        return (e1.toolbar.toString().compareTo(e2.toolbar.toString()));
1888
                }
1889
        }
1890

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

    
1929
                        if (e1.actiontool!=null) {
1930
                                if (e1.actiontool.hasPosition())
1931
                                        e1Position = e1.actiontool.getPosition();
1932
                        }
1933
                        else if (e1.selectabletool!=null) {
1934
                                if (e1.selectabletool.hasPosition())
1935
                                        e1Position = e1.selectabletool.getPosition();
1936
                        }
1937

    
1938
                        if (e2.actiontool!=null) {
1939
                                if (e2.actiontool.hasPosition())
1940
                                        e2Position = e2.actiontool.getPosition();
1941
                        }
1942
                        else if (e2.selectabletool!=null){
1943
                                if (e2.selectabletool.hasPosition())
1944
                                        e2Position = e2.selectabletool.getPosition();
1945
                        }
1946

    
1947
                        if (e1Position==-1 && e2Position!=-1) {
1948
                                return 1;
1949
                        }
1950
                        if (e1Position!=-1 && e2Position==-1) {
1951
                                return -1;
1952
                        }
1953
                        if (e1Position!=-1 && e2Position!=-1) {
1954
                                result = e1Position - e2Position;
1955
                                // we don't return 0 unless both objects are the same, otherwise the objects get overwritten in the treemap
1956
                                if (result!=0) return result;
1957
                        }
1958
                        return e1.toString().compareTo(e2.toString());
1959
                }
1960
        }
1961

    
1962

    
1963
        /**
1964
         * validates the user before starting gvsig
1965
         *
1966
         */
1967
        private static void validate(){
1968

    
1969
                IAuthentication session =  null;
1970
                try {
1971
                        session = (IAuthentication)Class.forName("com.iver.andami.authentication.Session").newInstance();
1972

    
1973
                } catch (ClassNotFoundException e) {
1974
                        // TODO Auto-generated catch block
1975
                        //e.printStackTrace();
1976
                        return;
1977
                } catch (InstantiationException e) {
1978
                        // TODO Auto-generated catch block
1979
                        //e.printStackTrace();
1980
                        return;
1981
                } catch (IllegalAccessException e) {
1982
                        // TODO Auto-generated catch block
1983
                        //e.printStackTrace();
1984
                        return;
1985
                }
1986

    
1987
                session.setPluginDirectory( andamiConfig.getPluginsDirectory() );
1988
                if (session.validationRequired()){
1989
                        if(session.Login()){
1990
                                System.out.println("You are logged in");
1991
                        }
1992
                        else{
1993
                                JOptionPane.showMessageDialog((Component)PluginServices.getMainFrame(),
1994
                                                 "You are not logged in");
1995
                                //System.exit(0);
1996
                        }
1997
                        PluginServices.setAuthentication(session);
1998
                }
1999
        }
2000

    
2001
        public static String getDefaultLookAndFeel() {
2002
                String osName = (String) System.getProperty("os.name");
2003

    
2004
                if (osName.length() > 4 && osName.substring(0,5).toLowerCase().equals("linux"))
2005
                        return nonWinDefaultLookAndFeel;
2006
                
2007
                return UIManager.getSystemLookAndFeelClassName();
2008
        }
2009

    
2010
        /**
2011
         * Gets the ISO 839 two-characters-long language code matching the
2012
         * provided language code (which may be an ISO 839-2/T
2013
         * three-characters-long code or an ISO 839-1 two-characters-long
2014
         * code).
2015
         *
2016
         * If the provided parameter is already two characters long, it
2017
         * returns the parameter without any modification.
2018
         *
2019
         * @param langCode A language code representing either
2020
         *  an ISO 839-2/T language code or an ISO 839-1 code.
2021
         * @return A two-characters-long code specifying
2022
         *  an ISO 839 language code.
2023
         */
2024
        private static String normalizeLanguageCode(String langCode) {
2025
                final String fileName = "iso_639.tab";
2026
                if (langCode.length()==2)
2027
                        return langCode;
2028
                else if (langCode.length()==3) {
2029
                        if (langCode.equals("va") || langCode.equals("val")) { // special case for Valencian
2030
                                return "ca";
2031
                        }
2032
                        URL isoCodes = Launcher.class.getClassLoader().getResource(fileName);
2033
                        if (isoCodes!=null) {
2034
                                try {
2035
                                        BufferedReader reader =
2036
                                                new BufferedReader(new InputStreamReader(isoCodes.openStream(), "ISO-8859-1"));
2037
                                                String line;
2038

    
2039
                                                while ((line = reader.readLine()) != null) {
2040
                                                        String[] language = line.split("\t");
2041
                                                        if (language[0].equals(langCode)) // first column is the three characters code
2042
                                                                return language[2]; // third column i the two characters code
2043
                                                }
2044
                                }
2045
                                catch (IOException ex) {
2046
                                        logger.error(Messages.getString("Error_reading_isocodes_file"), ex);
2047
                                        return "es";
2048
                                }
2049
                        }
2050
                        else {
2051
                                logger.error(Messages.getString("Error_reading_isocodes_file"));
2052
                                return "es";
2053
                        }
2054
                }
2055
                return "es";
2056
        }
2057

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

    
2101
        }
2102

    
2103
        /**
2104
         * Gets Home Directory location of the application.
2105
         * May be set from outside the aplication by means of
2106
         * -DgvSIG.home=C:/data/gvSIG, where gvSIG its the name
2107
         * of the application
2108
         * @return
2109
         */
2110
        public static String getAppHomeDir() {
2111
                return appHomeDir;
2112
        }
2113

    
2114
        /**
2115
         * Sets Home Directory location of the application.
2116
         * May be set from outside the aplication by means of
2117
         * -DgvSIG.home=C:/data/gvSIG, where gvSIG its the name
2118
         * of the application
2119
         * @param appHomeDir
2120
         */
2121
        public static void setAppHomeDir(String appHomeDir) {
2122
                Launcher.appHomeDir = appHomeDir;
2123
        }
2124

    
2125
        /**
2126
         * Initialize the extesion that have to take the control
2127
         *  of the state of action controls of the UI of all extensions.
2128
         * <br>
2129
         * <br>
2130
         * For use this option you have to add an argument
2131
         * to the command line like this:
2132
         * <br>
2133
         * <br>
2134
         * -exclusiveUI={pathToExtensionClass}
2135
         * <br>
2136
         *  @see com.iver.andami.plugins.IExtension#isEnabled(IExtension extension)
2137
         *  @see com.iver.andami.plugins.IExtension#isVisible(IExtension extension)
2138
         */
2139
        private static void initializeExclusiveUIExtension(){
2140
                String name = PluginServices.getArgumentByName("exclusiveUI");
2141
                if (name == null)
2142
                        return;
2143

    
2144

    
2145
                Iterator iter  = classesExtensions.keySet().iterator();
2146
                int charIndex;
2147
                Class key;
2148
                while (iter.hasNext()) {
2149
                        key = (Class)iter.next();
2150
                        charIndex = key.getName().indexOf(name);
2151
                        //System.out.println("key='"+key.getName()+"' name='"+name+"' charIndex="+charIndex);
2152
                        if (charIndex == 0) {
2153
                                IExtension ext =(IExtension)classesExtensions.get(key);
2154
                                if (ext instanceof ExtensionDecorator)
2155
                                        ext = ((ExtensionDecorator)ext).getExtension();
2156
                                PluginServices.setExclusiveUIExtension(ext);
2157
                                break;
2158
                        }
2159
                }
2160

    
2161
                logger.error(Messages.getString("No_se_encontro_la_extension_especificada_en_el_parametro_exclusiveUI") + " '" + name +"'");
2162
        }
2163
}