Statistics
| Revision:

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

History | View | Annotate | Download (64.1 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.ComboCoords;
116
import com.iver.andami.plugins.config.generate.ComboScale;
117
import com.iver.andami.plugins.config.generate.Depends;
118
import com.iver.andami.plugins.config.generate.Extension;
119
import com.iver.andami.plugins.config.generate.Extensions;
120
import com.iver.andami.plugins.config.generate.LabelSet;
121
import com.iver.andami.plugins.config.generate.Menu;
122
import com.iver.andami.plugins.config.generate.PluginConfig;
123
import com.iver.andami.plugins.config.generate.PopupMenu;
124
import com.iver.andami.plugins.config.generate.PopupMenus;
125
import com.iver.andami.plugins.config.generate.SelectableTool;
126
import com.iver.andami.plugins.config.generate.SkinExtension;
127
import com.iver.andami.plugins.config.generate.SkinExtensionType;
128
import com.iver.andami.plugins.config.generate.ToolBar;
129
import com.iver.andami.ui.AndamiEventQueue;
130
import com.iver.andami.ui.MDIManagerLoadException;
131
import com.iver.andami.ui.fonts.FontUtils;
132
import com.iver.andami.ui.mdiFrame.MDIFrame;
133
import com.iver.andami.ui.mdiManager.MDIManagerFactory;
134
import com.iver.andami.ui.splash.MultiSplashWindow;
135
import com.iver.andami.ui.theme.Theme;
136
import com.iver.utiles.XMLEntity;
137
import com.iver.utiles.xmlEntity.generate.XmlTag;
138

    
139

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

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

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

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

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

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

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

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

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

    
203
                    appName = args[0];
204

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

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

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

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

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

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

    
243
                    configureLocales(args);
244

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

    
267
                    validate();
268

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
339
                    // Se instalan los bookmarks de los plugins
340

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

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

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

    
360
    }
361

    
362
    /**
363
     * Obtiene la personalizaci?n de los iconos, splash, fondo y el nombre de
364
     * la aplicaci?n.
365
     *
366
     * @return Theme
367
     */
368
    private static Theme getTheme() {
369
            Theme theme=new Theme();
370
            String name=PluginServices.getArgumentByName("andamiTheme");
371
                //File file=new File("theme/andami-theme.xml");
372
            File file;
373
            if (name==null){
374
                    file=new File("theme/andami-theme.xml");
375
            }else{
376
                    file=new File(name);
377
            }
378

    
379
            if (file.exists()) {
380
                        theme.readTheme(file);
381
                }
382
                return theme;
383
        }
384
        /**
385
     *Establece los datos que ten?amos guardados respecto de la configuraci?n
386
     *del proxy.
387
     */
388
        private static void configureProxy() {
389
                String host = prefs.get("firewall.http.host", "");
390
                String port = prefs.get("firewall.http.port", "");
391

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

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

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

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

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

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

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

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

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

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

    
500
                XMLEntity entity = new XMLEntity();
501

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

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

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

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

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

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

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

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

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

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

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

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

    
576
                                Class skinClass;
577

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
913
                        ComboButton[] comboButtonArray = ext.getComboButton();
914
                        for (int k=0; k < comboButtonArray.length; k++) {
915
                                ComboButtonElement[] elementList = comboButtonArray[k].getComboButtonElement();
916
                                org.gvsig.gui.beans.controls.combobutton.ComboButton combo = new org.gvsig.gui.beans.controls.combobutton.ComboButton();
917
                                String name = comboButtonArray[k].getName();
918
                                if (name!=null)
919
                                        combo.setName(name);
920
                                for (int currentElement=0; currentElement<elementList.length; currentElement++) {
921
                                        ComboButtonElement element = elementList[currentElement];
922
                                        ImageIcon icon;
923
                                        URL iconLocation = loader.getResource(element.getIcon());
924
                                        if (iconLocation==null)
925
                                                logger.error(Messages.getString("Icon_not_found_")+element.getIcon());
926
                                        else {
927
                                                icon = new ImageIcon(iconLocation);
928
                                                JButton button = new JButton(icon);
929
                                                combo.addButton(button);
930
                                                button.setActionCommand(element.getActionCommand());
931
                                        }
932
                                }
933
                                try {
934
                                        frame.addStatusBarControl(loader.loadClass(ext.getClassName()), combo);
935
                                } catch (ClassNotFoundException e1) {
936
                                        logger.error(Messages.getString("Launcher.error_getting_class_loader_for_status_bar_control"), e1);
937
                                }
938
                        }
939
                }
940

    
941
                // Add the tools from MDI extensions to the ordered tool-list, so that we get a sorted list containing all the tools
942
                i = pluginsConfig.keySet().iterator();
943
                while (i.hasNext()) {
944
                        String pName = (String) i.next();
945
                        PluginConfig pc = (PluginConfig) pluginsConfig.get(pName);
946
                        PluginServices ps = (PluginServices) pluginsServices.get(pName);
947

    
948
                        SkinExtension skinExt = pc.getExtensions().getSkinExtension();
949

    
950
                        if (skinExt != null) {
951
                                ToolBar[] toolbars = skinExt.getToolBar();
952

    
953
                                for (int k = 0; k < toolbars.length; k++) {
954
                                        ActionTool[] tools = toolbars[k].getActionTool();
955

    
956
                                        for (int t = 0; t < tools.length; t++) {
957
                                                SortableTool stb=new SortableTool(ps.getClassLoader(), skinExt,
958
                                                                toolbars[k], tools[t]);
959
                                                orderedTools.put(stb,null);
960
                                        }
961

    
962
                                        SelectableTool[] sTools = toolbars[k].getSelectableTool();
963

    
964
                                        for (int t = 0; t < sTools.length; t++) {
965
                                                SortableTool stb=new SortableTool(ps.getClassLoader(), skinExt,
966
                                                                toolbars[k], sTools[t]);
967
                                                orderedTools.put(stb,null);
968
                                        }
969
                                }
970
                        }
971
                        // Install popup menus
972
                        PopupMenus pus = pc.getPopupMenus();
973

    
974
                        if (pus != null) {
975
                                PopupMenu[] menus = pus.getPopupMenu();
976

    
977
                                for (int j = 0; j < menus.length; j++) {
978
                                        frame.addPopupMenu(ps.getClassLoader(), menus[j]);
979
                                }
980
                        }
981
                }
