Statistics
| Revision:

root / branches / v10 / frameworks / _fwAndami / src / com / iver / andami / Launcher.java @ 7513

History | View | Annotate | Download (58.2 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.KeyboardFocusManager;
47
import java.awt.Point;
48
import java.awt.Toolkit;
49
import java.io.BufferedInputStream;
50
import java.io.BufferedOutputStream;
51
import java.io.BufferedReader;
52
import java.io.File;
53
import java.io.FileFilter;
54
import java.io.FileInputStream;
55
import java.io.FileNotFoundException;
56
import java.io.FileOutputStream;
57
import java.io.FileReader;
58
import java.io.FileWriter;
59
import java.io.FilenameFilter;
60
import java.io.IOException;
61
import java.io.InputStream;
62
import java.io.InputStreamReader;
63
import java.lang.reflect.InvocationTargetException;
64
import java.net.MalformedURLException;
65
import java.net.URL;
66
import java.net.URLConnection;
67
import java.security.AllPermission;
68
import java.security.CodeSource;
69
import java.security.PermissionCollection;
70
import java.security.Permissions;
71
import java.security.Policy;
72
import java.util.ArrayList;
73
import java.util.Comparator;
74
import java.util.Date;
75
import java.util.HashMap;
76
import java.util.HashSet;
77
import java.util.Iterator;
78
import java.util.Locale;
79
import java.util.Properties;
80
import java.util.Set;
81
import java.util.TreeMap;
82

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

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

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

    
132

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

    
153
    private static ArrayList pluginsOrdered = new ArrayList();
154

    
155
        /**
156
         * DOCUMENT ME!
157
         *
158
         * @param args DOCUMENT ME!
159
         * @throws Exception
160
         *
161
         * @throws InterruptedException
162
         * @throws InvocationTargetException
163
         * @throws ConfigurationException
164
         * @throws MDIManagerLoadException
165
         * @throws IOException
166
         */
167
        public static void main(String[] args) throws Exception {
168
            try{
169

    
170
            if (!validJVM()){
171
                System.exit(-1);
172
            }
173

    
174
            if (args.length < 1) {
175
                        System.err.println("Uso: Launcher appName plugins-directory [language=locale]");
176
                }
177

    
178
            //  Clean temporal files
179
                Utilities.cleanUpTempFiles();
180

    
181
                appName = args[0];
182

    
183
                //Se crea el directorio de configuraci?n de la aplicaci?n
184
                File parent = new File(System.getProperty("user.home") +
185
                                File.separator + args[0] + File.separator);
186
                parent.mkdirs();
187

    
188
                andamiConfigPath = System.getProperty("user.home") + File.separator +
189
                        appName + File.separator + "andami-config.xml";
190
                pluginsPersistencePath = System.getProperty("user.home") +
191
                        File.separator + appName + File.separator +
192
                        "plugins-persistence.xml";
193

    
194
                // Configurar el log4j
195
                PropertyConfigurator.configure(Launcher.class.getClassLoader()
196
                                                                                                         .getResource("log4j.properties"));
197

    
198
                PatternLayout l = new PatternLayout("%p %t %C - %m%n");
199
                RollingFileAppender fa = new RollingFileAppender(l,
200
                                System.getProperty("user.home") + File.separator + args[0] +
201
                                File.separator + args[0] + ".log", false);
202
                fa.setMaxFileSize("512KB");
203
                fa.setMaxBackupIndex(3);
204
                Logger.getRootLogger().addAppender(fa);
205

    
206
                // Leer el fichero de configuraci?n de andami (andami-config.xsd)
207
                // locale
208
                // Buscar actualizaci?nes al comenzar
209
                //  Andami
210
                //  Plugins
211
                // Directorio de las extensiones
212
                andamiConfigFromXML(andamiConfigPath);
213
                andamiConfig.setPluginsDirectory(args[1]);
214

    
215
                // Hacemos visibles los argumentos como una propiedad est?tica
216
                // de plugin services para quien lo quiera usar (por ejemplo, para
217
                // cargar un proyecto por l?nea de comandos)
218
                PluginServices.setArguments(args);
219

    
220
                configureLocales(args);
221

    
222
                //Se pone el lookAndFeel
223
                try {
224
                        String lookAndFeel = getAndamiConfig().getLookAndFeel();
225
                        if (lookAndFeel == null)
226
                                lookAndFeel = getDefaultLookAndFeel();
227
                        UIManager.setLookAndFeel(lookAndFeel);
228
                } catch (Exception e) {
229
                        logger.warn(Messages.getString("Launcher.look_and_feel"), e);
230
                }
231

    
232

    
233
                // Solucionamos el problema de permisos que se produc?a con Java Web Start con este c?digo.
234
                // System.setSecurityManager(null);
235
             Policy.setPolicy(new Policy() {
236
             public PermissionCollection getPermissions(CodeSource codesource) {
237
                      Permissions perms = new Permissions();
238
                      perms.add(new AllPermission());
239
                      return (perms);
240
             }
241
             public void
242
                         refresh() {}
243
             });
244

    
245

    
246
                // Mostrar la ventana de inicio
247
                splashWindow = new SplashWindow(null);
248

    
249
                // TODO Buscar actualizaciones de los plugins
250
                downloadExtensions(andamiConfig.getPluginsDirectory());
251

    
252
                validate();
253

    
254
                // Se leen los config.xml de los plugins -----++++
255
                loadPlugins(andamiConfig.getPluginsDirectory());
256

    
257
                // Se configura el classloader del plugin
258
                pluginsClassLoaders();
259

    
260
                // Se carga un Skin si alguno de los plugins trae informaci?n para ello
261
                skinPlugin();
262

    
263
                //Se configura la cola de eventos
264
                EventQueue waitQueue = new AndamiEventQueue();
265
                Toolkit.getDefaultToolkit().getSystemEventQueue().push(waitQueue);
266

    
267
                // Se configura la mensajer?a del plugin
268
                pluginsMessages();
269

    
270
                // Se modifica el andami-config con los plugins nuevos
271
                updateAndamiConfig();
272

    
273
                // Se prepara el MainFrame para albergar las extensiones
274
                frame = new MDIFrame();
275

    
276
                // Se configura el nombre e icono de la aplicaci?n
277
                frameIcon();
278

    
279
                SwingUtilities.invokeAndWait(new Runnable() {
280
                                public void run() {
281
                                        frame.init();
282
                                }
283
                        });
284

    
285
                // Se instalan los controles de las extensiones de los plugins
286
                SwingUtilities.invokeAndWait(new Runnable() {
287
                                public void run() {
288
                                        installPluginsControls();
289
                                        installPluginsMenus();
290
                                        installPluginsLabels();
291
                                }
292
                        });
293

    
294
                // Leer el fichero de persistencia
295
                //  info de los plugins
296
                //  bookmarks de los plugins
297
                loadPluginsPersistence();
298

    
299
                // Se instalan los controles del skin
300
                // Se inicializan todas las extensiones de todos los plugins
301
                SwingUtilities.invokeAndWait(new Runnable() {
302
                                public void run() {
303
                                        initializeExtensions();
304
                                }
305
                        });
306
                frame.setClassesExtensions(classesExtensions);
307

    
308
                // Se instalan los bookmarks de los plugins
309
                splashWindow.close();
310

    
311
                //Se muestra el frame principal
312
                frame.show();
313

    
314
                // Definimos un KeyEventDispatcher global para que las extensiones
315
                // puedan registrar sus "teclas r?pidas".
316
                GlobalKeyEventDispatcher keyDispatcher = GlobalKeyEventDispatcher.getInstance();
317
                KeyboardFocusManager.getCurrentKeyboardFocusManager().addKeyEventDispatcher(keyDispatcher);
318

    
319
        SwingUtilities.invokeAndWait(new Runnable() {
320
                                public void run() {
321
                                        frame.enableControls();
322
                                }
323
                        });
324
            }catch(Exception e){
325
                logger.error("excepci?n al arrancar", e);
326
                System.exit(-1);
327
            }
328

    
329
        }
330

    
331
        /**
332
         * Recupera la geometr?a (tama?o, posici?n y estado) de la ventana principal de Andami.
333
         * TODO Pendiente de ver como se asigna un pluginServices para el launcher.
334
         * @author LWS
335
         */
336
        private static void restoreMDIStatus(XMLEntity xml) {
337
                //System.err.println("Launcher: restoreMDIStatus()");
338
                if (xml == null) xml = new XMLEntity();
339
                //  restore frame size
340
                Dimension sz = new Dimension(700,580);
341
                if (xml.contains("MDIFrameSize")) {
342
                        int [] wh = xml.getIntArrayProperty("MDIFrameSize");
343
                        sz = new Dimension(wh[0], wh[1]);
344
                }
345
                frame.setSize(sz);
346
                //  restore frame location
347
                Point pos = new Point(10,10);
348
                if (xml.contains("MDIFramePos")) {
349
                        int [] xy = xml.getIntArrayProperty("MDIFramePos");
350
                        pos = new Point(xy[0], xy[1]);
351
                }
352
                frame.setLocation(pos);
353

    
354
                //  restore frame status (Maximized, minimized, etc);
355
                int state = java.awt.Frame.MAXIMIZED_BOTH;
356
                if (xml.contains("MDIFrameState")) {
357
                        state = xml.getIntProperty("MDIFrameState");
358
                }
359
                frame.setExtendedState(state);
360
        }
361

    
362
        private static XMLEntity saveMDIStatus() {
363
                XMLEntity xml = new XMLEntity();
364
                // save frame size
365
                int [] wh = new int[2];
366
                wh[0] = frame.getWidth();
367
                wh[1] = frame.getHeight();
368
                xml.putProperty("MDIFrameSize", wh);
369
                // save frame location
370
                int [] xy = new int[2];
371
                xy[0] = frame.getX();
372
                xy[1] = frame.getY();
373
                xml.putProperty("MDIFramePos", xy);
374
                // save frame status
375
                xml.putProperty("MDIFrameState", frame.getExtendedState());
376
                return xml;
377
        }
378

    
379
        /**
380
     * @return
381
     */
382
    private static boolean validJVM() {
383
        char thirdCharacter = System.getProperty("java.version").charAt(2);
384
        if (thirdCharacter < '4'){
385
            return false;
386
            }else{
387
                return true;
388
            }
389
    }
390

    
391
    /**
392
         * DOCUMENT ME!
393
         *
394
         * @throws ConfigurationException
395
         */
396
        private static void loadPluginsPersistence() throws ConfigurationException {
397
                XMLEntity entity = persistenceFromXML();
398

    
399
                //System.err.println("loadPluginPersistence()");
400
                for (int i = 0; i < entity.getChildrenCount(); i++) {
401
                        XMLEntity plugin = entity.getChild(i);
402
                        String pName = plugin.getStringProperty(
403
                                        "com.iver.andami.pluginName");
404
                        //System.err.println("--> "+pName);
405
                        if (pluginsServices.get(pName)!= null){
406
                                ((PluginServices) pluginsServices.get(pName)).setPersistentXML(plugin);
407
                        } else {
408
                                if (pName.startsWith("Andami.Launcher"))
409
                                        restoreMDIStatus(plugin);
410
                        }
411
                }
412
        }
413

    
414
        /**
415
         * Salva la persistencia de los plugins.
416
         * @author LWS
417
         */
418
        private static void savePluginPersistence() {
419
                Iterator i = pluginsConfig.keySet().iterator();
420

    
421
                XMLEntity entity = new XMLEntity();
422

    
423
                while (i.hasNext()) {
424
                        String pName = (String) i.next();
425
                        PluginServices ps = (PluginServices) pluginsServices.get(pName);
426
                        XMLEntity ent = ps.getPersistentXML();
427

    
428
                        if (ent != null) {
429
                                ent.putProperty("com.iver.andami.pluginName", pName);
430
                                entity.addChild(ent);
431
                        }
432
                }
433
                XMLEntity ent = saveMDIStatus();
434
                if (ent != null) {
435
                        ent.putProperty("com.iver.andami.pluginName", "Andami.Launcher");
436
                        entity.addChild(ent);
437
                }
438
                try {
439
                        persistenceToXML(entity);
440
                } catch (ConfigurationException e1) {
441
                        logger.error(Messages.getString(
442
                                        "Launcher.Se_produjo_un_error_guardando_la_configuracion_de_los_plugins"),
443
                                e1);
444
                }
445
        }
446

    
447
        /**
448
         * DOCUMENT ME!
449
         */
450
        private static void installPluginsLabels() {
451
                Iterator i = pluginsConfig.keySet().iterator();
452

    
453
                while (i.hasNext()) {
454
                        String name = (String) i.next();
455
                        PluginConfig pc = (PluginConfig) pluginsConfig.get(name);
456
                        PluginServices ps = (PluginServices) pluginsServices.get(name);
457

    
458
                        LabelSet[] ls = pc.getLabelSet();
459

    
460
                        for (int j = 0; j < ls.length; j++) {
461
                                PluginClassLoader loader = ps.getClassLoader();
462

    
463
                                try {
464
                                        Class clase = loader.loadClass(ls[j].getClassName());
465
                                        frame.setLabels(clase, ls[j].getLabel());
466
                                } catch (ClassNotFoundException e) {
467
                                        logger.error(Messages.getString("Launcher.labelset_class"),
468
                                                e);
469
                                }
470
                        }
471
                }
472
        }
473

    
474
        /**
475
         * DOCUMENT ME!
476
         *
477
         * @throws MDIManagerLoadException
478
         */
479
        private static void skinPlugin() throws MDIManagerLoadException {
480
                Iterator i = pluginsConfig.keySet().iterator();
481

    
482
                while (i.hasNext()) {
483
                        String name = (String) i.next();
484
                        PluginConfig pc = (PluginConfig) pluginsConfig.get(name);
485
                        PluginServices ps = (PluginServices) pluginsServices.get(name);
486

    
487
                        if (pc.getExtensions().getSkinExtension() != null) {
488
                                if (MDIManagerFactory.getSkinExtension() != null) {
489
                                        logger.warn(Messages.getString(
490
                                                        "Launcher.Dos_skin_extension"));
491
                                }
492

    
493
                                SkinExtension se = pc.getExtensions().getSkinExtension();
494

    
495
                                MDIManagerFactory.setSkinExtension(se, ps.getClassLoader());
496

    
497
                                Class skinClass;
498

    
499
                                try {
500
                                        skinClass = ps.getClassLoader().loadClass(se.getClassName());
501

    
502
                                        com.iver.andami.plugins.IExtension skinInstance = (com.iver.andami.plugins.IExtension) skinClass.newInstance();
503
                                        // classesExtensions.put(skinClass, skinInstance);
504
                                        // jaume
505
                                        ExtensionDecorator newExtensionDecorator = new ExtensionDecorator(skinInstance, ExtensionDecorator.INACTIVE);
506
                                        classesExtensions.put(skinClass, newExtensionDecorator);
507
                                } catch (ClassNotFoundException e) {
508
                                        logger.error(Messages.getString(
509
                                                        "Launcher.No_se_encontro_la_clase_mdi_manager"), e);
510
                                        throw new MDIManagerLoadException(e);
511
                                } catch (InstantiationException e) {
512
                                        logger.error(Messages.getString(
513
                                                        "Launcher.No_se_pudo_instanciar_la_clase_mdi_manager"),
514
                                                e);
515
                                        throw new MDIManagerLoadException(e);
516
                                } catch (IllegalAccessException e) {
517
                                        logger.error(Messages.getString(
518
                                                        "Launcher.No_se_pudo_acceder_a_la_clase_mdi_manager"),
519
                                                e);
520
                                        throw new MDIManagerLoadException(e);
521
                                }
522
                        }
523
                }
524
        }
525

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

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

    
537
                        if (pc.getIcon() != null) {
538
                                ImageIcon icon = new ImageIcon(ps.getClassLoader().getResource(pc.getIcon()
539
                                                                                                                                                                 .getSrc()));
540
                                frame.setIconImage(icon.getImage());
541
                                frame.setTitlePrefix(pc.getIcon().getText());
542
                        }
543
                }
