Statistics
| Revision:

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

History | View | Annotate | Download (60.7 KB)

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

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

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

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

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

    
134

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

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

    
163
                private ProxyAuth(String user, String pass) {
164
                        auth = new PasswordAuthentication(user, pass.toCharArray());
165
                }
166

    
167
                protected PasswordAuthentication getPasswordAuthentication() {
168
                        return auth;
169
                }
170
        }
171

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

    
187
                    if (!validJVM()){
188
                            System.exit(-1);
189
                    }
190

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

    
195
                    //  Clean temporal files
196
                    Utilities.cleanUpTempFiles();
197

    
198
                    appName = args[0];
199

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

    
209
                    andamiConfigPath = appHomeDir + "andami-config.xml";
210
                    pluginsPersistencePath = appHomeDir +
211
                    "plugins-persistence.xml";
212

    
213
                    // Configurar el log4j
214
                    PropertyConfigurator.configure(Launcher.class.getClassLoader()
215
                                    .getResource("log4j.properties"));
216

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

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

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

    
238
                    configureLocales(args);
239

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

    
261
                    validate();
262
                    // Mostrar la ventana de inicio
263
                    Frame f=new Frame();
264
                    splashWindow=new MultiSplashWindow(f);
265
                    
266
                    // Ponemos los datos del proxy
267
                    String host = prefs.get("firewall.http.host", "");
268
                        String port = prefs.get("firewall.http.port", "");
269

    
270
                        System.getProperties().put("http.proxyHost", host);
271
                        System.getProperties().put("http.proxyPort", port);
272

    
273
                    // Ponemos el usuario y clave del proxy, si existe                    
274
                    String proxyUser = prefs.get("firewall.http.user",null);
275
                    String proxyPassword = prefs.get("firewall.http.password", null);
276
                        if (proxyUser != null )
277
                        {
278
                                System.getProperties().put("http.proxyUserName", proxyUser);
279
                                System.getProperties().put("http.proxyPassword", proxyPassword);
280

    
281
                                Authenticator.setDefault(new ProxyAuth(proxyUser,
282
                                                                proxyPassword));
283
                        } else {
284
                                Authenticator.setDefault(new ProxyAuth("", ""));
285
                        }
286
                    
287

    
288
                    // TODO Buscar actualizaciones de los plugins
289
                    downloadExtensions(andamiConfig.getPluginsDirectory());
290

    
291
                    // Se leen los config.xml de los plugins -----++++
292
                    loadPlugins(andamiConfig.getPluginsDirectory());
293

    
294
                    // Se configura el classloader del plugin
295
                    pluginsClassLoaders();
296

    
297
                    // Se carga un Skin si alguno de los plugins trae informaci?n para ello
298
                    skinPlugin();
299

    
300
                    //Se configura la cola de eventos
301
                    EventQueue waitQueue = new AndamiEventQueue();
302
                    Toolkit.getDefaultToolkit().getSystemEventQueue().push(waitQueue);
303

    
304
                    // Se configura la mensajer?a del plugin
305
                    pluginsMessages();
306

    
307
                    // Se modifica el andami-config con los plugins nuevos
308
                    updateAndamiConfig();
309

    
310
                    // Se prepara el MainFrame para albergar las extensiones
311
                    frame = new MDIFrame();
312

    
313
                    // Se configura el nombre e icono de la aplicaci?n
314
                    frameIcon();
315

    
316
                    SwingUtilities.invokeAndWait(new Runnable() {
317
                            public void run() {
318
                                    frame.init();
319
                            }
320
                    });
321

    
322
                    // Se instalan los controles de las extensiones de los plugins
323
                    SwingUtilities.invokeAndWait(new Runnable() {
324
                            public void run() {
325
                                    installPluginsControls();
326
                                    installPluginsMenus();
327
                                    installPluginsLabels();
328
                            }
329
                    });
330

    
331
                    // Leer el fichero de persistencia
332
                    //  info de los plugins
333
                    //  bookmarks de los plugins
334
                    loadPluginsPersistence();
335

    
336
                    // Se instalan los controles del skin
337
                    // Se inicializan todas las extensiones de todos los plugins
338
                    SwingUtilities.invokeAndWait(new Runnable() {
339
                            public void run() {
340
                                    initializeExtensions();
341
                                    postInitializeExtensions();
342
                            }
343
                    });
344
                    frame.setClassesExtensions(classesExtensions);
345

    
346
                    // Se instalan los bookmarks de los plugins
347

    
348
                    //Se muestra el frame principal
349
                    frame.show();
350

    
351
                    // Definimos un KeyEventDispatcher global para que las extensiones
352
                    // puedan registrar sus "teclas r?pidas".
353
                    GlobalKeyEventDispatcher keyDispatcher = GlobalKeyEventDispatcher.getInstance();
354
                    KeyboardFocusManager.getCurrentKeyboardFocusManager().addKeyEventDispatcher(keyDispatcher);
355

    
356
                    SwingUtilities.invokeAndWait(new Runnable() {
357
                            public void run() {
358
                                    frame.enableControls();
359
                            }
360
                    });
361
                    splashWindow.close();
362
            }catch(Exception e){
363
                    logger.error("excepci?n al arrancar", e);
364
                    System.exit(-1);
365
            }
366

    
367
    }
368

    
369
        /**
370
         * Recupera la geometr?a (tama?o, posici?n y estado) de la ventana principal de Andami.
371
         * TODO Pendiente de ver como se asigna un pluginServices para el launcher.
372
         * @author LWS
373
         */
374
        private static void restoreMDIStatus(XMLEntity xml) {
375
                //System.err.println("Launcher: restoreMDIStatus()");
376
                if (xml == null) xml = new XMLEntity();
377
                //  restore frame size
378
                Dimension sz = new Dimension(700,580);
379
                if (xml.contains("MDIFrameSize")) {
380
                        int [] wh = xml.getIntArrayProperty("MDIFrameSize");
381
                        sz = new Dimension(wh[0], wh[1]);
382
                }
383
                frame.setSize(sz);
384
                //  restore frame location
385
                Point pos = new Point(10,10);
386
                if (xml.contains("MDIFramePos")) {
387
                        int [] xy = xml.getIntArrayProperty("MDIFramePos");
388
                        pos = new Point(xy[0], xy[1]);
389
                }
390
                frame.setLocation(pos);
391

    
392
                //  restore frame status (Maximized, minimized, etc);
393
                int state = java.awt.Frame.MAXIMIZED_BOTH;
394
                if (xml.contains("MDIFrameState")) {
395
                        state = xml.getIntProperty("MDIFrameState");
396
                }
397
                frame.setExtendedState(state);
398
        }
399

    
400
        private static XMLEntity saveMDIStatus() {
401
                XMLEntity xml = new XMLEntity();
402
                // save frame size
403
                int [] wh = new int[2];
404
                wh[0] = frame.getWidth();
405
                wh[1] = frame.getHeight();
406
                xml.putProperty("MDIFrameSize", wh);
407
                // save frame location
408
                int [] xy = new int[2];
409
                xy[0] = frame.getX();
410
                xy[1] = frame.getY();
411
                xml.putProperty("MDIFramePos", xy);
412
                // save frame status
413
                xml.putProperty("MDIFrameState", frame.getExtendedState());
414
                return xml;
415
        }
416

    
417
        /**
418
     * @return
419
     */
420
    private static boolean validJVM() {
421
        char thirdCharacter = System.getProperty("java.version").charAt(2);
422
        if (thirdCharacter < '4'){
423
            return false;
424
            }else{
425
                return true;
426
            }
427
    }
428

    
429
    /**
430
         * DOCUMENT ME!
431
         *
432
         * @throws ConfigurationException
433
         */
434
        private static void loadPluginsPersistence() throws ConfigurationException {
435
                XMLEntity entity = persistenceFromXML();
436

    
437
                //System.err.println("loadPluginPersistence()");
438
                for (int i = 0; i < entity.getChildrenCount(); i++) {
439
                        XMLEntity plugin = entity.getChild(i);
440
                        String pName = plugin.getStringProperty(
441
                                        "com.iver.andami.pluginName");
442
                        //System.err.println("--> "+pName);
443
                        if (pluginsServices.get(pName)!= null){
444
                                ((PluginServices) pluginsServices.get(pName)).setPersistentXML(plugin);
445
                        } else {
446
                                if (pName.startsWith("Andami.Launcher"))
447
                                        restoreMDIStatus(plugin);
448
                        }
449
                }
450
        }
451

    
452
        /**
453
         * Salva la persistencia de los plugins.
454
         * @author LWS
455
         */
456
        private static void savePluginPersistence() {
457
                Iterator i = pluginsConfig.keySet().iterator();
458

    
459
                XMLEntity entity = new XMLEntity();
460

    
461
                while (i.hasNext()) {
462
                        String pName = (String) i.next();
463
                        PluginServices ps = (PluginServices) pluginsServices.get(pName);
464
                        XMLEntity ent = ps.getPersistentXML();
465

    
466
                        if (ent != null) {
467
                                ent.putProperty("com.iver.andami.pluginName", pName);
468
                                entity.addChild(ent);
469
                        }
470
                }
471
                XMLEntity ent = saveMDIStatus();
472
                if (ent != null) {
473
                        ent.putProperty("com.iver.andami.pluginName", "Andami.Launcher");
474
                        entity.addChild(ent);
475
                }
476
                try {
477
                        persistenceToXML(entity);
478
                } catch (ConfigurationException e1) {
479
                        logger.error(Messages.getString(
480
                                        "Launcher.Se_produjo_un_error_guardando_la_configuracion_de_los_plugins"),
481
                                e1);
482
                }
483
        }