982

    
983
                // loop on the ordered extension list, to add them to the interface in an ordered way
984
                Iterator t = orderedTools.keySet().iterator();
985
                while (t.hasNext()) {
986
                        try {
987
                                SortableTool stb = (SortableTool) t.next();
988
                                if (stb.actiontool!=null)
989
                                        frame.addTool(stb.loader, stb.extension,stb.toolbar, stb.actiontool);
990
                                else
991
                                        frame.addTool(stb.loader, stb.extension,stb.toolbar, stb.selectabletool);
992
                        } catch (ClassNotFoundException ex) {
993
                                logger.error(Messages.getString(
994
                                "Launcher.No_se_encontro_la_clase_de_la_extension"), ex);
995
                        }
996
                }
997
        }
998

    
999
        /**
1000
         * Adds new plugins to the the andami-config file.
1001
         */
1002
        private static void updateAndamiConfig() {
1003
                HashSet olds = new HashSet();
1004

    
1005
                Plugin[] plugins = andamiConfig.getPlugin();
1006

    
1007
                for (int i = 0; i < plugins.length; i++) {
1008
                        olds.add(plugins[i].getName());
1009
                }
1010

    
1011
                Iterator i = pluginsServices.values().iterator();
1012

    
1013
                while (i.hasNext()) {
1014
                        PluginServices ps = (PluginServices) i.next();
1015

    
1016
                        if (!olds.contains(ps.getPluginName())) {
1017
                                Plugin p = new Plugin();
1018
                                p.setName(ps.getPluginName());
1019
                                p.setUpdate(false);
1020

    
1021
                                andamiConfig.addPlugin(p);
1022
                        }
1023
                }
1024
        }
1025

    
1026
        /**
1027
         * DOCUMENT ME!
1028
         */
1029
        private static void pluginsClassLoaders() {
1030
                HashSet instalados = new HashSet();
1031

    
1032
                // Se itera hasta que est?n todos instalados
1033
                while (instalados.size() != pluginsConfig.size()) {
1034
                        boolean circle = true;
1035

    
1036
                        //Hacemos una pasada por todos los plugins
1037
                        Iterator i = pluginsConfig.keySet().iterator();
1038

    
1039
                        while (i.hasNext()) {
1040
                                String pluginName = (String) i.next();
1041
                                PluginConfig config = (PluginConfig) pluginsConfig.get(pluginName);
1042

    
1043
                                if (instalados.contains(pluginName)) {
1044
                                        continue;
1045
                                }
1046

    
1047
                                //Se obtienen las dependencias y sus class loaders
1048
                                boolean ready = true;
1049
                                Depends[] dependencies = config.getDepends();
1050
                                PluginClassLoader[] loaders = new PluginClassLoader[dependencies.length];
1051

    
1052
                                for (int j = 0; j < dependencies.length; j++) {
1053
                                        if (pluginsConfig.get(dependencies[j].getPluginName()) == null) {
1054
                                                logger.error(Messages.getString(
1055
                                                                "Launcher.Dependencia_no_resuelta_en_plugin") +
1056
                                                        pluginName + ": " +
1057
                                                        dependencies[j].getPluginName());
1058

    
1059
                                                continue;
1060
                                        }
1061

    
1062
                                        if (!instalados.contains(dependencies[j].getPluginName())) {
1063
                                                ready = false;
1064
                                        } else {
1065
                                                loaders[j] = ((PluginServices) pluginsServices.get(dependencies[j].getPluginName())).getClassLoader();
1066
                                        }
1067
                                }
1068

    
1069
                                //Si no est?n sus dependencias satisfechas se aborta la instalaci?n
1070
                                if (!ready) {
1071
                                        continue;
1072
                                }
1073

    
1074
                                //Se genera el class loader
1075
                                String jardir = config.getLibraries().getLibraryDir();
1076
                                File jarDir = new File(andamiConfig.getPluginsDirectory() +
1077
                                                File.separator + pluginName + File.separator + jardir);
1078
                                File[] jarFiles = jarDir.listFiles(new FileFilter() {
1079
                                                        public boolean accept(File pathname) {
1080
                                                                return (pathname.getName().toUpperCase()
1081
                                                                                                .endsWith(".JAR")) ||
1082
                                                                (pathname.getName().toUpperCase().endsWith(".ZIP"));
1083
                                                        }
1084
                                                });
1085

    
1086
                                URL[] urls = new URL[jarFiles.length];
1087

    
1088
                                for (int j = 0; j < jarFiles.length; j++) {
1089
                                        try {
1090
                                                urls[j] = new URL("file:" + jarFiles[j]);
1091
                                        } catch (MalformedURLException e) {
1092
                                                logger.error(Messages.getString(
1093
                                                                "Launcher.No_se_puede_acceder_a") +
1094
                                                        jarFiles[j]);
1095
                                        }
1096
                                }
1097

    
1098
                                PluginClassLoader loader;
1099

    
1100
                                try {
1101
                                        loader = new PluginClassLoader(urls,
1102
                                                        andamiConfig.getPluginsDirectory() +
1103
                                                        File.separator + pluginName,
1104
                                                        Launcher.class.getClassLoader(), loaders);
1105

    
1106
                                        PluginServices ps = new PluginServices(loader);
1107

    
1108
                                        pluginsServices.put(ps.getPluginName(), ps);
1109

    
1110
                                        instalados.add(pluginName);
1111
                    // FJP: Los metemos ordenados para luego no cargar uno que necesita de otro antes de tiempo. Esto lo usaremos al
1112
                    // inicializar los plugins
1113
                    pluginsOrdered.add(pluginName);
1114

    
1115
                                        circle = false;
1116
                                } catch (IOException e) {
1117
                                        logger.error(Messages.getString(
1118
                                                        "Launcher.Error_con_las_librerias_del_plugin"), e);
1119
                                        pluginsConfig.remove(pluginName);
1120
                                        i = pluginsConfig.keySet().iterator();
1121
                                }
1122
                        }
1123

    
1124
                        if (circle) {
1125
                                logger.error(Messages.getString(
1126
                                                "Launcher.Hay_dependencias_circulares"));
1127

    
1128
                                break;
1129
                        }
1130
                }
1131

    
1132
                //Se eliminan los plugins que no fueron instalados
1133
                Iterator i = pluginsConfig.keySet().iterator();
1134

    
1135
                while (i.hasNext()) {
1136
                        String pluginName = (String) i.next();
1137
                        PluginConfig config = (PluginConfig) pluginsConfig.get(pluginName);
1138
                        PluginServices ps = (PluginServices) pluginsServices.get(pluginName);
1139

    
1140
                        if (ps == null) {
1141
                                pluginsConfig.remove(pluginName);
1142
                                i = pluginsConfig.keySet().iterator();
1143
                        }
1144
                }
1145
        }
