Statistics
| Revision:

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

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

    
141

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

    
163
    private static ArrayList pluginsOrdered = new ArrayList();
164
    private static ArrayList extensions=new ArrayList();
165
    private static String appHomeDir = null;
166

    
167
        private static final class ProxyAuth extends Authenticator {
168
                private PasswordAuthentication auth;
169

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

    
174
                protected PasswordAuthentication getPasswordAuthentication() {
175
                        return auth;
176
                }
177
        }
178

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

    
194
                    if (!validJVM()){
195
                            System.exit(-1);
196
                    }
197

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

    
202
                    //  Clean temporal files
203
                    Utilities.cleanUpTempFiles();
204

    
205
                    appName = args[0];
206

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

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

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

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

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

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

    
245
                    configureLocales(args);
246

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

    
269
                    validate();
270

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

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

    
278
                    // Ponemos los datos del proxy
279
                    configureProxy();
280

    
281
                    // TODO Buscar actualizaciones de los plugins
282
                    downloadExtensions(andamiConfig.getPluginsDirectory());
283

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

    
287
                    // Se configura el classloader del plugin
288
                    pluginsClassLoaders();
289

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

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

    
297
                    // Se configura la mensajer?a del plugin
298
                    pluginsMessages();
299

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

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

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

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

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

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

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

    
341
                    // Se instalan los bookmarks de los plugins
342

    
343
                    //Se muestra el frame principal
344
                    frame.show();
345

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

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

    
362
    }
363

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

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

    
394
                System.getProperties().put("http.proxyHost", host);
395
                System.getProperties().put("http.proxyPort", port);
396

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

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

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

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

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

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

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

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

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

    
502
                XMLEntity entity = new XMLEntity();
503

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

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

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

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

    
539
                        LabelSet[] ls = pc.getLabelSet();
540

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

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

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

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

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

    
574
                                SkinExtension se = pc.getExtensions().getSkinExtension();
575

    
576
                                MDIManagerFactory.setSkinExtension(se, ps.getClassLoader());
577

    
578
                                Class skinClass;
579

    
580
                                try {
581
                                        skinClass = ps.getClassLoader().loadClass(se.getClassName());
582

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

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

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

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

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

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

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

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

    
653
                        Extension[] exts = pc.getExtensions().getExtension();
654

    
655
                        TreeMap orderedExtensions = new TreeMap(new ExtensionComparator());
656

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

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

    
668
                                orderedExtensions.put(exts[j], null);
669
                        }
670

    
671
                        Iterator e = orderedExtensions.keySet().iterator();
672

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

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

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

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

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

    
731
                Iterator i = pluginsConfig.keySet().iterator();
732

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

    
738
                        Extension[] exts = pc.getExtensions().getExtension();
739

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

    
745
                                Menu[] menus = exts[j].getMenu();
746

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

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

    
757
                                        orderedMenus.put(sm, null);
758
                                }
759
                        }
760

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

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

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

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

    
777
                                        orderedMenus.put(sm, null);
778
                                }
779
                        }
780
                }
781

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

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

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

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

    
805
                HashMap extensionPluginServices = new HashMap();
806
                HashMap extensionPluginConfig = new HashMap();
807
                TreeMap orderedExtensions = new TreeMap(new ExtensionComparator());
808

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

    
817
                        Extension[] exts = pc.getExtensions().getExtension();
818

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

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

    
834
                TreeMap orderedTools = new TreeMap(new ToolComparator());
835
                Iterator e = orderedExtensions.keySet().iterator();
836

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

    
842
                        ToolBar[] toolbars = ext.getToolBar();
843

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

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

    
854
                                SelectableTool[] sTools = toolbars[k].getSelectableTool();
855

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

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

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

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

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

    
938
                        SkinExtension skinExt = pc.getExtensions().getSkinExtension();