484

    
485
        /**
486
         * DOCUMENT ME!
487
         */
488
        private static void installPluginsLabels() {
489
                Iterator i = pluginsConfig.keySet().iterator();
490

    
491
                while (i.hasNext()) {
492
                        String name = (String) i.next();
493
                        PluginConfig pc = (PluginConfig) pluginsConfig.get(name);
494
                        PluginServices ps = (PluginServices) pluginsServices.get(name);
495

    
496
                        LabelSet[] ls = pc.getLabelSet();
497

    
498
                        for (int j = 0; j < ls.length; j++) {
499
                                PluginClassLoader loader = ps.getClassLoader();
500

    
501
                                try {
502
                                        Class clase = loader.loadClass(ls[j].getClassName());
503
                                        frame.setLabels(clase, ls[j].getLabel());
504
                                } catch (ClassNotFoundException e) {
505
                                        logger.error(Messages.getString("Launcher.labelset_class"),
506
                                                e);
507
                                }
508
                        }
509
                }
510
        }
511

    
512
        /**
513
         * DOCUMENT ME!
514
         *
515
         * @throws MDIManagerLoadException
516
         */
517
        private static void skinPlugin() throws MDIManagerLoadException {
518
                Iterator i = pluginsConfig.keySet().iterator();
519

    
520
                while (i.hasNext()) {
521
                        String name = (String) i.next();
522
                        PluginConfig pc = (PluginConfig) pluginsConfig.get(name);
523
                        PluginServices ps = (PluginServices) pluginsServices.get(name);
524

    
525
                        if (pc.getExtensions().getSkinExtension() != null) {
526
                                if (MDIManagerFactory.getSkinExtension() != null) {
527
                                        logger.warn(Messages.getString(
528
                                                        "Launcher.Dos_skin_extension"));
529
                                }
530

    
531
                                SkinExtension se = pc.getExtensions().getSkinExtension();
532

    
533
                                MDIManagerFactory.setSkinExtension(se, ps.getClassLoader());
534

    
535
                                Class skinClass;
536

    
537
                                try {
538
                                        skinClass = ps.getClassLoader().loadClass(se.getClassName());
539

    
540
                                        com.iver.andami.plugins.IExtension skinInstance = (com.iver.andami.plugins.IExtension) skinClass.newInstance();
541
                                        // classesExtensions.put(skinClass, skinInstance);
542
                                        // jaume
543
                                        ExtensionDecorator newExtensionDecorator = new ExtensionDecorator(skinInstance, ExtensionDecorator.INACTIVE);
544
                                        classesExtensions.put(skinClass, newExtensionDecorator);
545
                                } catch (ClassNotFoundException e) {
546
                                        logger.error(Messages.getString(
547
                                                        "Launcher.No_se_encontro_la_clase_mdi_manager"), e);
548
                                        throw new MDIManagerLoadException(e);
549
                                } catch (InstantiationException e) {
550
                                        logger.error(Messages.getString(
551
                                                        "Launcher.No_se_pudo_instanciar_la_clase_mdi_manager"),
552
                                                e);
553
                                        throw new MDIManagerLoadException(e);
554
                                } catch (IllegalAccessException e) {
555
                                        logger.error(Messages.getString(
556
                                                        "Launcher.No_se_pudo_acceder_a_la_clase_mdi_manager"),
557
                                                e);
558
                                        throw new MDIManagerLoadException(e);
559
                                }
560
                        }
561
                }
562
        }
563

    
564
        /**
565
         *
566
         */
567
        private static void frameIcon() {
568
                Iterator i = pluginsConfig.keySet().iterator();
569

    
570
                while (i.hasNext()) {
571
                        String pName = (String) i.next();
572
                        PluginConfig pc = (PluginConfig) pluginsConfig.get(pName);
573
                        PluginServices ps = (PluginServices) pluginsServices.get(pName);
574

    
575
                        if (pc.getIcon() != null) {
576
                                ImageIcon icon = new ImageIcon(ps.getClassLoader().getResource(pc.getIcon()
577
                                                                                                                                                                 .getSrc()));
578
                                frame.setIconImage(icon.getImage());
579
                                frame.setTitlePrefix(pc.getIcon().getText());
580
                        }
581
                }
582
        }
583

    
584
        /**
585
         *
586
         */
587
        private static void initializeExtensions() {
588
                Iterator i = pluginsOrdered.iterator();
589

    
590
                while (i.hasNext()) {
591
                        String pName = (String) i.next();
592
            logger.debug("Initializing extensions from " + pName);
593
                        PluginConfig pc = (PluginConfig) pluginsConfig.get(pName);
594
                        PluginServices ps = (PluginServices) pluginsServices.get(pName);
595

    
596
                        Extension[] exts = pc.getExtensions().getExtension();
597

    
598
                        TreeMap orderedExtensions = new TreeMap(new ExtensionComparator());
599

    
600
                        for (int j = 0; j < exts.length; j++) {
601
                                if (!exts[j].getActive()) {
602
                                        continue;
603
                                }
604

    
605
                                if (orderedExtensions.containsKey(exts[j])) {
606
                                        logger.warn(Messages.getString(
607
                                                        "Launcher.Two_extensions_with_the_same_priority") +
608
                                                exts[j].getClassName());
609
                                }
610

    
611
                                orderedExtensions.put(exts[j], null);
612
                        }
613

    
614
                        Iterator e = orderedExtensions.keySet().iterator();
615

    
616
                        while (e.hasNext()) {
617
                                Extension extension = (Extension) e.next();
618
                                com.iver.andami.plugins.IExtension extensionInstance;
619

    
620
                                try {
621
                                        Class extensionClass = ps.getClassLoader().loadClass(extension.getClassName());
622
                                        extensionInstance = (com.iver.andami.plugins.IExtension) extensionClass.newInstance();
623

    
624
                                        // CON DECORATOR
625
                                        // ANTES: classesExtensions.put(extensionClass, extensionInstance);
626
                                        // AHORA: CREAMOS UNA ExtensionDecorator y asignamos esta instancia para
627
                                        // poder ampliar con nuevas propiedades (AlwaysVisible, por ejemplo)
628
                                        // Para crear la nueva clase ExtensionDecorator, le pasamos como par?metro
629
                                        // la extensi?n original que acabamos de crear
630
                                        // 0-> Inactivo, controla la extension
631
                                        // 1-> Siempre visible
632
                                        // 2-> Invisible
633
                                        ExtensionDecorator newExtensionDecorator = new ExtensionDecorator(extensionInstance, ExtensionDecorator.INACTIVE);
634
                                        classesExtensions.put(extensionClass, newExtensionDecorator);
635
                                        System.err.println("Loading "+extension.getClassName()+"...");
636
                    // logger.debug("Initializing " + extension.getClassName());
637
                    extensionInstance.initialize();
638
                    extensions.add(extensionInstance);
639
                    // logger.debug(extension.getClassName() + " initialized.");
640

    
641
                                } catch (InstantiationException e1) {
642
                                        logger.error(Messages.getString(
643
                                                        "Launcher.Error_instanciando_la_extension") +
644
                                                extension.getClassName(), e1);
645
                                } catch (IllegalAccessException e1) {
646
                                        logger.error(Messages.getString(
647
                                                        "Launcher.Error_instanciando_la_extension") +
648
                                                extension.getClassName(), e1);
649
                                } catch (ClassNotFoundException e1) {
650
                                        logger.error(Messages.getString(
651
                                                        "Launcher.No_se_encontro_la_clase_de_la_extension") +
652
                                                extension.getClassName(), e1);
653
                                } catch (NoClassDefFoundError e1) {
654
                                        logger.error(Messages.getString(
655
                                                        "Launcher.Error_localizando_la_clase_de_la_extension") +
656
                                                extension.getClassName(), e1);
657
                                }
658
                        }
659
                }
660
        }
661

    
662
        private static void postInitializeExtensions() {
663
                for (int i=0;i<extensions.size();i++) {
664
                        com.iver.andami.plugins.IExtension extensionInstance=(com.iver.andami.plugins.IExtension)extensions.get(i);
665
                        extensionInstance.postInitialize();
666
                }
667
        }
668
        /**
669
         * DOCUMENT ME!
670
         */