1146

    
1147
        /**
1148
         * DOCUMENT ME!
1149
         */
1150
        private static void pluginsMessages() {
1151
                /* add gvsig translations first. This should be done using a generic "appPlugin" variable, instead
1152
                 * of using "com.iver.cit.gvsig" directly, but I'll do it when we use the new appgvSIG launcher.
1153
                 * I keep this workaround for the moment.
1154
                 */
1155
                PluginConfig config = (PluginConfig) pluginsConfig.get("com.iver.cit.gvsig");
1156
                PluginServices ps = (PluginServices) pluginsServices.get("com.iver.cit.gvsig");
1157
                if (config.getResourceBundle() != null) {
1158
                        org.gvsig.i18n.Messages.addResourceFamily(config.getResourceBundle().getName(), ps.getClassLoader(), "com.iver.cit.gvsig");
1159
                }
1160

    
1161
                //Iteramos por todos los plugins
1162
                Iterator i = pluginsConfig.keySet().iterator();
1163

    
1164
                while (i.hasNext()) {
1165
                        String pluginName = (String) i.next();
1166
                        if (!pluginName.equals("com.iver.cit.gvsig")) { // we've already loaded com.iver.cit.gvsig
1167
                                config = (PluginConfig) pluginsConfig.get(pluginName);
1168
                                ps = (PluginServices) pluginsServices.get(pluginName);
1169

    
1170
                                if (config.getResourceBundle() != null && !config.getResourceBundle().getName().equals("")) {
1171
                                        // add the locale files associated with the plugin
1172
                                        org.gvsig.i18n.Messages.addResourceFamily(config.getResourceBundle().getName(), ps.getClassLoader(), pluginName);
1173
                                }
1174
                        }
1175
                }
1176
        }
1177

    
1178
        /**
1179
         * DOCUMENT ME!
1180
         *
1181
         * @param name DOCUMENT ME!
1182
         *
1183
         * @return DOCUMENT ME!
1184
         */
1185
        static PluginServices getPluginServices(String name) {
1186
                return (PluginServices) pluginsServices.get(name);
1187
        }
1188

    
1189
        /**
1190
         * DOCUMENT ME!
1191
         *
1192
         * @return DOCUMENT ME!
1193
         */
1194
        static String getPluginsDir() {
1195
                return andamiConfig.getPluginsDirectory();
1196
        }
1197

    
1198
        /**
1199
         * DOCUMENT ME!
1200
         *
1201
         * @param s DOCUMENT ME!
1202
         */
1203
        static void setPluginsDir(String s) {
1204
                andamiConfig.setPluginsDirectory(s);
1205
        }
1206

    
1207
        /**
1208
         * DOCUMENT ME!
1209
         *
1210
         * @return DOCUMENT ME!
1211
         */
1212
        static MDIFrame getMDIFrame() {
1213
                return frame;
1214
        }
1215

    
1216
        /**
1217
         * DOCUMENT ME!
1218
         *
1219
         * @param pluginsDirectory
1220
         */
1221
        private static void loadPlugins(String pluginsDirectory) {
1222
                File pDir = new File(pluginsDirectory);
1223

    
1224
                if (!pDir.exists()) {
1225
                        return;
1226
                }
1227

    
1228
                File[] pluginDirs = pDir.listFiles();
1229

    
1230
                for (int i = 0; i < pluginDirs.length; i++) {
1231
                        if (pluginDirs[i].isDirectory()) {
1232
                                File configXml = new File(pluginDirs[i].getAbsolutePath() +
1233
                                                File.separator + "config.xml");
1234

    
1235
                                try {
1236
                                        FileInputStream is = new FileInputStream(configXml);
1237
                                        Reader xml = com.iver.utiles.xml.XMLEncodingUtils.getReader(is);
1238
                                        if (xml==null) {
1239
                                                // the encoding was not correctly detected, use system default
1240
                                                xml = new FileReader(configXml);
1241
                                        }
1242
                                        else {
1243
                                                // use a buffered reader to improve performance
1244
                                                xml = new BufferedReader(xml);
1245
                                        }
1246
                                        PluginConfig pConfig = (PluginConfig) PluginConfig.unmarshal(xml);
1247
                                        pluginsConfig.put(pluginDirs[i].getName(), pConfig);
1248
                                } catch (FileNotFoundException e) {
1249
                                        logger.info(Messages.getString(
1250
                                                        "Launcher.Ignorando_el_directorio") +
1251
                                                pluginDirs[i].getAbsolutePath() +
1252
                                                Messages.getString("Launcher.config_no_encontrado"));
1253
                                } catch (MarshalException e) {
1254
                                        logger.info(Messages.getString(
1255
                                                        "Launcher.Ignorando_el_directorio") +
1256
                                                pluginDirs[i].getAbsolutePath() +
1257
                                                Messages.getString("Launcher.config_mal_formado"), e);
1258
                                } catch (ValidationException e) {
1259
                                        logger.info(Messages.getString(
1260
                                                        "Launcher.Ignorando_el_directorio") +
1261
                                                pluginDirs[i].getAbsolutePath() +
1262
                                                Messages.getString("Launcher.config_mal_formado"), e);
1263
                                }
1264
                        }
1265
                }
1266
        }
1267

    
1268
        /**
1269
         * DOCUMENT ME!
1270
         *
1271
         * @param language
1272
         * @param country
1273
         * @param variant
1274
         *
1275
         * @return DOCUMENT ME!
1276
         */
