Statistics
| Revision:

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

History | View | Annotate | Download (65.8 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.nio.channels.FileChannel;
70
import java.security.AllPermission;
71
import java.security.CodeSource;
72
import java.security.PermissionCollection;
73
import java.security.Permissions;
74
import java.security.Policy;
75
import java.util.ArrayList;
76
import java.util.Comparator;
77
import java.util.Date;
78
import java.util.HashMap;
79
import java.util.HashSet;
80
import java.util.Iterator;
81
import java.util.Locale;
82
import java.util.Properties;
83
import java.util.TreeMap;
84
import java.util.prefs.Preferences;
85

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

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

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

    
139

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

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

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

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

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

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

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

    
203
                    appName = args[0];
204

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

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

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

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

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

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

    
243
                    configureLocales(args);
244

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

    
266
                    validate();
267

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
338
                    // Se instalan los bookmarks de los plugins
339

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

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

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

    
359
    }
360

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

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

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

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

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

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

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

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

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

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

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

    
499
                XMLEntity entity = new XMLEntity();
500

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

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

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

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

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

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

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

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

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

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

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

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

    
575
                                Class skinClass;
576

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
1046
                                                continue;
1047
                                        }
1048

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

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

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

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

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

    
1085
                                PluginClassLoader loader;
1086

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

    
1093
                                        PluginServices ps = new PluginServices(loader);
1094

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

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

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

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

    
1115
                                break;
1116
                        }
1117
                }
1118

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
1277
        /**
1278
         * DOCUMENT ME!
1279
         *
1280
         * @param file DOCUMENT ME!
1281
         *
1282
         * @throws IOException DOCUMENT ME!
1283
         * @throws MarshalException DOCUMENT ME!
1284
         * @throws ValidationException DOCUMENT ME!
1285
         */
1286
        private static void andamiConfigToXML(String file)
1287
                throws IOException, MarshalException, ValidationException {
1288
                // write on a temporary file in order to not destroy current file if there is some problem while marshaling
1289
                File tmpFile = new File(file+"-"+DateTime.getCurrentDate().getTime());
1290

    
1291
                File xml = new File(file);
1292
                File parent = tmpFile.getParentFile();
1293
                parent.mkdirs();
1294

    
1295
                FileWriter writer = new FileWriter(tmpFile);
1296
                andamiConfig.marshal(writer);
1297
                writer.close();
1298
                
1299
                // if marshaling process finished correctly, move the file to the correct one
1300
                xml.delete();
1301
                if (!tmpFile.renameTo(xml)) {
1302
                        // if rename was not succesful, try copying it
1303
                        FileChannel sourceChannel = new  FileInputStream(tmpFile).getChannel();
1304
                        FileChannel destinationChannel = new FileOutputStream(xml).getChannel();
1305
                        sourceChannel.transferTo(0, sourceChannel.size(), destinationChannel);
1306
                        sourceChannel.close();
1307
                        destinationChannel.close();             
1308
                }
1309
        }
1310

    
1311
        /**
1312
         * DOCUMENT ME!
1313
         *
1314
         * @param file DOCUMENT ME!
1315
         *
1316
         * @throws ConfigurationException DOCUMENT ME!
1317
         */
1318
        private static void andamiConfigFromXML(String file)
1319
                throws ConfigurationException {
1320
                File xml = new File(file);
1321
                FileReader reader = null;
1322
                try {
1323
                        //Se lee la configuraci?n
1324
                        reader = new FileReader(xml);
1325
                        andamiConfig = (AndamiConfig) AndamiConfig.unmarshal(reader);
1326
                } catch (FileNotFoundException e) {
1327
                        //Si no existe se ponen los valores por defecto
1328
                        andamiConfig = getDefaultAndamiConfig();
1329
                } catch (MarshalException e) {
1330
                        // try to close the stream, maybe it remains open
1331
                        if (reader!=null) {
1332
                                try { reader.close(); } catch (IOException e1) {}
1333
                        }
1334
                        // if there was a problem reading the file, backup it and create a new one with default values
1335
                        String backupFile = file+"-"+DateTime.getCurrentDate().getTime();
1336
                        NotificationManager.addError(Messages.getString("Error_reading_andami_config_New_file_created_A_backup_was_made_on_")+backupFile, new ConfigurationException(e));
1337
                        xml.renameTo(new File(backupFile));
1338
                        andamiConfig = getDefaultAndamiConfig();
1339
                } catch (ValidationException e) {
1340
                        throw new ConfigurationException(e);
1341
                }
1342
        }
1343
        