671
        private static void installPluginsMenus() {
672
                TreeMap orderedMenus = new TreeMap(new MenuComparator());
673

    
674
                Iterator i = pluginsConfig.keySet().iterator();
675

    
676
                while (i.hasNext()) {
677
                        String pName = (String) i.next();
678
                        PluginServices ps = (PluginServices) pluginsServices.get(pName);
679
                        PluginConfig pc = (PluginConfig) pluginsConfig.get(pName);
680

    
681
                        Extension[] exts = pc.getExtensions().getExtension();
682

    
683
                        for (int j = 0; j < exts.length; j++) {
684
                                if (!exts[j].getActive()) {
685
                                        continue;
686
                                }
687

    
688
                                Menu[] menus = exts[j].getMenu();
689

    
690
                                for (int k = 0; k < menus.length; k++) {
691
                                        SortableMenu sm = new SortableMenu(ps.getClassLoader(),
692
                                                        exts[j], menus[k]);
693

    
694
                                        if (orderedMenus.containsKey(sm)) {
695
                                                logger.error(Messages.getString(
696
                                                                "Launcher.Two_menus_with_the_same_position") + " - " +
697
                                                        menus[k].getText()+ " - " + exts[j].getClassName());
698
                                        }
699

    
700
                                        orderedMenus.put(sm, null);
701
                                }
702
                        }
703

    
704
                        // Se instalan las extensiones de MDI
705
                        SkinExtension skinExt = pc.getExtensions().getSkinExtension();
706

    
707
                        if (skinExt != null) {
708
                                Menu[] menu = skinExt.getMenu();
709

    
710
                                for (int k = 0; k < menu.length; k++) {
711
                                        SortableMenu sm = new SortableMenu(ps.getClassLoader(),
712
                                                        skinExt, menu[k]);
713

    
714
                                        if (orderedMenus.containsKey(sm)) {
715
                                                logger.error(Messages.getString(
716
                                                                "Launcher.Two_menus_with_the_same_position") +
717
                                                        skinExt.getClassName());
718
                                        }
719

    
720
                                        orderedMenus.put(sm, null);
721
                                }
722
                        }
723
                }
724

    
725
                //Se itera por los menus ordenados
726
                Iterator e = orderedMenus.keySet().iterator();
727

    
728
                // Se ordenan los menues
729
                while (e.hasNext()) {
730
                        try {
731
                                SortableMenu sm = (SortableMenu) e.next();
732

    
733
                                frame.addMenu(sm.loader, sm.extension, sm.menu);
734
                        } catch (ClassNotFoundException ex) {
735
                                logger.error(Messages.getString(
736
                                                "Launcher.No_se_encontro_la_clase_de_la_extension"), ex);
737
                        }
738
                }
739
        }
740

    
741
        /**
742
         * Installs the menus, toolbars, actiontools, selectable toolbars and combos.
743
         * The order in which they are shown is determined here.
744
         */
745
        private static void installPluginsControls() {
746
                Iterator i = pluginsConfig.keySet().iterator();
747

    
748
                HashMap extensionPluginServices = new HashMap();
749
                HashMap extensionPluginConfig = new HashMap();
750
                TreeMap orderedExtensions = new TreeMap(new ExtensionComparator());
751

    
752
                // First of all, sort the extensions.
753
                // We need to iterate on the plugins, and iterate on each plugin's extensions
754
                // (each plugin may contain one or more extensions)
755
                while (i.hasNext()) { // iterate on the plugins
756
                        String pName = (String) i.next();
757
                        PluginConfig pc = (PluginConfig) pluginsConfig.get(pName);
758
                        PluginServices ps = (PluginServices) pluginsServices.get(pName);
759

    
760
                        Extension[] exts = pc.getExtensions().getExtension();
761

    
762
                        for (int j = 0; j < exts.length; j++) { // iterate on the extensions
763
                                if (exts[j].getActive()) {
764
                                        if (orderedExtensions.containsKey(exts[j])) {
765
                                                logger.error(Messages.getString(
766
                                                "Launcher.Two_extensions_with_the_same_priority") +
767
                                                exts[j].getClassName());
768
                                        }
769

    
770
                                        orderedExtensions.put(exts[j], null);
771
                                        extensionPluginServices.put(exts[j], ps);
772
                                        extensionPluginConfig.put(exts[j], pc);
773
                                }
774
                        }
775
                }
776

    
777
                TreeMap orderedTools = new TreeMap(new ToolComparator());
778
                Iterator e = orderedExtensions.keySet().iterator();
779

    
780
                // sort the toolbars and tools from 'normal' extensions (actiontools, selectabletools)
781
                // and load the  combo-scales and combo-buttons for the status bar
782
                while (e.hasNext()) {
783
                        Extension ext = (Extension) e.next();
784

    
785
                        ToolBar[] toolbars = ext.getToolBar();
786

    
787
                        // get tools from toolbars
788
                        for (int k = 0; k < toolbars.length; k++) {
789
                                ActionTool[] tools = toolbars[k].getActionTool();
790

    
791
                                for (int t = 0; t < tools.length; t++) {
792
                                        SortableTool sm = new SortableTool(((PluginServices)extensionPluginServices.get(ext)).getClassLoader(), ext,
793
                                                        toolbars[k], tools[t]);
794
                                        orderedTools.put(sm, null);
795
                                }
796

    
797
                                SelectableTool[] sTools = toolbars[k].getSelectableTool();
798

    
799
                                for (int t = 0; t < sTools.length; t++) {
800
                                        SortableTool sm=new SortableTool(((PluginServices)extensionPluginServices.get(ext)).getClassLoader(), ext,
801
                                                        toolbars[k], sTools[t]);
802
                                        orderedTools.put(sm, null);
803
                                }
804
                        }
805

    
806
                        // get controls for statusBar
807
                        PluginServices ps = (PluginServices) extensionPluginServices.get(ext);
808
                        PluginClassLoader loader = ps.getClassLoader();
809

    
810
                        //ArrayList componentList = new ArrayList();
811
                        ComboScale[] comboScaleArray = ext.getComboScale();
812
                        for (int k=0; k < comboScaleArray.length; k++) {
813
                                org.gvsig.gui.beans.controls.comboscale.ComboScale combo = new org.gvsig.gui.beans.controls.comboscale.ComboScale();
814
                                String label = comboScaleArray[k].getLabel();
815
                                if (label!=null)
816
                                        combo.setLabel(label);
817
                                String name = comboScaleArray[k].getName();
818
                                if (name!=null)
819
                                        combo.setName(name);
820
                                String[] elementsString = ((String)comboScaleArray[k].getElements()).split(";");
821
                                long[] elements = new long[elementsString.length];
822
                                for (int currentElem=0; currentElem<elementsString.length; currentElem++) {
823
                                        try {
824
                                                elements[currentElem] = Long.parseLong(elementsString[currentElem]);
825
                                        }
826
                                        catch (NumberFormatException nfex1) {
827
                                                logger.error(ext.getClassName()+" -- "+Messages.getString( "error_parsing_comboscale_elements"));
828
                                                elements[currentElem] = 0;
829
                                        }
830
                                }
831
                                combo.setItems(elements);
832
                                try {
833
                                        long value = Long.parseLong((String)comboScaleArray[k].getValue());
834
                                        combo.setScale(value);
835
                                }
836
                                catch (NumberFormatException nfex2) {
837
                                        logger.error(ext.getClassName()+" -- "+Messages.getString( "error_parsing_comboscale_value"));
838
                                }
839
                                try {
840
                                        frame.addStatusBarControl(loader.loadClass(ext.getClassName()),combo);
841
                                } catch (ClassNotFoundException e1) {
842
                                        logger.error(Messages.getString("Launcher.error_getting_class_loader_for_status_bar_control"), e1);
843
                                }
844
                        }
845

    
846
                        ComboButton[] comboButtonArray = ext.getComboButton();
847
                        for (int k=0; k < comboButtonArray.length; k++) {
848
                                ComboButtonElement[] elementList = comboButtonArray[k].getComboButtonElement();
849
                                org.gvsig.gui.beans.controls.combobutton.ComboButton combo = new org.gvsig.gui.beans.controls.combobutton.ComboButton();
850
                                String name = comboButtonArray[k].getName();
851
                                if (name!=null)
852
                                        combo.setName(name);
853
                                for (int currentElement=0; currentElement<elementList.length; currentElement++) {
854
                                        ComboButtonElement element = elementList[currentElement];
855
                                        ImageIcon icon;
856
                                        URL iconLocation = loader.getResource(element.getIcon());
857
                                        if (iconLocation==null)
858
                                                logger.error(Messages.getString("Icon_not_found_")+element.getIcon());
859
                                        else {
860
                                                icon = new ImageIcon(iconLocation);
861
                                                JButton button = new JButton(icon);
862
                                                combo.addButton(button);
863
                                                button.setActionCommand(element.getActionCommand());
864
                                        }
865
                                }
866
                                try {
867
                                        frame.addStatusBarControl(loader.loadClass(ext.getClassName()), combo);
868
                                } catch (ClassNotFoundException e1) {
869
                                        logger.error(Messages.getString("Launcher.error_getting_class_loader_for_status_bar_control"), e1);
870
                                }
871
                        }
872
                }
873

    
874
                // Add the tools from MDI extensions to the ordered tool-list, so that we get a sorted list containing all the tools
875
                i = pluginsConfig.keySet().iterator();
876
                while (i.hasNext()) {
877
                        String pName = (String) i.next();
878
                        PluginConfig pc = (PluginConfig) pluginsConfig.get(pName);
879
                        PluginServices ps = (PluginServices) pluginsServices.get(pName);
880

    
881
                        SkinExtension skinExt = pc.getExtensions().getSkinExtension();
882

    
883
                        if (skinExt != null) {
884
                                ToolBar[] toolbars = skinExt.getToolBar();
885

    
886
                                for (int k = 0; k < toolbars.length; k++) {
887
                                        ActionTool[] tools = toolbars[k].getActionTool();
888

    
889
                                        for (int t = 0; t < tools.length; t++) {
890
                                                SortableTool stb=new SortableTool(ps.getClassLoader(), skinExt,
891
                                                                toolbars[k], tools[t]);
892
                                                orderedTools.put(stb,null);
893
                                        }
894

    
895
                                        SelectableTool[] sTools = toolbars[k].getSelectableTool();
896

    
897
                                        for (int t = 0; t < sTools.length; t++) {
898
                                                SortableTool stb=new SortableTool(ps.getClassLoader(), skinExt,
899
                                                                toolbars[k], sTools[t]);
900
                                                orderedTools.put(stb,null);
901
                                        }
902
                                }
903
                        }
904
                        // Install popup menus
905
                        PopupMenus pus = pc.getPopupMenus();
906

    
907
                        if (pus != null) {
908
                                PopupMenu[] menus = pus.getPopupMenu();
909

    
910
                                for (int j = 0; j < menus.length; j++) {
911
                                        frame.addPopupMenu(ps.getClassLoader(), menus[j]);
912
                                }
913
                        }
914
                }
915

    
916
                // loop on the ordered extension list, to add them to the interface in an ordered way
917
                Iterator t = orderedTools.keySet().iterator();
918
                while (t.hasNext()) {
919
                        try {
920
                                SortableTool stb = (SortableTool) t.next();
921
                                if (stb.actiontool!=null)
922
                                        frame.addTool(stb.loader, stb.extension,stb.toolbar, stb.actiontool);
923
                                else
924
                                        frame.addTool(stb.loader, stb.extension,stb.toolbar, stb.selectabletool);
925
                        } catch (ClassNotFoundException ex) {
926
                                logger.error(Messages.getString(
927
                                "Launcher.No_se_encontro_la_clase_de_la_extension"), ex);
928
                        }
929
                }
930
        }