939

    
940
                        if (skinExt != null) {
941
                                ToolBar[] toolbars = skinExt.getToolBar();
942

    
943
                                for (int k = 0; k < toolbars.length; k++) {
944
                                        ActionTool[] tools = toolbars[k].getActionTool();
945

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

    
952
                                        SelectableTool[] sTools = toolbars[k].getSelectableTool();
953

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

    
964
                        if (pus != null) {
965
                                PopupMenu[] menus = pus.getPopupMenu();
966

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

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

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

    
995
                Plugin[] plugins = andamiConfig.getPlugin();
996

    
997
                for (int i = 0; i < plugins.length; i++) {
998
                        olds.add(plugins[i].getName());
999
                }
1000

    
1001
                Iterator i = pluginsServices.values().iterator();
1002

    
1003
                while (i.hasNext()) {
1004
                        PluginServices ps = (PluginServices) i.next();
1005

    
1006
                        if (!olds.contains(ps.getPluginName())) {
1007
                                Plugin p = new Plugin();
1008
                                p.setName(ps.getPluginName());
1009
                                p.setUpdate(false);
1010

    
1011
                                andamiConfig.addPlugin(p);
1012
                        }
1013
                }
1014
        }
1015

    
1016
        /**
1017
         * DOCUMENT ME!
1018
         */
1019
        private static void pluginsClassLoaders() {
1020
                HashSet instalados = new HashSet();
1021

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

    
1026
                        //Hacemos una pasada por todos los plugins
1027
                        Iterator i = pluginsConfig.keySet().iterator();
1028

    
1029
                        while (i.hasNext()) {
1030
                                String pluginName = (String) i.next();
1031
                                PluginConfig config = (PluginConfig) pluginsConfig.get(pluginName);
1032

    
1033
                                if (instalados.contains(pluginName)) {
1034
                                        continue;
1035
                                }
1036

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

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

    
1049
                                                continue;
1050
                                        }
1051

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

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

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

    
1076
                                URL[] urls = new URL[jarFiles.length];
1077

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

    
1088
                                PluginClassLoader loader;
1089

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

    
1096
                                        PluginServices ps = new PluginServices(loader);
1097

    
1098
                                        pluginsServices.put(ps.getPluginName(), ps);
1099

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

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

    
1114
                        if (circle) {
1115
                                logger.error(Messages.getString(
1116
                                                "Launcher.Hay_dependencias_circulares"));
1117

    
1118
                                break;
1119
                        }
1120
                }
1121

    
1122
                //Se eliminan los plugins que no fueron instalados
1123
                Iterator i = pluginsConfig.keySet().iterator();
1124

    
1125
                while (i.hasNext()) {
1126
                        String pluginName = (String) i.next();
1127
                        PluginConfig config = (PluginConfig) pluginsConfig.get(pluginName);
1128
                        PluginServices ps = (PluginServices) pluginsServices.get(pluginName);
1129

    
1130
                        if (ps == null) {
1131
                                pluginsConfig.remove(pluginName);
1132
                                i = pluginsConfig.keySet().iterator();
1133
                        }
1134
                }
1135
        }
1136

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

    
1151
                //Iteramos por todos los plugins
1152
                Iterator i = pluginsConfig.keySet().iterator();
1153

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

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

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

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

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

    
1197
        /**
1198
         * DOCUMENT ME!
1199
         *
1200
         * @return DOCUMENT ME!
1201
         */
1202
        static MDIFrame getMDIFrame() {
1203
                return frame;
1204
        }
1205

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

    
1214
                if (!pDir.exists()) {
1215
                        return;
1216
                }
1217

    
1218
                File[] pluginDirs = pDir.listFiles();
1219

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

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

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

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

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

    
1313
        /**
1314
         * DOCUMENT ME!
1315
         *
1316
         * @param file DOCUMENT ME!
1317
         *
1318
         * @throws ConfigurationException DOCUMENT ME!
1319
         */
1320
        private static void andamiConfigFromXML(String file)
1321
                throws ConfigurationException {
1322
                File xml = new File(file);
1323

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

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

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

    
1366
                andamiConfig.setPlugin(new Plugin[0]);
1367
                return andamiConfig;
1368
        }
1369
         
1370

    
1371
        /**
1372
         * DOCUMENT ME!
1373
         *
1374
         * @return DOCUMENT ME!
1375
         *
1376
         * @throws ConfigurationException DOCUMENT ME!
1377
         */
1378
        private static XMLEntity persistenceFromXML() throws ConfigurationException {
1379
                File xml = new File(pluginsPersistencePath);
1380

    
1381
                if (xml.exists()) {
1382
                        FileReader reader = null;
1383

    
1384
                        try {
1385
                                reader = new FileReader(xml);
1386

    
1387
                                XmlTag tag = (XmlTag) XmlTag.unmarshal(reader);
1388

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

    
1409
        /**
1410
         * DOCUMENT ME!
1411
         *
1412
         * @param entity DOCUMENT ME!
1413
         *
1414
         * @throws ConfigurationException DOCUMENT ME!
1415
         */
1416
        private static void persistenceToXML(XMLEntity entity)
1417
                throws ConfigurationException {
1418
                // write on a temporary file in order to not destroy current file if there is some problem while marshaling
1419
                File tmpFile = new File(pluginsPersistencePath+"-"+DateTime.getCurrentDate().getTime());
1420
                
1421
                File xml = new File(pluginsPersistencePath);
1422
                FileWriter writer=null;
1423
                try {
1424
                        writer = new FileWriter(tmpFile);
1425
                        entity.getXmlTag().marshal(writer);
1426
                        writer.close();
1427
                        
1428
                        // if marshaling process finished correctly, move the file to the correct one 
1429
                        xml.delete();
1430
                        if (!tmpFile.renameTo(xml)) {
1431
                                // if rename was not succesful, try copying it
1432
                                FileChannel sourceChannel = new  FileInputStream(tmpFile).getChannel();
1433
                                FileChannel destinationChannel = new FileOutputStream(xml).getChannel();
1434
                                sourceChannel.transferTo(0, sourceChannel.size(), destinationChannel);
1435
                                sourceChannel.close();
1436
                                destinationChannel.close();
1437
                     
1438
                        }
1439
                } catch (FileNotFoundException e) {
1440
                        throw new ConfigurationException(e);
1441
                } catch (MarshalException e) {
1442
                        // try to close the stream, maybe it remains open
1443
                        if (writer!=null) {
1444
                                try { writer.close(); } catch (IOException e1) {}
1445
                        }
1446
                } catch (ValidationException e) {
1447
                        throw new ConfigurationException(e);
1448
                } catch (IOException e) {
1449
                        throw new ConfigurationException(e);
1450
                }
1451
        }
1452

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

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

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

    
1478
                                        if (!types.contains(s)) {
1479
                                                types.add(s);
1480
                                        }
1481
                                }
1482
                        }
1483
                }
1484

    
1485
                return (String[]) types.toArray(new String[0]);
1486
        }