544
        }
545

    
546
        /**
547
         *
548
         */
549
        private static void initializeExtensions() {
550
                Iterator i = pluginsOrdered.iterator();
551

    
552
                while (i.hasNext()) {
553
                        String pName = (String) i.next();
554
            logger.debug("Initializing extensions from " + pName);
555
                        PluginConfig pc = (PluginConfig) pluginsConfig.get(pName);
556
                        PluginServices ps = (PluginServices) pluginsServices.get(pName);
557

    
558
                        Extension[] exts = pc.getExtensions().getExtension();
559

    
560
                        TreeMap orderedExtensions = new TreeMap(new ExtensionComparator());
561

    
562
                        for (int j = 0; j < exts.length; j++) {
563
                                if (!exts[j].getActive()) {
564
                                        continue;
565
                                }
566

    
567
                                if (orderedExtensions.containsKey(exts[j])) {
568
                                        logger.warn(Messages.getString(
569
                                                        "Launcher.Two_extensions_with_the_same_priority") +
570
                                                exts[j].getClassName());
571
                                }
572

    
573
                                orderedExtensions.put(exts[j], null);
574
                        }
575

    
576
                        Iterator e = orderedExtensions.keySet().iterator();
577

    
578
                        while (e.hasNext()) {
579
                                Extension extension = (Extension) e.next();
580
                                com.iver.andami.plugins.IExtension extensionInstance;
581

    
582
                                try {
583
                                        Class extensionClass = ps.getClassLoader().loadClass(extension.getClassName());
584
                                        extensionInstance = (com.iver.andami.plugins.IExtension) extensionClass.newInstance();
585

    
586
                                        // CON DECORATOR
587
                                        // ANTES: classesExtensions.put(extensionClass, extensionInstance);
588
                                        // AHORA: CREAMOS UNA ExtensionDecorator y asignamos esta instancia para
589
                                        // poder ampliar con nuevas propiedades (AlwaysVisible, por ejemplo)
590
                                        // Para crear la nueva clase ExtensionDecorator, le pasamos como par?metro
591
                                        // la extensi?n original que acabamos de crear
592
                                        // 0-> Inactivo, controla la extension
593
                                        // 1-> Siempre visible
594
                                        // 2-> Invisible
595
                                        ExtensionDecorator newExtensionDecorator = new ExtensionDecorator(extensionInstance, ExtensionDecorator.INACTIVE);
596
                                        classesExtensions.put(extensionClass, newExtensionDecorator);
597
                                        System.err.println("Loading "+extension.getClassName()+"...");
598
                    // logger.debug("Initializing " + extension.getClassName());
599
                    extensionInstance.initialize();
600
                    // logger.debug(extension.getClassName() + " initialized.");
601

    
602
                                } catch (InstantiationException e1) {
603
                                        logger.error(Messages.getString(
604
                                                        "Launcher.Error_instanciando_la_extension") +
605
                                                extension.getClassName(), e1);
606
                                } catch (IllegalAccessException e1) {
607
                                        logger.error(Messages.getString(
608
                                                        "Launcher.Error_instanciando_la_extension") +
609
                                                extension.getClassName(), e1);
610
                                } catch (ClassNotFoundException e1) {
611
                                        logger.error(Messages.getString(
612
                                                        "Launcher.No_se_encontro_la_clase_de_la_extension") +
613
                                                extension.getClassName(), e1);
614
                                } catch (NoClassDefFoundError e1) {
615
                                        logger.error(Messages.getString(
616
                                                        "Launcher.Error_localizando_la_clase_de_la_extension") +
617
                                                extension.getClassName(), e1);
618
                                }
619
                        }
620
                }
621
        }
