Statistics
| Revision:

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

History | View | Annotate | Download (58.7 KB)

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

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

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

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

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

    
133

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

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

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

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

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

    
182
                    appName = args[0];
183

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

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

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

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

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

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

    
221
                    configureLocales(args);
222

    
223
                    //Se pone el lookAndFeel
224
                    try {
225
                            String lookAndFeel = getAndamiConfig().getLookAndFeel();
226
                            if (lookAndFeel == null)
227
                                    lookAndFeel = getDefaultLookAndFeel();
228
                            UIManager.setLookAndFeel(lookAndFeel);
229
                    } catch (Exception e) {
230
                            logger.warn(Messages.getString("Launcher.look_and_feel"), e);
231
                    }
232
                // Solucionamos el problema de permisos que se produc?a con Java Web Start con este c?digo.
233
                // System.setSecurityManager(null);
234
             Policy.setPolicy(new Policy() {
235
             public PermissionCollection getPermissions(CodeSource codesource) {
236
                      Permissions perms = new Permissions();
237
                      perms.add(new AllPermission());
238
                      return (perms);
239
             }
240
             public void
241
                         refresh() {}
242
             });
243

    
244
                    validate();
245
                    // Mostrar la ventana de inicio
246
                    Frame f=new Frame();
247
                    splashWindow=new MultiSplashWindow(f);
248

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

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

    
255
                    // Se configura el classloader del plugin
256
                    pluginsClassLoaders();
257

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

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

    
265
                    // Se configura la mensajer?a del plugin
266
                    pluginsMessages();
267

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

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

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

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

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

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

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

    
307
                    // Se instalan los bookmarks de los plugins
308

    
309
                    //Se muestra el frame principal
310
                    frame.show();
311

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

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

    
328
    }
329

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

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

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

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

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

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

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

    
420
                XMLEntity entity = new XMLEntity();
421

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

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

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

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

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

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

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

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

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

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

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

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

    
496
                                Class skinClass;
497

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
585
                                        // CON DECORATOR
586
                                        // ANTES: classesExtensions.put(extensionClass, extensionInstance);
587
                                        // AHORA: CREAMOS UNA ExtensionDecorator y asignamos esta instancia para
588
                                        // poder ampliar con nuevas propiedades (AlwaysVisible, por ejemplo)
589
                                        // Para crear la nueva clase ExtensionDecorator, le pasamos como par?metro
590
                                        // la extensi?n original que acabamos de crear
591
                                        // 0-> Inactivo, controla la extension
592
                                        // 1-> Siempre visible
593
                                        // 2-> Invisible
594
                                        ExtensionDecorator newExtensionDecorator = new ExtensionDecorator(extensionInstance, ExtensionDecorator.INACTIVE);
595
                                        classesExtensions.put(extensionClass, newExtensionDecorator);
596
                                        System.err.println("Loading "+extension.getClassName()+"...");
597
                    // logger.debug("Initializing " + extension.getClassName());
598
                    extensionInstance.initialize();
599
                    extensions.add(extensionInstance);
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
        private static void postInitializeExtensions() {
624
                for (int i=0;i<extensions.size();i++) {
625
                        com.iver.andami.plugins.IExtension extensionInstance=(com.iver.andami.plugins.IExtension)extensions.get(i);
626
                        extensionInstance.postInitialize();
627
                }
628
        }
629
        /**
630
         * DOCUMENT ME!
631
         */
632
        private static void installPluginsMenus() {
633
                TreeMap orderedMenus = new TreeMap(new MenuComparator());
634

    
635
                Iterator i = pluginsConfig.keySet().iterator();
636

    
637
                while (i.hasNext()) {
638
                        String pName = (String) i.next();
639
                        PluginServices ps = (PluginServices) pluginsServices.get(pName);
640
                        PluginConfig pc = (PluginConfig) pluginsConfig.get(pName);
641

    
642
                        Extension[] exts = pc.getExtensions().getExtension();
643

    
644
                        for (int j = 0; j < exts.length; j++) {
645
                                if (!exts[j].getActive()) {
646
                                        continue;
647
                                }
648

    
649
                                Menu[] menus = exts[j].getMenu();
650

    
651
                                for (int k = 0; k < menus.length; k++) {
652
                                        SortableMenu sm = new SortableMenu(ps.getClassLoader(),
653
                                                        exts[j], menus[k]);
654

    
655
                                        if (orderedMenus.containsKey(sm)) {
656
                                                logger.error(Messages.getString(
657
                                                                "Launcher.Two_menus_with_the_same_position") + " - " +
658
                                                        menus[k].getText()+ " - " + exts[j].getClassName());
659
                                        }
660

    
661
                                        orderedMenus.put(sm, null);
662
                                }
663
                        }
664

    
665
                        // Se instalan las extensiones de MDI
666
                        SkinExtension skinExt = pc.getExtensions().getSkinExtension();
667

    
668
                        if (skinExt != null) {
669
                                Menu[] menu = skinExt.getMenu();
670

    
671
                                for (int k = 0; k < menu.length; k++) {
672
                                        SortableMenu sm = new SortableMenu(ps.getClassLoader(),
673
                                                        skinExt, menu[k]);
674

    
675
                                        if (orderedMenus.containsKey(sm)) {
676
                                                logger.error(Messages.getString(
677
                                                                "Launcher.Two_menus_with_the_same_position") +
678
                                                        skinExt.getClassName());
679
                                        }
680

    
681
                                        orderedMenus.put(sm, null);
682
                                }
683
                        }
684
                }
685

    
686
                //Se itera por los menus ordenados
687
                Iterator e = orderedMenus.keySet().iterator();
688

    
689
                // Se ordenan los menues
690
                while (e.hasNext()) {
691
                        try {
692
                                SortableMenu sm = (SortableMenu) e.next();
693

    
694
                                frame.addMenu(sm.loader, sm.extension, sm.menu);
695
                        } catch (ClassNotFoundException ex) {
696
                                logger.error(Messages.getString(
697
                                                "Launcher.No_se_encontro_la_clase_de_la_extension"), ex);
698
                        }
699
                }
700
        }