931

    
932
        /**
933
         * Adds new plugins to the the andami-config file.
934
         */
935
        private static void updateAndamiConfig() {
936
                HashSet olds = new HashSet();
937

    
938
                Plugin[] plugins = andamiConfig.getPlugin();
939

    
940
                for (int i = 0; i < plugins.length; i++) {
941
                        olds.add(plugins[i].getName());
942
                }
943

    
944
                Iterator i = pluginsServices.values().iterator();
945

    
946
                while (i.hasNext()) {
947
                        PluginServices ps = (PluginServices) i.next();
948

    
949
                        if (!olds.contains(ps.getPluginName())) {
950
                                Plugin p = new Plugin();
951
                                p.setName(ps.getPluginName());
952
                                p.setUpdate(false);
953

    
954
                                andamiConfig.addPlugin(p);
955
                        }
956
                }
957
        }
958

    
959
        /**
960
         * DOCUMENT ME!
961
         */
962
        private static void pluginsClassLoaders() {
963
                HashSet instalados = new HashSet();
964

    
965
                // Se itera hasta que est?n todos instalados
966
                while (instalados.size() != pluginsConfig.size()) {
967
                        boolean circle = true;
968

    
969
                        //Hacemos una pasada por todos los plugins
970
                        Iterator i = pluginsConfig.keySet().iterator();
971

    
972
                        while (i.hasNext()) {
973
                                String pluginName = (String) i.next();
974
                                PluginConfig config = (PluginConfig) pluginsConfig.get(pluginName);
975

    
976
                                if (instalados.contains(pluginName)) {
977
                                        continue;
978
                                }
979

    
980
                                //Se obtienen las dependencias y sus class loaders
981
                                boolean ready = true;
982
                                Depends[] dependencies = config.getDepends();
983
                                PluginClassLoader[] loaders = new PluginClassLoader[dependencies.length];
984

    
985
                                for (int j = 0; j < dependencies.length; j++) {
986
                                        if (pluginsConfig.get(dependencies[j].getPluginName()) == null) {
987
                                                logger.error(Messages.getString(
988
                                                                "Launcher.Dependencia_no_resuelta_en_plugin") +
989
                                                        pluginName + ": " +
990
                                                        dependencies[j].getPluginName());
991

    
992
                                                continue;
993
                                        }
994

    
995
                                        if (!instalados.contains(dependencies[j].getPluginName())) {
996
                                                ready = false;
997
                                        } else {
998
                                                loaders[j] = ((PluginServices) pluginsServices.get(dependencies[j].getPluginName())).getClassLoader();
999
                                        }
1000
                                }
1001

    
1002
                                //Si no est?n sus dependencias satisfechas se aborta la instalaci?n
1003
                                if (!ready) {
1004
                                        continue;
1005
                                }
1006

    
1007
                                //Se genera el class loader
1008
                                String jardir = config.getLibraries().getLibraryDir();
1009
                                File jarDir = new File(andamiConfig.getPluginsDirectory() +
1010
                                                File.separator + pluginName + File.separator + jardir);
1011
                                File[] jarFiles = jarDir.listFiles(new FileFilter() {
1012
                                                        public boolean accept(File pathname) {
1013
                                                                return (pathname.getName().toUpperCase()
1014
                                                                                                .endsWith(".JAR")) ||
1015
                                                                (pathname.getName().toUpperCase().endsWith(".ZIP"));
1016
                                                        }
1017
                                                });
1018

    
1019
                                URL[] urls = new URL[jarFiles.length];
1020

    
1021
                                for (int j = 0; j < jarFiles.length; j++) {
1022
                                        try {
1023
                                                urls[j] = new URL("file:" + jarFiles[j]);
1024
                                        } catch (MalformedURLException e) {
1025
                                                logger.error(Messages.getString(
1026
                                                                "Launcher.No_se_puede_acceder_a") +
1027
                                                        jarFiles[j]);
1028
                                        }
1029
                                }
1030

    
1031
                                PluginClassLoader loader;
1032

    
1033
                                try {
1034
                                        loader = new PluginClassLoader(urls,
1035
                                                        andamiConfig.getPluginsDirectory() +
1036
                                                        File.separator + pluginName,
1037
                                                        Launcher.class.getClassLoader(), loaders);
1038

    
1039
                                        PluginServices ps = new PluginServices(loader);
1040

    
1041
                                        pluginsServices.put(ps.getPluginName(), ps);
1042

    
1043
                                        instalados.add(pluginName);
1044
                    // FJP: Los metemos ordenados para luego no cargar uno que necesita de otro antes de tiempo. Esto lo usaremos al
1045
                    // inicializar los plugins
1046
                    pluginsOrdered.add(pluginName);
1047

    
1048
                                        circle = false;
1049
                                } catch (IOException e) {
1050
                                        logger.error(Messages.getString(
1051
                                                        "Launcher.Error_con_las_librerias_del_plugin"), e);
1052
                                        pluginsConfig.remove(pluginName);
1053
                                        i = pluginsConfig.keySet().iterator();
1054
                                }
1055
                        }
1056

    
1057
                        if (circle) {
1058
                                logger.error(Messages.getString(
1059
                                                "Launcher.Hay_dependencias_circulares"));
1060

    
1061
                                break;
1062
                        }
1063
                }
1064

    
1065
                //Se eliminan los plugins que no fueron instalados
1066
                Iterator i = pluginsConfig.keySet().iterator();
1067

    
1068
                while (i.hasNext()) {
1069
                        String pluginName = (String) i.next();
1070
                        PluginConfig config = (PluginConfig) pluginsConfig.get(pluginName);
1071
                        PluginServices ps = (PluginServices) pluginsServices.get(pluginName);
1072

    
1073
                        if (ps == null) {
1074
                                pluginsConfig.remove(pluginName);
1075
                                i = pluginsConfig.keySet().iterator();
1076
                        }
1077
                }
1078
        }
1079

    
1080
        /**
1081
         * DOCUMENT ME!
1082
         */
1083
        private static void pluginsMessages() {
1084
                /* add gvsig translations first. This should be done using a generic "appPlugin" variable, instead
1085
                 * of using "com.iver.cit.gvsig" directly, but I'll do it when we use the new appgvSIG launcher.
1086
                 * I keep this workaround for the moment.
1087
                 */
1088
                PluginConfig config = (PluginConfig) pluginsConfig.get("com.iver.cit.gvsig");
1089
                PluginServices ps = (PluginServices) pluginsServices.get("com.iver.cit.gvsig");
1090
                if (config.getResourceBundle() != null) {
1091
                        org.gvsig.i18n.Messages.addResourceFamily(config.getResourceBundle().getName(), ps.getClassLoader(), "com.iver.cit.gvsig");
1092
                }
1093

    
1094
                //Iteramos por todos los plugins
1095
                Iterator i = pluginsConfig.keySet().iterator();
1096

    
1097
                while (i.hasNext()) {
1098
                        String pluginName = (String) i.next();
1099
                        if (!pluginName.equals("com.iver.cit.gvsig")) { // we've already loaded com.iver.cit.gvsig
1100
                                config = (PluginConfig) pluginsConfig.get(pluginName);
1101
                                ps = (PluginServices) pluginsServices.get(pluginName);
1102

    
1103
                                if (config.getResourceBundle() != null && !config.getResourceBundle().getName().equals("")) {
1104
                                        // add the locale files associated with the plugin
1105
                                        org.gvsig.i18n.Messages.addResourceFamily(config.getResourceBundle().getName(), ps.getClassLoader(), pluginName);
1106
                                }
1107
                        }
1108
                }
1109
        }