1277
        private static Locale getLocale(String language, String country,
1278
                String variant) {
1279
                if (variant != null) {
1280
                        return new Locale(language, country, variant);
1281
                } else if (country != null) {
1282
                        return new Locale(language, country);
1283
                } else if (language != null) {
1284
                        return new Locale(language);
1285
                } else {
1286
                        return new Locale("es");
1287
                }
1288
        }
1289

    
1290
        /**
1291
         * DOCUMENT ME!
1292
         *
1293
         * @param file DOCUMENT ME!
1294
         *
1295
         * @throws IOException DOCUMENT ME!
1296
         * @throws MarshalException DOCUMENT ME!
1297
         * @throws ValidationException DOCUMENT ME!
1298
         */
1299
        private static void andamiConfigToXML(String file)
1300
                throws IOException, MarshalException, ValidationException {
1301
                File xml = new File(file);
1302
                File parent = xml.getParentFile();
1303
                parent.mkdirs();
1304

    
1305
                FileWriter writer = new FileWriter(xml);
1306
                andamiConfig.marshal(writer);
1307
        }
1308

    
1309
        /**
1310
         * DOCUMENT ME!
1311
         *
1312
         * @param file DOCUMENT ME!
1313
         *
1314
         * @throws ConfigurationException DOCUMENT ME!
1315
         */
1316
        private static void andamiConfigFromXML(String file)
1317
                throws ConfigurationException {
1318
                File xml = new File(file);
1319

    
1320
                //Si no existe se ponen los valores por defecto
1321
                if (!xml.exists()) {
1322
                        andamiConfig = new AndamiConfig();
1323

    
1324
                        Andami andami = new Andami();
1325
                        andami.setUpdate(true);
1326
                        andamiConfig.setAndami(andami);
1327
                        andamiConfig.setLocaleCountry(Locale.getDefault().getCountry());
1328
                        andamiConfig.setLocaleLanguage(Locale.getDefault().getLanguage());
1329
                        andamiConfig.setLocaleVariant(Locale.getDefault().getVariant());
1330

    
1331
                        if (System.getProperty("javawebstart.version") != null) // Es java web start)
1332
                         {
1333
                                andamiConfig.setPluginsDirectory(new File(appHomeDir
1334
                                                + "extensiones").getAbsolutePath());
1335
                        } else {
1336
                                andamiConfig.setPluginsDirectory(new File(appName +
1337
                                                File.separator + "extensiones").getAbsolutePath());
1338
                        }
1339

    
1340
                        andamiConfig.setPlugin(new Plugin[0]);
1341
                } else {
1342
                        //Se lee la configuraci?n
1343
                        FileReader reader;
1344

    
1345
                        try {
1346
                                reader = new FileReader(xml);
1347
                                andamiConfig = (AndamiConfig) AndamiConfig.unmarshal(reader);
1348
                        } catch (FileNotFoundException e) {
1349
                                throw new ConfigurationException(e);
1350
                        } catch (MarshalException e) {
1351
                                throw new ConfigurationException(e);
1352
                        } catch (ValidationException e) {
1353
                                throw new ConfigurationException(e);
1354
                        }
1355
                }
1356
        }
1357

    
1358
        /**
1359
         * DOCUMENT ME!
1360
         *
1361
         * @return DOCUMENT ME!
1362
         *
1363
         * @throws ConfigurationException DOCUMENT ME!
1364
         */
1365
        private static XMLEntity persistenceFromXML() throws ConfigurationException {
1366
                File xml = new File(pluginsPersistencePath);
1367

    
1368
                if (xml.exists()) {
1369
                        FileReader reader;
1370

    
1371
                        try {
1372
                                reader = new FileReader(xml);
1373

    
1374
                                XmlTag tag = (XmlTag) XmlTag.unmarshal(reader);
1375

    
1376
                                return new XMLEntity(tag);
1377
                        } catch (FileNotFoundException e) {
1378
                                throw new ConfigurationException(e);
1379
                        } catch (MarshalException e) {
1380
                                throw new ConfigurationException(e);
1381
                        } catch (ValidationException e) {
1382
                                throw new ConfigurationException(e);
1383
                        }
1384
                } else {
1385
                        return new XMLEntity();
1386
                }
1387
        }
1388

    
1389
        /**
1390
         * DOCUMENT ME!
1391
         *
1392
         * @param entity DOCUMENT ME!
1393
         *
1394
         * @throws ConfigurationException DOCUMENT ME!
1395
         */
1396
        private static void persistenceToXML(XMLEntity entity)
1397
                throws ConfigurationException {
1398
                File xml = new File(pluginsPersistencePath);
1399

    
1400
                FileWriter writer;
1401

    
1402
                try {
1403
                        writer = new FileWriter(xml);
1404
                        entity.getXmlTag().marshal(writer);
1405
                } catch (FileNotFoundException e) {
1406
                        throw new ConfigurationException(e);
1407
                } catch (MarshalException e) {
1408
                        throw new ConfigurationException(e);
1409
                } catch (ValidationException e) {
1410
                        throw new ConfigurationException(e);
1411
                } catch (IOException e) {
1412
                        throw new ConfigurationException(e);
1413
                }
1414
        }
1415

    
1416
        /**
1417
         * Devuelve un array con los directorios de los plugins
1418
         *
1419
         * @param dirExt Directorio de las extensiones a partir del cual cuelgan
1420
         *                   todos los directorios de los plugins
1421
         *
1422
         * @return ArrayList con los directorios
1423
         */
1424
        private String[] getLocales(File dirExt) {
1425
                ArrayList types = new ArrayList();
1426
                File[] files = dirExt.listFiles();
1427

    
1428
                for (int i = 0; i < files.length; i++) {
1429
                        if (files[i].isDirectory()) {
1430
                                File[] textFile = files[i].listFiles(new FilenameFilter() {
1431
                                                        public boolean accept(File dir, String fileName) {
1432
                                                                return fileName.toLowerCase().startsWith("text_"); //$NON-NLS-1$
1433
                                                        }
1434
                                                });
1435

    
1436
                                for (int j = 0; j < textFile.length; j++) {
1437
                                        String s = (textFile[j]).getName().replaceAll("text_", "");
1438
                                        s = s.replaceAll(".properties", "");
1439
                                        s = s.trim();
1440

    
1441
                                        if (!types.contains(s)) {
1442
                                                types.add(s);
1443
                                        }
1444
                                }
1445
                        }
1446
                }
1447

    
1448
                return (String[]) types.toArray(new String[0]);
1449
        }