1344
        private static AndamiConfig getDefaultAndamiConfig() {
1345
                AndamiConfig andamiConfig = new AndamiConfig();
1346

    
1347
                Andami andami = new Andami();
1348
                andami.setUpdate(true);
1349
                andamiConfig.setAndami(andami);
1350
                andamiConfig.setLocaleCountry(Locale.getDefault().getCountry());
1351
                andamiConfig.setLocaleLanguage(Locale.getDefault().getLanguage());
1352
                andamiConfig.setLocaleVariant(Locale.getDefault().getVariant());
1353

    
1354
                if (System.getProperty("javawebstart.version") != null) // Es java web start)
1355
                 {
1356
                        andamiConfig.setPluginsDirectory(new File(appHomeDir
1357
                                        + "extensiones").getAbsolutePath());
1358
                } else {
1359
                        andamiConfig.setPluginsDirectory(new File(appName +
1360
                                        File.separator + "extensiones").getAbsolutePath());
1361
                }
1362

    
1363
                andamiConfig.setPlugin(new Plugin[0]);
1364
                return andamiConfig;
1365
        }
1366
        /**
1367
         * DOCUMENT ME!
1368
         *
1369
         * @return DOCUMENT ME!
1370
         *
1371
         * @throws ConfigurationException DOCUMENT ME!
1372
         */
1373
        private static XMLEntity persistenceFromXML() throws ConfigurationException {
1374
                File xml = new File(pluginsPersistencePath);
1375

    
1376
                if (xml.exists()) {
1377
                        FileReader reader=null;
1378

    
1379
                        try {
1380
                                reader = new FileReader(xml);
1381

    
1382
                                XmlTag tag = (XmlTag) XmlTag.unmarshal(reader);
1383

    
1384
                                return new XMLEntity(tag);
1385
                        } catch (FileNotFoundException e) {
1386
                                throw new ConfigurationException(e);
1387
                        } catch (MarshalException e) {
1388
                                // try to close the stream, maybe it remains open
1389
                                if (reader!=null) {
1390
                                        try { reader.close(); } catch (IOException e1) {}
1391
                                }
1392
                                String backupFile = pluginsPersistencePath+"-"+DateTime.getCurrentDate().getTime();
1393
                                NotificationManager.addError(Messages.getString("Error_reading_plugin_persinstence_New_file_created_A_backup_was_made_on_")+backupFile, new ConfigurationException(e));
1394
                                xml.renameTo(new File(backupFile));
1395
                                return new XMLEntity();
1396
                        } catch (ValidationException e) {
1397
                                throw new ConfigurationException(e);
1398
                        }
1399
                } else {
1400
                        return new XMLEntity();
1401
                }
1402
        }
1403

    
1404
        /**
1405
         * DOCUMENT ME!
1406
         *
1407
         * @param entity DOCUMENT ME!
1408
         *
1409
         * @throws ConfigurationException DOCUMENT ME!
1410
         */
1411
        private static void persistenceToXML(XMLEntity entity)
1412
                throws ConfigurationException {
1413
                // write on a temporary file in order to not destroy current file if there is some problem while marshaling
1414
                File tmpFile = new File(pluginsPersistencePath+"-"+DateTime.getCurrentDate().getTime());
1415
                File xml = new File(pluginsPersistencePath);
1416

    
1417
                FileWriter writer=null;
1418

    
1419
                try {
1420
                        writer = new FileWriter(tmpFile);
1421
                        entity.getXmlTag().marshal(writer);
1422
                        writer.close();
1423
                        
1424
                        // if marshaling process finished correctly, move the file to the correct one 
1425
                        xml.delete();
1426
                        if (!tmpFile.renameTo(xml)) {
1427
                                // if rename was not succesful, try copying it
1428
                                FileChannel sourceChannel = new  FileInputStream(tmpFile).getChannel();
1429
                                FileChannel destinationChannel = new FileOutputStream(xml).getChannel();
1430
                                sourceChannel.transferTo(0, sourceChannel.size(), destinationChannel);
1431
                                sourceChannel.close();
1432
                                destinationChannel.close();
1433
                     
1434
                        }
1435
                } catch (FileNotFoundException e) {
1436
                        throw new ConfigurationException(e);
1437
                } catch (MarshalException e) {
1438
                        // try to close the stream, maybe it remains open
1439
                        if (writer!=null) {
1440
                                try { writer.close(); } catch (IOException e1) {}
1441
                        }
1442
                        throw new ConfigurationException(e);
1443
                } catch (ValidationException e) {
1444
                        throw new ConfigurationException(e);
1445
                } catch (IOException e) {
1446
                        throw new ConfigurationException(e);
1447
                }
1448
        }
1449

    
1450
        /**
1451
         * Devuelve un array con los directorios de los plugins
1452
         *
1453
         * @param dirExt Directorio de las extensiones a partir del cual cuelgan
1454
         *                   todos los directorios de los plugins
1455
         *
1456
         * @return ArrayList con los directorios
1457
         */
