Statistics
| Revision:

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

History | View | Annotate | Download (63.3 KB)

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

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

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

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

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

    
137

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

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

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

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

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

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

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

    
201
                    appName = args[0];
202

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

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

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

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

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

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

    
241
                    configureLocales(args);
242

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

    
264
                    validate();
265

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

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

    
273
                    // Ponemos los datos del proxy
274
                    configureProxy();
275

    
276
                    // TODO Buscar actualizaciones de los plugins
277
                    downloadExtensions(andamiConfig.getPluginsDirectory());
278

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

    
282
                    // Se configura el classloader del plugin
283
                    pluginsClassLoaders();
284

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

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

    
292
                    // Se configura la mensajer?a del plugin
293
                    pluginsMessages();
294

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

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

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

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

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

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

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

    
336
                    // Se instalan los bookmarks de los plugins
337

    
338
                    //Se muestra el frame principal
339
                    frame.show();
340

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

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

    
357
    }
358

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

    
389
                System.getProperties().put("http.proxyHost", host);
390
                System.getProperties().put("http.proxyPort", port);
391

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

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

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

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

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

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

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

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

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

    
497
                XMLEntity entity = new XMLEntity();
498

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

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

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

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

    
534
                        LabelSet[] ls = pc.getLabelSet();
535

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

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

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

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

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

    
569
                                SkinExtension se = pc.getExtensions().getSkinExtension();
570

    
571
                                MDIManagerFactory.setSkinExtension(se, ps.getClassLoader());
572

    
573
                                Class skinClass;
574

    
575
                                try {
576
                                        skinClass = ps.getClassLoader().loadClass(se.getClassName());
577

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

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

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

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

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

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

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

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

    
648
                        Extension[] exts = pc.getExtensions().getExtension();
649

    
650
                        TreeMap orderedExtensions = new TreeMap(new ExtensionComparator());
651

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

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

    
663
                                orderedExtensions.put(exts[j], null);
664
                        }
665

    
666
                        Iterator e = orderedExtensions.keySet().iterator();
667

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

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

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

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

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

    
726
                Iterator i = pluginsConfig.keySet().iterator();
727

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

    
733
                        Extension[] exts = pc.getExtensions().getExtension();
734

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

    
740
                                Menu[] menus = exts[j].getMenu();
741

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

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

    
752
                                        orderedMenus.put(sm, null);
753
                                }
754
                        }
755

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

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

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

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

    
772
                                        orderedMenus.put(sm, null);
773
                                }
774
                        }
775
                }
776

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

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

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

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

    
800
                HashMap extensionPluginServices = new HashMap();
801
                HashMap extensionPluginConfig = new HashMap();
802
                TreeMap orderedExtensions = new TreeMap(new ExtensionComparator());
803

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

    
812
                        Extension[] exts = pc.getExtensions().getExtension();
813

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

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

    
829
                TreeMap orderedTools = new TreeMap(new ToolComparator());
830
                Iterator e = orderedExtensions.keySet().iterator();
831

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

    
837
                        ToolBar[] toolbars = ext.getToolBar();
838

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

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

    
849
                                SelectableTool[] sTools = toolbars[k].getSelectableTool();
850

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

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

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

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

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

    
933
                        SkinExtension skinExt = pc.getExtensions().getSkinExtension();
934

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

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

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

    
947
                                        SelectableTool[] sTools = toolbars[k].getSelectableTool();
948

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

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

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

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

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

    
990
                Plugin[] plugins = andamiConfig.getPlugin();
991

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

    
996
                Iterator i = pluginsServices.values().iterator();
997

    
998
                while (i.hasNext()) {
999
                        PluginServices ps = (PluginServices) i.next();
1000

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

    
1006
                                andamiConfig.addPlugin(p);
1007
                        }
1008
                }
1009
        }
1010

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

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

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

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

    
1028
                                if (instalados.contains(pluginName)) {
1029
                                        continue;
1030
                                }
1031

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

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

    
1044
                                                continue;
1045
                                        }
1046

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

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

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

    
1071
                                URL[] urls = new URL[jarFiles.length];
1072

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

    
1083
                                PluginClassLoader loader;
1084

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

    
1091
                                        PluginServices ps = new PluginServices(loader);
1092

    
1093
                                        pluginsServices.put(ps.getPluginName(), ps);
1094

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

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

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

    
1113
                                break;
1114
                        }
1115
                }
1116

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

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

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

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

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

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

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

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

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

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

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

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

    
1209
                if (!pDir.exists()) {
1210
                        return;
1211
                }
1212

    
1213
                File[] pluginDirs = pDir.listFiles();
1214

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

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

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

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

    
1290
                FileWriter writer = new FileWriter(xml);
1291
                andamiConfig.marshal(writer);
1292
        }
1293

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

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

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

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

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

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

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

    
1353
                if (xml.exists()) {
1354
                        FileReader reader;
1355

    
1356
                        try {
1357
                                reader = new FileReader(xml);
1358

    
1359
                                XmlTag tag = (XmlTag) XmlTag.unmarshal(reader);
1360

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

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

    
1385
                FileWriter writer;
1386

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

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

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

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

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

    
1433
                return (String[]) types.toArray(new String[0]);
1434
        }
1435

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

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

    
1463
                //Persistencia de los plugins
1464
                savePluginPersistence();
1465

    
1466
                //Finalize all the extensions
1467
                finalizeExtensions();
1468

    
1469
                // Clean any temp data created
1470
                Utilities.cleanUpTempFiles();
1471

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

    
1475
        System.exit(0);
1476
        }
1477

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

    
1490

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

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

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

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

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

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

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

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

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

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

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

    
1558
                                if (!timeFile.exists()) {
1559
                                        timeFile.createNewFile();
1560
                                }
1561

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

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

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

    
1577
                                                return;
1578
                                        }
1579

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

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

    
1590
                logger.debug(temp.getAbsolutePath());
1591

    
1592
                temp.deleteOnExit();
1593
                FileOutputStream file = new FileOutputStream(temp);
1594

    
1595
                byte[] lt_read = new byte[1];
1596

    
1597
                while (stream.read(lt_read) > 0)
1598
                  file.write(lt_read);
1599

    
1600
                                stream.close();
1601
                stream = null;
1602
                file.close();
1603
                file = null;
1604

    
1605
                System.gc();
1606

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

    
1611
                                System.out.println("Extrayendo a " + destDir.getAbsolutePath());
1612

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

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

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

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

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

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

    
1657
                return (Extensions[]) array.toArray(new Extensions[0]);
1658
        }
1659

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

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

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

    
1687
                return null;
1688
        }
1689

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
1960

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

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

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

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

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

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

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

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

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

    
2095
        }
2096

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

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

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

    
2138

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

    
2155
                logger.error(Messages.getString("No_se_encontro_la_extension_especificada_en_el_parametro_exclusiveUI") + " '" + name +"'");
2156
        }
2157
}