622

    
623
        /**
624
         * DOCUMENT ME!
625
         */
626
        private static void installPluginsMenus() {
627
                TreeMap orderedMenus = new TreeMap(new MenuComparator());
628

    
629
                Iterator i = pluginsConfig.keySet().iterator();
630

    
631
                while (i.hasNext()) {
632
                        String pName = (String) i.next();
633
                        PluginServices ps = (PluginServices) pluginsServices.get(pName);
634
                        PluginConfig pc = (PluginConfig) pluginsConfig.get(pName);
635

    
636
                        Extension[] exts = pc.getExtensions().getExtension();
637

    
638
                        for (int j = 0; j < exts.length; j++) {
639
                                if (!exts[j].getActive()) {
640
                                        continue;
641
                                }
642

    
643
                                Menu[] menus = exts[j].getMenu();
644

    
645
                                for (int k = 0; k < menus.length; k++) {
646
                                        SortableMenu sm = new SortableMenu(ps.getClassLoader(),
647
                                                        exts[j], menus[k]);
648

    
649
                                        if (orderedMenus.containsKey(sm)) {
650
                                                logger.error(Messages.getString(
651
                                                                "Launcher.Two_menus_with_the_same_position") + " - " +
652
                                                        menus[k].getText()+ " - " + exts[j].getClassName());
653
                                        }
654

    
655
                                        orderedMenus.put(sm, null);
656
                                }
657
                        }
658

    
659
                        // Se instalan las extensiones de MDI
660
                        SkinExtension skinExt = pc.getExtensions().getSkinExtension();
661

    
662
                        if (skinExt != null) {
663
                                Menu[] menu = skinExt.getMenu();
664

    
665
                                for (int k = 0; k < menu.length; k++) {
666
                                        SortableMenu sm = new SortableMenu(ps.getClassLoader(),
667
                                                        skinExt, menu[k]);
668

    
669
                                        if (orderedMenus.containsKey(sm)) {
670
                                                logger.error(Messages.getString(
671
                                                                "Launcher.Two_menus_with_the_same_position") +
672
                                                        skinExt.getClassName());
673
                                        }
674

    
675
                                        orderedMenus.put(sm, null);
676
                                }
677
                        }
678
                }
679

    
680
                //Se itera por los menus ordenados
681
                Iterator e = orderedMenus.keySet().iterator();
682

    
683
                // Se ordenan los menues
684
                while (e.hasNext()) {
685
                        try {
686
                                SortableMenu sm = (SortableMenu) e.next();
687

    
688
                                frame.addMenu(sm.loader, sm.extension, sm.menu);
689
                        } catch (ClassNotFoundException ex) {
690
                                logger.error(Messages.getString(
691
                                                "Launcher.No_se_encontro_la_clase_de_la_extension"), ex);
692
                        }
693
                }
694
        }
695

    
696
        /**
697
         * Installs the menus, toolbars, actiontools, selectable toolbars and combos.
698
         * The order in which they are shown is determined here.
699
         */
700
        private static void installPluginsControls() {
701
                Iterator i = pluginsConfig.keySet().iterator();
702

    
703
                HashMap extensionPluginServices = new HashMap();
704
                HashMap extensionPluginConfig = new HashMap();
705
                TreeMap orderedExtensions = new TreeMap(new ExtensionComparator());
706

    
707
                // First of all, sort the extensions.
708
                // We need to iterate on the plugins, and iterate on each plugin's extensions
709
                // (each plugin may contain one or more extensions)
710
                while (i.hasNext()) { // iterate on the plugins
711
                        String pName = (String) i.next();
712
                        PluginConfig pc = (PluginConfig) pluginsConfig.get(pName);
713
                        PluginServices ps = (PluginServices) pluginsServices.get(pName);
714

    
715
                        Extension[] exts = pc.getExtensions().getExtension();
716

    
717
                        for (int j = 0; j < exts.length; j++) { // iterate on the extensions
718
                                if (exts[j].getActive()) {
719
                                        if (orderedExtensions.containsKey(exts[j])) {
720
                                                logger.error(Messages.getString(
721
                                                "Launcher.Two_extensions_with_the_same_priority") +
722
                                                exts[j].getClassName());
723
                                        }
724

    
725
                                        orderedExtensions.put(exts[j], null);
726
                                        extensionPluginServices.put(exts[j], ps);
727
                                        extensionPluginConfig.put(exts[j], pc);
728
                                }
729
                        }
730
                }
731

    
732
                TreeMap orderedTools = new TreeMap(new ToolComparator());
733
                Iterator e = orderedExtensions.keySet().iterator();
734

    
735
                // sort the toolbars and tools from 'normal' extensions (actiontools, selectabletools)
736
                // and load the  combo-scales and combo-buttons for the status bar
737
                while (e.hasNext()) {
738
                        Extension ext = (Extension) e.next();
739

    
740
                        ToolBar[] toolbars = ext.getToolBar();
741

    
742
                        // get tools from toolbars
743
                        for (int k = 0; k < toolbars.length; k++) {
744
                                ActionTool[] tools = toolbars[k].getActionTool();
745

    
746
                                for (int t = 0; t < tools.length; t++) {
747
                                        SortableTool sm = new SortableTool(((PluginServices)extensionPluginServices.get(ext)).getClassLoader(), ext,
748
                                                        toolbars[k], tools[t]);
749
                                        orderedTools.put(sm, null);
750
                                }
751

    
752
                                SelectableTool[] sTools = toolbars[k].getSelectableTool();
753

    
754
                                for (int t = 0; t < sTools.length; t++) {
755
                                        SortableTool sm=new SortableTool(((PluginServices)extensionPluginServices.get(ext)).getClassLoader(), ext,
756
                                                        toolbars[k], sTools[t]);
757
                                        orderedTools.put(sm, null);
758
                                }
759
                        }
760

    
761
                        // get controls for statusBar
762
                        PluginServices ps = (PluginServices) extensionPluginServices.get(ext);
763
                        PluginClassLoader loader = ps.getClassLoader();
764

    
765
                        //ArrayList componentList = new ArrayList();
766
                        ComboScale[] comboScaleArray = ext.getComboScale();
767
                        for (int k=0; k < comboScaleArray.length; k++) {
768
                                org.gvsig.gui.beans.controls.comboscale.ComboScale combo = new org.gvsig.gui.beans.controls.comboscale.ComboScale();
769
                                String label = comboScaleArray[k].getLabel();
770
                                if (label!=null)
771
                                        combo.setLabel(label);
772
                                String name = comboScaleArray[k].getName();
773
                                if (name!=null)
774
                                        combo.setName(name);
775
                                String[] elementsString = ((String)comboScaleArray[k].getElements()).split(";");
776
                                long[] elements = new long[elementsString.length];
777
                                for (int currentElem=0; currentElem<elementsString.length; currentElem++) {
778
                                        try {
779
                                                elements[currentElem] = Long.parseLong(elementsString[currentElem]);
780
                                        }
781
                                        catch (NumberFormatException nfex1) {
782
                                                logger.error(ext.getClassName()+" -- "+Messages.getString( "error_parsing_comboscale_elements"));
783
                                                elements[currentElem] = 0;
784
                                        }
785
                                }
786
                                combo.setItems(elements);
787
                                try {
788
                                        long value = Long.parseLong((String)comboScaleArray[k].getValue());
789
                                        combo.setScale(value);
790
                                }
791
                                catch (NumberFormatException nfex2) {
792
                                        logger.error(ext.getClassName()+" -- "+Messages.getString( "error_parsing_comboscale_value"));
793
                                }
794
                                try {
795
                                        frame.addStatusBarControl(loader.loadClass(ext.getClassName()),combo);
796
                                } catch (ClassNotFoundException e1) {
797
                                        logger.error(Messages.getString("Launcher.error_getting_class_loader_for_status_bar_control"), e1);
798
                                }
799
                        }
800

    
801
                        ComboButton[] comboButtonArray = ext.getComboButton();
802
                        for (int k=0; k < comboButtonArray.length; k++) {
803
                                ComboButtonElement[] elementList = comboButtonArray[k].getComboButtonElement();
804
                                org.gvsig.gui.beans.controls.combobutton.ComboButton combo = new org.gvsig.gui.beans.controls.combobutton.ComboButton();
805
                                String name = comboButtonArray[k].getName();
806
                                if (name!=null)
807
                                        combo.setName(name);
808
                                for (int currentElement=0; currentElement<elementList.length; currentElement++) {
809
                                        ComboButtonElement element = elementList[currentElement];
810
                                        ImageIcon icon;
811
                                        URL iconLocation = loader.getResource(element.getIcon());
812
                                        if (iconLocation==null)
813
                                                logger.error(Messages.getString("Icon_not_found_")+element.getIcon());
814
                                        else {
815
                                                icon = new ImageIcon(iconLocation);
816
                                                JButton button = new JButton(icon);
817
                                                combo.addButton(button);
818
                                                button.setActionCommand(element.getActionCommand());
819
                                        }
820
                                }
821
                                try {
822
                                        frame.addStatusBarControl(loader.loadClass(ext.getClassName()), combo);
823
                                } catch (ClassNotFoundException e1) {
824
                                        logger.error(Messages.getString("Launcher.error_getting_class_loader_for_status_bar_control"), e1);
825
                                }
826
                        }
827
                }
828

    
829
                // Add the tools from MDI extensions to the ordered tool-list, so that we get a sorted list containing all the tools
830
                i = pluginsConfig.keySet().iterator();
831
                while (i.hasNext()) {
832
                        String pName = (String) i.next();
833
                        PluginConfig pc = (PluginConfig) pluginsConfig.get(pName);
834
                        PluginServices ps = (PluginServices) pluginsServices.get(pName);
835

    
836
                        SkinExtension skinExt = pc.getExtensions().getSkinExtension();
837

    
838
                        if (skinExt != null) {
839
                                ToolBar[] toolbars = skinExt.getToolBar();
840

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

    
844
                                        for (int t = 0; t < tools.length; t++) {
845
                                                SortableTool stb=new SortableTool(ps.getClassLoader(), skinExt,
846
                                                                toolbars[k], tools[t]);
847
                                                orderedTools.put(stb,null);
848
                                        }
849

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

    
852
                                        for (int t = 0; t < sTools.length; t++) {
853
                                                SortableTool stb=new SortableTool(ps.getClassLoader(), skinExt,
854
                                                                toolbars[k], sTools[t]);
855
                                                orderedTools.put(stb,null);
856
                                        }
857
                                }
858
                        }
859
                        // Install popup menus
860
                        PopupMenus pus = pc.getPopupMenus();
861

    
862
                        if (pus != null) {
863
                                PopupMenu[] menus = pus.getPopupMenu();
864

    
865
                                for (int j = 0; j < menus.length; j++) {
866
                                        frame.addPopupMenu(ps.getClassLoader(), menus[j]);
867
                                }
868
                        }
869
                }