1487

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

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

    
1515
                //Persistencia de los plugins
1516
                savePluginPersistence();
1517

    
1518
                //Finalize all the extensions
1519
                finalizeExtensions();
1520

    
1521
                // Clean any temp data created
1522
                Utilities.cleanUpTempFiles();
1523

    
1524
                //Para la depuraci?n de memory leaks
1525
                System.gc();
1526

    
1527
        System.exit(0);
1528
        }
1529

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

    
1542

    
1543
        /**
1544
         * DOCUMENT ME!
1545
         *
1546
         * @return DOCUMENT ME!
1547
         */
1548
        static HashMap getClassesExtensions() {
1549
                return classesExtensions;
1550
        }
1551

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

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

    
1567
                                //Se descargan las extensiones
1568
                                MultiSplashWindow.process(5,
1569
                                        "Descargando las extensiones desde " + baseURL + " a " +
1570
                                        extDir);
1571

    
1572
                                URL url = new URL(baseURL + "extensiones.zip");
1573
                                URLConnection connection = url.openConnection();
1574

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

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

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

    
1597
                                if (!destDir.exists()) {
1598
                                        // Creamos gvSIG
1599
                                        destDir.getParentFile().mkdir();
1600

    
1601
                                        if (!destDir.mkdir()) {
1602
                                                System.err.println("Imposible crear el directorio " +
1603
                                                        destDir.getAbsolutePath());
1604
                                        }
1605
                                }