1458
        private String[] getLocales(File dirExt) {
1459
                ArrayList types = new ArrayList();
1460
                File[] files = dirExt.listFiles();
1461

    
1462
                for (int i = 0; i < files.length; i++) {
1463
                        if (files[i].isDirectory()) {
1464
                                File[] textFile = files[i].listFiles(new FilenameFilter() {
1465
                                                        public boolean accept(File dir, String fileName) {
1466
                                                                return fileName.toLowerCase().startsWith("text_"); //$NON-NLS-1$
1467
                                                        }
1468
                                                });
1469

    
1470
                                for (int j = 0; j < textFile.length; j++) {
1471
                                        String s = (textFile[j]).getName().replaceAll("text_", "");
1472
                                        s = s.replaceAll(".properties", "");
1473
                                        s = s.trim();
1474

    
1475
                                        if (!types.contains(s)) {
1476
                                                types.add(s);
1477
                                        }
1478
                                }
1479
                        }
1480
                }
1481

    
1482
                return (String[]) types.toArray(new String[0]);
1483
        }
1484

    
1485
        /**
1486
         * DOCUMENT ME!
1487
         *
1488
         * @return Returns the frame.
1489
         */
1490
        static MDIFrame getFrame() {
1491
                return frame;
1492
        }
1493

    
1494
        /**
1495
         * Secuencia de cerrado de Andami
1496
         */
1497
        public static void closeApplication() {
1498
                //Configuraci?n de Andami
1499
                try {
1500
                        andamiConfigToXML(andamiConfigPath);
1501
                } catch (MarshalException e) {
1502
                        logger.error(Messages.getString(
1503
                                        "Launcher.No_se_pudo_guardar_la_configuracion_de_andami"), e);
1504
                } catch (ValidationException e) {
1505
                        logger.error(Messages.getString(
1506
                                        "Launcher.No_se_pudo_guardar_la_configuracion_de_andami"), e);
1507
                } catch (IOException e) {
1508
                        logger.error(Messages.getString(
1509
                                        "Launcher.No_se_pudo_guardar_la_configuracion_de_andami"), e);
1510
                }
1511

    
1512
                //Persistencia de los plugins
1513
                savePluginPersistence();
1514

    
1515
                //Finalize all the extensions
1516
                finalizeExtensions();
1517

    
1518
                // Clean any temp data created
1519
                Utilities.cleanUpTempFiles();
1520

    
1521
                //Para la depuraci?n de memory leaks
1522
                System.gc();
1523

    
1524
        System.exit(0);
1525
        }
1526

    
1527
        /**
1528
         * Exectutes the terminate method for all the extensions, in the reverse
1529
         * order they were initialized
1530
         *
1531
         */
1532
        private static void finalizeExtensions() {
1533
                for (int i=extensions.size()-1; i>=0; i--) {
1534
                        com.iver.andami.plugins.IExtension extensionInstance=(com.iver.andami.plugins.IExtension)extensions.get(i);
1535
                        extensionInstance.terminate();
1536
                }
1537
        }
1538

    
1539

    
1540
        /**
1541
         * DOCUMENT ME!
1542
         *
1543
         * @return DOCUMENT ME!
1544
         */
1545
        static HashMap getClassesExtensions() {
1546
                return classesExtensions;
1547
        }
1548

    
1549
        /**
1550
         * DOCUMENT ME!
1551
         *
1552
         * @param extDir DOCUMENT ME!
1553
         */