870

    
871
                // loop on the ordered extension list, to add them to the interface in an ordered way
872
                Iterator t = orderedTools.keySet().iterator();
873
                while (t.hasNext()) {
874
                        try {
875
                                SortableTool stb = (SortableTool) t.next();
876
                                if (stb.actiontool!=null)
877
                                        frame.addTool(stb.loader, stb.extension,stb.toolbar, stb.actiontool);
878
                                else
879
                                        frame.addTool(stb.loader, stb.extension,stb.toolbar, stb.selectabletool);
880
                        } catch (ClassNotFoundException ex) {
881
                                logger.error(Messages.getString(
882
                                "Launcher.No_se_encontro_la_clase_de_la_extension"), ex);
883
                        }
884
                }
885
        }
886

    
887
        /**
888
         * Adds new plugins to the the andami-config file.
889
         */
890
        private static void updateAndamiConfig() {
891
                HashSet olds = new HashSet();
892

    
893
                Plugin[] plugins = andamiConfig.getPlugin();
894

    
895
                for (int i = 0; i < plugins.length; i++) {
896
                        olds.add(plugins[i].getName());
897
                }
898

    
899
                Iterator i = pluginsServices.values().iterator();
900

    
901
                while (i.hasNext()) {
902
                        PluginServices ps = (PluginServices) i.next();
903

    
904
                        if (!olds.contains(ps.getPluginName())) {
905
                                Plugin p = new Plugin();
906
                                p.setName(ps.getPluginName());
907
                                p.setUpdate(false);
908

    
909
                                andamiConfig.addPlugin(p);
910
                        }
911
                }
912
        }
913

    
914
        /**
915
         * DOCUMENT ME!
916
         */
917
        private static void pluginsClassLoaders() {
918
                HashSet instalados = new HashSet();
919

    
920
                // Se itera hasta que est?n todos instalados
921
                while (instalados.size() != pluginsConfig.size()) {
922
                        boolean circle = true;
923

    
924
                        //Hacemos una pasada por todos los plugins
925
                        Iterator i = pluginsConfig.keySet().iterator();
926

    
927
                        while (i.hasNext()) {
928
                                String pluginName = (String) i.next();
929
                                PluginConfig config = (PluginConfig) pluginsConfig.get(pluginName);
930

    
931
                                if (instalados.contains(pluginName)) {
932
                                        continue;
933
                                }
934

    
935
                                //Se obtienen las dependencias y sus class loaders
936
                                boolean ready = true;
937
                                Depends[] dependencies = config.getDepends();
938
                                PluginClassLoader[] loaders = new PluginClassLoader[dependencies.length];
939

    
940
                                for (int j = 0; j < dependencies.length; j++) {
941
                                        if (pluginsConfig.get(dependencies[j].getPluginName()) == null) {
942
                                                logger.error(Messages.getString(
943
                                                                "Launcher.Dependencia_no_resuelta_en_plugin") +
944
                                                        pluginName + ": " +
945
                                                        dependencies[j].getPluginName());
946

    
947
                                                continue;
948
                                        }
949

    
950
                                        if (!instalados.contains(dependencies[j].getPluginName())) {
951
                                                ready = false;
952
                                        } else {
953
                                                loaders[j] = ((PluginServices) pluginsServices.get(dependencies[j].getPluginName())).getClassLoader();
954
                                        }
955
                                }
956

    
957
                                //Si no est?n sus dependencias satisfechas se aborta la instalaci?n
958
                                if (!ready) {
959
                                        continue;
960
                                }
961

    
962
                                //Se genera el class loader
963
                                String jardir = config.getLibraries().getLibraryDir();
964
                                File jarDir = new File(andamiConfig.getPluginsDirectory() +
965
                                                File.separator + pluginName + File.separator + jardir);
966
                                File[] jarFiles = jarDir.listFiles(new FileFilter() {
967
                                                        public boolean accept(File pathname) {
968
                                                                return (pathname.getName().toUpperCase()
969
                                                                                                .endsWith(".JAR")) ||
970
                                                                (pathname.getName().toUpperCase().endsWith(".ZIP"));
971
                                                        }
972
                                                });
973

    
974
                                URL[] urls = new URL[jarFiles.length];
975

    
976
                                for (int j = 0; j < jarFiles.length; j++) {
977
                                        try {
978
                                                urls[j] = new URL("file:" + jarFiles[j]);
979
                                        } catch (MalformedURLException e) {
980
                                                logger.error(Messages.getString(
981
                                                                "Launcher.No_se_puede_acceder_a") +
982
                                                        jarFiles[j]);
983
                                        }
984
                                }
985

    
986
                                PluginClassLoader loader;
987

    
988
                                try {
989
                                        loader = new PluginClassLoader(urls,
990
                                                        andamiConfig.getPluginsDirectory() +
991
                                                        File.separator + pluginName,
992
                                                        Launcher.class.getClassLoader(), loaders);
993

    
994
                                        PluginServices ps = new PluginServices(loader);
995

    
996
                                        pluginsServices.put(ps.getPluginName(), ps);
997

    
998
                                        instalados.add(pluginName);
999
                    // FJP: Los metemos ordenados para luego no cargar uno que necesita de otro antes de tiempo. Esto lo usaremos al
1000
                    // inicializar los plugins
1001
                    pluginsOrdered.add(pluginName);
1002

    
1003
                                        circle = false;
1004
                                } catch (IOException e) {
1005
                                        logger.error(Messages.getString(
1006
                                                        "Launcher.Error_con_las_librerias_del_plugin"), e);
1007
                                        pluginsConfig.remove(pluginName);
1008
                                        i = pluginsConfig.keySet().iterator();
1009
                                }
1010
                        }
1011

    
1012
                        if (circle) {
1013
                                logger.error(Messages.getString(
1014
                                                "Launcher.Hay_dependencias_circulares"));
1015

    
1016
                                break;
1017
                        }
1018
                }
1019

    
1020
                //Se eliminan los plugins que no fueron instalados
1021
                Iterator i = pluginsConfig.keySet().iterator();
1022

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

    
1028
                        if (ps == null) {
1029
                                pluginsConfig.remove(pluginName);
1030
                                i = pluginsConfig.keySet().iterator();
1031
                        }
1032
                }
1033
        }
1034

    
1035
        /**
1036
         * DOCUMENT ME!
1037
         */