1606

    
1607
                                File timeFile = new File(destDir.getParent() + File.separator +
1608
                                                "timeStamp.properties");
1609

    
1610
                                if (!timeFile.exists()) {
1611
                                        timeFile.createNewFile();
1612
                                }
1613

    
1614
                                FileInputStream inAux = new FileInputStream(timeFile);
1615
                                Properties prop = new Properties();
1616
                                prop.load(inAux);
1617
                                inAux.close();
1618

    
1619
                                if (prop.getProperty("timestamp") != null) {
1620
                                        Long lastMiliSeconds = (Long) new Long(prop.getProperty(
1621
                                                                "timestamp"));
1622

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

    
1629
                                                return;
1630
                                        }
1631

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

    
1639
                                InputStream stream = url.openStream();
1640
                File temp = File.createTempFile("gvsig", ".zip");
1641

    
1642
                logger.debug(temp.getAbsolutePath());
1643

    
1644
                temp.deleteOnExit();
1645
                FileOutputStream file = new FileOutputStream(temp);
1646

    
1647
                byte[] lt_read = new byte[1];
1648

    
1649
                while (stream.read(lt_read) > 0)
1650
                  file.write(lt_read);
1651

    
1652
                                stream.close();
1653
                stream = null;
1654
                file.close();
1655
                file = null;
1656

    
1657
                System.gc();
1658

    
1659
                logger.debug("Ha creado el fichero ZIP");
1660
                                //Se extrae el zip
1661
                                MultiSplashWindow.process(5, "Extensiones descargadas.");
1662

    
1663
                                System.out.println("Extrayendo a " + destDir.getAbsolutePath());
1664

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

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

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

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

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

    
1705
                while (iter.hasNext()) {
1706
                        array.add(((PluginConfig) iter.next()).getExtensions());
1707
                }
1708

    
1709
                return (Extensions[]) array.toArray(new Extensions[0]);
1710
        }
1711

    
1712
        /**
1713
         * DOCUMENT ME!
1714
         *
1715
         * @return DOCUMENT ME!
1716
         */
1717
        public static HashMap getPluginConfig() {
1718
                return pluginsConfig;
1719
        }
1720

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

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

    
1739
                return null;
1740
        }
1741

    
1742
        /**
1743
         * DOCUMENT ME!
1744
         *
1745
         * @return DOCUMENT ME!
1746
         */
1747
        public static AndamiConfig getAndamiConfig() {
1748
                return andamiConfig;
1749
        }
1750

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

    
1770
                        if (!e1.hasPriority() && !e2.hasPriority()) {
1771
                                return -1;
1772
                        }
1773

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

    
1778
                        if (e2.hasPriority() && !e1.hasPriority()) {
1779
                                return Integer.MAX_VALUE;
1780
                        }
1781

    
1782
                        if (e1.getPriority() != e2.getPriority()){
1783
                                return e2.getPriority() - e1.getPriority();
1784
                        }else{
1785
                                return (e2.toString().compareTo(e1.toString()));
1786
                        }
1787
                }
1788
        }
1789

    
1790
        /**
1791
         * DOCUMENT ME!
1792
         */