1450

    
1451
        /**
1452
         * DOCUMENT ME!
1453
         *
1454
         * @return Returns the frame.
1455
         */
1456
        static MDIFrame getFrame() {
1457
                return frame;
1458
        }
1459

    
1460
        /**
1461
         * Secuencia de cerrado de Andami
1462
         */
1463
        public static void closeApplication() {
1464
                //Configuraci?n de Andami
1465
                try {
1466
                        andamiConfigToXML(andamiConfigPath);
1467
                } catch (MarshalException e) {
1468
                        logger.error(Messages.getString(
1469
                                        "Launcher.No_se_pudo_guardar_la_configuracion_de_andami"), e);
1470
                } catch (ValidationException e) {
1471
                        logger.error(Messages.getString(
1472
                                        "Launcher.No_se_pudo_guardar_la_configuracion_de_andami"), e);
1473
                } catch (IOException e) {
1474
                        logger.error(Messages.getString(
1475
                                        "Launcher.No_se_pudo_guardar_la_configuracion_de_andami"), e);
1476
                }
1477

    
1478
                //Persistencia de los plugins
1479
                savePluginPersistence();
1480

    
1481
                //Finalize all the extensions
1482
                finalizeExtensions();
1483

    
1484
                // Clean any temp data created
1485
                Utilities.cleanUpTempFiles();
1486

    
1487
                //Para la depuraci?n de memory leaks
1488
                System.gc();
1489

    
1490
        System.exit(0);
1491
        }
1492

    
1493
        /**
1494
         * Exectutes the terminate method for all the extensions, in the reverse
1495
         * order they were initialized
1496
         *
1497
         */
1498
        private static void finalizeExtensions() {
1499
                for (int i=extensions.size()-1; i>=0; i--) {
1500
                        com.iver.andami.plugins.IExtension extensionInstance=(com.iver.andami.plugins.IExtension)extensions.get(i);
1501
                        extensionInstance.terminate();
1502
                }
1503
        }
1504

    
1505

    
1506
        /**
1507
         * DOCUMENT ME!
1508
         *
1509
         * @return DOCUMENT ME!
1510
         */
1511
        static HashMap getClassesExtensions() {
1512
                return classesExtensions;
1513
        }
1514

    
1515
        /**
1516
         * DOCUMENT ME!
1517
         *
1518
         * @param extDir DOCUMENT ME!
1519
         */
1520
        private static void downloadExtensions(String extDir) {
1521
                java.util.Date fechaActual = null;
1522

    
1523
                try {
1524
                        if (System.getProperty("javawebstart.version") != null) {
1525
                                //Obtenemos la URL del servidor
1526
                                BasicService bs = (BasicService) ServiceManager.lookup(
1527
                                                "javax.jnlp.BasicService");
1528
                                URL baseURL = bs.getCodeBase();
1529

    
1530
                                //Se descargan las extensiones
1531
                                MultiSplashWindow.process(5,
1532
                                        "Descargando las extensiones desde " + baseURL + " a " +
1533
                                        extDir);
1534

    
1535
                                URL url = new URL(baseURL + "extensiones.zip");
1536
                                URLConnection connection = url.openConnection();
1537

    
1538
                                System.out.println(url.toExternalForm() + ":");
1539
                                System.out.println("  Content Type: " +
1540
                                        connection.getContentType());
1541
                                System.out.println("  Content Length: " +
1542
                                        connection.getContentLength());
1543
                                System.out.println("  Last Modified: " +
1544
                                        new Date(connection.getLastModified()));
1545
                                System.out.println("  Expiration: " +
1546
                                        connection.getExpiration());
1547
                                System.out.println("  Content Encoding: " +
1548
                                        connection.getContentEncoding());
1549

    
1550
                                // Guardamos la fecha del fichero de extensiones que nos hemos bajado, y
1551
                                // comprobamos el ?ltimo que se ha bajado. Si no son
1552
                                // iguales, nos bajamos el nuevo. Si son iguales, no
1553
                                // nos bajamos nada.
1554
                                Long miliSecondsInWeb = new Long(connection.getLastModified());
1555

    
1556
                                // PluginServices ps = PluginServices.getPluginServices("com.iver.core");
1557
                                // if (ps.getPersistentXML().getStringProperty("timestamp") != null)
1558
                                File destDir = new File(extDir);
1559

    
1560
                                if (!destDir.exists()) {
1561
                                        // Creamos gvSIG
1562
                                        destDir.getParentFile().mkdir();
1563

    
1564
                                        if (!destDir.mkdir()) {
1565
                                                System.err.println("Imposible crear el directorio " +
1566
                                                        destDir.getAbsolutePath());
1567
                                        }
1568
                                }
1569

    
1570
                                File timeFile = new File(destDir.getParent() + File.separator +
1571
                                                "timeStamp.properties");
1572

    
1573
                                if (!timeFile.exists()) {
1574
                                        timeFile.createNewFile();
1575
                                }
1576

    
1577
                                FileInputStream inAux = new FileInputStream(timeFile);
1578
                                Properties prop = new Properties();
1579
                                prop.load(inAux);
1580
                                inAux.close();
1581

    
1582
                                if (prop.getProperty("timestamp") != null) {
1583
                                        Long lastMiliSeconds = (Long) new Long(prop.getProperty(
1584
                                                                "timestamp"));
1585

    
1586
                                        if (lastMiliSeconds.longValue() == miliSecondsInWeb.longValue()) {
1587
                                                System.out.println("No hay nueva actualizaci?n");
1588
                        logger.debug("No hay nueva actualizaci?n -> Return");
1589
                        logger.debug("timeStampWeb= " + miliSecondsInWeb);
1590
                        logger.debug("timeStampLocal= " + lastMiliSeconds);
1591

    
1592
                                                return;
1593
                                        }
1594

    
1595
                                        System.out.println("timeStampWeb= " + miliSecondsInWeb);
1596
                                        System.out.println("timeStampLocal= " + lastMiliSeconds);
1597
                                } else {
1598
                                        System.out.println("El timeStamp no est? escrito en " +
1599
                                                timeFile.getAbsolutePath());
1600
                                }
1601

    
1602
                                InputStream stream = url.openStream();
1603
                File temp = File.createTempFile("gvsig", ".zip");
1604

    
1605
                logger.debug(temp.getAbsolutePath());
1606

    
1607
                temp.deleteOnExit();
1608
                FileOutputStream file = new FileOutputStream(temp);
1609

    
1610
                byte[] lt_read = new byte[1];
1611

    
1612
                while (stream.read(lt_read) > 0)
1613
                  file.write(lt_read);
1614

    
1615
                                stream.close();
1616
                stream = null;
1617
                file.close();
1618
                file = null;
1619

    
1620
                System.gc();
1621

    
1622
                logger.debug("Ha creado el fichero ZIP");
1623
                                //Se extrae el zip
1624
                                MultiSplashWindow.process(5, "Extensiones descargadas.");
1625

    
1626
                                System.out.println("Extrayendo a " + destDir.getAbsolutePath());
1627

    
1628
                                Date fechaDir = new Date(destDir.lastModified());
1629
                                System.out.println("Fecha del directorio " + extDir + " = " +
1630
                                        fechaDir.toString());
1631
                                Utilities.extractTo(temp, new File(extDir), splashWindow);
1632

    
1633
                                // Si todo ha ido bien, guardamos el timestamp.
1634
                                ///  App.instance.getPc().addProperties("timestamp", miliSecondsInWeb);
1635
                                // XMLEntity xml=ps.getPersistentXML();
1636
                                fechaActual = new java.util.Date();
1637

    
1638
                                FileOutputStream outAux = new FileOutputStream(timeFile);
1639
                                prop.setProperty("timestamp", miliSecondsInWeb.toString());
1640
                                prop.store(outAux, "last download");
1641
                                outAux.close();
1642
                                System.out.println("Fecha actual guardada: " +
1643
                                        fechaActual.toGMTString());
1644

    
1645
                                /* xml.putProperty("timestamp",fechaActual.toGMTString());
1646
                                   ps.setPresistentXML(xml); */
1647
                        }
1648
                } catch (IOException e) {
1649
                        NotificationManager.addError("", e);
1650
                } catch (UnavailableServiceException e) {
1651
                        NotificationManager.addError("", e);
1652
                } catch (SecurityException e) {
1653
                        System.err.println("No se puede escribir el timeStamp " +
1654
                                fechaActual.toGMTString());
1655
                        NotificationManager.addError("", e);
1656
                }
1657
        }