1554
        private static void downloadExtensions(String extDir) {
1555
                java.util.Date fechaActual = null;
1556

    
1557
                try {
1558
                        if (System.getProperty("javawebstart.version") != null) {
1559
                                //Obtenemos la URL del servidor
1560
                                BasicService bs = (BasicService) ServiceManager.lookup(
1561
                                                "javax.jnlp.BasicService");
1562
                                URL baseURL = bs.getCodeBase();
1563

    
1564
                                //Se descargan las extensiones
1565
                                MultiSplashWindow.process(5,
1566
                                        "Descargando las extensiones desde " + baseURL + " a " +
1567
                                        extDir);
1568

    
1569
                                URL url = new URL(baseURL + "extensiones.zip");
1570
                                URLConnection connection = url.openConnection();
1571

    
1572
                                System.out.println(url.toExternalForm() + ":");
1573
                                System.out.println("  Content Type: " +
1574
                                        connection.getContentType());
1575
                                System.out.println("  Content Length: " +
1576
                                        connection.getContentLength());
1577
                                System.out.println("  Last Modified: " +
1578
                                        new Date(connection.getLastModified()));
1579
                                System.out.println("  Expiration: " +
1580
                                        connection.getExpiration());
1581
                                System.out.println("  Content Encoding: " +
1582
                                        connection.getContentEncoding());
1583

    
1584
                                // Guardamos la fecha del fichero de extensiones que nos hemos bajado, y
1585
                                // comprobamos el ?ltimo que se ha bajado. Si no son
1586
                                // iguales, nos bajamos el nuevo. Si son iguales, no
1587
                                // nos bajamos nada.
1588
                                Long miliSecondsInWeb = new Long(connection.getLastModified());
1589

    
1590
                                // PluginServices ps = PluginServices.getPluginServices("com.iver.core");
1591
                                // if (ps.getPersistentXML().getStringProperty("timestamp") != null)
1592
                                File destDir = new File(extDir);
1593

    
1594
                                if (!destDir.exists()) {
1595
                                        // Creamos gvSIG
1596
                                        destDir.getParentFile().mkdir();
1597

    
1598
                                        if (!destDir.mkdir()) {
1599
                                                System.err.println("Imposible crear el directorio " +
1600
                                                        destDir.getAbsolutePath());
1601
                                        }
1602
                                }
1603

    
1604
                                File timeFile = new File(destDir.getParent() + File.separator +
1605
                                                "timeStamp.properties");
1606

    
1607
                                if (!timeFile.exists()) {
1608
                                        timeFile.createNewFile();
1609
                                }
1610

    
1611
                                FileInputStream inAux = new FileInputStream(timeFile);
1612
                                Properties prop = new Properties();
1613
                                prop.load(inAux);
1614
                                inAux.close();
1615

    
1616
                                if (prop.getProperty("timestamp") != null) {
1617
                                        Long lastMiliSeconds = (Long) new Long(prop.getProperty(
1618
                                                                "timestamp"));
1619

    
1620
                                        if (lastMiliSeconds.longValue() == miliSecondsInWeb.longValue()) {
1621
                                                System.out.println("No hay nueva actualizaci?n");
1622
                        logger.debug("No hay nueva actualizaci?n -> Return");
1623
                        logger.debug("timeStampWeb= " + miliSecondsInWeb);
1624
                        logger.debug("timeStampLocal= " + lastMiliSeconds);
1625

    
1626
                                                return;
1627
                                        }
1628

    
1629
                                        System.out.println("timeStampWeb= " + miliSecondsInWeb);
1630
                                        System.out.println("timeStampLocal= " + lastMiliSeconds);
1631
                                } else {
1632
                                        System.out.println("El timeStamp no est? escrito en " +
1633
                                                timeFile.getAbsolutePath());
1634
                                }
1635

    
1636
                                InputStream stream = url.openStream();
1637
                File temp = File.createTempFile("gvsig", ".zip");
1638

    
1639
                logger.debug(temp.getAbsolutePath());
1640

    
1641
                temp.deleteOnExit();
1642
                FileOutputStream file = new FileOutputStream(temp);
1643

    
1644
                byte[] lt_read = new byte[1];
1645

    
1646
                while (stream.read(lt_read) > 0)
1647
                  file.write(lt_read);
1648

    
1649
                                stream.close();
1650
                stream = null;
1651
                file.close();
1652
                file = null;
1653

    
1654
                System.gc();
1655

    
1656
                logger.debug("Ha creado el fichero ZIP");
1657
                                //Se extrae el zip
1658
                                MultiSplashWindow.process(5, "Extensiones descargadas.");
1659

    
1660
                                System.out.println("Extrayendo a " + destDir.getAbsolutePath());
1661

    
1662
                                Date fechaDir = new Date(destDir.lastModified());
1663
                                System.out.println("Fecha del directorio " + extDir + " = " +
1664
                                        fechaDir.toString());
1665
                                Utilities.extractTo(temp, new File(extDir), splashWindow);
1666

    
1667
                                // Si todo ha ido bien, guardamos el timestamp.
1668
                                ///  App.instance.getPc().addProperties("timestamp", miliSecondsInWeb);
1669
                                // XMLEntity xml=ps.getPersistentXML();
1670
                                fechaActual = new java.util.Date();
1671

    
1672
                                FileOutputStream outAux = new FileOutputStream(timeFile);
1673
                                prop.setProperty("timestamp", miliSecondsInWeb.toString());
1674
                                prop.store(outAux, "last download");
1675
                                outAux.close();
1676
                                System.out.println("Fecha actual guardada: " +
1677
                                        fechaActual.toGMTString());
1678

    
1679
                                /* xml.putProperty("timestamp",fechaActual.toGMTString());
1680
                                   ps.setPresistentXML(xml); */
1681
                        }
1682
                } catch (IOException e) {
1683
                        NotificationManager.addError("", e);
1684
                } catch (UnavailableServiceException e) {
1685
                        NotificationManager.addError("", e);
1686
                } catch (SecurityException e) {
1687
                        System.err.println("No se puede escribir el timeStamp " +
1688
                                fechaActual.toGMTString());
1689
                        NotificationManager.addError("", e);
1690
                }
1691
        }
1692

    
1693
        /**
1694
         * DOCUMENT ME!
1695
         *
1696
         * @return DOCUMENT ME!
1697
         */
1698
        private static Extensions[] getExtensions() {
1699
                ArrayList array = new ArrayList();
1700
                Iterator iter = pluginsConfig.values().iterator();
1701

    
1702
                while (iter.hasNext()) {
1703
                        array.add(((PluginConfig) iter.next()).getExtensions());
1704
                }
1705

    
1706
                return (Extensions[]) array.toArray(new Extensions[0]);
1707
        }