1793
        private static class MenuComparator implements Comparator {
1794
                private static ExtensionComparator extComp = new ExtensionComparator();
1795

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

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

    
1818
                        if (e1.menu.hasPosition() && !e2.menu.hasPosition()) {
1819
                                return Integer.MIN_VALUE;
1820
                        }
1821

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

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

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

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

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

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

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

    
1924
                        if (e1.toolbar.hasPosition() && !e2.toolbar.hasPosition()) {
1925
                                return Integer.MIN_VALUE;
1926
                        }
1927

    
1928
                        if (e2.toolbar.hasPosition() && !e1.toolbar.hasPosition()) {
1929
                                return Integer.MAX_VALUE;
1930
                        }
1931
                        if (e1.toolbar.getPosition() != e2.toolbar.getPosition())
1932
                                return e1.toolbar.getPosition() - e2.toolbar.getPosition();
1933

    
1934
                        if (e1.toolbar.getActionTool().equals(e2.toolbar.getActionTool()) && e1.toolbar.getSelectableTool().equals(e2.toolbar.getSelectableTool())){
1935
                                return 0;
1936
                        }
1937
                        return (e1.toolbar.toString().compareTo(e2.toolbar.toString()));
1938
                }
1939
        }
1940

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

    
1979
                        if (e1.actiontool!=null) {
1980
                                if (e1.actiontool.hasPosition())
1981
                                        e1Position = e1.actiontool.getPosition();
1982
                        }
1983
                        else if (e1.selectabletool!=null) {
1984
                                if (e1.selectabletool.hasPosition())
1985
                                        e1Position = e1.selectabletool.getPosition();
1986
                        }
1987

    
1988
                        if (e2.actiontool!=null) {
1989
                                if (e2.actiontool.hasPosition())
1990
                                        e2Position = e2.actiontool.getPosition();
1991
                        }
1992
                        else if (e2.selectabletool!=null){
1993
                                if (e2.selectabletool.hasPosition())
1994
                                        e2Position = e2.selectabletool.getPosition();
1995
                        }
1996

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

    
2012

    
2013
        /**
2014
         * validates the user before starting gvsig
2015
         *
2016
         */
2017
        private static void validate(){
2018

    
2019
                IAuthentication session =  null;
2020
                try {
2021
                        session = (IAuthentication)Class.forName("com.iver.andami.authentication.Session").newInstance();
2022

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

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

    
2051
        public static String getDefaultLookAndFeel() {
2052
                String osName = (String) System.getProperty("os.name");
2053

    
2054
                if (osName.length() > 4 && osName.substring(0,5).toLowerCase().equals("linux"))
2055
                        return nonWinDefaultLookAndFeel;
2056

    
2057
                return UIManager.getSystemLookAndFeelClassName();
2058
        }
2059

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

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

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

    
2151
        }
2152

    
2153
        /**
2154
         * Gets Home Directory location of the application.
2155
         * May be set from outside the aplication by means of
2156
         * -DgvSIG.home=C:/data/gvSIG, where gvSIG its the name
2157
         * of the application
2158
         * @return
2159
         */
2160
        public static String getAppHomeDir() {
2161
                return appHomeDir;
2162
        }
2163

    
2164
        /**
2165
         * Sets Home Directory location of the application.
2166
         * May be set from outside the aplication by means of
2167
         * -DgvSIG.home=C:/data/gvSIG, where gvSIG its the name
2168
         * of the application
2169
         * @param appHomeDir
2170
         */
2171
        public static void setAppHomeDir(String appHomeDir) {
2172
                Launcher.appHomeDir = appHomeDir;
2173
        }
2174

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

    
2194

    
2195
                Iterator iter  = classesExtensions.keySet().iterator();
2196
                int charIndex;
2197
                Class key;
2198
                while (iter.hasNext()) {
2199
                        key = (Class)iter.next();
2200
                        charIndex = key.getName().indexOf(name);
2201
                        //System.out.println("key='"+key.getName()+"' name='"+name+"' charIndex="+charIndex);
2202
                        if (charIndex == 0) {
2203
                                IExtension ext =(IExtension)classesExtensions.get(key);
2204
                                if (ext instanceof ExtensionDecorator)
2205
                                        ext = ((ExtensionDecorator)ext).getExtension();
2206
                                PluginServices.setExclusiveUIExtension(ext);
2207
                                break;
2208
                        }
2209
                }
2210

    
2211
                logger.error(Messages.getString("No_se_encontro_la_extension_especificada_en_el_parametro_exclusiveUI") + " '" + name +"'");
2212
        }
2213
}