1658

    
1659
        /**
1660
         * DOCUMENT ME!
1661
         *
1662
         * @return DOCUMENT ME!
1663
         */
1664
        private static Extensions[] getExtensions() {
1665
                ArrayList array = new ArrayList();
1666
                Iterator iter = pluginsConfig.values().iterator();
1667

    
1668
                while (iter.hasNext()) {
1669
                        array.add(((PluginConfig) iter.next()).getExtensions());
1670
                }
1671

    
1672
                return (Extensions[]) array.toArray(new Extensions[0]);
1673
        }
1674

    
1675
        /**
1676
         * DOCUMENT ME!
1677
         *
1678
         * @return DOCUMENT ME!
1679
         */
1680
        public static HashMap getPluginConfig() {
1681
                return pluginsConfig;
1682
        }
1683

    
1684
        /**
1685
         * DOCUMENT ME!
1686
         *
1687
         * @param s DOCUMENT ME!
1688
         *
1689
         * @return DOCUMENT ME!
1690
         */
1691
        public static Extension getExtension(String s) {
1692
                Extensions[] exts = getExtensions();
1693

    
1694
                for (int i = 0; i < exts.length; i++) {
1695
                        for (int j = 0; j < exts[i].getExtensionCount(); j++) {
1696
                                if (exts[i].getExtension(j).getClassName().equals(s)) {
1697
                                        return exts[i].getExtension(j);
1698
                                }
1699
                        }
1700
                }
1701

    
1702
                return null;
1703
        }
1704

    
1705
        /**
1706
         * DOCUMENT ME!
1707
         *
1708
         * @return DOCUMENT ME!
1709
         */
1710
        public static AndamiConfig getAndamiConfig() {
1711
                return andamiConfig;
1712
        }
1713

    
1714
        /**
1715
         * DOCUMENT ME!
1716
         *
1717
         * @author $author$
1718
         * @version $Revision: 9956 $
1719
         */
1720
        private static class ExtensionComparator implements Comparator {
1721
                /**
1722
                 * DOCUMENT ME!
1723
                 *
1724
                 * @param o1 DOCUMENT ME!
1725
                 * @param o2 DOCUMENT ME!
1726
                 *
1727
                 * @return DOCUMENT ME!
1728
                 */
1729
                public int compare(Object o1, Object o2) {
1730
                        Extension e1 = (Extension) o1;
1731
                        Extension e2 = (Extension) o2;
1732

    
1733
                        if (!e1.hasPriority() && !e2.hasPriority()) {
1734
                                return -1;
1735
                        }
1736

    
1737
                        if (e1.hasPriority() && !e2.hasPriority()) {
1738
                                return Integer.MIN_VALUE;
1739
                        }
1740

    
1741
                        if (e2.hasPriority() && !e1.hasPriority()) {
1742
                                return Integer.MAX_VALUE;
1743
                        }
1744

    
1745
                        if (e1.getPriority() != e2.getPriority()){
1746
                                return e2.getPriority() - e1.getPriority();
1747
                        }else{
1748
                                return (e2.toString().compareTo(e1.toString()));
1749
                        }
1750
                }
1751
        }
1752

    
1753
        /**
1754
         * DOCUMENT ME!
1755
         */