701

    
702
        /**
703
         * Installs the menus, toolbars, actiontools, selectable toolbars and combos.
704
         * The order in which they are shown is determined here.
705
         */
706
        private static void installPluginsControls() {
707
                Iterator i = pluginsConfig.keySet().iterator();
708

    
709
                HashMap extensionPluginServices = new HashMap();
710
                HashMap extensionPluginConfig = new HashMap();
711
                TreeMap orderedExtensions = new TreeMap(new ExtensionComparator());
712

    
713
                // First of all, sort the extensions.
714
                // We need to iterate on the plugins, and iterate on each plugin's extensions
715
                // (each plugin may contain one or more extensions)
716
                while (i.hasNext()) { // iterate on the plugins
717
                        String pName = (String) i.next();
718
                        PluginConfig pc = (PluginConfig) pluginsConfig.get(pName);
719
                        PluginServices ps = (PluginServices) pluginsServices.get(pName);
720

    
721
                        Extension[] exts = pc.getExtensions().getExtension();
722

    
723
                        for (int j = 0; j < exts.length; j++) { // iterate on the extensions
724
                                if (exts[j].getActive()) {
725
                                        if (orderedExtensions.containsKey(exts[j])) {
726
                                                logger.error(Messages.getString(
727
                                                "Launcher.Two_extensions_with_the_same_priority") +
728
                                                exts[j].getClassName());
729
                                        }
730

    
731
                                        orderedExtensions.put(exts[j], null);
732
                                        extensionPluginServices.put(exts[j], ps);
733
                                        extensionPluginConfig.put(exts[j], pc);
734
                                }
735
                        }
736
                }
737

    
738
                TreeMap orderedTools = new TreeMap(new ToolComparator());
739
                Iterator e = orderedExtensions.keySet().iterator();
740

    
741
                // sort the toolbars and tools from 'normal' extensions (actiontools, selectabletools)
742
                // and load the  combo-scales and combo-buttons for the status bar
743
                while (e.hasNext()) {
744
                        Extension ext = (Extension) e.next();
745

    
746
                        ToolBar[] toolbars = ext.getToolBar();
747

    
748
                        // get tools from toolbars
749
                        for (int k = 0; k < toolbars.length; k++) {
750
                                ActionTool[] tools = toolbars[k].getActionTool();
751

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

    
758
                                SelectableTool[] sTools = toolbars[k].getSelectableTool();
759

    
760
                                for (int t = 0; t < sTools.length; t++) {
761
                                        SortableTool sm=new SortableTool(((PluginServices)extensionPluginServices.get(ext)).getClassLoader(), ext,
762
                                                        toolbars[k], sTools[t]);
763
                                        orderedTools.put(sm, null);
764
                                }
765
                        }
766

    
767
                        // get controls for statusBar
768
                        PluginServices ps = (PluginServices) extensionPluginServices.get(ext);
769
                        PluginClassLoader loader = ps.getClassLoader();
770

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

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

    
835
                // Add the tools from MDI extensions to the ordered tool-list, so that we get a sorted list containing all the tools
836
                i = pluginsConfig.keySet().iterator();
837
                while (i.hasNext()) {
838
                        String pName = (String) i.next();
839
                        PluginConfig pc = (PluginConfig) pluginsConfig.get(pName);
840
                        PluginServices ps = (PluginServices) pluginsServices.get(pName);
841

    
842
                        SkinExtension skinExt = pc.getExtensions().getSkinExtension();
843

    
844
                        if (skinExt != null) {
845
                                ToolBar[] toolbars = skinExt.getToolBar();
846

    
847
                                for (int k = 0; k < toolbars.length; k++) {
848
                                        ActionTool[] tools = toolbars[k].getActionTool();
849

    
850
                                        for (int t = 0; t < tools.length; t++) {
851
                                                SortableTool stb=new SortableTool(ps.getClassLoader(), skinExt,
852
                                                                toolbars[k], tools[t]);
853
                                                orderedTools.put(stb,null);
854
                                        }
855

    
856
                                        SelectableTool[] sTools = toolbars[k].getSelectableTool();
857

    
858
                                        for (int t = 0; t < sTools.length; t++) {
859
                                                SortableTool stb=new SortableTool(ps.getClassLoader(), skinExt,
860
                                                                toolbars[k], sTools[t]);
861
                                                orderedTools.put(stb,null);
862
                                        }
863
                                }
864
                        }
865
                        // Install popup menus
866
                        PopupMenus pus = pc.getPopupMenus();
867

    
868
                        if (pus != null) {
869
                                PopupMenu[] menus = pus.getPopupMenu();
870

    
871
                                for (int j = 0; j < menus.length; j++) {
872
                                        frame.addPopupMenu(ps.getClassLoader(), menus[j]);
873
                                }
874
                        }
875
                }
876

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

    
893
        /**
894
         * Adds new plugins to the the andami-config file.
895
         */
896
        private static void updateAndamiConfig() {
897
                HashSet olds = new HashSet();
898

    
899
                Plugin[] plugins = andamiConfig.getPlugin();
900

    
901
                for (int i = 0; i < plugins.length; i++) {
902
                        olds.add(plugins[i].getName());
903
                }
904

    
905
                Iterator i = pluginsServices.values().iterator();
906

    
907
                while (i.hasNext()) {
908
                        PluginServices ps = (PluginServices) i.next();
909

    
910
                        if (!olds.contains(ps.getPluginName())) {
911
                                Plugin p = new Plugin();
912
                                p.setName(ps.getPluginName());
913
                                p.setUpdate(false);
914

    
915
                                andamiConfig.addPlugin(p);
916
                        }
917
                }
918
        }
919

    
920
        /**
921
         * DOCUMENT ME!
922
         */
923
        private static void pluginsClassLoaders() {
924
                HashSet instalados = new HashSet();
925

    
926
                // Se itera hasta que est?n todos instalados
927
                while (instalados.size() != pluginsConfig.size()) {
928
                        boolean circle = true;
929

    
930
                        //Hacemos una pasada por todos los plugins
931
                        Iterator i = pluginsConfig.keySet().iterator();
932

    
933
                        while (i.hasNext()) {
934
                                String pluginName = (String) i.next();
935
                                PluginConfig config = (PluginConfig) pluginsConfig.get(pluginName);
936

    
937
                                if (instalados.contains(pluginName)) {
938
                                        continue;
939
                                }
940

    
941
                                //Se obtienen las dependencias y sus class loaders
942
                                boolean ready = true;
943
                                Depends[] dependencies = config.getDepends();
944
                                PluginClassLoader[] loaders = new PluginClassLoader[dependencies.length];
945

    
946
                                for (int j = 0; j < dependencies.length; j++) {
947
                                        if (pluginsConfig.get(dependencies[j].getPluginName()) == null) {
948
                                                logger.error(Messages.getString(
949
                                                                "Launcher.Dependencia_no_resuelta_en_plugin") +
950
                                                        pluginName + ": " +
951
                                                        dependencies[j].getPluginName());
952

    
953
                                                continue;
954
                                        }
955

    
956
                                        if (!instalados.contains(dependencies[j].getPluginName())) {
957
                                                ready = false;
958
                                        } else {
959
                                                loaders[j] = ((PluginServices) pluginsServices.get(dependencies[j].getPluginName())).getClassLoader();
960
                                        }
961
                                }
962

    
963
                                //Si no est?n sus dependencias satisfechas se aborta la instalaci?n
964
                                if (!ready) {
965
                                        continue;
966
                                }
967

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

    
980
                                URL[] urls = new URL[jarFiles.length];
981

    
982
                                for (int j = 0; j < jarFiles.length; j++) {
983
                                        try {
984
                                                urls[j] = new URL("file:" + jarFiles[j]);
985
                                        } catch (MalformedURLException e) {
986
                                                logger.error(Messages.getString(
987
                                                                "Launcher.No_se_puede_acceder_a") +
988
                                                        jarFiles[j]);
989
                                        }
990
                                }
991

    
992
                                PluginClassLoader loader;
993

    
994
                                try {
995
                                        loader = new PluginClassLoader(urls,
996
                                                        andamiConfig.getPluginsDirectory() +
997
                                                        File.separator + pluginName,
998
                                                        Launcher.class.getClassLoader(), loaders);
999

    
1000
                                        PluginServices ps = new PluginServices(loader);
1001

    
1002
                                        pluginsServices.put(ps.getPluginName(), ps);
1003

    
1004
                                        instalados.add(pluginName);
1005
                    // FJP: Los metemos ordenados para luego no cargar uno que necesita de otro antes de tiempo. Esto lo usaremos al
1006
                    // inicializar los plugins
1007
                    pluginsOrdered.add(pluginName);
1008

    
1009
                                        circle = false;
1010
                                } catch (IOException e) {
1011
                                        logger.error(Messages.getString(
1012
                                                        "Launcher.Error_con_las_librerias_del_plugin"), e);
1013
                                        pluginsConfig.remove(pluginName);
1014
                                        i = pluginsConfig.keySet().iterator();
1015
                                }
1016
                        }
1017

    
1018
                        if (circle) {
1019
                                logger.error(Messages.getString(
1020
                                                "Launcher.Hay_dependencias_circulares"));
1021

    
1022
                                break;
1023
                        }
1024
                }
1025

    
1026
                //Se eliminan los plugins que no fueron instalados
1027
                Iterator i = pluginsConfig.keySet().iterator();
1028

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

    
1034
                        if (ps == null) {
1035
                                pluginsConfig.remove(pluginName);
1036
                                i = pluginsConfig.keySet().iterator();
1037
                        }
1038
                }
1039
        }
1040

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

    
1055
                //Iteramos por todos los plugins
1056
                Iterator i = pluginsConfig.keySet().iterator();
1057

    
1058
                while (i.hasNext()) {
1059
                        String pluginName = (String) i.next();
1060
                        if (!pluginName.equals("com.iver.cit.gvsig")) { // we've already loaded com.iver.cit.gvsig
1061
                                config = (PluginConfig) pluginsConfig.get(pluginName);
1062
                                ps = (PluginServices) pluginsServices.get(pluginName);
1063

    
1064
                                if (config.getResourceBundle() != null && !config.getResourceBundle().getName().equals("")) {
1065
                                        // add the locale files associated with the plugin
1066
                                        org.gvsig.i18n.Messages.addResourceFamily(config.getResourceBundle().getName(), ps.getClassLoader(), pluginName);
1067
                                }
1068
                        }
1069
                }
1070
        }