1708

    
1709
        /**
1710
         * DOCUMENT ME!
1711
         *
1712
         * @return DOCUMENT ME!
1713
         */
1714
        public static HashMap getPluginConfig() {
1715
                return pluginsConfig;
1716
        }
1717

    
1718
        /**
1719
         * DOCUMENT ME!
1720
         *
1721
         * @param s DOCUMENT ME!
1722
         *
1723
         * @return DOCUMENT ME!
1724
         */
1725
        public static Extension getExtension(String s) {
1726
                Extensions[] exts = getExtensions();
1727

    
1728
                for (int i = 0; i < exts.length; i++) {
1729
                        for (int j = 0; j < exts[i].getExtensionCount(); j++) {
1730
                                if (exts[i].getExtension(j).getClassName().equals(s)) {
1731
                                        return exts[i].getExtension(j);
1732
                                }
1733
                        }
1734
                }
1735

    
1736
                return null;
1737
        }
1738

    
1739
        /**
1740
         * DOCUMENT ME!
1741
         *
1742
         * @return DOCUMENT ME!
1743
         */
1744
        public static AndamiConfig getAndamiConfig() {
1745
                return andamiConfig;
1746
        }
1747

    
1748
        /**
1749
         * DOCUMENT ME!
1750
         *
1751
         * @author $author$
1752
         * @version $Revision: 10309 $
1753
         */
1754
        private static class ExtensionComparator implements Comparator {
1755
                /**
1756
                 * DOCUMENT ME!
1757
                 *
1758
                 * @param o1 DOCUMENT ME!
1759
                 * @param o2 DOCUMENT ME!
1760
                 *
1761
                 * @return DOCUMENT ME!
1762
                 */
1763
                public int compare(Object o1, Object o2) {
1764
                        Extension e1 = (Extension) o1;
1765
                        Extension e2 = (Extension) o2;
1766

    
1767
                        if (!e1.hasPriority() && !e2.hasPriority()) {
1768
                                return -1;
1769
                        }
1770

    
1771
                        if (e1.hasPriority() && !e2.hasPriority()) {
1772
                                return Integer.MIN_VALUE;
1773
                        }
1774

    
1775
                        if (e2.hasPriority() && !e1.hasPriority()) {
1776
                                return Integer.MAX_VALUE;
1777
                        }
1778

    
1779
                        if (e1.getPriority() != e2.getPriority()){
1780
                                return e2.getPriority() - e1.getPriority();
1781
                        }else{
1782
                                return (e2.toString().compareTo(e1.toString()));
1783
                        }
1784
                }
1785
        }
1786

    
1787
        /**
1788
         * DOCUMENT ME!
1789
         */
1790
        private static class MenuComparator implements Comparator {
1791
                private static ExtensionComparator extComp = new ExtensionComparator();
1792

    
1793
                /**
1794
                 * DOCUMENT ME!
1795
                 *
1796
                 * @param o1 DOCUMENT ME!
1797
                 * @param o2 DOCUMENT ME!
1798
                 *
1799
                 * @return DOCUMENT ME!
1800
                 */
1801
                public int compare(Object o1, Object o2) {
1802
                        SortableMenu e1 = (SortableMenu) o1;
1803
                        SortableMenu e2 = (SortableMenu) o2;
1804

    
1805
                        if (!e1.menu.hasPosition() && !e2.menu.hasPosition()) {
1806
                                if (e1.extension instanceof SkinExtensionType) {
1807
                                        return 1;
1808
                                } else if (e2.extension instanceof SkinExtensionType) {
1809
                                        return -1;
1810
                                } else {
1811
                                        return extComp.compare(e1.extension, e2.extension);
1812
                                }
1813
                        }
1814

    
1815
                        if (e1.menu.hasPosition() && !e2.menu.hasPosition()) {
1816
                                return Integer.MIN_VALUE;
1817
                        }
1818

    
1819
                        if (e2.menu.hasPosition() && !e1.menu.hasPosition()) {
1820
                                return Integer.MAX_VALUE;
1821
                        }
1822
                        if (e1.menu.getPosition() != e2.menu.getPosition()){
1823
                                //we don't return 0 unless both objects are the same, otherwise the objects get overwritten in the treemap
1824
                                return e1.menu.getPosition() - e2.menu.getPosition();
1825
                        }else{
1826
                                return (e1.toString().compareTo(e2.toString()));
1827
                        }
1828
                }
1829
        }
1830

    
1831
        /**
1832
         * DOCUMENT ME!
1833
         *
1834
         * @author $author$
1835
         * @version $Revision: 10309 $
1836
         */
1837
        private static class SortableMenu {
1838
                public PluginClassLoader loader;
1839
                public Menu menu;
1840
                public SkinExtensionType extension;
1841

    
1842
                /**
1843
                 * DOCUMENT ME!
1844
                 *
1845
                 * @param loader DOCUMENT ME!
1846
                 * @param skinExt
1847
                 * @param menu2
1848
                 */
1849
                public SortableMenu(PluginClassLoader loader,
1850
                        SkinExtensionType skinExt, Menu menu2) {
1851
                        extension = skinExt;
1852
                        menu = menu2;
1853
                        this.loader = loader;
1854
                }
1855
        }