1756
        private static class MenuComparator implements Comparator {
1757
                private static ExtensionComparator extComp = new ExtensionComparator();
1758

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

    
1771
                        if (!e1.menu.hasPosition() && !e2.menu.hasPosition()) {
1772
                                if (e1.extension instanceof SkinExtensionType) {
1773
                                        return 1;
1774
                                } else if (e2.extension instanceof SkinExtensionType) {
1775
                                        return -1;
1776
                                } else {
1777
                                        return extComp.compare(e1.extension, e2.extension);
1778
                                }
1779
                        }
1780

    
1781
                        if (e1.menu.hasPosition() && !e2.menu.hasPosition()) {
1782
                                return Integer.MIN_VALUE;
1783
                        }
1784

    
1785
                        if (e2.menu.hasPosition() && !e1.menu.hasPosition()) {
1786
                                return Integer.MAX_VALUE;
1787
                        }
1788
                        if (e1.menu.getPosition() != e2.menu.getPosition()){
1789
                                //we don't return 0 unless both objects are the same, otherwise the objects get overwritten in the treemap
1790
                                return e1.menu.getPosition() - e2.menu.getPosition();
1791
                        }else{
1792
                                return (e1.toString().compareTo(e2.toString()));
1793
                        }
1794
                }
1795
        }
1796

    
1797
        /**
1798
         * DOCUMENT ME!
1799
         *
1800
         * @author $author$
1801
         * @version $Revision: 9956 $
1802
         */
1803
        private static class SortableMenu {
1804
                public PluginClassLoader loader;
1805
                public Menu menu;
1806
                public SkinExtensionType extension;
1807

    
1808
                /**
1809
                 * DOCUMENT ME!
1810
                 *
1811
                 * @param loader DOCUMENT ME!
1812
                 * @param skinExt
1813
                 * @param menu2
1814
                 */
1815
                public SortableMenu(PluginClassLoader loader,
1816
                        SkinExtensionType skinExt, Menu menu2) {
1817
                        extension = skinExt;
1818
                        menu = menu2;
1819
                        this.loader = loader;
1820
                }
1821
        }
1822
        /**
1823
         * DOCUMENT ME!
1824
         */
1825
        private static class SortableTool {
1826
                public PluginClassLoader loader;
1827
                public ToolBar toolbar;
1828
                public ActionTool actiontool;
1829
                public SelectableTool selectabletool;
1830
                public SkinExtensionType extension;
1831

    
1832
                /**
1833
                 * DOCUMENT ME!
1834
                 *
1835
                 * @param loader DOCUMENT ME!
1836
                 * @param skinExt
1837
                 * @param menu2
1838
                 */
1839
                public SortableTool(PluginClassLoader loader,
1840
                        SkinExtensionType skinExt, ToolBar toolbar2,ActionTool actiontool2) {
1841
                        extension = skinExt;
1842
                        toolbar = toolbar2;
1843
                        actiontool=actiontool2;
1844
                        this.loader = loader;
1845
                }
1846
                public SortableTool(PluginClassLoader loader,
1847
                                SkinExtensionType skinExt, ToolBar toolbar2,SelectableTool selectabletool2) {
1848
                        extension = skinExt;
1849
                        toolbar = toolbar2;
1850
                        selectabletool=selectabletool2;
1851
                        this.loader = loader;
1852
                }
1853
        }
1854
        /**
1855
         * DOCUMENT ME!
1856
         */
1857
        private static class ToolBarComparator implements Comparator {
1858
                private static ExtensionComparator extComp = new ExtensionComparator();
1859

    
1860
                /**
1861
                 * DOCUMENT ME!
1862
                 *
1863
                 * @param o1 DOCUMENT ME!
1864
                 * @param o2 DOCUMENT ME!
1865
                 *
1866
                 * @return DOCUMENT ME!
1867
                 */
1868
                public int compare(Object o1, Object o2) {
1869
                        SortableTool e1 = (SortableTool) o1;
1870
                        SortableTool e2 = (SortableTool) o2;
1871

    
1872
                        // if the toolbars have the same name, they are considered to be
1873
                        // the same toolbar, so we don't need to do further comparing
1874
                        if (e1.toolbar.getName().equals(e2.toolbar.getName()))
1875
                                return 0;
1876

    
1877
                        if (!e1.toolbar.hasPosition() && !e2.toolbar.hasPosition()) {
1878
                                if (e1.extension instanceof SkinExtensionType) {
1879
                                        return 1;
1880
                                } else if (e2.extension instanceof SkinExtensionType) {
1881
                                        return -1;
1882
                                } else {
1883
                                        return extComp.compare(e1.extension, e2.extension);
1884
                                }
1885
                        }
1886

    
1887
                        if (e1.toolbar.hasPosition() && !e2.toolbar.hasPosition()) {
1888
                                return Integer.MIN_VALUE;
1889
                        }
1890

    
1891
                        if (e2.toolbar.hasPosition() && !e1.toolbar.hasPosition()) {
1892
                                return Integer.MAX_VALUE;
1893
                        }
1894
                        if (e1.toolbar.getPosition() != e2.toolbar.getPosition())
1895
                                return e1.toolbar.getPosition() - e2.toolbar.getPosition();
1896

    
1897
                        if (e1.toolbar.getActionTool().equals(e2.toolbar.getActionTool()) && e1.toolbar.getSelectableTool().equals(e2.toolbar.getSelectableTool())){
1898
                                return 0;
1899
                        }
1900
                        return (e1.toolbar.toString().compareTo(e2.toolbar.toString()));
1901
                }
1902
        }
1903

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

    
1942
                        if (e1.actiontool!=null) {
1943
                                if (e1.actiontool.hasPosition())
1944
                                        e1Position = e1.actiontool.getPosition();
1945
                        }
1946
                        else if (e1.selectabletool!=null) {
1947
                                if (e1.selectabletool.hasPosition())
1948
                                        e1Position = e1.selectabletool.getPosition();
1949
                        }
1950

    
1951
                        if (e2.actiontool!=null) {
1952
                                if (e2.actiontool.hasPosition())
1953
                                        e2Position = e2.actiontool.getPosition();
1954
                        }
1955
                        else if (e2.selectabletool!=null){
1956
                                if (e2.selectabletool.hasPosition())
1957
                                        e2Position = e2.selectabletool.getPosition();
1958
                        }
1959

    
1960
                        if (e1Position==-1 && e2Position!=-1) {
1961
                                return 1;
1962
                        }
1963
                        if (e1Position!=-1 && e2Position==-1) {
1964
                                return -1;
1965
                        }