1038
        private static void pluginsMessages() {
1039
                /* add gvsig translations first. This should be done using a generic "appPlugin" variable, instead
1040
                 * of using "com.iver.cit.gvsig" directly, but I'll do it when we use the new appgvSIG launcher.
1041
                 * I keep this workaround for the moment.
1042
                 */
1043
                PluginConfig config = (PluginConfig) pluginsConfig.get("com.iver.cit.gvsig");
1044
                PluginServices ps = (PluginServices) pluginsServices.get("com.iver.cit.gvsig");
1045
                if (config.getResourceBundle() != null) {
1046
                        org.gvsig.i18n.Messages.addResourceFamily(config.getResourceBundle().getName(), ps.getClassLoader(), "com.iver.cit.gvsig");
1047
                }
1048

    
1049
                //Iteramos por todos los plugins
1050
                Iterator i = pluginsConfig.keySet().iterator();
1051

    
1052
                while (i.hasNext()) {
1053
                        String pluginName = (String) i.next();
1054
                        if (!pluginName.equals("com.iver.cit.gvsig")) { // we've already loaded com.iver.cit.gvsig
1055
                                config = (PluginConfig) pluginsConfig.get(pluginName);
1056
                                ps = (PluginServices) pluginsServices.get(pluginName);
1057

    
1058
                                if (config.getResourceBundle() != null && !config.getResourceBundle().getName().equals("")) {
1059
                                        // add the locale files associated with the plugin
1060
                                        org.gvsig.i18n.Messages.addResourceFamily(config.getResourceBundle().getName(), ps.getClassLoader(), pluginName);
1061
                                }
1062
                        }
1063
                }
1064
        }
1065

    
1066
        /**
1067
         * DOCUMENT ME!
1068
         *
1069
         * @param name DOCUMENT ME!
1070
         *
1071
         * @return DOCUMENT ME!
1072
         */
1073
        static PluginServices getPluginServices(String name) {
1074
                return (PluginServices) pluginsServices.get(name);
1075
        }
1076

    
1077
        /**
1078
         * DOCUMENT ME!
1079
         *
1080
         * @return DOCUMENT ME!
1081
         */
1082
        static String getPluginsDir() {
1083
                return andamiConfig.getPluginsDirectory();
1084
        }
1085

    
1086
        /**
1087
         * DOCUMENT ME!
1088
         *
1089
         * @param s DOCUMENT ME!
1090
         */
1091
        static void setPluginsDir(String s) {
1092
                andamiConfig.setPluginsDirectory(s);
1093
        }
1094

    
1095
        /**
1096
         * DOCUMENT ME!
1097
         *
1098
         * @return DOCUMENT ME!
1099
         */
1100
        static MDIFrame getMDIFrame() {
1101
                return frame;
1102
        }
1103

    
1104
        /**
1105
         * DOCUMENT ME!
1106
         *
1107
         * @param pluginsDirectory
1108
         */
1109
        private static void loadPlugins(String pluginsDirectory) {
1110
                File pDir = new File(pluginsDirectory);
1111

    
1112
                if (!pDir.exists()) {
1113
                        return;
1114
                }
1115

    
1116
                File[] pluginDirs = pDir.listFiles();
1117

    
1118
                for (int i = 0; i < pluginDirs.length; i++) {
1119
                        if (pluginDirs[i].isDirectory()) {
1120
                                File configXml = new File(pluginDirs[i].getAbsolutePath() +
1121
                                                File.separator + "config.xml");
1122

    
1123
                                try {
1124
                                        FileReader xml = new FileReader(configXml);
1125
                                        PluginConfig pConfig = (PluginConfig) PluginConfig.unmarshal(xml);
1126
                                        pluginsConfig.put(pluginDirs[i].getName(), pConfig);
1127
                                } catch (FileNotFoundException e) {
1128
                                        logger.info(Messages.getString(
1129
                                                        "Launcher.Ignorando_el_directorio") +
1130
                                                pluginDirs[i].getAbsolutePath() +
1131
                                                Messages.getString("Launcher.config_no_encontrado"));
1132
                                } catch (MarshalException e) {
1133
                                        logger.info(Messages.getString(
1134
                                                        "Launcher.Ignorando_el_directorio") +
1135
                                                pluginDirs[i].getAbsolutePath() +
1136
                                                Messages.getString("Launcher.config_mal_formado"), e);
1137
                                } catch (ValidationException e) {
1138
                                        logger.info(Messages.getString(
1139
                                                        "Launcher.Ignorando_el_directorio") +
1140
                                                pluginDirs[i].getAbsolutePath() +
1141
                                                Messages.getString("Launcher.config_mal_formado"), e);
1142
                                }
1143
                        }
1144
                }
1145
        }
1146

    
1147
        /**
1148
         * DOCUMENT ME!
1149
         *
1150
         * @param language
1151
         * @param country
1152
         * @param variant
1153
         *
1154
         * @return DOCUMENT ME!
1155
         */
1156
        private static Locale getLocale(String language, String country,
1157
                String variant) {
1158
                if (variant != null) {
1159
                        return new Locale(language, country, variant);
1160
                } else if (country != null) {
1161
                        return new Locale(language, country);
1162
                } else if (language != null) {
1163
                        return new Locale(language);
1164
                } else {
1165
                        return new Locale("es");
1166
                }
1167
        }
1168

    
1169
        /**
1170
         * DOCUMENT ME!
1171
         *
1172
         * @param file DOCUMENT ME!
1173
         *
1174
         * @throws IOException DOCUMENT ME!
1175
         * @throws MarshalException DOCUMENT ME!
1176
         * @throws ValidationException DOCUMENT ME!
1177
         */
1178
        private static void andamiConfigToXML(String file)
1179
                throws IOException, MarshalException, ValidationException {
1180
                File xml = new File(file);
1181
                File parent = xml.getParentFile();
1182
                parent.mkdirs();
1183

    
1184
                FileWriter writer = new FileWriter(xml);
1185
                andamiConfig.marshal(writer);
1186
        }
1187

    
1188
        /**
1189
         * DOCUMENT ME!
1190
         *
1191
         * @param file DOCUMENT ME!
1192
         *
1193
         * @throws ConfigurationException DOCUMENT ME!
1194
         */
1195
        private static void andamiConfigFromXML(String file)
1196
                throws ConfigurationException {
1197
                File xml = new File(file);
1198

    
1199
                //Si no existe se ponen los valores por defecto
1200
                if (!xml.exists()) {
1201
                        andamiConfig = new AndamiConfig();
1202

    
1203
                        Andami andami = new Andami();
1204
                        andami.setUpdate(true);
1205
                        andamiConfig.setAndami(andami);
1206
                        andamiConfig.setLocaleCountry(Locale.getDefault().getCountry());
1207
                        andamiConfig.setLocaleLanguage(Locale.getDefault().getLanguage());
1208
                        andamiConfig.setLocaleVariant(Locale.getDefault().getVariant());
1209

    
1210
                        if (System.getProperty("javawebstart.version") != null) // Es java web start)
1211
                         {
1212
                                andamiConfig.setPluginsDirectory(new File(System.getProperty(
1213
                                                        "user.home") + File.separator + appName +
1214
                                                File.separator + "extensiones").getAbsolutePath());
1215
                        } else {
1216
                                andamiConfig.setPluginsDirectory(new File(appName +
1217
                                                File.separator + "extensiones").getAbsolutePath());
1218
                        }
1219

    
1220
                        andamiConfig.setPlugin(new Plugin[0]);
1221
                } else {
1222
                        //Se lee la configuraci?n
1223
                        FileReader reader;
1224

    
1225
                        try {
1226
                                reader = new FileReader(xml);
1227
                                andamiConfig = (AndamiConfig) AndamiConfig.unmarshal(reader);
1228
                        } catch (FileNotFoundException e) {
1229
                                throw new ConfigurationException(e);
1230
                        } catch (MarshalException e) {
1231
                                throw new ConfigurationException(e);
1232
                        } catch (ValidationException e) {
1233
                                throw new ConfigurationException(e);
1234
                        }
1235
                }
1236
        }
1237

    
1238
        /**
1239
         * DOCUMENT ME!
1240
         *
1241
         * @return DOCUMENT ME!
1242
         *
1243
         * @throws ConfigurationException DOCUMENT ME!
1244
         */
1245
        private static XMLEntity persistenceFromXML() throws ConfigurationException {
1246
                File xml = new File(pluginsPersistencePath);
1247

    
1248
                if (xml.exists()) {
1249
                        FileReader reader;
1250

    
1251
                        try {
1252
                                reader = new FileReader(xml);
1253

    
1254
                                XmlTag tag = (XmlTag) XmlTag.unmarshal(reader);
1255

    
1256
                                return new XMLEntity(tag);
1257
                        } catch (FileNotFoundException e) {
1258
                                throw new ConfigurationException(e);
1259
                        } catch (MarshalException e) {
1260
                                throw new ConfigurationException(e);
1261
                        } catch (ValidationException e) {
1262
                                throw new ConfigurationException(e);
1263
                        }
1264
                } else {
1265
                        return new XMLEntity();
1266
                }
1267
        }
1268

    
1269
        /**
1270
         * DOCUMENT ME!
1271
         *
1272
         * @param entity DOCUMENT ME!
1273
         *
1274
         * @throws ConfigurationException DOCUMENT ME!
1275
         */
1276
        private static void persistenceToXML(XMLEntity entity)