1856
        /**
1857
         * DOCUMENT ME!
1858
         */
1859
        private static class SortableTool {
1860
                public PluginClassLoader loader;
1861
                public ToolBar toolbar;
1862
                public ActionTool actiontool;
1863
                public SelectableTool selectabletool;
1864
                public SkinExtensionType extension;
1865

    
1866
                /**
1867
                 * DOCUMENT ME!
1868
                 *
1869
                 * @param loader DOCUMENT ME!
1870
                 * @param skinExt
1871
                 * @param menu2
1872
                 */
1873
                public SortableTool(PluginClassLoader loader,
1874
                        SkinExtensionType skinExt, ToolBar toolbar2,ActionTool actiontool2) {
1875
                        extension = skinExt;
1876
                        toolbar = toolbar2;
1877
                        actiontool=actiontool2;
1878
                        this.loader = loader;
1879
                }
1880
                public SortableTool(PluginClassLoader loader,
1881
                                SkinExtensionType skinExt, ToolBar toolbar2,SelectableTool selectabletool2) {
1882
                        extension = skinExt;
1883
                        toolbar = toolbar2;
1884
                        selectabletool=selectabletool2;
1885
                        this.loader = loader;
1886
                }
1887
        }
1888
        /**
1889
         * DOCUMENT ME!
1890
         */
1891
        private static class ToolBarComparator implements Comparator {
1892
                private static ExtensionComparator extComp = new ExtensionComparator();
1893

    
1894
                /**
1895
                 * DOCUMENT ME!
1896
                 *
1897
                 * @param o1 DOCUMENT ME!
1898
                 * @param o2 DOCUMENT ME!
1899
                 *
1900
                 * @return DOCUMENT ME!
1901
                 */
1902
                public int compare(Object o1, Object o2) {
1903
                        SortableTool e1 = (SortableTool) o1;
1904
                        SortableTool e2 = (SortableTool) o2;
1905

    
1906
                        // if the toolbars have the same name, they are considered to be
1907
                        // the same toolbar, so we don't need to do further comparing
1908
                        if (e1.toolbar.getName().equals(e2.toolbar.getName()))
1909
                                return 0;
1910

    
1911
                        if (!e1.toolbar.hasPosition() && !e2.toolbar.hasPosition()) {
1912
                                if (e1.extension instanceof SkinExtensionType) {
1913
                                        return 1;
1914
                                } else if (e2.extension instanceof SkinExtensionType) {
1915
                                        return -1;
1916
                                } else {
1917
                                        return extComp.compare(e1.extension, e2.extension);
1918
                                }
1919
                        }
1920

    
1921
                        if (e1.toolbar.hasPosition() && !e2.toolbar.hasPosition()) {
1922
                                return Integer.MIN_VALUE;
1923
                        }
1924

    
1925
                        if (e2.toolbar.hasPosition() && !e1.toolbar.hasPosition()) {
1926
                                return Integer.MAX_VALUE;
1927
                        }
1928
                        if (e1.toolbar.getPosition() != e2.toolbar.getPosition())
1929
                                return e1.toolbar.getPosition() - e2.toolbar.getPosition();
1930

    
1931
                        if (e1.toolbar.getActionTool().equals(e2.toolbar.getActionTool()) && e1.toolbar.getSelectableTool().equals(e2.toolbar.getSelectableTool())){
1932
                                return 0;
1933
                        }
1934
                        return (e1.toolbar.toString().compareTo(e2.toolbar.toString()));
1935
                }
1936
        }
1937

    
1938
        /**
1939
         * <p>This class is used to compare tools (selectabletool and actiontool),
1940
         * using the "position"
1941
         * attribute.</p>
1942
         * <p>The ordering criteria are:</p>
1943
         * <ul><li>If the tools are placed in different toolbars, they use the toolbars'
1944
         * order.
1945
         * (using the ToolBarComparator).</li>
1946
         * <li></li>
1947
         * <li>If any of the tools has not 'position' attribute, the tool which
1948
         * <strong>has</strong> the attribute will be placed first.</li>
1949
         * <li>If both tools have the same position (or they don't have a
1950
         * 'position' attribute), the priority of the extensions where the tool is defined.</li></ul>
1951
         *
1952
         * @author cesar
1953
         * @version $Revision: 10309 $
1954
         */