1966
                        if (e1Position!=-1 && e2Position!=-1) {
1967
                                result = e1Position - e2Position;
1968
                                // we don't return 0 unless both objects are the same, otherwise the objects get overwritten in the treemap
1969
                                if (result!=0) return result;
1970
                        }
1971
                        return e1.toString().compareTo(e2.toString());
1972
                }
1973
        }
1974

    
1975

    
1976
        /**
1977
         * validates the user before starting gvsig
1978
         *
1979
         */
1980
        private static void validate(){
1981

    
1982
                IAuthentication session =  null;
1983
                try {
1984
                        session = (IAuthentication)Class.forName("com.iver.andami.authentication.Session").newInstance();
1985

    
1986
                } catch (ClassNotFoundException e) {
1987
                        // TODO Auto-generated catch block
1988
                        //e.printStackTrace();
1989
                        return;
1990
                } catch (InstantiationException e) {
1991
                        // TODO Auto-generated catch block
1992
                        //e.printStackTrace();
1993
                        return;
1994
                } catch (IllegalAccessException e) {
1995
                        // TODO Auto-generated catch block
1996
                        //e.printStackTrace();
1997
                        return;
1998
                }
1999

    
2000
                session.setPluginDirectory( andamiConfig.getPluginsDirectory() );
2001
                if (session.validationRequired()){
2002
                        if(session.Login()){
2003
                                System.out.println("You are logged in");
2004
                        }
2005
                        else{
2006
                                JOptionPane.showMessageDialog((Component)PluginServices.getMainFrame(),
2007
                                                 "You are not logged in");
2008
                                //System.exit(0);
2009
                        }
2010
                        PluginServices.setAuthentication(session);
2011
                }
2012
        }
2013

    
2014
        public static String getDefaultLookAndFeel() {
2015
                String osName = (String) System.getProperty("os.name");
2016

    
2017
                if (osName.length() > 4 && osName.substring(0,5).toLowerCase().equals("linux"))
2018
                        return nonWinDefaultLookAndFeel;
2019

    
2020
                return UIManager.getSystemLookAndFeelClassName();
2021
        }
2022

    
2023
        /**
2024
         * Gets the ISO 839 two-characters-long language code matching the
2025
         * provided language code (which may be an ISO 839-2/T
2026
         * three-characters-long code or an ISO 839-1 two-characters-long
2027
         * code).
2028
         *
2029
         * If the provided parameter is already two characters long, it
2030
         * returns the parameter without any modification.
2031
         *
2032
         * @param langCode A language code representing either
2033
         *  an ISO 839-2/T language code or an ISO 839-1 code.
2034
         * @return A two-characters-long code specifying
2035
         *  an ISO 839 language code.
2036
         */
2037
        private static String normalizeLanguageCode(String langCode) {
2038
                final String fileName = "iso_639.tab";
2039
                if (langCode.length()==2)
2040
                        return langCode;
2041
                else if (langCode.length()==3) {
2042
                        if (langCode.equals("va") || langCode.equals("val")) { // special case for Valencian
2043
                                return "ca";
2044
                        }
2045
                        URL isoCodes = Launcher.class.getClassLoader().getResource(fileName);
2046
                        if (isoCodes!=null) {
2047
                                try {
2048
                                        BufferedReader reader =
2049
                                                new BufferedReader(new InputStreamReader(isoCodes.openStream(), "ISO-8859-1"));
2050
                                                String line;
2051

    
2052
                                                while ((line = reader.readLine()) != null) {
2053
                                                        String[] language = line.split("\t");
2054
                                                        if (language[0].equals(langCode)) // first column is the three characters code
2055
                                                                return language[2]; // third column i the two characters code
2056
                                                }
2057
                                }
2058
                                catch (IOException ex) {
2059
                                        logger.error(Messages.getString("Error_reading_isocodes_file"), ex);
2060
                                        return "es";
2061
                                }
2062
                        }
2063
                        else {
2064
                                logger.error(Messages.getString("Error_reading_isocodes_file"));
2065
                                return "es";
2066
                        }
2067
                }
2068
                return "es";
2069
        }
2070

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

    
2114
        }
2115

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

    
2127
        /**
2128
         * Sets Home Directory location of the application.
2129
         * May be set from outside the aplication by means of
2130
         * -DgvSIG.home=C:/data/gvSIG, where gvSIG its the name
2131
         * of the application
2132
         * @param appHomeDir
2133
         */
2134
        public static void setAppHomeDir(String appHomeDir) {
2135
                Launcher.appHomeDir = appHomeDir;
2136
        }
2137

    
2138
        /**
2139
         * Initialize the extesion that have to take the control
2140
         *  of the state of action controls of the UI of all extensions.
2141
         * <br>
2142
         * <br>
2143
         * For use this option you have to add an argument
2144
         * to the command line like this:
2145
         * <br>
2146
         * <br>
2147
         * -exclusiveUI={pathToExtensionClass}
2148
         * <br>
2149
         *  @see com.iver.andami.plugins.IExtension#isEnabled(IExtension extension)
2150
         *  @see com.iver.andami.plugins.IExtension#isVisible(IExtension extension)
2151
         */
2152
        private static void initializeExclusiveUIExtension(){
2153
                String name = PluginServices.getArgumentByName("exclusiveUI");
2154
                if (name == null)
2155
                        return;
2156

    
2157

    
2158
                Iterator iter  = classesExtensions.keySet().iterator();
2159
                int charIndex;
2160
                Class key;
2161
                while (iter.hasNext()) {
2162
                        key = (Class)iter.next();
2163
                        charIndex = key.getName().indexOf(name);
2164
                        //System.out.println("key='"+key.getName()+"' name='"+name+"' charIndex="+charIndex);
2165
                        if (charIndex == 0) {
2166
                                IExtension ext =(IExtension)classesExtensions.get(key);
2167
                                if (ext instanceof ExtensionDecorator)
2168
                                        ext = ((ExtensionDecorator)ext).getExtension();
2169
                                PluginServices.setExclusiveUIExtension(ext);
2170
                                break;
2171
                        }
2172
                }
2173

    
2174
                logger.error(Messages.getString("No_se_encontro_la_extension_especificada_en_el_parametro_exclusiveUI") + " '" + name +"'");
2175
        }
2176
}