1277
                throws ConfigurationException {
1278
                File xml = new File(pluginsPersistencePath);
1279

    
1280
                FileWriter writer;
1281

    
1282
                try {
1283
                        writer = new FileWriter(xml);
1284
                        entity.getXmlTag().marshal(writer);
1285
                } catch (FileNotFoundException e) {
1286
                        throw new ConfigurationException(e);
1287
                } catch (MarshalException e) {
1288
                        throw new ConfigurationException(e);
1289
                } catch (ValidationException e) {
1290
                        throw new ConfigurationException(e);
1291
                } catch (IOException e) {
1292
                        throw new ConfigurationException(e);
1293
                }
1294
        }
1295

    
1296
        /**
1297
         * Devuelve un array con los directorios de los plugins
1298
         *
1299
         * @param dirExt Directorio de las extensiones a partir del cual cuelgan
1300
         *                   todos los directorios de los plugins
1301
         *
1302
         * @return ArrayList con los directorios
1303
         */
1304
        private String[] getLocales(File dirExt) {
1305
                ArrayList types = new ArrayList();
1306
                File[] files = dirExt.listFiles();
1307

    
1308
                for (int i = 0; i < files.length; i++) {
1309
                        if (files[i].isDirectory()) {
1310
                                File[] textFile = files[i].listFiles(new FilenameFilter() {
1311
                                                        public boolean accept(File dir, String fileName) {
1312
                                                                return fileName.toLowerCase().startsWith("text_"); //$NON-NLS-1$
1313
                                                        }
1314
                                                });
1315

    
1316
                                for (int j = 0; j < textFile.length; j++) {
1317
                                        String s = (textFile[j]).getName().replaceAll("text_", "");
1318
                                        s = s.replaceAll(".properties", "");
1319
                                        s = s.trim();
1320

    
1321
                                        if (!types.contains(s)) {
1322
                                                types.add(s);
1323
                                        }
1324
                                }
1325
                        }
1326
                }
1327

    
1328
                return (String[]) types.toArray(new String[0]);
1329
        }
1330

    
1331
        /**
1332
         * DOCUMENT ME!
1333
         *
1334
         * @return Returns the frame.
1335
         */
1336
        static MDIFrame getFrame() {
1337
                return frame;
1338
        }
1339

    
1340
        /**
1341
         * Secuencia de cerrado de Andami
1342
         */
1343
        public static void closeApplication() {
1344
                //Configuraci?n de Andami
1345
                try {
1346
                        andamiConfigToXML(andamiConfigPath);
1347
                } catch (MarshalException e) {
1348
                        logger.error(Messages.getString(
1349
                                        "Launcher.No_se_pudo_guardar_la_configuracion_de_andami"), e);
1350
                } catch (ValidationException e) {
1351
                        logger.error(Messages.getString(
1352
                                        "Launcher.No_se_pudo_guardar_la_configuracion_de_andami"), e);
1353
                } catch (IOException e) {
1354
                        logger.error(Messages.getString(
1355
                                        "Launcher.No_se_pudo_guardar_la_configuracion_de_andami"), e);
1356
                }
1357

    
1358
                //Persistencia de los plugins
1359
                savePluginPersistence();
1360

    
1361
                //Finalize all the extensions
1362
                finalizeExtensions();
1363

    
1364
                // Clean any temp data created
1365
                Utilities.cleanUpTempFiles();
1366

    
1367
                //Para la depuraci?n de memory leaks
1368
                System.gc();
1369

    
1370
        System.exit(0);
1371
        }
1372

    
1373
        /**
1374
         * Exectutes the finalize method for all the extensions
1375
         *
1376
         */
1377
        private static void finalizeExtensions() {
1378
                Set extensions = getClassesExtensions().keySet();
1379
                Object[] keys = extensions.toArray();
1380

    
1381
                for (int i=0 ; i<keys.length ; i++){
1382
                        ExtensionDecorator extensionDecorator =
1383
                                (ExtensionDecorator) getClassesExtensions().get(keys[i]);
1384
                        extensionDecorator.getExtension().terminate();
1385
                }
1386
        }
1387

    
1388

    
1389
        /**
1390
         * DOCUMENT ME!
1391
         *
1392
         * @return DOCUMENT ME!
1393
         */
1394
        static HashMap getClassesExtensions() {
1395
                return classesExtensions;
1396
        }
1397

    
1398
        /**
1399
         * DOCUMENT ME!
1400
         *
1401
         * @param extDir DOCUMENT ME!
1402
         */
1403
        private static void downloadExtensions(String extDir) {
1404
                java.util.Date fechaActual = null;
1405

    
1406
                try {
1407
                        if (System.getProperty("javawebstart.version") != null) {
1408
                                //Obtenemos la URL del servidor
1409
                                BasicService bs = (BasicService) ServiceManager.lookup(
1410
                                                "javax.jnlp.BasicService");
1411
                                URL baseURL = bs.getCodeBase();
1412

    
1413
                                //Se descargan las extensiones
1414
                                SplashWindow.process(5,
1415
                                        "Descargando las extensiones desde " + baseURL + " a " +
1416
                                        extDir);
1417

    
1418
                                URL url = new URL(baseURL + "extensiones.zip");
1419
                                URLConnection connection = url.openConnection();
1420

    
1421
                                System.out.println(url.toExternalForm() + ":");
1422
                                System.out.println("  Content Type: " +
1423
                                        connection.getContentType());
1424
                                System.out.println("  Content Length: " +
1425
                                        connection.getContentLength());
1426
                                System.out.println("  Last Modified: " +
1427
                                        new Date(connection.getLastModified()));
1428
                                System.out.println("  Expiration: " +
1429
                                        connection.getExpiration());
1430
                                System.out.println("  Content Encoding: " +
1431
                                        connection.getContentEncoding());
1432

    
1433
                                // Guardamos la fecha del fichero de extensiones que nos hemos bajado, y
1434
                                // comprobamos el ?ltimo que se ha bajado. Si no son
1435
                                // iguales, nos bajamos el nuevo. Si son iguales, no
1436
                                // nos bajamos nada.
1437
                                Long miliSecondsInWeb = new Long(connection.getLastModified());
1438

    
1439
                                // PluginServices ps = PluginServices.getPluginServices("com.iver.core");
1440
                                // if (ps.getPersistentXML().getStringProperty("timestamp") != null)
1441
                                File destDir = new File(extDir);
1442

    
1443
                                if (!destDir.exists()) {
1444
                                        // Creamos gvSIG
1445
                                        destDir.getParentFile().mkdir();
1446

    
1447
                                        if (!destDir.mkdir()) {
1448
                                                System.err.println("Imposible crear el directorio " +
1449
                                                        destDir.getAbsolutePath());
1450
                                        }
1451
                                }
1452

    
1453
                                File timeFile = new File(destDir.getParent() + File.separator +
1454
                                                "timeStamp.properties");
1455

    
1456
                                if (!timeFile.exists()) {
1457
                                        timeFile.createNewFile();
1458
                                }
1459

    
1460
                                FileInputStream inAux = new FileInputStream(timeFile);
1461
                                Properties prop = new Properties();
1462
                                prop.load(inAux);
1463
                                inAux.close();
1464

    
1465
                                if (prop.getProperty("timestamp") != null) {
1466
                                        Long lastMiliSeconds = (Long) new Long(prop.getProperty(
1467
                                                                "timestamp"));
1468

    
1469
                                        if (lastMiliSeconds.longValue() == miliSecondsInWeb.longValue()) {
1470
                                                System.out.println("No hay nueva actualizaci?n");
1471
                        logger.debug("No hay nueva actualizaci?n -> Return");
1472
                        logger.debug("timeStampWeb= " + miliSecondsInWeb);
1473
                        logger.debug("timeStampLocal= " + lastMiliSeconds);
1474

    
1475
                                                return;
1476
                                        }
1477

    
1478
                                        System.out.println("timeStampWeb= " + miliSecondsInWeb);
1479
                                        System.out.println("timeStampLocal= " + lastMiliSeconds);
1480
                                } else {
1481
                                        System.out.println("El timeStamp no est? escrito en " +
1482
                                                timeFile.getAbsolutePath());
1483
                                }
1484

    
1485
                                InputStream stream = url.openStream();
1486
                File temp = File.createTempFile("gvsig", ".zip");
1487

    
1488
                logger.debug(temp.getAbsolutePath());
1489

    
1490
                temp.deleteOnExit();
1491
                FileOutputStream file = new FileOutputStream(temp);
1492

    
1493
                byte[] lt_read = new byte[1];
1494

    
1495
                while (stream.read(lt_read) > 0)
1496
                  file.write(lt_read);
1497

    
1498
                stream.close();
1499
                stream = null;
1500
                file.close();
1501
                file = null;
1502

    
1503
                System.gc();
1504

    
1505
                logger.debug("Ha creado el fichero ZIP");
1506
                                //Se extrae el zip
1507
                                SplashWindow.process(5, "Extensiones descargadas.");
1508

    
1509
                                System.out.println("Extrayendo a " + destDir.getAbsolutePath());
1510

    
1511
                                Date fechaDir = new Date(destDir.lastModified());
1512
                                System.out.println("Fecha del directorio " + extDir + " = " +
1513
                                        fechaDir.toString());
1514
                                Utilities.extractTo(temp, new File(extDir), splashWindow);
1515

    
1516
                                // Si todo ha ido bien, guardamos el timestamp.
1517
                                ///  App.instance.getPc().addProperties("timestamp", miliSecondsInWeb);
1518
                                // XMLEntity xml=ps.getPersistentXML();
1519
                                fechaActual = new java.util.Date();
1520

    
1521
                                FileOutputStream outAux = new FileOutputStream(timeFile);
1522
                                prop.setProperty("timestamp", miliSecondsInWeb.toString());
1523
                                prop.store(outAux, "last download");
1524
                                outAux.close();
1525
                                System.out.println("Fecha actual guardada: " +
1526
                                        fechaActual.toGMTString());
1527

    
1528
                                /* xml.putProperty("timestamp",fechaActual.toGMTString());
1529
                                   ps.setPresistentXML(xml); */
1530
                        }
1531
                } catch (IOException e) {
1532
                        NotificationManager.addError("", e);
1533
                } catch (UnavailableServiceException e) {
1534
                        NotificationManager.addError("", e);
1535
                } catch (SecurityException e) {
1536
                        System.err.println("No se puede escribir el timeStamp " +
1537
                                fechaActual.toGMTString());
1538
                        NotificationManager.addError("", e);
1539
                }
1540
        }