1110

    
1111
        /**
1112
         * DOCUMENT ME!
1113
         *
1114
         * @param name DOCUMENT ME!
1115
         *
1116
         * @return DOCUMENT ME!
1117
         */
1118
        static PluginServices getPluginServices(String name) {
1119
                return (PluginServices) pluginsServices.get(name);
1120
        }
1121

    
1122
        /**
1123
         * DOCUMENT ME!
1124
         *
1125
         * @return DOCUMENT ME!
1126
         */
1127
        static String getPluginsDir() {
1128
                return andamiConfig.getPluginsDirectory();
1129
        }
1130

    
1131
        /**
1132
         * DOCUMENT ME!
1133
         *
1134
         * @param s DOCUMENT ME!
1135
         */
1136
        static void setPluginsDir(String s) {
1137
                andamiConfig.setPluginsDirectory(s);
1138
        }
1139

    
1140
        /**
1141
         * DOCUMENT ME!
1142
         *
1143
         * @return DOCUMENT ME!
1144
         */
1145
        static MDIFrame getMDIFrame() {
1146
                return frame;
1147
        }
1148

    
1149
        /**
1150
         * DOCUMENT ME!
1151
         *
1152
         * @param pluginsDirectory
1153
         */
1154
        private static void loadPlugins(String pluginsDirectory) {
1155
                File pDir = new File(pluginsDirectory);
1156

    
1157
                if (!pDir.exists()) {
1158
                        return;
1159
                }
1160

    
1161
                File[] pluginDirs = pDir.listFiles();
1162

    
1163
                for (int i = 0; i < pluginDirs.length; i++) {
1164
                        if (pluginDirs[i].isDirectory()) {
1165
                                File configXml = new File(pluginDirs[i].getAbsolutePath() +
1166
                                                File.separator + "config.xml");
1167

    
1168
                                try {
1169
                                        FileInputStream is = new FileInputStream(configXml);
1170
                                        Reader xml = com.iver.utiles.xml.XMLEncodingUtils.getReader(is);
1171
                                        if (xml==null) {
1172
                                                // the encoding was not correctly detected, use system default
1173
                                                xml = new FileReader(configXml);
1174
                                        }
1175
                                        else {
1176
                                                // use a buffered reader to improve performance
1177
                                                xml = new BufferedReader(xml);
1178
                                        }
1179
                                        PluginConfig pConfig = (PluginConfig) PluginConfig.unmarshal(xml);
1180
                                        pluginsConfig.put(pluginDirs[i].getName(), pConfig);
1181
                                } catch (FileNotFoundException e) {
1182
                                        logger.info(Messages.getString(
1183
                                                        "Launcher.Ignorando_el_directorio") +
1184
                                                pluginDirs[i].getAbsolutePath() +
1185
                                                Messages.getString("Launcher.config_no_encontrado"));
1186
                                } catch (MarshalException e) {
1187
                                        logger.info(Messages.getString(
1188
                                                        "Launcher.Ignorando_el_directorio") +
1189
                                                pluginDirs[i].getAbsolutePath() +
1190
                                                Messages.getString("Launcher.config_mal_formado"), e);
1191
                                } catch (ValidationException e) {
1192
                                        logger.info(Messages.getString(
1193
                                                        "Launcher.Ignorando_el_directorio") +
1194
                                                pluginDirs[i].getAbsolutePath() +
1195
                                                Messages.getString("Launcher.config_mal_formado"), e);
1196
                                }
1197
                        }
1198
                }
1199
        }
1200

    
1201
        /**
1202
         * DOCUMENT ME!
1203
         *
1204
         * @param language
1205
         * @param country
1206
         * @param variant
1207
         *
1208
         * @return DOCUMENT ME!
1209
         */
1210
        private static Locale getLocale(String language, String country,
1211
                String variant) {
1212
                if (variant != null) {
1213
                        return new Locale(language, country, variant);
1214
                } else if (country != null) {
1215
                        return new Locale(language, country);
1216
                } else if (language != null) {
1217
                        return new Locale(language);
1218
                } else {
1219
                        return new Locale("es");
1220
                }
1221
        }
1222

    
1223
        /**
1224
         * DOCUMENT ME!
1225
         *
1226
         * @param file DOCUMENT ME!
1227
         *
1228
         * @throws IOException DOCUMENT ME!
1229
         * @throws MarshalException DOCUMENT ME!
1230
         * @throws ValidationException DOCUMENT ME!
1231
         */
1232
        private static void andamiConfigToXML(String file)
1233
                throws IOException, MarshalException, ValidationException {
1234
                File xml = new File(file);
1235
                File parent = xml.getParentFile();
1236
                parent.mkdirs();
1237

    
1238
                FileWriter writer = new FileWriter(xml);
1239
                andamiConfig.marshal(writer);
1240
        }
1241

    
1242
        /**
1243
         * DOCUMENT ME!
1244
         *
1245
         * @param file DOCUMENT ME!
1246
         *
1247
         * @throws ConfigurationException DOCUMENT ME!
1248
         */
1249
        private static void andamiConfigFromXML(String file)
1250
                throws ConfigurationException {
1251
                File xml = new File(file);
1252

    
1253
                //Si no existe se ponen los valores por defecto
1254
                if (!xml.exists()) {
1255
                        andamiConfig = new AndamiConfig();
1256

    
1257
                        Andami andami = new Andami();
1258
                        andami.setUpdate(true);
1259
                        andamiConfig.setAndami(andami);
1260
                        andamiConfig.setLocaleCountry(Locale.getDefault().getCountry());
1261
                        andamiConfig.setLocaleLanguage(Locale.getDefault().getLanguage());
1262
                        andamiConfig.setLocaleVariant(Locale.getDefault().getVariant());
1263

    
1264
                        if (System.getProperty("javawebstart.version") != null) // Es java web start)
1265
                         {
1266
                                andamiConfig.setPluginsDirectory(new File(appHomeDir
1267
                                                + "extensiones").getAbsolutePath());
1268
                        } else {
1269
                                andamiConfig.setPluginsDirectory(new File(appName +
1270
                                                File.separator + "extensiones").getAbsolutePath());
1271
                        }
1272

    
1273
                        andamiConfig.setPlugin(new Plugin[0]);
1274
                } else {
1275
                        //Se lee la configuraci?n
1276
                        FileReader reader;
1277

    
1278
                        try {
1279
                                reader = new FileReader(xml);
1280
                                andamiConfig = (AndamiConfig) AndamiConfig.unmarshal(reader);
1281
                        } catch (FileNotFoundException e) {
1282
                                throw new ConfigurationException(e);
1283
                        } catch (MarshalException e) {
1284
                                throw new ConfigurationException(e);
1285
                        } catch (ValidationException e) {
1286
                                throw new ConfigurationException(e);
1287
                        }
1288
                }
1289
        }
1290

    
1291
        /**
1292
         * DOCUMENT ME!
1293
         *
1294
         * @return DOCUMENT ME!
1295
         *
1296
         * @throws ConfigurationException DOCUMENT ME!
1297
         */
1298
        private static XMLEntity persistenceFromXML() throws ConfigurationException {
1299
                File xml = new File(pluginsPersistencePath);
1300

    
1301
                if (xml.exists()) {
1302
                        FileReader reader;
1303

    
1304
                        try {
1305
                                reader = new FileReader(xml);
1306

    
1307
                                XmlTag tag = (XmlTag) XmlTag.unmarshal(reader);
1308

    
1309
                                return new XMLEntity(tag);
1310
                        } catch (FileNotFoundException e) {
1311
                                throw new ConfigurationException(e);
1312
                        } catch (MarshalException e) {
1313
                                throw new ConfigurationException(e);
1314
                        } catch (ValidationException e) {
1315
                                throw new ConfigurationException(e);
1316
                        }
1317
                } else {
1318
                        return new XMLEntity();
1319
                }
1320
        }
1321

    
1322
        /**
1323
         * DOCUMENT ME!
1324
         *
1325
         * @param entity DOCUMENT ME!
1326
         *
1327
         * @throws ConfigurationException DOCUMENT ME!
1328
         */
1329
        private static void persistenceToXML(XMLEntity entity)
1330
                throws ConfigurationException {
1331
                File xml = new File(pluginsPersistencePath);
1332

    
1333
                FileWriter writer;
1334

    
1335
                try {
1336
                        writer = new FileWriter(xml);
1337
                        entity.getXmlTag().marshal(writer);
1338
                } catch (FileNotFoundException e) {
1339
                        throw new ConfigurationException(e);
1340
                } catch (MarshalException e) {
1341
                        throw new ConfigurationException(e);
1342
                } catch (ValidationException e) {
1343
                        throw new ConfigurationException(e);
1344
                } catch (IOException e) {
1345
                        throw new ConfigurationException(e);
1346
                }
1347
        }