1955
        private static class ToolComparator implements Comparator {
1956
                private static ToolBarComparator toolBarComp = new ToolBarComparator();
1957
                /**
1958
                 * DOCUMENT ME!
1959
                 *
1960
                 * @param o1 DOCUMENT ME!
1961
                 * @param o2 DOCUMENT ME!
1962
                 *
1963
                 * @return DOCUMENT ME!
1964
                 */
1965
                public int compare(Object o1, Object o2) {
1966
                        // compare the toolbars which contain the tools
1967
                        int result = toolBarComp.compare(o1, o2);
1968
                        if (result != 0) { // if the toolbars are different, use their order
1969
                                return result;
1970
                        }
1971
                        // otherwise, compare the tools
1972
                        SortableTool e1 = (SortableTool) o1;
1973
                        SortableTool e2 = (SortableTool) o2;
1974
                        int e1Position=-1, e2Position=-1;
1975

    
1976
                        if (e1.actiontool!=null) {
1977
                                if (e1.actiontool.hasPosition())
1978
                                        e1Position = e1.actiontool.getPosition();
1979
                        }
1980
                        else if (e1.selectabletool!=null) {
1981
                                if (e1.selectabletool.hasPosition())
1982
                                        e1Position = e1.selectabletool.getPosition();
1983
                        }
1984

    
1985
                        if (e2.actiontool!=null) {
1986
                                if (e2.actiontool.hasPosition())
1987
                                        e2Position = e2.actiontool.getPosition();
1988
                        }
1989
                        else if (e2.selectabletool!=null){
1990
                                if (e2.selectabletool.hasPosition())
1991
                                        e2Position = e2.selectabletool.getPosition();
1992
                        }
1993

    
1994
                        if (e1Position==-1 && e2Position!=-1) {
1995
                                return 1;
1996
                        }
1997
                        if (e1Position!=-1 && e2Position==-1) {
1998
                                return -1;
1999
                        }
2000
                        if (e1Position!=-1 && e2Position!=-1) {
2001
                                result = e1Position - e2Position;
2002
                                // we don't return 0 unless both objects are the same, otherwise the objects get overwritten in the treemap
2003
                                if (result!=0) return result;
2004
                        }
2005
                        return e1.toString().compareTo(e2.toString());
2006
                }
2007
        }
2008

    
2009

    
2010
        /**
2011
         * validates the user before starting gvsig
2012
         *
2013
         */
2014
        private static void validate(){
2015

    
2016
                IAuthentication session =  null;
2017
                try {
2018
                        session = (IAuthentication)Class.forName("com.iver.andami.authentication.Session").newInstance();
2019

    
2020
                } catch (ClassNotFoundException e) {
2021
                        // TODO Auto-generated catch block
2022
                        //e.printStackTrace();
2023
                        return;
2024
                } catch (InstantiationException e) {
2025
                        // TODO Auto-generated catch block
2026
                        //e.printStackTrace();
2027
                        return;
2028
                } catch (IllegalAccessException e) {
2029
                        // TODO Auto-generated catch block
2030
                        //e.printStackTrace();
2031
                        return;
2032
                }
2033

    
2034
                session.setPluginDirectory( andamiConfig.getPluginsDirectory() );
2035
                if (session.validationRequired()){
2036
                        if(session.Login()){
2037
                                System.out.println("You are logged in");
2038
                        }
2039
                        else{
2040
                                JOptionPane.showMessageDialog((Component)PluginServices.getMainFrame(),
2041
                                                 "You are not logged in");
2042
                                //System.exit(0);
2043
                        }
2044
                        PluginServices.setAuthentication(session);
2045
                }
2046
        }
2047

    
2048
        public static String getDefaultLookAndFeel() {
2049
                String osName = (String) System.getProperty("os.name");
2050

    
2051
                if (osName.length() > 4 && osName.substring(0,5).toLowerCase().equals("linux"))
2052
                        return nonWinDefaultLookAndFeel;
2053
                   return UIManager.getSystemLookAndFeelClassName();
2054
        }
2055

    
2056
        /**
2057
         * Gets the ISO 839 two-characters-long language code matching the
2058
         * provided language code (which may be an ISO 839-2/T
2059
         * three-characters-long code or an ISO 839-1 two-characters-long
2060
         * code).
2061
         *
2062
         * If the provided parameter is already two characters long, it
2063
         * returns the parameter without any modification.
2064
         *
2065
         * @param langCode A language code representing either
2066
         *  an ISO 839-2/T language code or an ISO 839-1 code.
2067
         * @return A two-characters-long code specifying
2068
         *  an ISO 839 language code.
2069
         */
2070
        private static String normalizeLanguageCode(String langCode) {
2071
                final String fileName = "iso_639.tab";
2072
                if (langCode.length()==2)
2073
                        return langCode;
2074
                else if (langCode.length()==3) {
2075
                        if (langCode.equals("va") || langCode.equals("val")) { // special case for Valencian
2076
                                return "ca";
2077
                        }
2078
                        URL isoCodes = Launcher.class.getClassLoader().getResource(fileName);
2079
                        if (isoCodes!=null) {
2080
                                try {
2081
                                        BufferedReader reader =
2082
                                                new BufferedReader(new InputStreamReader(isoCodes.openStream(), "ISO-8859-1"));
2083
                                                String line;
2084

    
2085
                                                while ((line = reader.readLine()) != null) {
2086
                                                        String[] language = line.split("\t");
2087
                                                        if (language[0].equals(langCode)) // first column is the three characters code
2088
                                                                return language[2]; // third column i the two characters code
2089
                                                }
2090
                                }
2091
                                catch (IOException ex) {
2092
                                        logger.error(Messages.getString("Error_reading_isocodes_file"), ex);
2093
                                        return "es";
2094
                                }
2095
                        }
2096
                        else {
2097
                                logger.error(Messages.getString("Error_reading_isocodes_file"));
2098
                                return "es";
2099
                        }
2100
                }
2101
                return "es";
2102
        }