1541

    
1542
        /**
1543
         * DOCUMENT ME!
1544
         *
1545
         * @return DOCUMENT ME!
1546
         */
1547
        private static Extensions[] getExtensions() {
1548
                ArrayList array = new ArrayList();
1549
                Iterator iter = pluginsConfig.values().iterator();
1550

    
1551
                while (iter.hasNext()) {
1552
                        array.add(((PluginConfig) iter.next()).getExtensions());
1553
                }
1554

    
1555
                return (Extensions[]) array.toArray(new Extensions[0]);
1556
        }
1557

    
1558
        /**
1559
         * DOCUMENT ME!
1560
         *
1561
         * @return DOCUMENT ME!
1562
         */
1563
        public static HashMap getPluginConfig() {
1564
                return pluginsConfig;
1565
        }
1566

    
1567
        /**
1568
         * DOCUMENT ME!
1569
         *
1570
         * @param s DOCUMENT ME!
1571
         *
1572
         * @return DOCUMENT ME!
1573
         */
1574
        public static Extension getExtension(String s) {
1575
                Extensions[] exts = getExtensions();
1576

    
1577
                for (int i = 0; i < exts.length; i++) {
1578
                        for (int j = 0; j < exts[i].getExtensionCount(); j++) {
1579
                                if (exts[i].getExtension(j).getClassName().equals(s)) {
1580
                                        return exts[i].getExtension(j);
1581
                                }
1582
                        }
1583
                }
1584

    
1585
                return null;
1586
        }
1587

    
1588
        /**
1589
         * DOCUMENT ME!
1590
         *
1591
         * @return DOCUMENT ME!
1592
         */
1593
        public static AndamiConfig getAndamiConfig() {
1594
                return andamiConfig;
1595
        }
1596

    
1597
        /**
1598
         * DOCUMENT ME!
1599
         *
1600
         * @author $author$
1601
         * @version $Revision: 7513 $
1602
         */
1603
        private static class ExtensionComparator implements Comparator {
1604
                /**
1605
                 * DOCUMENT ME!
1606
                 *
1607
                 * @param o1 DOCUMENT ME!
1608
                 * @param o2 DOCUMENT ME!
1609
                 *
1610
                 * @return DOCUMENT ME!
1611
                 */
1612
                public int compare(Object o1, Object o2) {
1613
                        Extension e1 = (Extension) o1;
1614
                        Extension e2 = (Extension) o2;
1615

    
1616
                        if (!e1.hasPriority() && !e2.hasPriority()) {
1617
                                return -1;
1618
                        }
1619

    
1620
                        if (e1.hasPriority() && !e2.hasPriority()) {
1621
                                return Integer.MIN_VALUE;
1622
                        }
1623

    
1624
                        if (e2.hasPriority() && !e1.hasPriority()) {
1625
                                return Integer.MAX_VALUE;
1626
                        }
1627

    
1628
                        if (e1.getPriority() != e2.getPriority()){
1629
                                return e2.getPriority() - e1.getPriority();
1630
                        }else{
1631
                                return (e2.toString().compareTo(e1.toString()));
1632
                        }
1633
                }
1634
        }
1635

    
1636
        /**
1637
         * DOCUMENT ME!
1638
         */
1639
        private static class MenuComparator implements Comparator {
1640
                private static ExtensionComparator extComp = new ExtensionComparator();
1641

    
1642
                /**
1643
                 * DOCUMENT ME!
1644
                 *
1645
                 * @param o1 DOCUMENT ME!
1646
                 * @param o2 DOCUMENT ME!
1647
                 *
1648
                 * @return DOCUMENT ME!
1649
                 */
1650
                public int compare(Object o1, Object o2) {
1651
                        SortableMenu e1 = (SortableMenu) o1;
1652
                        SortableMenu e2 = (SortableMenu) o2;
1653

    
1654
                        if (!e1.menu.hasPosition() && !e2.menu.hasPosition()) {
1655
                                if (e1.extension instanceof SkinExtensionType) {
1656
                                        return 1;
1657
                                } else if (e2.extension instanceof SkinExtensionType) {
1658
                                        return -1;
1659
                                } else {
1660
                                        return extComp.compare(e1.extension, e2.extension);
1661
                                }
1662
                        }
1663

    
1664
                        if (e1.menu.hasPosition() && !e2.menu.hasPosition()) {
1665
                                return Integer.MIN_VALUE;
1666
                        }
1667

    
1668
                        if (e2.menu.hasPosition() && !e1.menu.hasPosition()) {
1669
                                return Integer.MAX_VALUE;
1670
                        }
1671
                        if (e1.menu.getPosition() != e2.menu.getPosition()){
1672
                                //we don't return 0 unless both objects are the same, otherwise the objects get overwritten in the treemap
1673
                                return e1.menu.getPosition() - e2.menu.getPosition();
1674
                        }else{
1675
                                return (e1.toString().compareTo(e2.toString()));
1676
                        }
1677
                }
1678
        }
1679

    
1680
        /**
1681
         * DOCUMENT ME!
1682
         *
1683
         * @author $author$
1684
         * @version $Revision: 7513 $
1685
         */
1686
        private static class SortableMenu {
1687
                public PluginClassLoader loader;
1688
                public Menu menu;
1689
                public SkinExtensionType extension;
1690

    
1691
                /**
1692
                 * DOCUMENT ME!
1693
                 *
1694
                 * @param loader DOCUMENT ME!
1695
                 * @param skinExt
1696
                 * @param menu2
1697
                 */
1698
                public SortableMenu(PluginClassLoader loader,
1699
                        SkinExtensionType skinExt, Menu menu2) {
1700
                        extension = skinExt;
1701
                        menu = menu2;
1702
                        this.loader = loader;
1703
                }
1704
        }
1705
        /**
1706
         * DOCUMENT ME!
1707
         */
1708
        private static class SortableTool {
1709
                public PluginClassLoader loader;
1710
                public ToolBar toolbar;
1711
                public ActionTool actiontool;
1712
                public SelectableTool selectabletool;
1713
                public SkinExtensionType extension;
1714

    
1715
                /**
1716
                 * DOCUMENT ME!
1717
                 *
1718
                 * @param loader DOCUMENT ME!
1719
                 * @param skinExt
1720
                 * @param menu2
1721
                 */
1722
                public SortableTool(PluginClassLoader loader,
1723
                        SkinExtensionType skinExt, ToolBar toolbar2,ActionTool actiontool2) {
1724
                        extension = skinExt;
1725
                        toolbar = toolbar2;
1726
                        actiontool=actiontool2;
1727
                        this.loader = loader;
1728
                }
1729
                public SortableTool(PluginClassLoader loader,
1730
                                SkinExtensionType skinExt, ToolBar toolbar2,SelectableTool selectabletool2) {
1731
                        extension = skinExt;
1732
                        toolbar = toolbar2;
1733
                        selectabletool=selectabletool2;
1734
                        this.loader = loader;
1735
                }
1736
        }
1737
        /**
1738
         * DOCUMENT ME!
1739
         */
1740
        private static class ToolBarComparator implements Comparator {
1741
                private static ExtensionComparator extComp = new ExtensionComparator();
1742

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

    
1755
                        // if the toolbars have the same name, they are considered to be
1756
                        // the same toolbar, so we don't need to do further comparing
1757
                        if (e1.toolbar.getName().equals(e2.toolbar.getName()))
1758
                                return 0;
1759

    
1760
                        if (!e1.toolbar.hasPosition() && !e2.toolbar.hasPosition()) {
1761
                                if (e1.extension instanceof SkinExtensionType) {
1762
                                        return 1;
1763
                                } else if (e2.extension instanceof SkinExtensionType) {
1764
                                        return -1;
1765
                                } else {
1766
                                        return extComp.compare(e1.extension, e2.extension);
1767
                                }
1768
                        }
1769

    
1770
                        if (e1.toolbar.hasPosition() && !e2.toolbar.hasPosition()) {
1771
                                return Integer.MIN_VALUE;
1772
                        }
1773

    
1774
                        if (e2.toolbar.hasPosition() && !e1.toolbar.hasPosition()) {
1775
                                return Integer.MAX_VALUE;
1776
                        }
1777
                        if (e1.toolbar.getPosition() != e2.toolbar.getPosition())
1778
                                return e1.toolbar.getPosition() - e2.toolbar.getPosition();
1779

    
1780
                        if (e1.toolbar.getActionTool().equals(e2.toolbar.getActionTool()) && e1.toolbar.getSelectableTool().equals(e2.toolbar.getSelectableTool())){
1781
                                return 0;
1782
                        }
1783
                        return (e1.toolbar.toString().compareTo(e2.toolbar.toString()));
1784
                }