1348

    
1349
        /**
1350
         * Devuelve un array con los directorios de los plugins
1351
         *
1352
         * @param dirExt Directorio de las extensiones a partir del cual cuelgan
1353
         *                   todos los directorios de los plugins
1354
         *
1355
         * @return ArrayList con los directorios
1356
         */
1357
        private String[] getLocales(File dirExt) {
1358
                ArrayList types = new ArrayList();
1359
                File[] files = dirExt.listFiles();
1360

    
1361
                for (int i = 0; i < files.length; i++) {
1362
                        if (files[i].isDirectory()) {
1363
                                File[] textFile = files[i].listFiles(new FilenameFilter() {
1364
                                                        public boolean accept(File dir, String fileName) {
1365
                                                                return fileName.toLowerCase().startsWith("text_"); //$NON-NLS-1$
1366
                                                        }
1367
                                                });
1368

    
1369
                                for (int j = 0; j < textFile.length; j++) {
1370
                                        String s = (textFile[j]).getName().replaceAll("text_", "");
1371
                                        s = s.replaceAll(".properties", "");
1372
                                        s = s.trim();
1373

    
1374
                                        if (!types.contains(s)) {
1375
                                                types.add(s);
1376
                                        }
1377
                                }
1378
                        }
1379
                }
1380

    
1381
                return (String[]) types.toArray(new String[0]);
1382
        }
1383

    
1384
        /**
1385
         * DOCUMENT ME!
1386
         *
1387
         * @return Returns the frame.
1388
         */
1389
        static MDIFrame getFrame() {
1390
                return frame;
1391
        }
1392

    
1393
        /**
1394
         * Secuencia de cerrado de Andami
1395
         */
1396
        public static void closeApplication() {
1397
                //Configuraci?n de Andami
1398
                try {
1399
                        andamiConfigToXML(andamiConfigPath);
1400
                } catch (MarshalException e) {
1401
                        logger.error(Messages.getString(
1402
                                        "Launcher.No_se_pudo_guardar_la_configuracion_de_andami"), e);
1403
                } catch (ValidationException e) {
1404
                        logger.error(Messages.getString(
1405
                                        "Launcher.No_se_pudo_guardar_la_configuracion_de_andami"), e);
1406
                } catch (IOException e) {
1407
                        logger.error(Messages.getString(
1408
                                        "Launcher.No_se_pudo_guardar_la_configuracion_de_andami"), e);
1409
                }
1410

    
1411
                //Persistencia de los plugins
1412
                savePluginPersistence();
1413

    
1414
                //Finalize all the extensions
1415
                finalizeExtensions();
1416

    
1417
                // Clean any temp data created
1418
                Utilities.cleanUpTempFiles();
1419

    
1420
                //Para la depuraci?n de memory leaks
1421
                System.gc();
1422

    
1423
        System.exit(0);
1424
        }
1425

    
1426
        /**
1427
         * Exectutes the terminate method for all the extensions, in the reverse
1428
         * order they were initialized
1429
         *
1430
         */
1431
        private static void finalizeExtensions() {
1432
                for (int i=extensions.size()-1; i>=0; i--) {
1433
                        com.iver.andami.plugins.IExtension extensionInstance=(com.iver.andami.plugins.IExtension)extensions.get(i);
1434
                        extensionInstance.terminate();
1435
                }
1436
        }
1437

    
1438

    
1439
        /**
1440
         * DOCUMENT ME!
1441
         *
1442
         * @return DOCUMENT ME!
1443
         */
1444
        static HashMap getClassesExtensions() {
1445
                return classesExtensions;
1446
        }
1447

    
1448
        /**
1449
         * DOCUMENT ME!
1450
         *
1451
         * @param extDir DOCUMENT ME!
1452
         */
1453
        private static void downloadExtensions(String extDir) {
1454
                java.util.Date fechaActual = null;
1455

    
1456
                try {
1457
                        if (System.getProperty("javawebstart.version") != null) {
1458
                                //Obtenemos la URL del servidor
1459
                                BasicService bs = (BasicService) ServiceManager.lookup(
1460
                                                "javax.jnlp.BasicService");
1461
                                URL baseURL = bs.getCodeBase();
1462

    
1463
                                //Se descargan las extensiones
1464
                                MultiSplashWindow.process(5,
1465
                                        "Descargando las extensiones desde " + baseURL + " a " +
1466
                                        extDir);
1467

    
1468
                                URL url = new URL(baseURL + "extensiones.zip");
1469
                                URLConnection connection = url.openConnection();
1470

    
1471
                                System.out.println(url.toExternalForm() + ":");
1472
                                System.out.println("  Content Type: " +
1473
                                        connection.getContentType());
1474
                                System.out.println("  Content Length: " +
1475
                                        connection.getContentLength());
1476
                                System.out.println("  Last Modified: " +
1477
                                        new Date(connection.getLastModified()));
1478
                                System.out.println("  Expiration: " +
1479
                                        connection.getExpiration());
1480
                                System.out.println("  Content Encoding: " +
1481
                                        connection.getContentEncoding());
1482

    
1483
                                // Guardamos la fecha del fichero de extensiones que nos hemos bajado, y
1484
                                // comprobamos el ?ltimo que se ha bajado. Si no son
1485
                                // iguales, nos bajamos el nuevo. Si son iguales, no
1486
                                // nos bajamos nada.
1487
                                Long miliSecondsInWeb = new Long(connection.getLastModified());
1488

    
1489
                                // PluginServices ps = PluginServices.getPluginServices("com.iver.core");
1490
                                // if (ps.getPersistentXML().getStringProperty("timestamp") != null)
1491
                                File destDir = new File(extDir);
1492

    
1493
                                if (!destDir.exists()) {
1494
                                        // Creamos gvSIG
1495
                                        destDir.getParentFile().mkdir();
1496

    
1497
                                        if (!destDir.mkdir()) {
1498
                                                System.err.println("Imposible crear el directorio " +
1499
                                                        destDir.getAbsolutePath());
1500
                                        }
1501
                                }
1502

    
1503
                                File timeFile = new File(destDir.getParent() + File.separator +
1504
                                                "timeStamp.properties");
1505

    
1506
                                if (!timeFile.exists()) {
1507
                                        timeFile.createNewFile();
1508
                                }
1509

    
1510
                                FileInputStream inAux = new FileInputStream(timeFile);
1511
                                Properties prop = new Properties();
1512
                                prop.load(inAux);
1513
                                inAux.close();
1514

    
1515
                                if (prop.getProperty("timestamp") != null) {
1516
                                        Long lastMiliSeconds = (Long) new Long(prop.getProperty(
1517
                                                                "timestamp"));
1518

    
1519
                                        if (lastMiliSeconds.longValue() == miliSecondsInWeb.longValue()) {
1520
                                                System.out.println("No hay nueva actualizaci?n");
1521
                        logger.debug("No hay nueva actualizaci?n -> Return");
1522
                        logger.debug("timeStampWeb= " + miliSecondsInWeb);
1523
                        logger.debug("timeStampLocal= " + lastMiliSeconds);
1524

    
1525
                                                return;
1526
                                        }
1527

    
1528
                                        System.out.println("timeStampWeb= " + miliSecondsInWeb);
1529
                                        System.out.println("timeStampLocal= " + lastMiliSeconds);
1530
                                } else {
1531
                                        System.out.println("El timeStamp no est? escrito en " +
1532
                                                timeFile.getAbsolutePath());
1533
                                }
1534

    
1535
                                InputStream stream = url.openStream();
1536
                File temp = File.createTempFile("gvsig", ".zip");
1537

    
1538
                logger.debug(temp.getAbsolutePath());
1539

    
1540
                temp.deleteOnExit();
1541
                FileOutputStream file = new FileOutputStream(temp);
1542

    
1543
                byte[] lt_read = new byte[1];
1544

    
1545
                while (stream.read(lt_read) > 0)
1546
                  file.write(lt_read);
1547

    
1548
                                stream.close();
1549
                stream = null;
1550
                file.close();
1551
                file = null;
1552

    
1553
                System.gc();
1554

    
1555
                logger.debug("Ha creado el fichero ZIP");
1556
                                //Se extrae el zip
1557
                                MultiSplashWindow.process(5, "Extensiones descargadas.");
1558

    
1559
                                System.out.println("Extrayendo a " + destDir.getAbsolutePath());
1560

    
1561
                                Date fechaDir = new Date(destDir.lastModified());
1562
                                System.out.println("Fecha del directorio " + extDir + " = " +
1563
                                        fechaDir.toString());
1564
                                Utilities.extractTo(temp, new File(extDir), splashWindow);
1565

    
1566
                                // Si todo ha ido bien, guardamos el timestamp.
1567
                                ///  App.instance.getPc().addProperties("timestamp", miliSecondsInWeb);
1568
                                // XMLEntity xml=ps.getPersistentXML();
1569
                                fechaActual = new java.util.Date();
1570

    
1571
                                FileOutputStream outAux = new FileOutputStream(timeFile);
1572
                                prop.setProperty("timestamp", miliSecondsInWeb.toString());
1573
                                prop.store(outAux, "last download");
1574
                                outAux.close();
1575
                                System.out.println("Fecha actual guardada: " +
1576
                                        fechaActual.toGMTString());
1577

    
1578
                                /* xml.putProperty("timestamp",fechaActual.toGMTString());
1579
                                   ps.setPresistentXML(xml); */
1580
                        }
1581
                } catch (IOException e) {
1582
                        NotificationManager.addError("", e);
1583
                } catch (UnavailableServiceException e) {
1584
                        NotificationManager.addError("", e);
1585
                } catch (SecurityException e) {
1586
                        System.err.println("No se puede escribir el timeStamp " +
1587
                                fechaActual.toGMTString());
1588
                        NotificationManager.addError("", e);
1589
                }
1590
        }