1071

    
1072
        /**
1073
         * DOCUMENT ME!
1074
         *
1075
         * @param name DOCUMENT ME!
1076
         *
1077
         * @return DOCUMENT ME!
1078
         */
1079
        static PluginServices getPluginServices(String name) {
1080
                return (PluginServices) pluginsServices.get(name);
1081
        }
1082

    
1083
        /**
1084
         * DOCUMENT ME!
1085
         *
1086
         * @return DOCUMENT ME!
1087
         */
1088
        static String getPluginsDir() {
1089
                return andamiConfig.getPluginsDirectory();
1090
        }
1091

    
1092
        /**
1093
         * DOCUMENT ME!
1094
         *
1095
         * @param s DOCUMENT ME!
1096
         */
1097
        static void setPluginsDir(String s) {
1098
                andamiConfig.setPluginsDirectory(s);
1099
        }
1100

    
1101
        /**
1102
         * DOCUMENT ME!
1103
         *
1104
         * @return DOCUMENT ME!
1105
         */
1106
        static MDIFrame getMDIFrame() {
1107
                return frame;
1108
        }
1109

    
1110
        /**
1111
         * DOCUMENT ME!
1112
         *
1113
         * @param pluginsDirectory
1114
         */
1115
        private static void loadPlugins(String pluginsDirectory) {
1116
                File pDir = new File(pluginsDirectory);
1117

    
1118
                if (!pDir.exists()) {
1119
                        return;
1120
                }
1121

    
1122
                File[] pluginDirs = pDir.listFiles();
1123

    
1124
                for (int i = 0; i < pluginDirs.length; i++) {
1125
                        if (pluginDirs[i].isDirectory()) {
1126
                                File configXml = new File(pluginDirs[i].getAbsolutePath() +
1127
                                                File.separator + "config.xml");
1128

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

    
1153
        /**
1154
         * DOCUMENT ME!
1155
         *
1156
         * @param language
1157
         * @param country
1158
         * @param variant
1159
         *
1160
         * @return DOCUMENT ME!
1161
         */
1162
        private static Locale getLocale(String language, String country,
1163
                String variant) {
1164
                if (variant != null) {
1165
                        return new Locale(language, country, variant);
1166
                } else if (country != null) {
1167
                        return new Locale(language, country);
1168
                } else if (language != null) {
1169
                        return new Locale(language);
1170
                } else {
1171
                        return new Locale("es");
1172
                }
1173
        }
1174

    
1175
        /**
1176
         * DOCUMENT ME!
1177
         *
1178
         * @param file DOCUMENT ME!
1179
         *
1180
         * @throws IOException DOCUMENT ME!
1181
         * @throws MarshalException DOCUMENT ME!
1182
         * @throws ValidationException DOCUMENT ME!
1183
         */
1184
        private static void andamiConfigToXML(String file)
1185
                throws IOException, MarshalException, ValidationException {
1186
                File xml = new File(file);
1187
                File parent = xml.getParentFile();
1188
                parent.mkdirs();
1189

    
1190
                FileWriter writer = new FileWriter(xml);
1191
                andamiConfig.marshal(writer);
1192
        }
1193

    
1194
        /**
1195
         * DOCUMENT ME!
1196
         *
1197
         * @param file DOCUMENT ME!
1198
         *
1199
         * @throws ConfigurationException DOCUMENT ME!
1200
         */
1201
        private static void andamiConfigFromXML(String file)
1202
                throws ConfigurationException {
1203
                File xml = new File(file);
1204

    
1205
                //Si no existe se ponen los valores por defecto
1206
                if (!xml.exists()) {
1207
                        andamiConfig = new AndamiConfig();
1208

    
1209
                        Andami andami = new Andami();
1210
                        andami.setUpdate(true);
1211
                        andamiConfig.setAndami(andami);
1212
                        andamiConfig.setLocaleCountry(Locale.getDefault().getCountry());
1213
                        andamiConfig.setLocaleLanguage(Locale.getDefault().getLanguage());
1214
                        andamiConfig.setLocaleVariant(Locale.getDefault().getVariant());
1215

    
1216
                        if (System.getProperty("javawebstart.version") != null) // Es java web start)
1217
                         {
1218
                                andamiConfig.setPluginsDirectory(new File(System.getProperty(
1219
                                                        "user.home") + File.separator + appName +
1220
                                                File.separator + "extensiones").getAbsolutePath());
1221
                        } else {
1222
                                andamiConfig.setPluginsDirectory(new File(appName +
1223
                                                File.separator + "extensiones").getAbsolutePath());
1224
                        }
1225

    
1226
                        andamiConfig.setPlugin(new Plugin[0]);
1227
                } else {
1228
                        //Se lee la configuraci?n
1229
                        FileReader reader;
1230

    
1231
                        try {
1232
                                reader = new FileReader(xml);
1233
                                andamiConfig = (AndamiConfig) AndamiConfig.unmarshal(reader);
1234
                        } catch (FileNotFoundException e) {
1235
                                throw new ConfigurationException(e);
1236
                        } catch (MarshalException e) {
1237
                                throw new ConfigurationException(e);
1238
                        } catch (ValidationException e) {
1239
                                throw new ConfigurationException(e);
1240
                        }
1241
                }
1242
        }
1243

    
1244
        /**
1245
         * DOCUMENT ME!
1246
         *
1247
         * @return DOCUMENT ME!
1248
         *
1249
         * @throws ConfigurationException DOCUMENT ME!
1250
         */
1251
        private static XMLEntity persistenceFromXML() throws ConfigurationException {
1252
                File xml = new File(pluginsPersistencePath);
1253

    
1254
                if (xml.exists()) {
1255
                        FileReader reader;
1256

    
1257
                        try {
1258
                                reader = new FileReader(xml);
1259

    
1260
                                XmlTag tag = (XmlTag) XmlTag.unmarshal(reader);
1261

    
1262
                                return new XMLEntity(tag);
1263
                        } catch (FileNotFoundException e) {
1264
                                throw new ConfigurationException(e);
1265
                        } catch (MarshalException e) {
1266
                                throw new ConfigurationException(e);
1267
                        } catch (ValidationException e) {
1268
                                throw new ConfigurationException(e);
1269
                        }
1270
                } else {
1271
                        return new XMLEntity();
1272
                }
1273
        }
1274

    
1275
        /**
1276
         * DOCUMENT ME!
1277
         *
1278
         * @param entity DOCUMENT ME!
1279
         *
1280
         * @throws ConfigurationException DOCUMENT ME!
1281
         */
1282
        private static void persistenceToXML(XMLEntity entity)
1283
                throws ConfigurationException {
1284
                File xml = new File(pluginsPersistencePath);
1285

    
1286
                FileWriter writer;
1287

    
1288
                try {
1289
                        writer = new FileWriter(xml);
1290
                        entity.getXmlTag().marshal(writer);
1291
                } catch (FileNotFoundException e) {
1292
                        throw new ConfigurationException(e);
1293
                } catch (MarshalException e) {
1294
                        throw new ConfigurationException(e);
1295
                } catch (ValidationException e) {
1296
                        throw new ConfigurationException(e);
1297
                } catch (IOException e) {
1298
                        throw new ConfigurationException(e);
1299
                }
1300
        }
1301

    
1302
        /**
1303
         * Devuelve un array con los directorios de los plugins
1304
         *
1305
         * @param dirExt Directorio de las extensiones a partir del cual cuelgan
1306
         *                   todos los directorios de los plugins
1307
         *
1308
         * @return ArrayList con los directorios
1309
         */
1310
        private String[] getLocales(File dirExt) {
1311
                ArrayList types = new ArrayList();
1312
                File[] files = dirExt.listFiles();
1313

    
1314
                for (int i = 0; i < files.length; i++) {
1315
                        if (files[i].isDirectory()) {
1316
                                File[] textFile = files[i].listFiles(new FilenameFilter() {
1317
                                                        public boolean accept(File dir, String fileName) {
1318
                                                                return fileName.toLowerCase().startsWith("text_"); //$NON-NLS-1$
1319
                                                        }
1320
                                                });
1321

    
1322
                                for (int j = 0; j < textFile.length; j++) {
1323
                                        String s = (textFile[j]).getName().replaceAll("text_", "");
1324
                                        s = s.replaceAll(".properties", "");
1325
                                        s = s.trim();
1326

    
1327
                                        if (!types.contains(s)) {
1328
                                                types.add(s);
1329
                                        }
1330
                                }
1331
                        }
1332
                }
1333

    
1334
                return (String[]) types.toArray(new String[0]);
1335
        }
1336

    
1337
        /**
1338
         * DOCUMENT ME!
1339
         *
1340
         * @return Returns the frame.
1341
         */
1342
        static MDIFrame getFrame() {
1343
                return frame;
1344
        }
1345

    
1346
        /**
1347
         * Secuencia de cerrado de Andami
1348
         */
1349
        public static void closeApplication() {
1350
                //Configuraci?n de Andami
1351
                try {
1352
                        andamiConfigToXML(andamiConfigPath);
1353
                } catch (MarshalException e) {
1354
                        logger.error(Messages.getString(
1355
                                        "Launcher.No_se_pudo_guardar_la_configuracion_de_andami"), e);
1356
                } catch (ValidationException e) {
1357
                        logger.error(Messages.getString(
1358
                                        "Launcher.No_se_pudo_guardar_la_configuracion_de_andami"), e);
1359
                } catch (IOException e) {
1360
                        logger.error(Messages.getString(
1361
                                        "Launcher.No_se_pudo_guardar_la_configuracion_de_andami"), e);
1362
                }
1363

    
1364
                //Persistencia de los plugins
1365
                savePluginPersistence();
1366

    
1367
                //Finalize all the extensions
1368
                finalizeExtensions();
1369

    
1370
                // Clean any temp data created
1371
                Utilities.cleanUpTempFiles();
1372

    
1373
                //Para la depuraci?n de memory leaks
1374
                System.gc();
1375

    
1376
        System.exit(0);
1377
        }
1378

    
1379
        /**
1380
         * Exectutes the finalize method for all the extensions
1381
         *
1382
         */
1383
        private static void finalizeExtensions() {
1384
                Set extensions = getClassesExtensions().keySet();
1385
                Object[] keys = extensions.toArray();
1386

    
1387
                for (int i=0 ; i<keys.length ; i++){
1388
                        ExtensionDecorator extensionDecorator =
1389
                                (ExtensionDecorator) getClassesExtensions().get(keys[i]);
1390
                        extensionDecorator.getExtension().terminate();
1391
                }
1392
        }
1393

    
1394

    
1395
        /**
1396
         * DOCUMENT ME!
1397
         *
1398
         * @return DOCUMENT ME!
1399
         */
1400
        static HashMap getClassesExtensions() {
1401
                return classesExtensions;
1402
        }
1403

    
1404
        /**
1405
         * DOCUMENT ME!
1406
         *
1407
         * @param extDir DOCUMENT ME!
1408
         */
1409
        private static void downloadExtensions(String extDir) {
1410
                java.util.Date fechaActual = null;
1411

    
1412
                try {
1413
                        if (System.getProperty("javawebstart.version") != null) {
1414
                                //Obtenemos la URL del servidor
1415
                                BasicService bs = (BasicService) ServiceManager.lookup(
1416
                                                "javax.jnlp.BasicService");
1417
                                URL baseURL = bs.getCodeBase();
1418

    
1419
                                //Se descargan las extensiones
1420
                                MultiSplashWindow.process(5,
1421
                                        "Descargando las extensiones desde " + baseURL + " a " +
1422
                                        extDir);
1423

    
1424
                                URL url = new URL(baseURL + "extensiones.zip");
1425
                                URLConnection connection = url.openConnection();
1426

    
1427
                                System.out.println(url.toExternalForm() + ":");
1428
                                System.out.println("  Content Type: " +
1429
                                        connection.getContentType());
1430
                                System.out.println("  Content Length: " +
1431
                                        connection.getContentLength());
1432
                                System.out.println("  Last Modified: " +
1433
                                        new Date(connection.getLastModified()));
1434
                                System.out.println("  Expiration: " +
1435
                                        connection.getExpiration());
1436
                                System.out.println("  Content Encoding: " +
1437
                                        connection.getContentEncoding());
1438

    
1439
                                // Guardamos la fecha del fichero de extensiones que nos hemos bajado, y
1440
                                // comprobamos el ?ltimo que se ha bajado. Si no son
1441
                                // iguales, nos bajamos el nuevo. Si son iguales, no
1442
                                // nos bajamos nada.
1443
                                Long miliSecondsInWeb = new Long(connection.getLastModified());
1444

    
1445
                                // PluginServices ps = PluginServices.getPluginServices("com.iver.core");
1446
                                // if (ps.getPersistentXML().getStringProperty("timestamp") != null)
1447
                                File destDir = new File(extDir);
1448

    
1449
                                if (!destDir.exists()) {
1450
                                        // Creamos gvSIG
1451
                                        destDir.getParentFile().mkdir();
1452

    
1453
                                        if (!destDir.mkdir()) {
1454
                                                System.err.println("Imposible crear el directorio " +
1455
                                                        destDir.getAbsolutePath());
1456
                                        }
1457
                                }
1458

    
1459
                                File timeFile = new File(destDir.getParent() + File.separator +
1460
                                                "timeStamp.properties");
1461

    
1462
                                if (!timeFile.exists()) {
1463
                                        timeFile.createNewFile();
1464
                                }
1465

    
1466
                                FileInputStream inAux = new FileInputStream(timeFile);
1467
                                Properties prop = new Properties();
1468
                                prop.load(inAux);
1469
                                inAux.close();
1470

    
1471
                                if (prop.getProperty("timestamp") != null) {
1472
                                        Long lastMiliSeconds = (Long) new Long(prop.getProperty(
1473
                                                                "timestamp"));
1474

    
1475
                                        if (lastMiliSeconds.longValue() == miliSecondsInWeb.longValue()) {
1476
                                                System.out.println("No hay nueva actualizaci?n");
1477
                        logger.debug("No hay nueva actualizaci?n -> Return");
1478
                        logger.debug("timeStampWeb= " + miliSecondsInWeb);
1479
                        logger.debug("timeStampLocal= " + lastMiliSeconds);
1480

    
1481
                                                return;
1482
                                        }
1483

    
1484
                                        System.out.println("timeStampWeb= " + miliSecondsInWeb);
1485
                                        System.out.println("timeStampLocal= " + lastMiliSeconds);
1486
                                } else {
1487
                                        System.out.println("El timeStamp no est? escrito en " +
1488
                                                timeFile.getAbsolutePath());
1489
                                }
1490

    
1491
                                InputStream stream = url.openStream();
1492
                File temp = File.createTempFile("gvsig", ".zip");
1493

    
1494
                logger.debug(temp.getAbsolutePath());
1495

    
1496
                temp.deleteOnExit();
1497
                FileOutputStream file = new FileOutputStream(temp);
1498

    
1499
                byte[] lt_read = new byte[1];
1500

    
1501
                while (stream.read(lt_read) > 0)
1502
                  file.write(lt_read);
1503

    
1504
                                stream.close();
1505
                stream = null;
1506
                file.close();
1507
                file = null;
1508

    
1509
                System.gc();
1510

    
1511
                logger.debug("Ha creado el fichero ZIP");
1512
                                //Se extrae el zip
1513
                                MultiSplashWindow.process(5, "Extensiones descargadas.");
1514

    
1515
                                System.out.println("Extrayendo a " + destDir.getAbsolutePath());
1516

    
1517
                                Date fechaDir = new Date(destDir.lastModified());
1518
                                System.out.println("Fecha del directorio " + extDir + " = " +
1519
                                        fechaDir.toString());
1520
                                Utilities.extractTo(temp, new File(extDir), splashWindow);
1521

    
1522
                                // Si todo ha ido bien, guardamos el timestamp.
1523
                                ///  App.instance.getPc().addProperties("timestamp", miliSecondsInWeb);
1524
                                // XMLEntity xml=ps.getPersistentXML();
1525
                                fechaActual = new java.util.Date();
1526

    
1527
                                FileOutputStream outAux = new FileOutputStream(timeFile);
1528
                                prop.setProperty("timestamp", miliSecondsInWeb.toString());
1529
                                prop.store(outAux, "last download");
1530
                                outAux.close();
1531
                                System.out.println("Fecha actual guardada: " +
1532
                                        fechaActual.toGMTString());
1533

    
1534
                                /* xml.putProperty("timestamp",fechaActual.toGMTString());
1535
                                   ps.setPresistentXML(xml); */
1536
                        }
1537
                } catch (IOException e) {
1538
                        NotificationManager.addError("", e);
1539
                } catch (UnavailableServiceException e) {
1540
                        NotificationManager.addError("", e);
1541
                } catch (SecurityException e) {
1542
                        System.err.println("No se puede escribir el timeStamp " +
1543
                                fechaActual.toGMTString());
1544
                        NotificationManager.addError("", e);
1545
                }
1546
        }
1547

    
1548
        /**
1549
         * DOCUMENT ME!
1550
         *
1551
         * @return DOCUMENT ME!
1552
         */
1553
        private static Extensions[] getExtensions() {
1554
                ArrayList array = new ArrayList();
1555
                Iterator iter = pluginsConfig.values().iterator();
1556

    
1557
                while (iter.hasNext()) {
1558
                        array.add(((PluginConfig) iter.next()).getExtensions());
1559
                }
1560

    
1561
                return (Extensions[]) array.toArray(new Extensions[0]);
1562
        }
1563

    
1564
        /**
1565
         * DOCUMENT ME!
1566
         *
1567
         * @return DOCUMENT ME!
1568
         */
1569
        public static HashMap getPluginConfig() {
1570
                return pluginsConfig;
1571
        }
1572

    
1573
        /**
1574
         * DOCUMENT ME!
1575
         *
1576
         * @param s DOCUMENT ME!
1577
         *
1578
         * @return DOCUMENT ME!
1579
         */
1580
        public static Extension getExtension(String s) {
1581
                Extensions[] exts = getExtensions();
1582

    
1583
                for (int i = 0; i < exts.length; i++) {
1584
                        for (int j = 0; j < exts[i].getExtensionCount(); j++) {
1585
                                if (exts[i].getExtension(j).getClassName().equals(s)) {
1586
                                        return exts[i].getExtension(j);
1587
                                }
1588
                        }
1589
                }
1590

    
1591
                return null;
1592
        }
1593

    
1594
        /**
1595
         * DOCUMENT ME!
1596
         *
1597
         * @return DOCUMENT ME!
1598
         */
1599
        public static AndamiConfig getAndamiConfig() {
1600
                return andamiConfig;
1601
        }
1602

    
1603
        /**
1604
         * DOCUMENT ME!
1605
         *
1606
         * @author $author$
1607
         * @version $Revision: 7584 $
1608
         */
1609
        private static class ExtensionComparator implements Comparator {
1610
                /**
1611
                 * DOCUMENT ME!
1612
                 *
1613
                 * @param o1 DOCUMENT ME!
1614
                 * @param o2 DOCUMENT ME!
1615
                 *
1616
                 * @return DOCUMENT ME!
1617
                 */
1618
                public int compare(Object o1, Object o2) {
1619
                        Extension e1 = (Extension) o1;
1620
                        Extension e2 = (Extension) o2;
1621

    
1622
                        if (!e1.hasPriority() && !e2.hasPriority()) {
1623
                                return -1;
1624
                        }
1625

    
1626
                        if (e1.hasPriority() && !e2.hasPriority()) {
1627
                                return Integer.MIN_VALUE;
1628
                        }
1629

    
1630
                        if (e2.hasPriority() && !e1.hasPriority()) {
1631
                                return Integer.MAX_VALUE;
1632
                        }
1633

    
1634
                        if (e1.getPriority() != e2.getPriority()){
1635
                                return e2.getPriority() - e1.getPriority();
1636
                        }else{
1637
                                return (e2.toString().compareTo(e1.toString()));
1638
                        }
1639
                }
1640
        }
1641

    
1642
        /**
1643
         * DOCUMENT ME!
1644
         */
1645
        private static class MenuComparator implements Comparator {
1646
                private static ExtensionComparator extComp = new ExtensionComparator();
1647

    
1648
                /**
1649
                 * DOCUMENT ME!
1650
                 *
1651
                 * @param o1 DOCUMENT ME!
1652
                 * @param o2 DOCUMENT ME!
1653
                 *
1654
                 * @return DOCUMENT ME!
1655
                 */
1656
                public int compare(Object o1, Object o2) {
1657
                        SortableMenu e1 = (SortableMenu) o1;
1658
                        SortableMenu e2 = (SortableMenu) o2;
1659

    
1660
                        if (!e1.menu.hasPosition() && !e2.menu.hasPosition()) {
1661
                                if (e1.extension instanceof SkinExtensionType) {
1662
                                        return 1;
1663
                                } else if (e2.extension instanceof SkinExtensionType) {
1664
                                        return -1;
1665
                                } else {
1666
                                        return extComp.compare(e1.extension, e2.extension);
1667
                                }
1668
                        }
1669

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

    
1674
                        if (e2.menu.hasPosition() && !e1.menu.hasPosition()) {
1675
                                return Integer.MAX_VALUE;
1676
                        }
1677
                        if (e1.menu.getPosition() != e2.menu.getPosition()){
1678
                                //we don't return 0 unless both objects are the same, otherwise the objects get overwritten in the treemap
1679
                                return e1.menu.getPosition() - e2.menu.getPosition();
1680
                        }else{
1681
                                return (e1.toString().compareTo(e2.toString()));
1682
                        }
1683
                }
1684
        }
1685

    
1686
        /**
1687
         * DOCUMENT ME!
1688
         *
1689
         * @author $author$
1690
         * @version $Revision: 7584 $
1691
         */
1692
        private static class SortableMenu {
1693
                public PluginClassLoader loader;
1694
                public Menu menu;
1695
                public SkinExtensionType extension;
1696

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

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

    
1749
                /**
1750
                 * DOCUMENT ME!
1751
                 *
1752
                 * @param o1 DOCUMENT ME!
1753
                 * @param o2 DOCUMENT ME!
1754
                 *
1755
                 * @return DOCUMENT ME!
1756
                 */
1757
                public int compare(Object o1, Object o2) {
1758
                        SortableTool e1 = (SortableTool) o1;
1759
                        SortableTool e2 = (SortableTool) o2;
1760

    
1761
                        // if the toolbars have the same name, they are considered to be
1762
                        // the same toolbar, so we don't need to do further comparing
1763
                        if (e1.toolbar.getName().equals(e2.toolbar.getName()))
1764
                                return 0;
1765

    
1766
                        if (!e1.toolbar.hasPosition() && !e2.toolbar.hasPosition()) {
1767
                                if (e1.extension instanceof SkinExtensionType) {
1768
                                        return 1;
1769
                                } else if (e2.extension instanceof SkinExtensionType) {
1770
                                        return -1;
1771
                                } else {
1772
                                        return extComp.compare(e1.extension, e2.extension);
1773
                                }
1774
                        }
1775

    
1776
                        if (e1.toolbar.hasPosition() && !e2.toolbar.hasPosition()) {
1777
                                return Integer.MIN_VALUE;
1778
                        }
1779

    
1780
                        if (e2.toolbar.hasPosition() && !e1.toolbar.hasPosition()) {
1781
                                return Integer.MAX_VALUE;
1782
                        }
1783
                        if (e1.toolbar.getPosition() != e2.toolbar.getPosition())
1784
                                return e1.toolbar.getPosition() - e2.toolbar.getPosition();
1785

    
1786
                        if (e1.toolbar.getActionTool().equals(e2.toolbar.getActionTool()) && e1.toolbar.getSelectableTool().equals(e2.toolbar.getSelectableTool())){
1787
                                return 0;
1788
                        }
1789
                        return (e1.toolbar.toString().compareTo(e2.toolbar.toString()));
1790
                }
1791
        }
1792

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

    
1831
                        if (e1.actiontool!=null) {
1832
                                if (e1.actiontool.hasPosition())
1833
                                        e1Position = e1.actiontool.getPosition();
1834
                        }
1835
                        else if (e1.selectabletool!=null) {
1836
                                if (e1.selectabletool.hasPosition())
1837
                                        e1Position = e1.selectabletool.getPosition();
1838
                        }
1839

    
1840
                        if (e2.actiontool!=null) {
1841
                                if (e2.actiontool.hasPosition())
1842
                                        e2Position = e2.actiontool.getPosition();
1843
                        }
1844
                        else if (e2.selectabletool!=null){
1845
                                if (e2.selectabletool.hasPosition())
1846
                                        e2Position = e2.selectabletool.getPosition();
1847
                        }
1848

    
1849
                        if (e1Position==-1 && e2Position!=-1) {
1850
                                return 1;
1851
                        }
1852
                        if (e1Position!=-1 && e2Position==-1) {
1853
                                return -1;
1854
                        }
1855
                        if (e1Position!=-1 && e2Position!=-1) {
1856
                                result = e1Position - e2Position;
1857
                                // we don't return 0 unless both objects are the same, otherwise the objects get overwritten in the treemap
1858
                                if (result!=0) return result;
1859
                        }
1860
                        return e1.toString().compareTo(e2.toString());
1861
                }
1862
        }
1863

    
1864

    
1865
        /**
1866
         * validates the user before starting gvsig
1867
         *
1868
         */
1869
        private static void validate(){
1870

    
1871
                IAuthentication session =  null;
1872
                try {
1873
                        session = (IAuthentication)Class.forName("com.iver.andami.authentication.Session").newInstance();
1874

    
1875
                } catch (ClassNotFoundException e) {
1876
                        // TODO Auto-generated catch block
1877
                        //e.printStackTrace();
1878
                        return;
1879
                } catch (InstantiationException e) {
1880
                        // TODO Auto-generated catch block
1881
                        //e.printStackTrace();
1882
                        return;
1883
                } catch (IllegalAccessException e) {
1884
                        // TODO Auto-generated catch block
1885
                        //e.printStackTrace();
1886
                        return;
1887
                }
1888

    
1889
                session.setPluginDirectory( andamiConfig.getPluginsDirectory() );
1890
                if (session.validationRequired()){
1891
                        if(session.Login()){
1892
                                System.out.println("You are logged in");
1893
                        }
1894
                        else{
1895
                                JOptionPane.showMessageDialog((Component)PluginServices.getMainFrame(),
1896
                                                 "You are not logged in");
1897
                                //System.exit(0);
1898
                        }
1899
                        PluginServices.setAuthentication(session);
1900
                }
1901
        }
1902

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

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

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

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

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

    
2000
        }
2001
}