1785
        }
1786

    
1787
        /**
1788
         * <p>This class is used to compare tools (selectabletool and actiontool),
1789
         * using the "position"
1790
         * attribute.</p>
1791
         * <p>The ordering criteria are:</p>
1792
         * <ul><li>If the tools are placed in different toolbars, they use the toolbars'
1793
         * order.
1794
         * (using the ToolBarComparator).</li>
1795
         * <li></li>
1796
         * <li>If any of the tools has not 'position' attribute, the tool which
1797
         * <strong>has</strong> the attribute will be placed first.</li>
1798
         * <li>If both tools have the same position (or they don't have a
1799
         * 'position' attribute), the priority of the extensions where the tool is defined.</li></ul>
1800
         *
1801
         * @author cesar
1802
         * @version $Revision: 7513 $
1803
         */
1804
        private static class ToolComparator implements Comparator {
1805
                private static ToolBarComparator toolBarComp = new ToolBarComparator();
1806
                /**
1807
                 * DOCUMENT ME!
1808
                 *
1809
                 * @param o1 DOCUMENT ME!
1810
                 * @param o2 DOCUMENT ME!
1811
                 *
1812
                 * @return DOCUMENT ME!
1813
                 */
1814
                public int compare(Object o1, Object o2) {
1815
                        // compare the toolbars which contain the tools
1816
                        int result = toolBarComp.compare(o1, o2);
1817
                        if (result != 0) { // if the toolbars are different, use their order
1818
                                return result;
1819
                        }
1820
                        // otherwise, compare the tools
1821
                        SortableTool e1 = (SortableTool) o1;
1822
                        SortableTool e2 = (SortableTool) o2;
1823
                        int e1Position=-1, e2Position=-1;
1824

    
1825
                        if (e1.actiontool!=null) {
1826
                                if (e1.actiontool.hasPosition())
1827
                                        e1Position = e1.actiontool.getPosition();
1828
                        }
1829
                        else if (e1.selectabletool!=null) {
1830
                                if (e1.selectabletool.hasPosition())
1831
                                        e1Position = e1.selectabletool.getPosition();
1832
                        }
1833

    
1834
                        if (e2.actiontool!=null) {
1835
                                if (e2.actiontool.hasPosition())
1836
                                        e2Position = e2.actiontool.getPosition();
1837
                        }
1838
                        else if (e2.selectabletool!=null){
1839
                                if (e2.selectabletool.hasPosition())
1840
                                        e2Position = e2.selectabletool.getPosition();
1841
                        }
1842

    
1843
                        if (e1Position==-1 && e2Position!=-1) {
1844
                                return 1;
1845
                        }
1846
                        if (e1Position!=-1 && e2Position==-1) {
1847
                                return -1;
1848
                        }
1849
                        if (e1Position!=-1 && e2Position!=-1) {
1850
                                result = e1Position - e2Position;
1851
                                // we don't return 0 unless both objects are the same, otherwise the objects get overwritten in the treemap
1852
                                if (result!=0) return result;
1853
                        }
1854
                        return e1.toString().compareTo(e2.toString());
1855
                }
1856
        }
1857

    
1858

    
1859
        /**
1860
         * validates the user before starting gvsig
1861
         *
1862
         */
1863
        private static void validate(){
1864

    
1865
                IAuthentication session =  null;
1866
                try {
1867

    
1868
                        //String location = getClassLocation(Class.forName("com.iver.andami.authentication.Session"));
1869
                        session = (IAuthentication)Class.forName("com.iver.andami.authentication.Session").newInstance();
1870

    
1871
                } catch (ClassNotFoundException e) {
1872
                        // TODO Auto-generated catch block
1873
                        //e.printStackTrace();
1874
                        return;
1875
                } catch (InstantiationException e) {
1876
                        // TODO Auto-generated catch block
1877
                        //e.printStackTrace();
1878
                        return;
1879
                } catch (IllegalAccessException e) {
1880
                        // TODO Auto-generated catch block
1881
                        //e.printStackTrace();
1882
                        return;
1883
                }
1884

    
1885
                session.setPluginDirectory( andamiConfig.getPluginsDirectory() );
1886
                if (session.validationRequired()){
1887

    
1888
                        //opens the login dialog for the user to validate
1889
                        //session.loging does not need arguments: they are read in the internal hashtable
1890
                        session.getUser();
1891
                        if(session.Login((String)session.get("user"),(String)session.get("pwd"))){
1892
                                System.out.println("You are logged in");
1893
                                //PluginServices.setSession( session );
1894
                        }
1895
                        else{
1896
                                JOptionPane.showMessageDialog((Component)PluginServices.getMainFrame(),
1897
                                                 "You are not logged in");
1898
                                System.exit(0);
1899
                        }
1900
                        PluginServices.setAuthentication(session);
1901
                }
1902
        }
1903

    
1904
        public static String getDefaultLookAndFeel() {
1905
                String osName = (String) System.getProperty("os.name");
1906

    
1907
            if (osName.substring(0,3).toLowerCase().equals("win"))
1908
                    return UIManager.getSystemLookAndFeelClassName();
1909
        else
1910
                return nonWinDefaultLookAndFeel;
1911
        }
1912

    
1913
        /**
1914
         * Gets the ISO 839 two-characters-long language code matching the
1915
         * provided language code (which may be an ISO 839-2/T
1916
         * three-characters-long code or an ISO 839-1 two-characters-long
1917
         * code).
1918
         *
1919
         * If the provided parameter is already two characters long, it
1920
         * returns the parameter without any modification.
1921
         *
1922
         * @param langCode A language code representing either
1923
         *  an ISO 839-2/T language code or an ISO 839-1 code.
1924
         * @return A two-characters-long code specifying
1925
         *  an ISO 839 language code.
1926
         */
1927
        private static String normalizeLanguageCode(String langCode) {
1928
                final String fileName = "iso_639.tab";
1929
                if (langCode.length()==2)
1930
                        return langCode;
1931
                else if (langCode.length()==3) {
1932
                        if (langCode.equals("va") || langCode.equals("val")) { // special case for Valencian
1933
                                return "ca";
1934
                        }
1935
                        URL isoCodes = Launcher.class.getClassLoader().getResource(fileName);
1936
                        if (isoCodes!=null) {
1937
                                try {
1938
                                        BufferedReader reader =
1939
                                                new BufferedReader(new InputStreamReader(isoCodes.openStream(), "ISO-8859-1"));
1940
                                                String line;
1941

    
1942
                                                while ((line = reader.readLine()) != null) {
1943
                                                        String[] language = line.split("\t");
1944
                                                        if (language[0].equals(langCode)) // first column is the three characters code
1945
                                                                return language[2]; // third column i the two characters code
1946
                                                }
1947
                                }
1948
                                catch (IOException ex) {
1949
                                        logger.error(Messages.getString("Error_reading_isocodes_file"), ex);
1950
                                        return "es";
1951
                                }
1952
                        }
1953
                        else {
1954
                                logger.error(Messages.getString("Error_reading_isocodes_file"));
1955
                                return "es";
1956
                        }
1957
                }
1958
                return "es";
1959
        }
1960

    
1961
        /**
1962
         * Configures the locales (languages and local resources) to be used
1963
         * by the application.
1964
         *
1965
         * First it tries to get the locale from the command line parameters,
1966
         * then the andami-config file is checked.
1967
         *
1968
         * The locale name is normalized to get a two characters language code
1969
         * as defined by ISO-639-1 (although ISO-639-2/T three characters codes
1970
         * are also accepted from the command line or the configuration file).
1971
         *
1972
         * Finally, the gvsig-i18n library and the default locales for Java and
1973
         * Swing are configured.
1974
         *
1975
         */
1976
        private static void configureLocales(String[] args) {
1977
                //                 Configurar el locale
1978
        String localeStr = null;
1979
        for (int i=2; i < args.length; i++)
1980
        {
1981
                int index = args[i].indexOf("language=");
1982
                if (index != -1)
1983
                        localeStr = args[i].substring(index+9);
1984
        }
1985
                if (localeStr == null)
1986
                {
1987
            localeStr = andamiConfig.getLocaleLanguage();
1988
                }
1989
                localeStr = normalizeLanguageCode(localeStr);
1990
                locale = getLocale(localeStr,
1991
                andamiConfig.getLocaleCountry(),
1992
                andamiConfig.getLocaleVariant());
1993
                Locale.setDefault(locale);
1994
                JComponent.setDefaultLocale(locale);
1995
        org.gvsig.i18n.Messages.addLocale(locale);
1996
                // add english and spanish as fallback languages
1997
                org.gvsig.i18n.Messages.addLocale(new Locale("en"));
1998
                org.gvsig.i18n.Messages.addLocale(new Locale("es"));
1999
        org.gvsig.i18n.Messages.addResourceFamily("com.iver.andami.text", "com.iver.andami.text");
2000

    
2001
        }
2002
}