1591

    
1592
        /**
1593
         * DOCUMENT ME!
1594
         *
1595
         * @return DOCUMENT ME!
1596
         */
1597
        private static Extensions[] getExtensions() {
1598
                ArrayList array = new ArrayList();
1599
                Iterator iter = pluginsConfig.values().iterator();
1600

    
1601
                while (iter.hasNext()) {
1602
                        array.add(((PluginConfig) iter.next()).getExtensions());
1603
                }
1604

    
1605
                return (Extensions[]) array.toArray(new Extensions[0]);
1606
        }
1607

    
1608
        /**
1609
         * DOCUMENT ME!
1610
         *
1611
         * @return DOCUMENT ME!
1612
         */
1613
        public static HashMap getPluginConfig() {
1614
                return pluginsConfig;
1615
        }
1616

    
1617
        /**
1618
         * DOCUMENT ME!
1619
         *
1620
         * @param s DOCUMENT ME!
1621
         *
1622
         * @return DOCUMENT ME!
1623
         */
1624
        public static Extension getExtension(String s) {
1625
                Extensions[] exts = getExtensions();
1626

    
1627
                for (int i = 0; i < exts.length; i++) {
1628
                        for (int j = 0; j < exts[i].getExtensionCount(); j++) {
1629
                                if (exts[i].getExtension(j).getClassName().equals(s)) {
1630
                                        return exts[i].getExtension(j);
1631
                                }
1632
                        }
1633
                }
1634

    
1635
                return null;
1636
        }
1637

    
1638
        /**
1639
         * DOCUMENT ME!
1640
         *
1641
         * @return DOCUMENT ME!
1642
         */
1643
        public static AndamiConfig getAndamiConfig() {
1644
                return andamiConfig;
1645
        }
1646

    
1647
        /**
1648
         * DOCUMENT ME!
1649
         *
1650
         * @author $author$
1651
         * @version $Revision: 8884 $
1652
         */
1653
        private static class ExtensionComparator implements Comparator {
1654
                /**
1655
                 * DOCUMENT ME!
1656
                 *
1657
                 * @param o1 DOCUMENT ME!
1658
                 * @param o2 DOCUMENT ME!
1659
                 *
1660
                 * @return DOCUMENT ME!
1661
                 */
1662
                public int compare(Object o1, Object o2) {
1663
                        Extension e1 = (Extension) o1;
1664
                        Extension e2 = (Extension) o2;
1665

    
1666
                        if (!e1.hasPriority() && !e2.hasPriority()) {
1667
                                return -1;
1668
                        }
1669

    
1670
                        if (e1.hasPriority() && !e2.hasPriority()) {
1671
                                return Integer.MIN_VALUE;
1672
                        }
1673

    
1674
                        if (e2.hasPriority() && !e1.hasPriority()) {
1675
                                return Integer.MAX_VALUE;
1676
                        }
1677

    
1678
                        if (e1.getPriority() != e2.getPriority()){
1679
                                return e2.getPriority() - e1.getPriority();
1680
                        }else{
1681
                                return (e2.toString().compareTo(e1.toString()));
1682
                        }
1683
                }
1684
        }
1685

    
1686
        /**
1687
         * DOCUMENT ME!
1688
         */
1689
        private static class MenuComparator implements Comparator {
1690
                private static ExtensionComparator extComp = new ExtensionComparator();
1691

    
1692
                /**
1693
                 * DOCUMENT ME!
1694
                 *
1695
                 * @param o1 DOCUMENT ME!
1696
                 * @param o2 DOCUMENT ME!
1697
                 *
1698
                 * @return DOCUMENT ME!
1699
                 */
1700
                public int compare(Object o1, Object o2) {
1701
                        SortableMenu e1 = (SortableMenu) o1;
1702
                        SortableMenu e2 = (SortableMenu) o2;
1703

    
1704
                        if (!e1.menu.hasPosition() && !e2.menu.hasPosition()) {
1705
                                if (e1.extension instanceof SkinExtensionType) {
1706
                                        return 1;
1707
                                } else if (e2.extension instanceof SkinExtensionType) {
1708
                                        return -1;
1709
                                } else {
1710
                                        return extComp.compare(e1.extension, e2.extension);
1711
                                }
1712
                        }
1713

    
1714
                        if (e1.menu.hasPosition() && !e2.menu.hasPosition()) {
1715
                                return Integer.MIN_VALUE;
1716
                        }
1717

    
1718
                        if (e2.menu.hasPosition() && !e1.menu.hasPosition()) {
1719
                                return Integer.MAX_VALUE;
1720
                        }
1721
                        if (e1.menu.getPosition() != e2.menu.getPosition()){
1722
                                //we don't return 0 unless both objects are the same, otherwise the objects get overwritten in the treemap
1723
                                return e1.menu.getPosition() - e2.menu.getPosition();
1724
                        }else{
1725
                                return (e1.toString().compareTo(e2.toString()));
1726
                        }
1727
                }
1728
        }
1729

    
1730
        /**
1731
         * DOCUMENT ME!
1732
         *
1733
         * @author $author$
1734
         * @version $Revision: 8884 $
1735
         */
1736
        private static class SortableMenu {
1737
                public PluginClassLoader loader;
1738
                public Menu menu;
1739
                public SkinExtensionType extension;
1740

    
1741
                /**
1742
                 * DOCUMENT ME!
1743
                 *
1744
                 * @param loader DOCUMENT ME!
1745
                 * @param skinExt
1746
                 * @param menu2
1747
                 */
1748
                public SortableMenu(PluginClassLoader loader,
1749
                        SkinExtensionType skinExt, Menu menu2) {
1750
                        extension = skinExt;
1751
                        menu = menu2;
1752
                        this.loader = loader;
1753
                }
1754
        }
1755
        /**
1756
         * DOCUMENT ME!
1757
         */
1758
        private static class SortableTool {
1759
                public PluginClassLoader loader;
1760
                public ToolBar toolbar;
1761
                public ActionTool actiontool;
1762
                public SelectableTool selectabletool;
1763
                public SkinExtensionType extension;
1764

    
1765
                /**
1766
                 * DOCUMENT ME!
1767
                 *
1768
                 * @param loader DOCUMENT ME!
1769
                 * @param skinExt
1770
                 * @param menu2
1771
                 */
1772
                public SortableTool(PluginClassLoader loader,
1773
                        SkinExtensionType skinExt, ToolBar toolbar2,ActionTool actiontool2) {
1774
                        extension = skinExt;
1775
                        toolbar = toolbar2;
1776
                        actiontool=actiontool2;
1777
                        this.loader = loader;
1778
                }
1779
                public SortableTool(PluginClassLoader loader,
1780
                                SkinExtensionType skinExt, ToolBar toolbar2,SelectableTool selectabletool2) {
1781
                        extension = skinExt;
1782
                        toolbar = toolbar2;
1783
                        selectabletool=selectabletool2;
1784
                        this.loader = loader;
1785
                }
1786
        }
1787
        /**
1788
         * DOCUMENT ME!
1789
         */
1790
        private static class ToolBarComparator implements Comparator {
1791
                private static ExtensionComparator extComp = new ExtensionComparator();
1792

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

    
1805
                        // if the toolbars have the same name, they are considered to be
1806
                        // the same toolbar, so we don't need to do further comparing
1807
                        if (e1.toolbar.getName().equals(e2.toolbar.getName()))
1808
                                return 0;
1809

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

    
1820
                        if (e1.toolbar.hasPosition() && !e2.toolbar.hasPosition()) {
1821
                                return Integer.MIN_VALUE;
1822
                        }
1823

    
1824
                        if (e2.toolbar.hasPosition() && !e1.toolbar.hasPosition()) {
1825
                                return Integer.MAX_VALUE;
1826
                        }
1827
                        if (e1.toolbar.getPosition() != e2.toolbar.getPosition())
1828
                                return e1.toolbar.getPosition() - e2.toolbar.getPosition();
1829

    
1830
                        if (e1.toolbar.getActionTool().equals(e2.toolbar.getActionTool()) && e1.toolbar.getSelectableTool().equals(e2.toolbar.getSelectableTool())){
1831
                                return 0;
1832
                        }
1833
                        return (e1.toolbar.toString().compareTo(e2.toolbar.toString()));
1834
                }
1835
        }