2103

    
2104
        /**
2105
         * Configures the locales (languages and local resources) to be used
2106
         * by the application.
2107
         *
2108
         * First it tries to get the locale from the command line parameters,
2109
         * then the andami-config file is checked.
2110
         *
2111
         * The locale name is normalized to get a two characters language code
2112
         * as defined by ISO-639-1 (although ISO-639-2/T three characters codes
2113
         * are also accepted from the command line or the configuration file).
2114
         *
2115
         * Finally, the gvsig-i18n library and the default locales for Java and
2116
         * Swing are configured.
2117
         *
2118
         */
2119
        private static void configureLocales(String[] args) {
2120
                //                 Configurar el locale
2121
        String localeStr = null;
2122
        for (int i=2; i < args.length; i++)
2123
        {
2124
                int index = args[i].indexOf("language=");
2125
                if (index != -1)
2126
                        localeStr = args[i].substring(index+9);
2127
        }
2128
                if (localeStr == null)
2129
                {
2130
            localeStr = andamiConfig.getLocaleLanguage();
2131
                }
2132
                localeStr = normalizeLanguageCode(localeStr);
2133
                locale = getLocale(localeStr,
2134
                andamiConfig.getLocaleCountry(),
2135
                andamiConfig.getLocaleVariant());
2136
                Locale.setDefault(locale);
2137
                JComponent.setDefaultLocale(locale);
2138
        org.gvsig.i18n.Messages.addLocale(locale);
2139
                // add english and spanish as fallback languages
2140
                org.gvsig.i18n.Messages.addLocale(new Locale("en"));
2141
                org.gvsig.i18n.Messages.addLocale(new Locale("es"));
2142
        org.gvsig.i18n.Messages.addResourceFamily("com.iver.andami.text", "com.iver.andami.text");
2143

    
2144
        }
2145

    
2146
        /**
2147
         * Gets Home Directory location of the application.
2148
         * May be set from outside the aplication by means of
2149
         * -DgvSIG.home=C:/data/gvSIG, where gvSIG its the name
2150
         * of the application
2151
         * @return
2152
         */
2153
        public static String getAppHomeDir() {
2154
                return appHomeDir;
2155
        }
2156

    
2157
        /**
2158
         * Sets Home Directory location of the application.
2159
         * May be set from outside the aplication by means of
2160
         * -DgvSIG.home=C:/data/gvSIG, where gvSIG its the name
2161
         * of the application
2162
         * @param appHomeDir
2163
         */
2164
        public static void setAppHomeDir(String appHomeDir) {
2165
                Launcher.appHomeDir = appHomeDir;
2166
        }
2167

    
2168
        /**
2169
         * Initialize the extesion that have to take the control
2170
         *  of the state of action controls of the UI of all extensions.
2171
         * <br>
2172
         * <br>
2173
         * For use this option you have to add an argument
2174
         * to the command line like this:
2175
         * <br>
2176
         * <br>
2177
         * -exclusiveUI={pathToExtensionClass}
2178
         * <br>
2179
         *  @see com.iver.andami.plugins.IExtension#isEnabled(IExtension extension)
2180
         *  @see com.iver.andami.plugins.IExtension#isVisible(IExtension extension)
2181
         */
2182
        private static void initializeExclusiveUIExtension(){
2183
                String name = PluginServices.getArgumentByName("exclusiveUI");
2184
                if (name == null)
2185
                        return;
2186

    
2187

    
2188
                Iterator iter  = classesExtensions.keySet().iterator();
2189
                int charIndex;
2190
                Class key;
2191
                while (iter.hasNext()) {
2192
                        key = (Class)iter.next();
2193
                        charIndex = key.getName().indexOf(name);
2194
                        //System.out.println("key='"+key.getName()+"' name='"+name+"' charIndex="+charIndex);
2195
                        if (charIndex == 0) {
2196
                                IExtension ext =(IExtension)classesExtensions.get(key);
2197
                                if (ext instanceof ExtensionDecorator)
2198
                                        ext = ((ExtensionDecorator)ext).getExtension();
2199
                                PluginServices.setExclusiveUIExtension(ext);
2200
                                break;
2201
                        }
2202
                }
2203

    
2204
                logger.error(Messages.getString("No_se_encontro_la_extension_especificada_en_el_parametro_exclusiveUI") + " '" + name +"'");
2205
        }
2206
}