1836

    
1837
        /**
1838
         * <p>This class is used to compare tools (selectabletool and actiontool),
1839
         * using the "position"
1840
         * attribute.</p>
1841
         * <p>The ordering criteria are:</p>
1842
         * <ul><li>If the tools are placed in different toolbars, they use the toolbars'
1843
         * order.
1844
         * (using the ToolBarComparator).</li>
1845
         * <li></li>
1846
         * <li>If any of the tools has not 'position' attribute, the tool which
1847
         * <strong>has</strong> the attribute will be placed first.</li>
1848
         * <li>If both tools have the same position (or they don't have a
1849
         * 'position' attribute), the priority of the extensions where the tool is defined.</li></ul>
1850
         *
1851
         * @author cesar
1852
         * @version $Revision: 8884 $
1853
         */
1854
        private static class ToolComparator implements Comparator {
1855
                private static ToolBarComparator toolBarComp = new ToolBarComparator();
1856
                /**
1857
                 * DOCUMENT ME!
1858
                 *
1859
                 * @param o1 DOCUMENT ME!
1860
                 * @param o2 DOCUMENT ME!
1861
                 *
1862
                 * @return DOCUMENT ME!
1863
                 */
1864
                public int compare(Object o1, Object o2) {
1865
                        // compare the toolbars which contain the tools
1866
                        int result = toolBarComp.compare(o1, o2);
1867
                        if (result != 0) { // if the toolbars are different, use their order
1868
                                return result;
1869
                        }
1870
                        // otherwise, compare the tools
1871
                        SortableTool e1 = (SortableTool) o1;
1872
                        SortableTool e2 = (SortableTool) o2;
1873
                        int e1Position=-1, e2Position=-1;
1874

    
1875
                        if (e1.actiontool!=null) {
1876
                                if (e1.actiontool.hasPosition())
1877
                                        e1Position = e1.actiontool.getPosition();
1878
                        }
1879
                        else if (e1.selectabletool!=null) {
1880
                                if (e1.selectabletool.hasPosition())
1881
                                        e1Position = e1.selectabletool.getPosition();
1882
                        }
1883

    
1884
                        if (e2.actiontool!=null) {
1885
                                if (e2.actiontool.hasPosition())
1886
                                        e2Position = e2.actiontool.getPosition();
1887
                        }
1888
                        else if (e2.selectabletool!=null){
1889
                                if (e2.selectabletool.hasPosition())
1890
                                        e2Position = e2.selectabletool.getPosition();
1891
                        }
1892

    
1893
                        if (e1Position==-1 && e2Position!=-1) {
1894
                                return 1;
1895
                        }
1896
                        if (e1Position!=-1 && e2Position==-1) {
1897
                                return -1;
1898
                        }
1899
                        if (e1Position!=-1 && e2Position!=-1) {
1900
                                result = e1Position - e2Position;
1901
                                // we don't return 0 unless both objects are the same, otherwise the objects get overwritten in the treemap
1902
                                if (result!=0) return result;
1903
                        }
1904
                        return e1.toString().compareTo(e2.toString());
1905
                }
1906
        }
1907

    
1908

    
1909
        /**
1910
         * validates the user before starting gvsig
1911
         *
1912
         */
1913
        private static void validate(){
1914

    
1915
                IAuthentication session =  null;
1916
                try {
1917
                        session = (IAuthentication)Class.forName("com.iver.andami.authentication.Session").newInstance();
1918

    
1919
                } catch (ClassNotFoundException e) {
1920
                        // TODO Auto-generated catch block
1921
                        //e.printStackTrace();
1922
                        return;
1923
                } catch (InstantiationException e) {
1924
                        // TODO Auto-generated catch block
1925
                        //e.printStackTrace();
1926
                        return;
1927
                } catch (IllegalAccessException e) {
1928
                        // TODO Auto-generated catch block
1929
                        //e.printStackTrace();
1930
                        return;
1931
                }
1932

    
1933
                session.setPluginDirectory( andamiConfig.getPluginsDirectory() );
1934
                if (session.validationRequired()){
1935
                        if(session.Login()){
1936
                                System.out.println("You are logged in");
1937
                        }
1938
                        else{
1939
                                JOptionPane.showMessageDialog((Component)PluginServices.getMainFrame(),
1940
                                                 "You are not logged in");
1941
                                //System.exit(0);
1942
                        }
1943
                        PluginServices.setAuthentication(session);
1944
                }
1945
        }
1946

    
1947
        public static String getDefaultLookAndFeel() {
1948
                String osName = (String) System.getProperty("os.name");
1949

    
1950
            if (osName.substring(0,3).toLowerCase().equals("win"))
1951
                    return UIManager.getSystemLookAndFeelClassName();
1952
        else
1953
                return nonWinDefaultLookAndFeel;
1954
        }
1955

    
1956
        /**
1957
         * Gets the ISO 839 two-characters-long language code matching the
1958
         * provided language code (which may be an ISO 839-2/T
1959
         * three-characters-long code or an ISO 839-1 two-characters-long
1960
         * code).
1961
         *
1962
         * If the provided parameter is already two characters long, it
1963
         * returns the parameter without any modification.
1964
         *
1965
         * @param langCode A language code representing either
1966
         *  an ISO 839-2/T language code or an ISO 839-1 code.
1967
         * @return A two-characters-long code specifying
1968
         *  an ISO 839 language code.
1969
         */
1970
        private static String normalizeLanguageCode(String langCode) {
1971
                final String fileName = "iso_639.tab";
1972
                if (langCode.length()==2)
1973
                        return langCode;
1974
                else if (langCode.length()==3) {
1975
                        if (langCode.equals("va") || langCode.equals("val")) { // special case for Valencian
1976
                                return "ca";
1977
                        }
1978
                        URL isoCodes = Launcher.class.getClassLoader().getResource(fileName);
1979
                        if (isoCodes!=null) {
1980
                                try {
1981
                                        BufferedReader reader =
1982
                                                new BufferedReader(new InputStreamReader(isoCodes.openStream(), "ISO-8859-1"));
1983
                                                String line;
1984

    
1985
                                                while ((line = reader.readLine()) != null) {
1986
                                                        String[] language = line.split("\t");
1987
                                                        if (language[0].equals(langCode)) // first column is the three characters code
1988
                                                                return language[2]; // third column i the two characters code
1989
                                                }
1990
                                }
1991
                                catch (IOException ex) {
1992
                                        logger.error(Messages.getString("Error_reading_isocodes_file"), ex);
1993
                                        return "es";
1994
                                }
1995
                        }
1996
                        else {
1997
                                logger.error(Messages.getString("Error_reading_isocodes_file"));
1998
                                return "es";
1999
                        }
2000
                }
2001
                return "es";
2002
        }
2003

    
2004
        /**
2005
         * Configures the locales (languages and local resources) to be used
2006
         * by the application.
2007
         *
2008
         * First it tries to get the locale from the command line parameters,
2009
         * then the andami-config file is checked.
2010
         *
2011
         * The locale name is normalized to get a two characters language code
2012
         * as defined by ISO-639-1 (although ISO-639-2/T three characters codes
2013
         * are also accepted from the command line or the configuration file).
2014
         *
2015
         * Finally, the gvsig-i18n library and the default locales for Java and
2016
         * Swing are configured.
2017
         *
2018
         */
2019
        private static void configureLocales(String[] args) {
2020
                //                 Configurar el locale
2021
        String localeStr = null;
2022
        for (int i=2; i < args.length; i++)
2023
        {
2024
                int index = args[i].indexOf("language=");
2025
                if (index != -1)
2026
                        localeStr = args[i].substring(index+9);
2027
        }
2028
                if (localeStr == null)
2029
                {
2030
            localeStr = andamiConfig.getLocaleLanguage();
2031
                }
2032
                localeStr = normalizeLanguageCode(localeStr);
2033
                locale = getLocale(localeStr,
2034
                andamiConfig.getLocaleCountry(),
2035
                andamiConfig.getLocaleVariant());
2036
                Locale.setDefault(locale);
2037
                JComponent.setDefaultLocale(locale);
2038
        org.gvsig.i18n.Messages.addLocale(locale);
2039
                // add english and spanish as fallback languages
2040
                org.gvsig.i18n.Messages.addLocale(new Locale("en"));
2041
                org.gvsig.i18n.Messages.addLocale(new Locale("es"));
2042
        org.gvsig.i18n.Messages.addResourceFamily("com.iver.andami.text", "com.iver.andami.text");
2043

    
2044
        }
2045

    
2046
        /**
2047
         * Gets Home Directory location of the application.
2048
         * May be set from outside the aplication by means of
2049
         * -DgvSIG.home=C:/data/gvSIG, where gvSIG its the name
2050
         * of the application
2051
         * @return
2052
         */
2053
        public static String getAppHomeDir() {
2054
                return appHomeDir;
2055
        }
2056

    
2057
        /**
2058
         * Sets Home Directory location of the application.
2059
         * May be set from outside the aplication by means of
2060
         * -DgvSIG.home=C:/data/gvSIG, where gvSIG its the name
2061
         * of the application
2062
         * @param appHomeDir
2063
         */
2064
        public static void setAppHomeDir(String appHomeDir) {
2065
                Launcher.appHomeDir = appHomeDir;
2066
        }
2067
}