Statistics
| Revision:

svn-gvsig-desktop / trunk / org.gvsig.desktop / org.gvsig.desktop.framework / org.gvsig.andami / src / main / java / org / gvsig / andami / Launcher.java @ 40617

History | View | Annotate | Download (112 KB)

1
/**
2
 * gvSIG. Desktop Geographic Information System.
3
 *
4
 * Copyright (C) 2007-2013 gvSIG Association.
5
 *
6
 * This program is free software; you can redistribute it and/or
7
 * modify it under the terms of the GNU General Public License
8
 * as published by the Free Software Foundation; either version 3
9
 * of the License, or (at your option) any later version.
10
 *
11
 * This program is distributed in the hope that it will be useful,
12
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14
 * GNU General Public License for more details.
15
 *
16
 * You should have received a copy of the GNU General Public License
17
 * along with this program; if not, write to the Free Software
18
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
19
 * MA  02110-1301, USA.
20
 *
21
 * For any additional information, do not hesitate to contact us
22
 * at info AT gvsig.com, or visit our website www.gvsig.com.
23
 */
24
package org.gvsig.andami;
25

    
26
import java.awt.BorderLayout;
27
import java.awt.Component;
28
import java.awt.Dimension;
29
import java.awt.EventQueue;
30
import java.awt.Frame;
31
import java.awt.KeyboardFocusManager;
32
import java.awt.Point;
33
import java.awt.Toolkit;
34
import java.io.BufferedOutputStream;
35
import java.io.BufferedReader;
36
import java.io.File;
37
import java.io.FileFilter;
38
import java.io.FileInputStream;
39
import java.io.FileNotFoundException;
40
import java.io.FileOutputStream;
41
import java.io.FileReader;
42
import java.io.IOException;
43
import java.io.InputStream;
44
import java.io.InputStreamReader;
45
import java.io.OutputStreamWriter;
46
import java.io.Reader;
47
import java.io.StringWriter;
48
import java.net.Authenticator;
49
import java.net.MalformedURLException;
50
import java.net.PasswordAuthentication;
51
import java.net.URL;
52
import java.net.URLClassLoader;
53
import java.nio.channels.FileChannel;
54
import java.security.AllPermission;
55
import java.security.CodeSource;
56
import java.security.PermissionCollection;
57
import java.security.Permissions;
58
import java.security.Policy;
59
import java.text.MessageFormat;
60
import java.util.ArrayList;
61
import java.util.Comparator;
62
import java.util.Enumeration;
63
import java.util.HashMap;
64
import java.util.HashSet;
65
import java.util.Iterator;
66
import java.util.List;
67
import java.util.Locale;
68
import java.util.Map;
69
import java.util.Properties;
70
import java.util.Set;
71
import java.util.TreeSet;
72
import java.util.prefs.Preferences;
73

    
74
import javax.swing.ImageIcon;
75
import javax.swing.JButton;
76
import javax.swing.JComponent;
77
import javax.swing.JFrame;
78
import javax.swing.JOptionPane;
79
import javax.swing.JPopupMenu;
80
import javax.swing.SwingUtilities;
81
import javax.swing.UIManager;
82

    
83
import org.apache.commons.cli.CommandLine;
84
import org.apache.commons.cli.CommandLineParser;
85
import org.apache.commons.cli.Options;
86
import org.apache.commons.cli.ParseException;
87
import org.apache.commons.cli.PosixParser;
88
import org.apache.commons.io.FileUtils;
89
import org.apache.log4j.AppenderSkeleton;
90
import org.apache.log4j.PatternLayout;
91
import org.apache.log4j.PropertyConfigurator;
92
import org.apache.log4j.RollingFileAppender;
93
import org.apache.log4j.spi.LoggingEvent;
94
import org.apache.log4j.spi.ThrowableInformation;
95
import org.exolab.castor.xml.MarshalException;
96
import org.exolab.castor.xml.ValidationException;
97
import org.slf4j.Logger;
98
import org.slf4j.LoggerFactory;
99

    
100
import org.gvsig.andami.actioninfo.ActionInfo;
101
import org.gvsig.andami.actioninfo.ActionInfoManager;
102
import org.gvsig.andami.authentication.IAuthentication;
103
import org.gvsig.andami.config.generate.Andami;
104
import org.gvsig.andami.config.generate.AndamiConfig;
105
import org.gvsig.andami.config.generate.Plugin;
106
import org.gvsig.andami.messages.Messages;
107
import org.gvsig.andami.messages.NotificationManager;
108
import org.gvsig.andami.plugins.ExclusiveUIExtension;
109
import org.gvsig.andami.plugins.ExtensionDecorator;
110
import org.gvsig.andami.plugins.IExtension;
111
import org.gvsig.andami.plugins.PluginClassLoader;
112
import org.gvsig.andami.plugins.config.generate.Action;
113
import org.gvsig.andami.plugins.config.generate.ActionTool;
114
import org.gvsig.andami.plugins.config.generate.AlternativeNames;
115
import org.gvsig.andami.plugins.config.generate.ComboButton;
116
import org.gvsig.andami.plugins.config.generate.ComboButtonElement;
117
import org.gvsig.andami.plugins.config.generate.ComboScale;
118
import org.gvsig.andami.plugins.config.generate.Depends;
119
import org.gvsig.andami.plugins.config.generate.Extension;
120
import org.gvsig.andami.plugins.config.generate.Extensions;
121
import org.gvsig.andami.plugins.config.generate.LabelSet;
122
import org.gvsig.andami.plugins.config.generate.Menu;
123
import org.gvsig.andami.plugins.config.generate.PluginConfig;
124
import org.gvsig.andami.plugins.config.generate.PopupMenu;
125
import org.gvsig.andami.plugins.config.generate.PopupMenus;
126
import org.gvsig.andami.plugins.config.generate.SelectableTool;
127
import org.gvsig.andami.plugins.config.generate.SkinExtension;
128
import org.gvsig.andami.plugins.config.generate.SkinExtensionType;
129
import org.gvsig.andami.plugins.config.generate.ToolBar;
130
import org.gvsig.andami.plugins.status.IExtensionStatus;
131
import org.gvsig.andami.plugins.status.IUnsavedData;
132
import org.gvsig.andami.ui.AndamiEventQueue;
133
import org.gvsig.andami.ui.MDIManagerLoadException;
134
import org.gvsig.andami.ui.ToolsWindowManager;
135
import org.gvsig.andami.ui.fonts.FontUtils;
136
import org.gvsig.andami.ui.mdiFrame.MDIFrame;
137
import org.gvsig.andami.ui.mdiFrame.MainFrame;
138
import org.gvsig.andami.ui.mdiManager.MDIManagerFactory;
139
import org.gvsig.andami.ui.splash.MultiSplashWindow;
140
import org.gvsig.andami.ui.theme.Theme;
141
import org.gvsig.andami.ui.wizard.UnsavedDataPanel;
142
import org.gvsig.installer.lib.api.InstallerLocator;
143
import org.gvsig.installer.lib.api.InstallerManager;
144
import org.gvsig.installer.lib.api.PackageInfo;
145
import org.gvsig.installer.swing.api.SwingInstallerLocator;
146
import org.gvsig.installer.swing.api.execution.AbstractInstallPackageWizard;
147
import org.gvsig.installer.swing.api.wizard.InstallerWizardActionListener;
148
import org.gvsig.installer.swing.api.wizard.InstallerWizardPanel;
149
import org.gvsig.tools.exception.ListBaseException;
150
import org.gvsig.tools.library.impl.DefaultLibrariesInitializer;
151
import org.gvsig.tools.swing.api.ToolsSwingLocator;
152
import org.gvsig.tools.swing.icontheme.IconTheme;
153
import org.gvsig.tools.swing.icontheme.IconThemeManager;
154
import org.gvsig.tools.util.FolderSet;
155
import org.gvsig.tools.util.FolderSet.FolderEntry;
156
import org.gvsig.utils.DateTime;
157
import org.gvsig.utils.XMLEntity;
158
import org.gvsig.utils.xml.XMLEncodingUtils;
159
import org.gvsig.utils.xmlEntity.generate.XmlTag;
160

    
161
/**
162
 * <p>
163
 * Andami's launching class. This is the class used to create the Andami's
164
 * plugin environment.<br>
165
 * </p>
166
 * 
167
 * <p>
168
 * <b>Syntax:</b> <br>
169
 * java [-Xmx512M (for 512MB of RAM)] [-classpath={a colon-separated(unix) or
170
 * semicolon-separated(windows) list of files containg base library of classes}]
171
 * [-Djava.library.path=PATH_TO_NATIVE_LIBRARIES]
172
 * PATH_TO_APPLICATION_HOME_DIRECTORY PATH_TO_APPLICATION_PLUGINS_DIRECTORY
173
 * [{list of additional custom application arguments separated by spaces}]
174
 * </p>
175
 * 
176
 * 
177
 * @author $author$
178
 * @version $Revision: 40305 $
179
 */
180
public class Launcher {
181

    
182
        public static abstract class MapWithAlias<Item> extends HashMap<String, Item> {
183
                private HashMap<String, String> aliases = new HashMap<String, String>();  
184
                
185
                protected abstract String[] getAliases(Item item);
186
                
187
                public Item get(Object key) {
188
                        Item item = super.get(key);
189
                        if( item != null ) {
190
                                return item;
191
                        }
192
                        String alias = aliases.get(key);
193
                        if( alias != null ) {
194
                                return super.get(alias);
195
                        }
196
                        return null;
197
                }
198
                
199
                public boolean containsKey(Object key) {
200
                        boolean contains = super.containsKey(key);
201
                        if( contains ) {
202
                                return true;
203
                        }
204
                        String alias = aliases.get(key);
205
                        return super.containsKey(alias);
206
                }
207
                
208
                public Item put(String key, Item value) {
209
                        super.put(key, value);
210
                        String[] aliases = getAliases(value);
211
                        if( aliases==null ) {
212
                                return value;
213
                        }
214
                        for( int n=0; n<aliases.length; n++ ) {
215
                                this.aliases.put(aliases[n].trim(), key);
216
                        }
217
                        return value;
218
                }
219
                
220
                public void putAll(Map<? extends String, ? extends Item> m) {
221
                        Iterator<?> it = m.entrySet().iterator();
222
                        while( it.hasNext() ) {
223
                                Map.Entry<String, Item> x = (Map.Entry<String, Item>) it.next();
224
                                this.put(x.getKey(), x.getValue());
225
                        }
226
                }
227
                
228
                public Item remove(Object key) {
229
                        Item item = super.get(key);
230
                        if( item == null ) {
231
                                String alias = aliases.get(key);
232
                                if( alias == null ) {
233
                                        return null;
234
                                }
235
                                item = super.get(alias);
236
                                super.remove(alias);
237
                        } else {
238
                                super.remove(key);
239
                        }
240
                        String[] aliases = getAliases(item);
241
                        if( aliases==null ) {
242
                                return item;
243
                        }
244
                        for( int n=0; n<aliases.length; n++ ) {
245
                                this.aliases.remove(aliases[n].trim());
246
                        }
247
                        return item;
248
                }
249
                
250
        }
251
        
252
        public static class PluginsConfig extends MapWithAlias<org.gvsig.andami.plugins.config.generate.PluginConfig>  {
253
                
254
                protected String[] getAliases(
255
                                org.gvsig.andami.plugins.config.generate.PluginConfig item) {
256
                        return getAlternativeNames(item);
257
                }
258

    
259
                static String[] getAlternativeNames(org.gvsig.andami.plugins.config.generate.PluginConfig item) {
260
                        AlternativeNames[] x = item.getAlternativeNames();
261
                        if( x == null ) {
262
                                return null;
263
                        }
264
                        String[] r = new String[x.length];
265
                        for( int i=0; i<x.length; i++) {
266
                                r[i] = x[i].getName();
267
                        }
268
                        return r;
269
                }
270
                
271
        }
272
        
273
        public static class PluginsServices extends MapWithAlias<org.gvsig.andami.PluginServices>  {
274

    
275
                protected String[] getAliases(org.gvsig.andami.PluginServices item) {
276
                        return item.getAlternativeNames();
277
                }
278
        }
279
        
280
        protected static Logger logger = LoggerFactory.getLogger(Launcher.class
281
                        .getName());
282
        protected static Preferences prefs = Preferences.userRoot().node(
283
                        "gvsig.connection");
284
        protected static AndamiConfig andamiConfig;
285
        protected static MultiSplashWindow splashWindow;
286
        protected static String appName;
287
        protected static Locale locale;
288
        protected static PluginsConfig pluginsConfig = new PluginsConfig();
289
        protected static PluginsServices pluginsServices = new PluginsServices();
290
        protected static MDIFrame frame;
291
        protected static HashMap<Class<? extends IExtension>, ExtensionDecorator> classesExtensions = new HashMap<Class<? extends IExtension>, ExtensionDecorator>();
292
        protected static String andamiConfigPath;
293
        protected static final String nonWinDefaultLookAndFeel = "com.jgoodies.looks.plastic.PlasticXPLookAndFeel";
294

    
295
        protected static ArrayList<String> pluginsOrdered = new ArrayList<String>();
296
        protected static ArrayList<IExtension> extensions = new ArrayList<IExtension>();
297
        protected static String appHomeDir = null;
298
        // it seems castor uses this encoding
299
        protected static final String CASTORENCODING = "UTF8";
300

    
301
        protected static ListBaseException launcherrors = null;
302

    
303
        protected static Theme theme = null;
304

    
305
        private static final class ProxyAuth extends Authenticator {
306

    
307
                private PasswordAuthentication auth;
308

    
309
                private ProxyAuth(String user, String pass) {
310
                        auth = new PasswordAuthentication(user, pass.toCharArray());
311
                }
312

    
313
                protected PasswordAuthentication getPasswordAuthentication() {
314
                        return auth;
315
                }
316
        }
317

    
318
        private static Launcher launcherInstance;
319

    
320
        public static Launcher getInstance() {
321
                if( launcherInstance == null ) {
322
                        launcherInstance = new Launcher();
323
                }
324
                return launcherInstance;
325
        }
326
        
327
        public static void main(String[] args) throws Exception {
328
                Launcher launcher = getInstance();
329
                boolean install = false;
330
                for (int i = 0; i < args.length; i++) {
331
                        if (args[i].equalsIgnoreCase("--install")) {
332
                                install = true;
333
                        }
334
                }
335
                try {
336
                        if (install) {
337
                                launcher.doInstall(args);
338
                        } else {
339
                                launcher.doMain(args);
340
                        }
341
                } catch (Exception e) {
342
                        logger.error("excepci?n al arrancar", e);
343
                        System.exit(-1);
344
                }
345
        }
346

    
347
        protected void downloadExtensions(String extDir) {
348
                // do nothing
349
        }
350

    
351
        public static class LaunchException extends ListBaseException {
352

    
353
                private static final long serialVersionUID = 4541192746962684705L;
354

    
355
                public LaunchException() {
356
                        super("Errors in initialization of application.",
357
                                        "_errors_in_initialization_of_application",
358
                                        serialVersionUID);
359
                }
360

    
361
        }
362

    
363
        protected void addError(Throwable ex) {
364
                if (launcherrors == null) {
365
                        launcherrors = new LaunchException();
366
                }
367
                launcherrors.add(ex);
368
        }
369

    
370
        protected void addError(String msg, Throwable cause) {
371
                logger.error(msg, cause);
372
                this.addError(new RuntimeException(msg, cause));
373
        }
374

    
375
        protected void addError(String msg) {
376
                this.addError(msg, null);
377
        }
378

    
379
        public void doMain(String[] args) throws Exception {
380

    
381
                if (args.length < 1) {
382
                        System.err.println("Usage: Launcher appName plugins-directory [language=locale]");
383
                        System.err.println("No arguments specified.");
384
                        System.err.println("Use default arguments 'gvSIG gvSIG/extensiones'");
385
                        args = new String[] { "gvSIG", "gvSIG/extensiones" };
386
                }
387

    
388
                initializeApp(args);
389

    
390
                // Solucionamos el problema de permisos que se produc?do con Java
391
                // Web Start con este codigo.
392
                // System.setSecurityManager(null);
393
                Policy.setPolicy(new Policy() {
394

    
395
                        public PermissionCollection getPermissions(CodeSource codesource) {
396
                                Permissions perms = new Permissions();
397
                                perms.add(new AllPermission());
398
                                return (perms);
399
                        }
400

    
401
                        public void refresh() {
402
                        }
403
                });
404

    
405
                /*
406
        new ToolsLibrary().initialize();
407
        new ToolsSwingLibrary().initialize();
408
        new ToolsSwingDefaultImplLibrary().initialize();
409
        */
410
        
411
        new DefaultLibrariesInitializer().fullInitialize(true);
412
        InstallerLocator.getInstallerManager().setDownloadBaseURL(
413
            new URL("http://downloads.gvsig.org/download/gvsig-desktop/"));
414

    
415
                try {
416
                        initIconThemes();
417
                } catch (Exception ex) {
418
                        this.addError("Can't initialize icon theme", ex);
419
                }
420
                // Registramos los iconos base
421
                try {
422
                        registerIcons();
423
                } catch (Exception ex) {
424
                        this.addError("Can't register icons", ex);
425
                }
426
                validate();
427

    
428
                // Obtener la personalizaci?n de la aplicaci?n.
429
                try {
430
                        logger.info("Initialize andami theme");
431
                        theme = getTheme(andamiConfig.getPluginsDirectory());
432
                } catch (Exception ex) {
433
                        this.addError("Can't get personalized theme for the application",
434
                                        ex);
435
                }
436

    
437
                // Mostrar la ventana de inicio
438
                Frame f = new Frame();
439
                splashWindow = new MultiSplashWindow(f, theme, 190);
440

    
441
                // 1. Ponemos los datos del proxy
442
                splashWindow.process(10, PluginServices.getText(Launcher.class,
443
                                "SplashWindow.configuring_proxy"));
444
                logger.info("Configute http proxy");
445
                configureProxy();
446

    
447
                // 2. TODO Buscar actualizaciones de los plugins
448
//                splashWindow.process(20, PluginServices.getText(Launcher.class,
449
//                                "SplashWindow.looking_for_updates"));
450
//                try {
451
//                        this.downloadExtensions(andamiConfig.getPluginsDirectory());
452
//                } catch (Exception ex) {
453
//                        this.addError("Can't downloads plugins", ex);
454
//                }
455

    
456
                // 2.5. Initialize andami libraries
457
                splashWindow.process(25, PluginServices.getText(Launcher.class,
458
                                "SplashWindow.initialize_andami_libraries"));
459
                
460
                File defaultAddonsRepository = PluginsLocator.getManager()
461
                                .getPluginsFolder();
462
                InstallerManager installerManager = InstallerLocator
463
                                .getInstallerManager();
464
                installerManager.addLocalAddonRepository(defaultAddonsRepository);
465
                installerManager
466
                                .setDefaultLocalAddonRepository(defaultAddonsRepository);
467
        
468
                logger.info("Dump system information");
469
                logger_info(getInformation());
470
                saveEnvironInformation();
471

    
472
                // 3. Se leen los config.xml de los plugins -----++++
473
                splashWindow.process(30, PluginServices.getText(Launcher.class,
474
                                "SplashWindow.reading_plugins_config.xml"));
475
                try {
476
                        logger.info("Load plugins information");
477
                        this.loadPlugins(andamiConfig.getPluginsDirectory());
478
                } catch (Exception ex) {
479
                        this.addError("Can't load plugins", ex);
480
                }
481

    
482
                // 4. Se configura el classloader del plugin
483
                splashWindow.process(40, PluginServices.getText(Launcher.class,
484
                                "SplashWindow.setting_up_class_loaders"));
485
                try {
486
                        logger.info("Configure plugins class loader");
487
                        this.pluginsClassLoaders();
488
                } catch (Exception ex) {
489
                        this.addError("Can't initialize plugin's classloaders  ", ex);
490
                }
491

    
492
                // 5. Initialize libraries
493
                splashWindow.process(50, PluginServices.getText(Launcher.class,
494
                                "SplashWindow.initialize_libraries"));
495
                initializeLibraries();
496

    
497
                // 6. Se carga un Skin si alguno ide los plugins trae informaci?n
498
                // para ello
499
                splashWindow.process(60, PluginServices.getText(Launcher.class,
500
                                "SplashWindow.looking_for_a_skin"));
501
                // skinPlugin( "com.iver.core.mdiManager.NewSkin");
502
                logger.info("Initialize skin");
503
                skinPlugin(null);
504

    
505
                // 7. Se configura la cola de eventos
506
                splashWindow.process(70, PluginServices.getText(Launcher.class,
507
                                "setting_up_event_queue"));
508
                EventQueue waitQueue = new AndamiEventQueue();
509
                Toolkit.getDefaultToolkit().getSystemEventQueue().push(waitQueue);
510

    
511
                // 8. Se configura la mensajer?a del plugin
512
                splashWindow.process(80, PluginServices.getText(Launcher.class,
513
                                "SplashWindow.starting_plugin_internationalization_system"));
514
                pluginsMessages();
515

    
516
                // 9. Se modifica el andami-config con los plugins nuevos
517
                splashWindow.process(90, PluginServices.getText(Launcher.class,
518
                                "SplashWindow.looking_for_a_skin"));
519
                updateAndamiConfig();
520

    
521
                frame = new MDIFrame();
522
                // 10. Se configura el nombre e icono de la aplicaci?n
523
                splashWindow.process(100, PluginServices.getText(Launcher.class,
524
                                "SplashWindow.setting_up_applications_name_and_icons"));
525
                frameIcon(theme);
526

    
527
                // 11. Se prepara el MainFrame para albergar las extensiones
528
                splashWindow.process(110, PluginServices.getText(Launcher.class,
529
                                "SplashWindow.preparing_workbench"));
530
                JPopupMenu.setDefaultLightWeightPopupEnabled(false);
531

    
532
                SwingUtilities.invokeAndWait(new Runnable() {
533

    
534
                        public void run() {
535
                                frame.init();
536
                        }
537
                });
538
                ToolsSwingLocator.registerWindowManager(ToolsWindowManager.class);
539

    
540
                // 12. Leer el fichero de persistencia
541
                // info de los plugins
542
                // bookmarks de los plugins
543
                splashWindow.process(120, PluginServices.getText(Launcher.class,
544
                                "SplashWindow.loading_plugin_settings"));
545
                loadPluginsPersistence();
546

    
547
                // Se instalan los controles del skin
548
                // 13. Se inicializan todas las extensiones de todos los plugins
549
                splashWindow.process(130, PluginServices.getText(Launcher.class,
550
                                "SplashWindow.initializing_extensions"));
551
                SwingUtilities.invokeAndWait(new Runnable() {
552

    
553
                        public void run() {
554
                                initializeExtensions();
555
                        }
556
                });
557

    
558
                // 14. Se inicializan la extensi?n exclusiva
559
                splashWindow.process(140, PluginServices.getText(Launcher.class,
560
                                "SplashWindow.setting_up_master_extension"));
561
                SwingUtilities.invokeAndWait(new Runnable() {
562

    
563
                        public void run() {
564
                                initializeExclusiveUIExtension();
565
                        }
566
                });
567
                frame.setClassesExtensions(classesExtensions);
568

    
569
                // 15. Se instalan los controles de las extensiones de los plugins
570
                splashWindow.process(150, PluginServices.getText(Launcher.class,
571
                                "SplashWindow.installing_extensions_controls"));
572
                SwingUtilities.invokeAndWait(new Runnable() {
573

    
574
                        public void run() {
575
                                installPluginsControls();
576

    
577
                        }
578
                });
579

    
580
                // 16. Se instalan los menus de las extensiones de los plugins
581
                splashWindow.process(160, PluginServices.getText(Launcher.class,
582
                                "SplashWindow.installing_extensions_menus"));
583
                SwingUtilities.invokeAndWait(new Runnable() {
584

    
585
                        public void run() {
586
                                installPluginsMenus();
587

    
588
                        }
589
                });
590

    
591
                // 17. Se instalan las etiquetas de las extensiones de los plugins
592
                splashWindow.process(170, PluginServices.getText(Launcher.class,
593
                                "SplashWindow.installing_extensions_labels"));
594
                SwingUtilities.invokeAndWait(new Runnable() {
595

    
596
                        public void run() {
597
                                installPluginsLabels();
598

    
599
                        }
600
                });
601

    
602
                // 18. Se instalan los bookmarks de los plugins
603

    
604
                // 19. Se muestra el frame principal
605
                splashWindow.process(180, PluginServices.getText(Launcher.class,
606
                                "creating_main_window"));
607
                frame.setVisible(true);
608

    
609
                /* 
610
                 * Initialize installer local repository folders 
611
                 */
612
                initializeLocalAddOnRepositoryFolders();
613

    
614
                // 19. Se ejecuta el postInitialize
615
                splashWindow.process(190, PluginServices.getText(Launcher.class,
616
                                "SplashWindow.post_initializing_extensions"));
617
                SwingUtilities.invokeAndWait(new Runnable() {
618

    
619
                        public void run() {
620
                                postInitializeExtensions();
621

    
622
                        }
623
                });
624

    
625
                // Definimos un KeyEventDispatcher global para que las extensiones
626
                // puedan registrar sus "teclas r?pidas".
627
                GlobalKeyEventDispatcher keyDispatcher = GlobalKeyEventDispatcher.getInstance();
628
                KeyboardFocusManager.getCurrentKeyboardFocusManager().addKeyEventDispatcher(keyDispatcher);
629

    
630
                SwingUtilities.invokeAndWait(new Runnable() {
631

    
632
                        public void run() {
633
                                frame.enableControls();
634
                        }
635
                });
636

    
637
                frame.message(Messages.getString("StatusBar.Aplicacion_iniciada"), JOptionPane.INFORMATION_MESSAGE);
638

    
639
                splashWindow.close();
640
                if (launcherrors != null) {
641
                        NotificationManager.addError(launcherrors);
642
                }
643

    
644
                
645
                org.apache.log4j.Logger.getRootLogger().addAppender(
646
                                new NotificationAppender());
647

    
648
        }
649

    
650
        private void initializeLocalAddOnRepositoryFolders() {
651
                InstallerManager installerManager = InstallerLocator.getInstallerManager();
652

    
653
                File defaultAddonsRepository = PluginsLocator.getManager().getPluginsFolder();
654

    
655
                installerManager.addLocalAddonRepository(defaultAddonsRepository);
656
                installerManager.setDefaultLocalAddonRepository(defaultAddonsRepository);
657
                
658
                IconThemeManager iconManager = ToolsSwingLocator.getIconThemeManager();
659
                FolderSet fset = iconManager.getRepository();
660
                Iterator<FolderSet.FolderEntry> it = fset.iterator();
661
                while( it.hasNext() ) {
662
                        FolderEntry entry = it.next();
663
                        installerManager.addLocalAddonRepository(entry.getFolder());
664
                }
665
        }
666
        
667

    
668
        
669
        /**
670
     * 
671
     */
672
        private void initializeLibraries() {
673
                List<ClassLoader> classLoaders = new ArrayList<ClassLoader>(
674
                                pluginsOrdered.size() + 1);
675
                classLoaders.add(getClass().getClassLoader());
676
                Iterator<String> iter = pluginsOrdered.iterator();
677

    
678
                logger.debug("Initializing plugins libraries: ");
679
                while (iter.hasNext()) {
680
                        String pName = (String) iter.next();
681
                        PluginServices ps = (PluginServices) pluginsServices.get(pName);
682
                        classLoaders.add(ps.getClassLoader());
683
                }
684

    
685
                // Create the libraries initializer and
686
                // initialize the plugin libraries
687
                new DefaultLibrariesInitializer(classLoaders
688
                                .toArray(new ClassLoader[classLoaders.size()]))
689
                                .fullInitialize(true);
690

    
691
                // Remove them all, we don't need them anymore
692
                classLoaders.clear();
693
                classLoaders = null;
694
        }
695

    
696
        /**
697
         * @param args
698
         * @throws IOException
699
         * @throws ConfigurationException
700
         */
701
        private void initializeApp(String[] args) throws IOException,
702
                        ConfigurationException {
703
                if (!validJVM()) {
704
                        System.exit(-1);
705
                }
706

    
707
                // Clean temporal files
708
                Utilities.cleanUpTempFiles();
709

    
710
                if( args.length<1 ) {
711
                        appName = "gvSIG"; // Nombre de aplicacion por defecto es "gvSIG"
712
                } else {
713
                        appName = args[0];
714
                }
715

    
716
                getOrCreateConfigFolder();
717

    
718
                configureLogging(appName);
719

    
720
                if( args.length<2 ) {
721
                        loadAndamiConfig("gvSIG/extensiones"); // Valor por defecto 
722
                } else {
723
                        loadAndamiConfig(args[1]);
724
                }
725

    
726
                // Hacemos visibles los argumentos como una propiedad est?tica
727
                // de plugin services para quien lo quiera usar (por ejemplo, para
728
                // cargar un proyecto por l?nea de comandos)
729
                PluginServices.setArguments(args);
730

    
731
                configureLocales(args);
732

    
733
                logger.info("Load and initialize andami and plugins libraries");
734
                // LibrariesInitializer libsInitializer =
735
                // new DefaultLibrariesInitializer();
736
                // libsInitializer.initialize(true);
737
                // libsInitializer.postInitialize(true);
738

    
739
                logger.info("Configure LookAndFeel");
740
                configureLookAndFeel();
741
        }
742

    
743
        /**
744
     * 
745
     */
746
        private void configureLookAndFeel() {
747
                // Se pone el lookAndFeel
748
                try {
749
                        String lookAndFeel = getAndamiConfig().getLookAndFeel();
750
                        if (lookAndFeel == null) {
751
                                lookAndFeel = getDefaultLookAndFeel();
752
                        }
753
                        UIManager.setLookAndFeel(lookAndFeel);
754
                } catch (Exception e) {
755
                        logger.warn(Messages.getString("Launcher.look_and_feel"), e);
756
                }
757
                FontUtils.initFonts();
758
        }
759

    
760
        /**
761
         * @param args
762
         * @throws ConfigurationException
763
         */
764
        private void loadAndamiConfig(String pluginFolder)
765
                        throws ConfigurationException {
766
                // Leer el fichero de configuraci?n de andami (andami-config.xsd)
767
                // locale
768
                // Buscar actualizaci?nes al comenzar
769
                // Andami
770
                // Plugins
771
                // Directorio de las extensiones
772
                andamiConfigPath = appHomeDir + File.separator + "andami-config.xml";
773
                andamiConfigFromXML(andamiConfigPath);
774
                andamiConfig.setPluginsDirectory(pluginFolder);
775
        }
776

    
777
        /**
778
     * 
779
     */
780
        private void getOrCreateConfigFolder() {
781
                // Create application configuration folder
782
                appHomeDir = System.getProperty(appName + ".home");
783
                if (appHomeDir == null) {
784
                        appHomeDir = System.getProperty("user.home");
785
                }
786

    
787
                appHomeDir += File.separator + appName;
788
                File parent = new File(appHomeDir);
789
                parent.mkdirs();
790
        }
791

    
792
        /**
793
         * @param args
794
         * @throws IOException
795
         */
796
        private void configureLogging(String appName) throws IOException {
797
                // Configurar el log4j
798

    
799
                URL config = Launcher.class.getClassLoader().getResource("log4j.properties");
800
                if( config == null ) {
801
                        config = Launcher.class.getClassLoader().getResource("default-log4j/log4j.properties");
802
                }
803
                PropertyConfigurator.configure(config);
804
                PatternLayout l = new PatternLayout("%p %t %C - %m%n");
805
                RollingFileAppender fa = new RollingFileAppender(l, appHomeDir
806
                                + File.separator + appName + ".log", false);
807
                fa.setMaxFileSize("512KB");
808
                fa.setMaxBackupIndex(3);
809
                org.apache.log4j.Logger.getRootLogger().addAppender(fa);
810
                logger.info("Loadded log4j.properties from " + config.toString());
811
        }
812

    
813
        private class NotificationAppender extends AppenderSkeleton {
814

    
815
                @Override
816
                protected void append(LoggingEvent event) {
817
                        if (event.getLevel() == org.apache.log4j.Level.ERROR
818
                                        || event.getLevel() == org.apache.log4j.Level.FATAL) {
819
                            
820
                            Throwable th = null;
821
                            ThrowableInformation thi = event.getThrowableInformation();
822
                            if (thi != null) {
823
                                th = thi.getThrowable();
824
                            }
825
                                NotificationManager.dispatchError(event.getRenderedMessage(), th);
826
                                return;
827
                        }
828
                        // if (event.getLevel() == org.apache.log4j.Level.WARN) {
829
                        // NotificationManager.dispatchWarning(event.getRenderedMessage(),
830
                        // null);
831
                        // return;
832
                        // }
833
                }
834

    
835
                  
836
                @Override
837
                public void close() {
838
                        // TODO Auto-generated method stub
839

    
840
                }
841

    
842
                @Override
843
                public boolean requiresLayout() {
844
                        // TODO Auto-generated method stub
845
                        return false;
846
                }
847

    
848
        }
849

    
850
        /**
851
         * Return the directory applicaction is installed.
852
         */
853
        public static String getApplicationDirectory() {
854
                return getApplicationFolder().getAbsolutePath();
855
        }
856
        
857
    public static File getApplicationFolder() {
858
        // TODO: check if there is a better way to handle this
859
        return new File(System.getProperty("user.dir"));
860
    }
861

    
862
        private void registerIcons() {
863
                IconTheme theme = PluginServices.getIconTheme();
864
                ClassLoader loader = Launcher.class.getClassLoader();        
865
                
866
                String[][] icons = {
867
                                // MultiSplashWindow
868
                                { "main", "splash-default" },
869
                                // NewStatusBar
870
                                { "main", "statusbar-info" },
871
                                { "main", "statusbar-warning" },
872
                                { "main", "statusbar-error" }
873
                };
874
                for( int i=0; i<icons.length; i++) {
875
                        try {
876
                                IconThemeHelper.registerIcon(icons[i][0], icons[i][1], Launcher.class);
877
                        } catch(Exception e) {
878
                                logger.info("Can't register icon '"+icons[i][0]+"' ("+icons[i][1]+").");
879
                        }
880
                }                
881
                theme.setDefaultIcon(loader.getResource("images/main/default-icon.png" ));
882
        }
883

    
884
        /**
885
         * Obtiene la personalizaci?n de los iconos, splash, fondo y el nombre de la
886
         * aplicaci?n.
887
         * 
888
         * @return Theme
889
         */
890
        private Theme getTheme(String pluginsDirectory) {
891
                File themeFile = null;
892
                Theme theme = new Theme();
893

    
894
                // Try to get theme from args
895
                String name = PluginServices.getArgumentByName("andamiTheme");
896
                if (name != null) {
897
                        themeFile = new File(name);
898
                        logger.info("search andami-theme in {}", themeFile
899
                                        .getAbsolutePath());
900
                        if (themeFile.exists()) {
901
                                theme.readTheme(themeFile);
902
                                logger.info("andami-theme found in {}", themeFile
903
                                                .getAbsolutePath());
904
                                return theme;
905
                        }
906
                }
907

    
908
                // Try to get theme from a plugin
909
                File pluginsDir = new File(pluginsDirectory);
910
                if (!pluginsDir.isAbsolute()) {
911
                        pluginsDir = new File(System.getProperty("user.dir"),
912
                                        pluginsDirectory);
913
                }
914
                if (pluginsDir.exists()) {
915
                        logger.info("search andami-theme in plugins folder.");
916
                        File[] pluginDirs = pluginsDir.listFiles();
917
                        if (pluginDirs.length > 0) {
918
                                for (int i = 0; i < pluginDirs.length; i++) {
919
                                        File pluginThemeFile = new File(pluginDirs[i], "theme"
920
                                                        + File.separator + "andami-theme.xml");
921
                                        if (pluginThemeFile.exists()) {
922
                                                themeFile = pluginThemeFile;
923
                                                // This if is a hack to allow more themes than the
924
                                                // one available in org.gvsig.app. Remove this
925
                                                // when a the theme format is changed to allow for
926
                                                // priorities
927
                                                if (!"org.gvsig.app".equals(pluginDirs[i].getName())) {
928
                                                        break;
929
                                                }
930
                                        }
931
                                }
932
                        }
933
                }
934

    
935
                // The theme file will be the one into a plugin or by default the one
936
                // in the org.gvsig.app plugin
937
                if (themeFile != null && themeFile.exists()) {
938
                        theme.readTheme(themeFile);
939
                        logger.info("andami-theme found in plugin {}", themeFile
940
                                        .getAbsolutePath());
941
                        return theme;
942
                }
943

    
944
                // Try to get theme from dir gvSIG in user home
945
                themeFile = new File(getAppHomeDir(), "theme" + File.separator
946
                                + "andami-theme.xml");
947
                logger.info("search andami-theme in user's home {}", themeFile
948
                                .getAbsolutePath());
949
                if (themeFile.exists()) {
950
                        theme.readTheme(themeFile);
951
                        logger.info("andami-theme found in user's home {}", themeFile
952
                                        .getAbsolutePath());
953
                        return theme;
954
                }
955

    
956
                // Try to get theme from the instalation dir of gvSIG.
957
                themeFile = new File(getApplicationDirectory(), "theme"
958
                                + File.separator + "andami-theme.xml");
959
                logger.info("search andami-theme in installation folder {}", themeFile
960
                                .getAbsolutePath());
961
                if (themeFile.exists()) {
962
                        theme.readTheme(themeFile);
963
                        logger.info("andami-theme found in instalation folder {}",
964
                                        themeFile.getAbsolutePath());
965
                        return theme;
966
                }
967
                logger.info("Apply default andami-theme.");
968
                return theme;
969
        }
970

    
971
        /**
972
         * Establece los datos que ten?amos guardados respecto de la configuraci?n
973
         * del proxy.
974
         */
975
        private void configureProxy() {
976
                String host = prefs.get("firewall.http.host", "");
977
                String port = prefs.get("firewall.http.port", "");
978

    
979
                System.getProperties().put("http.proxyHost", host);
980
                System.getProperties().put("http.proxyPort", port);
981

    
982
                // Ponemos el usuario y clave del proxy, si existe
983
                String proxyUser = prefs.get("firewall.http.user", null);
984
                String proxyPassword = prefs.get("firewall.http.password", null);
985
                if (proxyUser != null) {
986
                        System.getProperties().put("http.proxyUserName", proxyUser);
987
                        System.getProperties().put("http.proxyPassword", proxyPassword);
988

    
989
                        Authenticator.setDefault(new ProxyAuth(proxyUser, proxyPassword));
990
                } else {
991
                        Authenticator.setDefault(new ProxyAuth("", ""));
992
                }
993
        }
994

    
995
        /**
996
         * Recupera la geometr?a (tama?o, posic?n y estado) de la ventana principal
997
         * de Andami. TODO Pendiente de ver como se asigna un pluginServices para el
998
         * launcher.
999
         * 
1000
         * @author LWS
1001
         */
1002
        private void restoreMDIStatus(XMLEntity xml) {
1003
                if (xml == null) {
1004
                        xml = new XMLEntity();
1005
                }
1006
        // ====================================
1007
        // restore frame size
1008
        Dimension sz = new Dimension(
1009
            MainFrame.MAIN_FRAME_SIZE_DEFAULT[0],
1010
            MainFrame.MAIN_FRAME_SIZE_DEFAULT[1]);
1011
        if (xml.contains(MainFrame.MAIN_FRAME_SIZE)) {
1012
            int[] wh = xml.getIntArrayProperty(MainFrame.MAIN_FRAME_SIZE);
1013
            sz = new Dimension(wh[0], wh[1]);
1014
        }
1015
        frame.setSize(sz);
1016
        // ==========================================
1017
        // restore frame location
1018
        Point pos = new Point(
1019
            MainFrame.MAIN_FRAME_POS_DEFAULT[0],
1020
            MainFrame.MAIN_FRAME_POS_DEFAULT[1]);
1021
        if (xml.contains(MainFrame.MAIN_FRAME_POS)) {
1022
            int[] xy = xml.getIntArrayProperty(MainFrame.MAIN_FRAME_POS);
1023
            pos = new Point(xy[0], xy[1]);
1024
        }
1025
        frame.setLocation(pos);
1026
        // =============================================
1027
        // restore frame state (Maximized, minimized, etc);
1028
        int state = MainFrame.MAIN_FRAME_EXT_STATE_DEFAULT;
1029
        if (xml.contains(MainFrame.MAIN_FRAME_EXT_STATE)) {
1030
            state = xml.getIntProperty(MainFrame.MAIN_FRAME_EXT_STATE);
1031
        }
1032
        frame.setExtendedState(state);
1033
        }
1034

    
1035
        private XMLEntity saveMDIStatus() {
1036
                XMLEntity xml = new XMLEntity();
1037
                // save frame size
1038
                int[] wh = new int[2];
1039
                wh[0] = frame.getWidth();
1040
                wh[1] = frame.getHeight();
1041
                xml.putProperty(MainFrame.MAIN_FRAME_SIZE, wh);
1042
                // save frame location
1043
                int[] xy = new int[2];
1044
                xy[0] = frame.getX();
1045
                xy[1] = frame.getY();
1046
                xml.putProperty(MainFrame.MAIN_FRAME_POS, xy);
1047
                // save frame status
1048
                xml.putProperty(MainFrame.MAIN_FRAME_EXT_STATE,
1049
                    frame.getExtendedState());
1050
                return xml;
1051
        }
1052

    
1053
        private boolean validJVM() {
1054
                char thirdCharacter = System.getProperty("java.version").charAt(2);
1055
                if (thirdCharacter < '4') {
1056
                        return false;
1057
                } else {
1058
                        return true;
1059
                }
1060
        }
1061

    
1062
        private void loadPluginsPersistence() throws ConfigurationException {
1063
                XMLEntity entity = persistenceFromXML();
1064

    
1065
                for (int i = 0; i < entity.getChildrenCount(); i++) {
1066
                        XMLEntity plugin = entity.getChild(i);
1067
                        String pName = plugin
1068
                                        .getStringProperty("com.iver.andami.pluginName");
1069

    
1070
                        if (pName.compareToIgnoreCase("com.iver.cit.gvsig") == 0) {
1071
                                pName = "org.gvsig.app";
1072
                        }
1073
                        if (pluginsServices.get(pName) != null) {
1074
                                ((PluginServices) pluginsServices.get(pName))
1075
                                                .setPersistentXML(plugin);
1076
                        } else {
1077
                                if (pName.startsWith("Andami.Launcher")) {
1078
                                        restoreMDIStatus(plugin);
1079
                                }
1080
                        }
1081
                }
1082
        }
1083

    
1084
        /**
1085
         * Salva la persistencia de los plugins.
1086
         * 
1087
         * @author LWS
1088
         */
1089
        private void savePluginPersistence() {
1090
                Iterator<String> i = pluginsConfig.keySet().iterator();
1091

    
1092
                XMLEntity entity = new XMLEntity();
1093

    
1094
                while (i.hasNext()) {
1095
                        String pName = i.next();
1096
                        PluginServices ps = (PluginServices) pluginsServices.get(pName);
1097
                        XMLEntity ent = ps.getPersistentXML();
1098

    
1099
                        if (ent != null) {
1100
                                ent.putProperty("com.iver.andami.pluginName", pName);
1101
                                entity.addChild(ent);
1102
                        }
1103
                }
1104
                XMLEntity ent = saveMDIStatus();
1105
                if (ent != null) {
1106
                        ent.putProperty("com.iver.andami.pluginName", "Andami.Launcher");
1107
                        entity.addChild(ent);
1108
                }
1109
                try {
1110
                        persistenceToXML(entity);
1111
                } catch (ConfigurationException e1) {
1112
                        this
1113
                                        .addError(
1114
                                                        Messages
1115
                                                                        .getString("Launcher.Se_produjo_un_error_guardando_la_configuracion_de_los_plugins"),
1116
                                                        e1);
1117
                }
1118
        }
1119

    
1120
        private void installPluginsLabels() {
1121
                Iterator<String> i = pluginsConfig.keySet().iterator();
1122

    
1123
                while (i.hasNext()) {
1124
                        String name = i.next();
1125
                        PluginConfig pc = pluginsConfig.get(name);
1126
                        PluginServices ps = (PluginServices) pluginsServices.get(name);
1127

    
1128
                        LabelSet[] ls = pc.getLabelSet();
1129

    
1130
                        for (int j = 0; j < ls.length; j++) {
1131
                                PluginClassLoader loader = ps.getClassLoader();
1132

    
1133
                                try {
1134
                                        Class clase = loader.loadClass(ls[j].getClassName());
1135
                                        frame.setStatusBarLabels(clase, ls[j].getLabel());
1136
                                } catch (ClassNotFoundException e) {
1137
                                        this.addError(
1138
                                                        Messages.getString("Launcher.labelset_class"), e);
1139
                                }
1140
                        }
1141
                }
1142
        }
1143

    
1144
        private String configureSkin(XMLEntity xml, String defaultSkin) {
1145
                if (defaultSkin == null) {
1146
                        for (int i = 0; i < xml.getChildrenCount(); i++) {
1147
                                if (xml.getChild(i).contains("Skin-Selected")) {
1148
                                        String className = xml.getChild(i).getStringProperty(
1149
                                                        "Skin-Selected");
1150
                                        return className;
1151
                                }
1152
                        }
1153
                }
1154
                // return "com.iver.core.mdiManager.NewSkin";
1155
                return defaultSkin;
1156
        }
1157

    
1158
        private void fixSkin(SkinExtension skinExtension,
1159
                        PluginClassLoader pluginClassLoader) throws MDIManagerLoadException {
1160
                // now insert the skin selected.
1161
                MDIManagerFactory.setSkinExtension(skinExtension, pluginClassLoader);
1162
                // MDIManagerFactory.setSkinExtension(se,
1163
                // ps.getClassLoader());
1164

    
1165
                Class<? extends IExtension> skinClass;
1166

    
1167
                try {
1168
                        skinClass = (Class<? extends IExtension>) pluginClassLoader
1169
                                        .loadClass(skinExtension.getClassName());
1170

    
1171
                        IExtension skinInstance = skinClass.newInstance();
1172
                        ExtensionDecorator newExtensionDecorator = new ExtensionDecorator(
1173
                                        skinInstance, ExtensionDecorator.INACTIVE);
1174
                        classesExtensions.put(skinClass, newExtensionDecorator);
1175
                } catch (ClassNotFoundException e) {
1176
                        logger.error(Messages
1177
                                        .getString("Launcher.No_se_encontro_la_clase_mdi_manager"),
1178
                                        e);
1179
                        throw new MDIManagerLoadException(e);
1180
                } catch (InstantiationException e) {
1181
                        logger
1182
                                        .error(
1183
                                                        Messages
1184
                                                                        .getString("Launcher.No_se_pudo_instanciar_la_clase_mdi_manager"),
1185
                                                        e);
1186
                        throw new MDIManagerLoadException(e);
1187
                } catch (IllegalAccessException e) {
1188
                        logger
1189
                                        .error(
1190
                                                        Messages
1191
                                                                        .getString("Launcher.No_se_pudo_acceder_a_la_clase_mdi_manager"),
1192
                                                        e);
1193
                        throw new MDIManagerLoadException(e);
1194
                }
1195

    
1196
        }
1197

    
1198
        /**
1199
         * DOCUMENT ME!
1200
         * 
1201
         * @throws MDIManagerLoadException
1202
         */
1203
        private void skinPlugin(String defaultSkin) throws MDIManagerLoadException {
1204
                XMLEntity entity = null;
1205
                try {
1206
                        entity = persistenceFromXML();
1207
                } catch (ConfigurationException e1) {
1208
                        // TODO Auto-generated catch block
1209
                        e1.printStackTrace();
1210
                }
1211
                Iterator<String> i = pluginsConfig.keySet().iterator();
1212

    
1213
                SkinExtension skinExtension = null;
1214
                PluginClassLoader pluginClassLoader = null;
1215
                List<SkinExtension> skinExtensions = new ArrayList<SkinExtension>();
1216
                while (i.hasNext()) {
1217
                        String name = i.next();
1218
                        PluginConfig pc = pluginsConfig.get(name);
1219
                        PluginServices ps = pluginsServices.get(name);
1220

    
1221
                        if (pc.getExtensions().getSkinExtension() != null) {
1222
                                // if (MDIManagerFactory.getSkinExtension() != null) {
1223
                                // logger.warn(Messages.getString(
1224
                                // "Launcher.Dos_skin_extension"));
1225
                                // }
1226

    
1227
                                SkinExtension[] se = pc.getExtensions().getSkinExtension();
1228
                                for (int numExten = 0; numExten < se.length; numExten++) {
1229
                                        skinExtensions.add(se[numExten]);
1230
                                }
1231
                                for (int j = 0; j < se.length; j++) {
1232
                                        String configuredSkin = this.configureSkin(entity,
1233
                                                        defaultSkin);
1234
                                        if ((configuredSkin != null)
1235
                                                        && configuredSkin.equals(se[j].getClassName())) {
1236
                                                skinExtension = se[j];
1237
                                                pluginClassLoader = ps.getClassLoader();
1238
                                        }
1239
                                }
1240
                        }
1241
                }
1242

    
1243
                if ((skinExtension != null) && (pluginClassLoader != null)) {
1244
                        // configured skin was found
1245
                        fixSkin(skinExtension, pluginClassLoader);
1246
                } else {
1247
                        if (skinExtensions.contains("com.iver.core.mdiManager.NewSkin")) {
1248
                                // try first NewSkin (from CorePlugin)
1249
                                skinPlugin("com.iver.core.mdiManager.NewSkin");
1250
                        } else if (skinExtensions.size() > 0) {
1251
                                // try to load the first skin found
1252
                                SkinExtension se = (SkinExtension) skinExtensions.get(0);
1253
                                skinPlugin((String) se.getClassName());
1254
                        } else {
1255
                                throw new MDIManagerLoadException("No Skin-Extension installed");
1256
                        }
1257
                }
1258

    
1259
        }
1260

    
1261
        private static void frameIcon(Theme theme) {
1262
                Iterator<String> i = pluginsConfig.keySet().iterator();
1263

    
1264
                while (i.hasNext()) {
1265
                        String pName = i.next();
1266
                        PluginConfig pc = pluginsConfig.get(pName);
1267
                        if (pc.getIcon() != null) {
1268
                                if (theme.getIcon() != null) {
1269
                                        frame.setIconImage(theme.getIcon().getImage());
1270
                                } else {
1271

    
1272
                                        ImageIcon icon = PluginServices.getIconTheme().get(
1273
                                                        pc.getIcon().getSrc());
1274
                                        frame.setIconImage(icon.getImage());
1275

    
1276
                                }
1277
                                if (theme.getName() != null) {
1278
                                        frame.setTitlePrefix(theme.getName());
1279
                                } else {
1280
                                        frame.setTitlePrefix(pc.getIcon().getText());
1281
                                }
1282
                                if (theme.getBackgroundImage() != null) {
1283

    
1284
                                        PluginServices.getMDIManager().setBackgroundImage(
1285
                                                        theme.getBackgroundImage(), theme.getTypeDesktop());
1286
                                }
1287
                        }
1288
                }
1289
        }
1290

    
1291
        private void initializeExtensions() {
1292

    
1293
                List<ClassLoader> classLoaders = new ArrayList<ClassLoader>(
1294
                                pluginsOrdered.size());
1295
                classLoaders.add(getClass().getClassLoader());
1296
                Iterator<String> iter = pluginsOrdered.iterator();
1297

    
1298
                // logger.debug("Initializing plugins libraries: ");
1299
                // while (iter.hasNext()) {
1300
                // String pName = (String) iter.next();
1301
                // PluginServices ps = (PluginServices) pluginsServices.get(pName);
1302
                // classLoaders.add(ps.getClassLoader());
1303
                // }
1304
                //
1305
                // // Create the libraries initializer and
1306
                // // initialize the plugin libraries
1307
                // new DefaultLibrariesInitializer(
1308
                // classLoaders.toArray(new ClassLoader[classLoaders.size()]))
1309
                // .fullInitialize();
1310
                //
1311
                // // Remove them all, we don't need them anymore
1312
                // classLoaders.clear();
1313
                // classLoaders = null;
1314

    
1315
                logger.info("Initializing plugins: ");
1316
                // iter = pluginsOrdered.iterator();
1317
                while (iter.hasNext()) {
1318
                        String pName = (String) iter.next();
1319
                        logger.info("Initializing plugin " + pName);
1320
                        PluginConfig pc = (PluginConfig) pluginsConfig.get(pName);
1321
                        PluginServices ps = (PluginServices) pluginsServices.get(pName);
1322

    
1323
                        Extension[] exts = pc.getExtensions().getExtension();
1324

    
1325
                        TreeSet<Extension> orderedExtensions = new TreeSet<Extension>(
1326
                                        new ExtensionComparator());
1327

    
1328
                        for (int j = 0; j < exts.length; j++) {
1329
                                if (!exts[j].getActive()) {
1330
                                        continue;
1331
                                }
1332

    
1333
                                if (orderedExtensions.contains(exts[j])) {
1334
                                        logger.warn("Two extensions with the same priority ("
1335
                                                        + exts[j].getClassName() + ")");
1336
                                }
1337

    
1338
                                orderedExtensions.add(exts[j]);
1339
                        }
1340

    
1341
                        Iterator<Extension> e = orderedExtensions.iterator();
1342

    
1343
                        logger.info("Initializing extensions of plugin " + pName + ": ");
1344
                        while (e.hasNext()) {
1345
                                Extension extension = e.next();
1346
                                org.gvsig.andami.plugins.IExtension extensionInstance;
1347

    
1348
                                try {
1349
                                        logger.info("Initializing " + extension.getClassName()
1350
                                                        + "...");
1351
                                        Class<? extends IExtension> extensionClass = (Class<? extends IExtension>) ps
1352
                                                        .getClassLoader().loadClass(
1353
                                                                        extension.getClassName());
1354
                                        extensionInstance = extensionClass.newInstance();
1355

    
1356
                                        // CON DECORATOR
1357
                                        // ANTES: classesExtensions.put(extensionClass,
1358
                                        // extensionInstance);
1359
                                        // AHORA: CREAMOS UNA ExtensionDecorator y asignamos esta
1360
                                        // instancia para
1361
                                        // poder ampliar con nuevas propiedades (AlwaysVisible, por
1362
                                        // ejemplo)
1363
                                        // Para crear la nueva clase ExtensionDecorator, le pasamos
1364
                                        // como par?metro
1365
                                        // la extensi?n original que acabamos de crear
1366
                                        // 0-> Inactivo, controla la extension
1367
                                        // 1-> Siempre visible
1368
                                        // 2-> Invisible
1369
                                        ExtensionDecorator newExtensionDecorator = new ExtensionDecorator(
1370
                                                        extensionInstance, ExtensionDecorator.INACTIVE);
1371
                                        classesExtensions
1372
                                                        .put(extensionClass, newExtensionDecorator);
1373

    
1374
                                        extensionInstance.initialize();
1375
                                        extensions.add(extensionInstance);
1376

    
1377
                                } catch (NoClassDefFoundError e1) {
1378
                                        this.addError("Can't find class extension ("
1379
                                                        + extension.getClassName() + ")", e1);
1380
                                } catch (Throwable e1) {
1381
                                        this.addError("Can't initialize extension '"
1382
                                                        + extension.getClassName() + "'.", e1);
1383
                                }
1384
                        }
1385
                }
1386
        }
1387

    
1388
        private void postInitializeExtensions() {
1389
                logger.info("PostInitializing extensions: ");
1390

    
1391
                for (int i = 0; i < extensions.size(); i++) {
1392
                        org.gvsig.andami.plugins.IExtension extensionInstance = (org.gvsig.andami.plugins.IExtension) extensions
1393
                                        .get(i);
1394
                        logger.info("PostInitializing "
1395
                                        + extensionInstance.getClass().getName() + "...");
1396
                        try {
1397
                                extensionInstance.postInitialize();
1398
                        } catch (Throwable ex) {
1399
                                this.addError("postInitialize of extension '"
1400
                                                + extensionInstance.getClass().getName() + "' failed",
1401
                                                ex);
1402
                        }
1403
                }
1404
        }
1405

    
1406
        private void registerActionOfExtensions(ActionInfoManager actionManager,
1407
                        Enumeration<SkinExtensionType> extensiones, ClassLoader loader) {
1408
                ActionInfo actionInfo;
1409
                while (extensiones.hasMoreElements()) {
1410
                        SkinExtensionType extension = extensiones.nextElement();
1411
                        Class<? extends IExtension> classExtension;
1412
                        try {
1413
                                classExtension = (Class<? extends IExtension>) loader
1414
                                                .loadClass(extension.getClassName());
1415

    
1416
                                Enumeration<Action> actions = extension.enumerateAction();
1417
                                while (actions.hasMoreElements()) {
1418
                                        Action action = actions.nextElement();
1419
                                        if (action.getName() == null) {
1420
                                                logger.info("invalid action name (null) in "+ extension.getClassName()+" of "+ loader.toString());
1421
                                        } else {
1422
                                                actionInfo = actionManager.createAction(
1423
                                                                classExtension, action.getName(),
1424
                                                                action.getLabel(), action.getActionCommand(),
1425
                                                                action.getIcon(), action.getAccelerator(), action.getPosition(),
1426
                                                                action.getTooltip());
1427
                                                actionManager.registerAction(actionInfo);
1428
                                                if( action.getPosition() < 100000000 ) {
1429
                                                        logger.info("Invalid position in action ("+ actionInfo.toString()+ ").");
1430
                                                        action.setPosition( action.getPosition() + 1000000000);
1431
                                                }
1432
                                        }
1433
                                }
1434

    
1435
                                Enumeration<Menu> menus = extension.enumerateMenu();
1436
                                while (menus.hasMoreElements()) {
1437
                                        Menu menu = menus.nextElement();
1438
                                        if (!menu.getIs_separator() ) {
1439
                                                actionInfo = actionManager.createAction(
1440
                                                        classExtension, menu.getName(), menu.getText(),
1441
                                                        menu.getActionCommand(), menu.getIcon(),
1442
                                                        menu.getKey(), menu.getPosition(),
1443
                                                        menu.getTooltip());
1444
                                                actionInfo = actionManager.registerAction(actionInfo);
1445
                                                if (actionInfo != null) {
1446
                                                        menu.setActionCommand(actionInfo.getCommand());
1447
                                                        menu.setTooltip(actionInfo.getTooltip());
1448
                                                        menu.setIcon(actionInfo.getIconName());
1449
                                                        menu.setPosition(actionInfo.getPosition());
1450
                                                        menu.setKey(actionInfo.getAccelerator());
1451
                                                        menu.setName(actionInfo.getName());
1452
                                                }
1453
                                        } 
1454
                                        if( menu.getPosition() < 100000000 ) {
1455
                                                logger.info("Invalid position in menu ("+ menu.getText() + ").");
1456
                                                menu.setPosition( menu.getPosition() + 1000000000);
1457
                                        }
1458

    
1459
                                }
1460
                                Enumeration<ToolBar> toolBars = extension.enumerateToolBar();
1461
                                while (toolBars.hasMoreElements()) {
1462
                                        ToolBar toolBar = toolBars.nextElement();
1463

    
1464
                                        Enumeration<ActionTool> actionTools = toolBar
1465
                                                        .enumerateActionTool();
1466
                                        while (actionTools.hasMoreElements()) {
1467
                                                ActionTool actionTool = actionTools.nextElement();
1468
                                                actionInfo = actionManager.createAction(
1469
                                                                classExtension, actionTool.getName(),
1470
                                                                actionTool.getText(),
1471
                                                                actionTool.getActionCommand(),
1472
                                                                actionTool.getIcon(),
1473
                                                                null,
1474
                                                                actionTool.getPosition(),
1475
                                                                actionTool.getTooltip());
1476
                                                actionInfo = actionManager.registerAction(actionInfo);
1477
                                                if (actionInfo != null) {
1478
                                                        actionTool.setActionCommand(actionInfo.getCommand());
1479
                                                        actionTool.setTooltip(actionInfo.getTooltip());
1480
                                                        actionTool.setIcon(actionInfo.getIconName());
1481
                                                        actionTool.setPosition(actionInfo.getPosition());
1482
                                                        actionTool.setName(actionInfo.getName());
1483
                                                }
1484
                                        }
1485

    
1486
                                        Enumeration<SelectableTool> selectableTool = toolBar
1487
                                                        .enumerateSelectableTool();
1488
                                        while (selectableTool.hasMoreElements()) {
1489
                                                SelectableTool actionTool = selectableTool
1490
                                                                .nextElement();
1491
                                                actionInfo = actionManager.createAction(
1492
                                                                classExtension, actionTool.getName(),
1493
                                                                actionTool.getText(),
1494
                                                                actionTool.getActionCommand(),
1495
                                                                actionTool.getIcon(),
1496
                                                                null,
1497
                                                                actionTool.getPosition(),
1498
                                                                actionTool.getTooltip());
1499
                                                actionInfo = actionManager.registerAction(actionInfo);
1500
                                                if (actionInfo != null) {
1501
                                                        actionTool.setActionCommand(actionInfo.getCommand());
1502
                                                        actionTool.setTooltip(actionInfo.getTooltip());
1503
                                                        actionTool.setIcon(actionInfo.getIconName());
1504
                                                        actionTool.setPosition(actionInfo.getPosition());
1505
                                                        actionTool.setName(actionInfo.getName());
1506
                                                }
1507
                                        }
1508
                                }
1509
                        } catch (ClassNotFoundException e) {
1510
                                logger.warn(
1511
                                                "Can't register actions of extension '"
1512
                                                                + extension.getClassName() + "'", e);
1513
                        }
1514
                }
1515
        }
1516
        
1517
        @SuppressWarnings("unchecked")
1518
        private void registerActions() {
1519
                logger.info("registerActions");
1520

    
1521
                ActionInfoManager actionManager = PluginsLocator.getActionInfoManager();
1522
                Iterator<String> it = pluginsConfig.keySet().iterator();
1523

    
1524
                while (it.hasNext()) {
1525
                        String pluginName = it.next();
1526
                        PluginConfig pluginConfig = pluginsConfig.get(pluginName);
1527
                        PluginServices pluginService = pluginsServices.get(pluginName);
1528
                        PluginClassLoader loader =  pluginService.getClassLoader();
1529

    
1530
                        logger.info("registerActions of plugin '"+pluginName+"'.");
1531

    
1532
                        Extensions extensionConfig = pluginConfig.getExtensions();
1533
                        
1534
                        
1535
                        Enumeration<SkinExtensionType> extensiones = extensionConfig.enumerateExtension();
1536
                        registerActionOfExtensions(actionManager, extensiones, loader);
1537

    
1538
                        Enumeration<SkinExtensionType> skinSxtensiones = extensionConfig.enumerateSkinExtension();
1539
                        registerActionOfExtensions(actionManager, skinSxtensiones, loader);
1540

    
1541
                        PopupMenus pluginPopupMenus = pluginConfig.getPopupMenus();
1542
                        if (pluginPopupMenus != null) {
1543
                                PopupMenu[] menus1 = pluginPopupMenus.getPopupMenu();
1544
                                for (int j = 0; j < menus1.length; j++) {
1545
                                        PopupMenu popupMenu = menus1[j];
1546
                                        Enumeration<Menu> menus2 = popupMenu.enumerateMenu();
1547
                                        while (menus2.hasMoreElements()) {
1548
                                                Menu menu = menus2.nextElement();
1549
                                                if (!menu.getIs_separator() ) {
1550
                                                        if( menu.getName() == null) {   
1551
                                                                logger.info("Null name for popmenu '"+menu.getText()+"' in plugin "+ pluginService.getPluginName() );
1552
                                                        } else {
1553
                                                                ActionInfo actionInfo = actionManager.getAction(menu.getName());
1554
                                                                if( actionInfo!=null ) {
1555
                                                                        menu.setActionCommand(actionInfo.getCommand());
1556
                                                                        menu.setTooltip(actionInfo.getTooltip());
1557
                                                                        menu.setIcon(actionInfo.getIconName());
1558
                                                                        menu.setPosition(actionInfo.getPosition());
1559
                                                                        menu.setText( actionInfo.getLabel());
1560
                                                                        menu.setKey(actionInfo.getAccelerator());
1561
                                                                }
1562
                                                        }
1563
                                                }
1564
                                        }
1565
                                }
1566
                        }
1567
                        
1568

    
1569
                }
1570
        }
1571
        
1572

    
1573
        private TreeSet<SortableMenu> getOrderedMenus() { 
1574

    
1575
                TreeSet<SortableMenu> orderedMenus = new TreeSet<SortableMenu>(
1576
                                new MenuComparator());
1577

    
1578
                Iterator<String> i = pluginsConfig.keySet().iterator();
1579

    
1580
                while (i.hasNext()) {
1581
                        String pName = i.next();
1582
                        try {
1583
                                PluginServices ps = pluginsServices.get(pName);
1584
                                PluginConfig pc = pluginsConfig.get(pName);
1585

    
1586
                                Extension[] exts = pc.getExtensions().getExtension();
1587

    
1588
                                for (int j = 0; j < exts.length; j++) {
1589
                                        if (!exts[j].getActive()) {
1590
                                                continue;
1591
                                        }
1592

    
1593
                                        Menu[] menus = exts[j].getMenu();
1594

    
1595
                                        for (int k = 0; k < menus.length; k++) {
1596
                                                SortableMenu sm = new SortableMenu(ps.getClassLoader(),
1597
                                                                exts[j], menus[k]);
1598

    
1599
                                                if (orderedMenus.contains(sm)) {
1600
                                                        this
1601
                                                                        .addError(Messages
1602
                                                                                        .getString("Launcher.Two_menus_with_the_same_position")
1603
                                                                                        + " - "
1604
                                                                                        + menus[k].getText()
1605
                                                                                        + " - " + exts[j].getClassName());
1606
                                                }
1607

    
1608
                                                orderedMenus.add(sm);
1609
                                        }
1610
                                }
1611

    
1612
                                // Se instalan las extensiones de MDI
1613
                                SkinExtension[] skinExts = pc.getExtensions()
1614
                                                .getSkinExtension();
1615
                                for (int j = 0; j < skinExts.length; j++) {
1616

    
1617
                                        if (skinExts[j] != null) {
1618
                                                Menu[] menu = skinExts[j].getMenu();
1619

    
1620
                                                for (int k = 0; k < menu.length; k++) {
1621
                                                        SortableMenu sm = new SortableMenu(ps
1622
                                                                        .getClassLoader(), skinExts[j], menu[k]);
1623

    
1624
                                                        if (orderedMenus.contains(sm)) {
1625
                                                                this
1626
                                                                                .addError(Messages
1627
                                                                                                .getString("Launcher.Two_menus_with_the_same_position")
1628
                                                                                                + skinExts[j].getClassName());
1629
                                                        }
1630

    
1631
                                                        orderedMenus.add(sm);
1632
                                                }
1633
                                        }
1634
                                }
1635

    
1636
                        } catch (Throwable e) {
1637
                                addError("Error initializing menus of plugin '" + pName + "'",
1638
                                                e);
1639
                        }
1640

    
1641
                }
1642

    
1643
                return orderedMenus;
1644
        }
1645

    
1646
        private void installPluginsMenus() {
1647
                logger.info("installPluginsMenus");
1648

    
1649
                TreeSet<SortableMenu> orderedMenus = getOrderedMenus();
1650

    
1651
                // Se itera por los menus ordenados
1652
                Iterator<SortableMenu> e = orderedMenus.iterator();
1653

    
1654
                // Se ordenan los menues
1655
                while (e.hasNext()) {
1656
                        try {
1657
                                SortableMenu sm = e.next();
1658

    
1659
                                logger.debug(sm.menu.getPosition()+":"+sm.menu.getText()+":"+sm.loader.getPluginName()+":"+sm.extension.getClassName());
1660
                                
1661
                                frame.addMenu(sm.loader, sm.extension, sm.menu);
1662

    
1663
                        } catch (ClassNotFoundException ex) {
1664
                                this
1665
                                                .addError(
1666
                                                                Messages
1667
                                                                                .getString("Launcher.No_se_encontro_la_clase_de_la_extension"),
1668
                                                                ex);
1669
                        } catch (NoClassDefFoundError ex) {
1670
                                this
1671
                                                .addError(
1672
                                                                Messages
1673
                                                                                .getString("Launcher.No_se_encontro_la_clase_de_la_extension"),
1674
                                                                ex);
1675
                        } catch (Throwable ex) {
1676
                                this
1677
                                                .addError(
1678
                                                                Messages
1679
                                                                                .getString("Launcher.No_se_encontro_la_clase_de_la_extension"),
1680
                                                                ex);
1681
                        }
1682
                }
1683
        }
1684

    
1685
        public class PluginMenuItem {
1686
                private Menu menu;
1687
                private PluginClassLoader loader;
1688
                private SkinExtensionType extension;
1689

    
1690
                PluginMenuItem(PluginClassLoader loader,
1691
                                SkinExtensionType extension, Menu menu) {
1692
                        this.menu = menu;
1693
                        this.loader = loader;
1694
                        this.extension = extension;
1695
                }
1696
                
1697
                public PluginServices getPlugin() {
1698
                        String pluginName = loader.getPluginName();
1699
                        return PluginServices.getPluginServices(pluginName);
1700
                }
1701
                
1702
                public String getExtensionName() {
1703
                        return this.extension.getClassName();
1704
                }
1705
                
1706
                public IExtension getExtension() {
1707
                        Class<?> extensionClass;
1708
                        try {
1709
                                extensionClass = loader.loadClass(this.extension.getClassName());
1710
                        } catch (ClassNotFoundException e) {
1711
                                return null;
1712
                        }
1713
                        return PluginServices.getExtension(extensionClass);
1714
                }
1715
                
1716
                public String getText() {
1717
                        return this.menu.getText();
1718
                }
1719

    
1720
                public long getPosition() {
1721
                        return this.menu.getPosition();
1722
                }
1723
                
1724
                public String getName() {
1725
                        return this.menu.getName();
1726
                }
1727
                
1728
                public boolean isParent() {
1729
                        return menu.getIs_separator();
1730
                }
1731
                
1732
                public String getPluginName() {
1733
                        return this.loader.getPluginName();
1734
                }
1735
                
1736
                public ActionInfo getAction() {
1737
                        ActionInfoManager manager = PluginsLocator.getActionInfoManager();
1738
                        return manager.getAction(this.menu.getName());
1739
                }
1740
        }
1741
        
1742
        public List<PluginMenuItem> getPluginMenuItems() {
1743
                List<PluginMenuItem> menuItems = new ArrayList<Launcher.PluginMenuItem>();
1744

    
1745
                TreeSet<SortableMenu> orderedMenus = getOrderedMenus();
1746
                Iterator<SortableMenu> e = orderedMenus.iterator();
1747
                while (e.hasNext()) {
1748
                                SortableMenu sm = e.next();
1749
                                PluginMenuItem item = new PluginMenuItem(sm.loader, sm.extension, sm.menu);
1750
                                menuItems.add(item);
1751
                }
1752
                return menuItems;
1753
        }
1754

    
1755
        
1756
        /**
1757
         * Installs the menus, toolbars, actiontools, selectable toolbars and
1758
         * combos. The order in which they are shown is determined here.
1759
         */
1760
        private void installPluginsControls() {
1761
                logger.info("installPluginsControls (toolbars)");
1762

    
1763
                Iterator<String> i = pluginsConfig.keySet().iterator();
1764

    
1765
                Map<Extension, PluginServices> extensionPluginServices = new HashMap<Extension, PluginServices>();
1766
                Map<Extension, PluginConfig> extensionPluginConfig = new HashMap<Extension, PluginConfig>();
1767
                Set<Extension> orderedExtensions = new TreeSet<Extension>(
1768
                                new ExtensionComparator());
1769

    
1770
                // First of all, sort the extensions.
1771
                // We need to iterate on the plugins, and iterate on each plugin's
1772
                // extensions
1773
                // (each plugin may contain one or more extensions)
1774
                while (i.hasNext()) { // iterate on the plugins
1775
                        String pName = i.next();
1776
                        try {
1777
                                PluginConfig pc = pluginsConfig.get(pName);
1778
                                PluginServices ps = pluginsServices.get(pName);
1779

    
1780
                                Extension[] exts = pc.getExtensions().getExtension();
1781

    
1782
                                for (int j = 0; j < exts.length; j++) { // iterate on the
1783
                                        // extensions
1784
                                        String cname = "unknow";
1785
                                        try {
1786
                                                cname = exts[j].getClassName();
1787
                                                if (exts[j].getActive()
1788
                                                                && !cname.equals(LibraryExtension.class
1789
                                                                                .getName())) {
1790
                                                        if (orderedExtensions.contains(exts[j])) {
1791
                                                                this
1792
                                                                                .addError(Messages
1793
                                                                                                .getString("Launcher.Two_extensions_with_the_same_priority")
1794
                                                                                                + cname);
1795
                                                        }
1796

    
1797
                                                        orderedExtensions.add(exts[j]);
1798
                                                        extensionPluginServices.put(exts[j], ps);
1799
                                                        extensionPluginConfig.put(exts[j], pc);
1800
                                                }
1801
                                        } catch (Exception e) {
1802
                                                addError("Error initializing controls of plugin '"
1803
                                                                + pName + "' extension '" + cname + "'", e);
1804
                                        }
1805
                                }
1806
                        } catch (Throwable e) {
1807
                                addError("Error initializing controls of plugin '" + pName
1808
                                                + "'", e);
1809
                        }
1810
                }
1811

    
1812
                TreeSet<SortableTool> orderedTools = new TreeSet<SortableTool>(
1813
                                new ToolComparator());
1814
                Iterator<Extension> e = orderedExtensions.iterator();
1815

    
1816
                // sort the toolbars and tools from 'normal' extensions (actiontools,
1817
                // selectabletools)
1818
                // and load the combo-scales and combo-buttons for the status bar
1819
                while (e.hasNext()) {
1820
                        Extension ext = e.next();
1821
                        String extName = "unknow";
1822
                        try {
1823
                                extName = ext.getClassName();
1824
                                ToolBar[] toolbars = ext.getToolBar();
1825

    
1826
                                // get tools from toolbars
1827
                                for (int k = 0; k < toolbars.length; k++) {
1828
                                        ActionTool[] tools = toolbars[k].getActionTool();
1829

    
1830
                                        for (int t = 0; t < tools.length; t++) {
1831
                                                SortableTool sm = new SortableTool(
1832
                                                                (extensionPluginServices.get(ext))
1833
                                                                                .getClassLoader(), ext, toolbars[k],
1834
                                                                tools[t]);
1835
                                                orderedTools.add(sm);
1836
                                        }
1837

    
1838
                                        SelectableTool[] sTools = toolbars[k].getSelectableTool();
1839

    
1840
                                        for (int t = 0; t < sTools.length; t++) {
1841
                                                SortableTool sm = new SortableTool(
1842
                                                                (extensionPluginServices.get(ext))
1843
                                                                                .getClassLoader(), ext, toolbars[k],
1844
                                                                sTools[t]);
1845
                                                orderedTools.add(sm);
1846
                                        }
1847
                                }
1848

    
1849
                                // get controls for statusBar
1850
                                PluginServices ps = extensionPluginServices.get(ext);
1851
                                PluginClassLoader loader = ps.getClassLoader();
1852

    
1853
                                // ArrayList componentList = new ArrayList();
1854
                                ComboScale[] comboScaleArray = ext.getComboScale();
1855
                                for (int k = 0; k < comboScaleArray.length; k++) {
1856
                                        org.gvsig.gui.beans.controls.comboscale.ComboScale combo = new org.gvsig.gui.beans.controls.comboscale.ComboScale();
1857
                                        String label = comboScaleArray[k].getLabel();
1858
                                        if (label != null) {
1859
                                                combo.setLabel(label);
1860
                                        }
1861
                                        String name = comboScaleArray[k].getName();
1862
                                        if (name != null) {
1863
                                                combo.setName(name);
1864
                                        }
1865
                                        String[] elementsString = ((String) comboScaleArray[k]
1866
                                                        .getElements()).split(";");
1867
                                        long[] elements = new long[elementsString.length];
1868
                                        for (int currentElem = 0; currentElem < elementsString.length; currentElem++) {
1869
                                                try {
1870
                                                        elements[currentElem] = Long
1871
                                                                        .parseLong(elementsString[currentElem]);
1872
                                                } catch (NumberFormatException nfex1) {
1873
                                                        this
1874
                                                                        .addError(ext.getClassName()
1875
                                                                                        + " -- "
1876
                                                                                        + Messages
1877
                                                                                                        .getString("error_parsing_comboscale_elements"));
1878
                                                        elements[currentElem] = 0;
1879
                                                }
1880
                                        }
1881
                                        combo.setItems(elements);
1882
                                        try {
1883
                                                long value = Long.parseLong((String) comboScaleArray[k]
1884
                                                                .getValue());
1885
                                                combo.setScale(value);
1886
                                        } catch (NumberFormatException nfex2) {
1887
                                                this
1888
                                                                .addError(ext.getClassName()
1889
                                                                                + " -- "
1890
                                                                                + Messages
1891
                                                                                                .getString("error_parsing_comboscale_value"));
1892
                                        }
1893
                                        try {
1894
                                                frame.addStatusBarControl(loader.loadClass(ext
1895
                                                                .getClassName()), combo);
1896
                                        } catch (ClassNotFoundException e1) {
1897
                                                this
1898
                                                                .addError(
1899
                                                                                Messages
1900
                                                                                                .getString("Launcher.error_getting_class_loader_for_status_bar_control"),
1901
                                                                                e1);
1902
                                        }
1903
                                }
1904

    
1905
                                ComboButton[] comboButtonArray = ext.getComboButton();
1906
                                for (int k = 0; k < comboButtonArray.length; k++) {
1907
                                        ComboButtonElement[] elementList = comboButtonArray[k]
1908
                                                        .getComboButtonElement();
1909
                                        org.gvsig.gui.beans.controls.combobutton.ComboButton combo = new org.gvsig.gui.beans.controls.combobutton.ComboButton();
1910
                                        String name = comboButtonArray[k].getName();
1911
                                        if (name != null) {
1912
                                                combo.setName(name);
1913
                                        }
1914
                                        for (int currentElement = 0; currentElement < elementList.length; currentElement++) {
1915
                                                ComboButtonElement element = elementList[currentElement];
1916
                                                ImageIcon icon;
1917
                                                URL iconLocation = loader
1918
                                                                .getResource(element.getIcon());
1919
                                                if (iconLocation == null) {
1920
                                                        this.addError(Messages.getString("Icon_not_found_")
1921
                                                                        + element.getIcon());
1922
                                                } else {
1923
                                                        icon = new ImageIcon(iconLocation);
1924
                                                        JButton button = new JButton(icon);
1925
                                                        combo.addButton(button);
1926
                                                        button.setActionCommand(element.getActionCommand());
1927
                                                }
1928
                                        }
1929
                                        try {
1930
                                                frame.addStatusBarControl(loader.loadClass(ext
1931
                                                                .getClassName()), combo);
1932
                                        } catch (ClassNotFoundException e1) {
1933
                                                this
1934
                                                                .addError(
1935
                                                                                Messages
1936
                                                                                                .getString("Launcher.error_getting_class_loader_for_status_bar_control"),
1937
                                                                                e1);
1938
                                        }
1939
                                }
1940
                        } catch (Throwable e2) {
1941
                                addError(
1942
                                                "Error initializing tools and status bars of extension '"
1943
                                                                + extName + "'", e2);
1944
                        }
1945
                }
1946

    
1947
                // Add the tools from MDI extensions to the ordered tool-list, so that
1948
                // we get a sorted list containing all the tools
1949
                i = pluginsConfig.keySet().iterator();
1950
                while (i.hasNext()) {
1951
                        String pName = (String) i.next();
1952
                        try {
1953
                                PluginConfig pc = (PluginConfig) pluginsConfig.get(pName);
1954
                                PluginServices ps = (PluginServices) pluginsServices.get(pName);
1955

    
1956
                                SkinExtension[] skinExts = pc.getExtensions()
1957
                                                .getSkinExtension();
1958
                                for (int j = 0; j < skinExts.length; j++) {
1959

    
1960
                                        if (skinExts[j] != null) {
1961
                                                ToolBar[] toolbars = skinExts[j].getToolBar();
1962

    
1963
                                                for (int k = 0; k < toolbars.length; k++) {
1964
                                                        ActionTool[] tools = toolbars[k].getActionTool();
1965

    
1966
                                                        for (int t = 0; t < tools.length; t++) {
1967
                                                                SortableTool stb = new SortableTool(ps
1968
                                                                                .getClassLoader(), skinExts[j],
1969
                                                                                toolbars[k], tools[t]);
1970
                                                                orderedTools.add(stb);
1971
                                                        }
1972

    
1973
                                                        SelectableTool[] sTools = toolbars[k]
1974
                                                                        .getSelectableTool();
1975

    
1976
                                                        for (int t = 0; t < sTools.length; t++) {
1977
                                                                SortableTool stb = new SortableTool(ps
1978
                                                                                .getClassLoader(), skinExts[j],
1979
                                                                                toolbars[k], sTools[t]);
1980
                                                                orderedTools.add(stb);
1981
                                                        }
1982
                                                }
1983
                                        }
1984
                                }
1985
                                // Install popup menus
1986
                                PopupMenus pus = pc.getPopupMenus();
1987
                                if (pus != null) {
1988
                                        PopupMenu[] menus = pus.getPopupMenu();
1989
                                        for (int j = 0; j < menus.length; j++) {
1990
                                                String menuName = "(unknow)";
1991
                                                try  {
1992
                                                        menuName = menus[j].getName();
1993
                                                        frame.addPopupMenu(ps.getClassLoader(), menus[j]);
1994
                                                } catch(Throwable ex) {
1995
                                                        addError("Error adding popup menu' "+ menuName +"' in plugin '"+pName+"'.");
1996
                                                }
1997
                                        }
1998
                                }
1999
                        } catch (Throwable e3) {
2000
                                addError("Error initializing skins of the plugin '" + pName
2001
                                                + "'", e3);
2002
                        }
2003
                }
2004

    
2005
                // loop on the ordered extension list, to add them to the interface in
2006
                // an ordered way
2007
                Iterator<SortableTool> t = orderedTools.iterator();
2008
                while (t.hasNext()) {
2009
                        SortableTool stb = t.next();
2010
                        try {
2011
                                if (stb.actiontool != null) {
2012
                                        frame.addTool(stb.loader, stb.extension, stb.toolbar,
2013
                                                        stb.actiontool);
2014
                                } else {
2015
                                        frame.addTool(stb.loader, stb.extension, stb.toolbar,
2016
                                                        stb.selectabletool);
2017
                                }
2018
                        } catch (ClassNotFoundException ex) {
2019
                                this
2020
                                                .addError(
2021
                                                                Messages
2022
                                                                                .getString("Launcher.No_se_encontro_la_clase_de_la_extension"),
2023
                                                                ex);
2024
                        } catch (Throwable e2) {
2025
                                addError("Error adding tools to the interface of extension '"
2026
                                                + stb.extension.getClassName() + "'", e2);
2027
                        }
2028
                }
2029
        }
2030

    
2031
        /**
2032
         * Adds new plugins to the the andami-config file.
2033
         */
2034
        private void updateAndamiConfig() {
2035
                Set<String> olds = new HashSet<String>();
2036

    
2037
                Plugin[] plugins = andamiConfig.getPlugin();
2038

    
2039
                for (int i = 0; i < plugins.length; i++) {
2040
                        olds.add(plugins[i].getName());
2041
                }
2042

    
2043
                Iterator<PluginServices> i = pluginsServices.values().iterator();
2044

    
2045
                while (i.hasNext()) {
2046
                        PluginServices ps = i.next();
2047

    
2048
                        if (!olds.contains(ps.getPluginName())) {
2049
                                Plugin p = new Plugin();
2050
                                p.setName(ps.getPluginName());
2051
                                p.setUpdate(false);
2052

    
2053
                                andamiConfig.addPlugin(p);
2054
                        }
2055
                }
2056
        }
2057

    
2058
        private void pluginsClassLoaders() {
2059
                Set<String> installed = new HashSet<String>();
2060

    
2061
                // Se itera hasta que est?n todos instalados
2062
                while (installed.size() != pluginsConfig.size()) {
2063
                        boolean circle = true;
2064

    
2065
                        // Hacemos una pasada por todos los plugins
2066
                        Iterator<String> i = pluginsConfig.keySet().iterator();
2067

    
2068
                        while (i.hasNext()) {
2069
                                String pluginName = i.next();
2070
                                PluginConfig config = (PluginConfig) pluginsConfig
2071
                                                .get(pluginName);
2072

    
2073
                                if (installed.contains(pluginName)) {
2074
                                        continue;
2075
                                }
2076

    
2077
                                // Se obtienen las dependencias y sus class loaders
2078
                                boolean ready = true;
2079
                                Depends[] dependencies = config.getDepends();
2080
                                PluginClassLoader[] loaders = new PluginClassLoader[dependencies.length];
2081

    
2082
                                for (int j = 0; j < dependencies.length; j++) {
2083
                                        Depends dependency = dependencies[j];
2084
                                        String dependencyName = dependency.getPluginName();
2085
                                        PluginConfig dependencyPluginConfig = pluginsConfig.get(dependencyName);
2086
                                        PluginServices dependenyPluginService = pluginsServices.get(dependencyName);
2087
                                        
2088
                                        if ( dependencyPluginConfig == null) {
2089
                                                if( dependency.getOptional() ) {
2090
                                                        this.logger.info("Plugin '"+pluginName+"', optional dependency '"+dependencyName+"' not found");
2091
                                                } else {
2092
                                                        this.addError(Messages.getString("Launcher.Dependencia_no_resuelta_en_plugin")
2093
                                                                                + " "
2094
                                                                                + pluginName
2095
                                                                                + ": "
2096
                                                                                + dependencies[j].getPluginName());
2097
                                                }
2098
                                        } else {
2099
                                                if ( dependenyPluginService!=null && 
2100
                                                        installed.contains(dependenyPluginService.getPluginName())) {
2101
                                                        loaders[j] = (pluginsServices.get(dependencies[j]
2102
                                                                        .getPluginName())).getClassLoader();
2103
                                                } else {
2104
                                                        if( !dependency.getOptional() ) {
2105
                                                                ready = false;
2106
                                                        }
2107
                                                }
2108
                                        }
2109
                                }
2110

    
2111
                                // Si no est?n sus dependencias satisfechas se aborta la
2112
                                // instalaci?n
2113
                                if (!ready) {
2114
                                        continue;
2115
                                }
2116

    
2117
                                // Se genera el class loader
2118
                                String jardir = config.getLibraries().getLibraryDir();
2119
                                File jarDir = new File(andamiConfig.getPluginsDirectory(),
2120
                                                pluginName + File.separator + jardir);
2121
                                File[] jarFiles = jarDir.listFiles(new FileFilter() {
2122

    
2123
                                        public boolean accept(File pathname) {
2124
                                                return (pathname.getName().toUpperCase()
2125
                                                                .endsWith(".JAR"))
2126
                                                                || (pathname.getName().toUpperCase()
2127
                                                                                .endsWith(".ZIP"));
2128
                                        }
2129
                                });
2130
                                URL[] urls = null;
2131
                                if( jarFiles==null ) {
2132
                                        urls = new URL[0];
2133
                                } else {
2134
                                        urls = new URL[jarFiles.length];
2135
        
2136
                                        for (int j = 0; j < jarFiles.length; j++) {
2137
                                                try {
2138
                                                        urls[j] = new URL("file:" + jarFiles[j]);
2139
                                                } catch (MalformedURLException e) {
2140
                                                        this.addError(Messages
2141
                                                                        .getString("Launcher.No_se_puede_acceder_a")
2142
                                                                        + " " + jarFiles[j]);
2143
                                                }
2144
                                        }
2145
                                }
2146
                                
2147
                                PluginClassLoader loader;
2148

    
2149
                                try {
2150
                                        loader = new PluginClassLoader(urls, andamiConfig
2151
                                                        .getPluginsDirectory()
2152
                                                        + File.separator + pluginName, Launcher.class
2153
                                                        .getClassLoader(), loaders);
2154

    
2155
                                        PluginServices ps = new PluginServices(loader, PluginsConfig.getAlternativeNames(config));
2156

    
2157
                                        pluginsServices.put(ps.getPluginName(), ps);
2158

    
2159
                                        installed.add(pluginName);
2160
                                        // FJP: Los metemos ordenados para luego no cargar uno que
2161
                                        // necesita de otro antes de tiempo. Esto lo usaremos al
2162
                                        // inicializar los plugins
2163
                                        pluginsOrdered.add(pluginName);
2164

    
2165
                                        circle = false;
2166
                                } catch (IOException e) {
2167
                                        this
2168
                                                        .addError(
2169
                                                                        Messages
2170
                                                                                        .getString("Launcher.Error_con_las_librerias_del_plugin"),
2171
                                                                        e);
2172
                                        pluginsConfig.remove(pluginName);
2173
                                        i = pluginsConfig.keySet().iterator();
2174
                                }
2175
                        }
2176

    
2177
                        if (circle) {
2178
                                dumpPluginsDependencyInformation();
2179
                                this.addError("Has circular dependencies betewn plugins");
2180
                                break;
2181
                        }
2182
                }
2183

    
2184
                // Se eliminan los plugins que no fueron instalados
2185
                Iterator<String> i = pluginsConfig.keySet().iterator();
2186

    
2187
                while (i.hasNext()) {
2188
                        String pluginName = i.next();
2189
                        PluginServices ps = (PluginServices) pluginsServices
2190
                                        .get(pluginName);
2191

    
2192
                        if (ps == null) {
2193
                                pluginsConfig.remove(pluginName);
2194
                                i = pluginsConfig.keySet().iterator();
2195
                        }
2196
                }
2197
                registerActions();
2198
        }
2199

    
2200
        private void dumpPluginsDependencyInformation() {
2201
                logger.info("Plugin dependency information");
2202
                Iterator<String> i = pluginsConfig.keySet().iterator();
2203
                while (i.hasNext()) {
2204
                        String pluginName = i.next();
2205
                        PluginConfig config = (PluginConfig) pluginsConfig.get(pluginName);
2206
                        logger.info("  Plugin "+ pluginName);
2207
                        Depends[] dependencies = config.getDepends();
2208
                        for (int j = 0; j < dependencies.length; j++) {
2209
                                Depends dependency = dependencies[j];
2210
                                String dependencyName = dependency.getPluginName();
2211
                                logger.info("    Dependency "+ dependencyName);
2212
                        }
2213
                }
2214
        }
2215
        
2216
        private void pluginsMessages() {
2217
                Iterator<String> iterator = pluginsOrdered.iterator();
2218
                PluginConfig config;
2219
                PluginServices ps;
2220

    
2221
                while (iterator.hasNext()) {
2222
                        String pluginName = iterator.next();
2223
                        config = pluginsConfig.get(pluginName);
2224
                        ps = pluginsServices.get(pluginName);
2225

    
2226
                        if ((config.getResourceBundle() != null)
2227
                                        && !config.getResourceBundle().getName().equals("")) {
2228
                                // add the locale files associated with the plugin
2229
                                org.gvsig.i18n.Messages.addResourceFamily(config
2230
                                                .getResourceBundle().getName(), ps.getClassLoader(),
2231
                                                pluginName);
2232
                                org.gvsig.i18n.Messages.addResourceFamily("i18n."+config
2233
                                                .getResourceBundle().getName(), ps.getClassLoader(),
2234
                                                pluginName);
2235
                        }
2236
                }
2237
        }
2238

    
2239
        static public PluginServices getPluginServices(String name) {
2240
                return (PluginServices) pluginsServices.get(name);
2241
        }
2242

    
2243
        static String getPluginsDir() {
2244
                return andamiConfig.getPluginsDirectory();
2245
        }
2246

    
2247
        static void setPluginsDir(String s) {
2248
                andamiConfig.setPluginsDirectory(s);
2249
        }
2250

    
2251
        static MDIFrame getMDIFrame() {
2252
                return frame;
2253
        }
2254

    
2255
        private void loadPlugins(String pluginsDirectory) {
2256
                File pDir = new File(pluginsDirectory);
2257

    
2258
                if (!pDir.exists()) {
2259
                        logger
2260
                                        .error("\n\tPlugins directory not found: "
2261
                                                        + pDir.getAbsolutePath()
2262
                                                        + "\n\tDid you specify the correct directory in the Launch Configuration parameters?\n\tExiting now...");
2263
                        System.exit(-1);
2264
                        return;
2265
                }
2266

    
2267
                File[] pluginDirs = pDir.listFiles();
2268
                if (pluginDirs.length == 0) {
2269
                        logger
2270
                                        .error("\n\tPlugins directory is empty: "
2271
                                                        + pDir.getAbsolutePath()
2272
                                                        + "Did you specify the correct directory in the Launch Configuration parameters?\n\tExiting now...");
2273
                        System.exit(-1);
2274
                        return;
2275
                }
2276

    
2277
                for (int i = 0; i < pluginDirs.length; i++) {
2278
                        if (pluginDirs[i].isDirectory()) {
2279
                                String pluginName =  pluginDirs[i].getName();
2280
                                File configXml = new File(pluginDirs[i].getAbsolutePath(),
2281
                                                "config.xml");
2282

    
2283
                                try {
2284
                                        FileInputStream is = new FileInputStream(configXml);
2285
                                        Reader xml = org.gvsig.utils.xml.XMLEncodingUtils.getReader(is);
2286
                                        if (xml == null) {
2287
                                                // the encoding was not correctly detected, use system
2288
                                                // default
2289
                                                xml = new FileReader(configXml);
2290
                                        } else {
2291
                                                // use a buffered reader to improve performance
2292
                                                xml = new BufferedReader(xml);
2293
                                        }
2294
                                        PluginConfig pConfig = (PluginConfig) PluginConfig.unmarshal(xml);
2295
                                        pluginsConfig.put(pluginDirs[i].getName(), pConfig);
2296
                                } catch (FileNotFoundException e) {
2297
                                        logger.info("Plugin '"+pluginName+"' without config.xml ("
2298
                                                                        + pluginDirs[i].getAbsolutePath() + ").");
2299
                                } catch (MarshalException e) {
2300
                                        this.addError("Can't load plugin '"+pluginName+"', incorrect config.xml." + e.getMessage() +" ("
2301
                                                        + pluginDirs[i].getAbsolutePath() + ").", e);
2302
                                } catch (ValidationException e) {
2303
                                        this.addError("Can't load plugin '"+pluginName+"', invalid config.xml." + e.getMessage() +" ("
2304
                                                        + pluginDirs[i].getAbsolutePath() + ").", e);
2305
                                }
2306
                        }
2307
                }
2308

    
2309
                if (pluginsConfig.size() == 0) {
2310
                        logger.error("No valid plugin was found. The plugins directory currently is: "
2311
                                                        + pDir.getAbsolutePath()
2312
                                                        + "\n\tDid you specify the correct directory in the Launch Configuration parameters?\n\tExiting now...");
2313
                        System.exit(-1);
2314
                        return;
2315
                }
2316
        }
2317

    
2318
        private static Locale getLocale(String language, String country,
2319
                        String variant) {
2320
                if (variant != null) {
2321
                        return new Locale(language, country, variant);
2322
                } else if (country != null) {
2323
                        return new Locale(language, country);
2324
                } else if (language != null) {
2325
                        return new Locale(language);
2326
                } else {
2327
                        return new Locale("es");
2328
                }
2329
        }
2330

    
2331
        private static void andamiConfigToXML(String file) throws IOException,
2332
                        MarshalException, ValidationException {
2333
                // write on a temporary file in order to not destroy current file if
2334
                // there is some problem while marshaling
2335
                File tmpFile = new File(file + "-"
2336
                                + DateTime.getCurrentDate().getTime());
2337
                File xml = new File(file);
2338
                File parent = xml.getParentFile();
2339
                parent.mkdirs();
2340

    
2341
                BufferedOutputStream os = new BufferedOutputStream(
2342
                                new FileOutputStream(tmpFile));
2343
                OutputStreamWriter writer = new OutputStreamWriter(os, CASTORENCODING);
2344
                andamiConfig.marshal(writer);
2345
                writer.close();
2346

    
2347
                // if marshaling process finished correctly, move the file to the
2348
                // correct one
2349
                xml.delete();
2350
                if (!tmpFile.renameTo(xml)) {
2351
                        // if rename was not succesful, try copying it
2352
                        FileChannel sourceChannel = new FileInputStream(tmpFile)
2353
                                        .getChannel();
2354
                        FileChannel destinationChannel = new FileOutputStream(xml)
2355
                                        .getChannel();
2356
                        sourceChannel.transferTo(0, sourceChannel.size(),
2357
                                        destinationChannel);
2358
                        sourceChannel.close();
2359
                        destinationChannel.close();
2360
                }
2361
        }
2362

    
2363
        private static void andamiConfigFromXML(String file)
2364
                        throws ConfigurationException {
2365
                File xml = new File(file);
2366

    
2367
                InputStreamReader reader = null;
2368
                try {
2369
                        // Se lee la configuraci?n
2370
                        reader = XMLEncodingUtils.getReader(xml);
2371
                        andamiConfig = (AndamiConfig) AndamiConfig.unmarshal(reader);
2372
                } catch (FileNotFoundException e) {
2373
                        // Si no existe se ponen los valores por defecto
2374
                        andamiConfig = getDefaultAndamiConfig();
2375
                } catch (MarshalException e) {
2376
                        // try to close the stream, maybe it remains open
2377
                        if (reader != null) {
2378
                                try {
2379
                                        reader.close();
2380
                                } catch (IOException e1) {
2381
                                }
2382
                        }
2383
                        // if there was a problem reading the file, backup it and create a
2384
                        // new one with default values
2385
                        String backupFile = file + "-"
2386
                                        + DateTime.getCurrentDate().getTime();
2387
                        NotificationManager
2388
                                        .addError(
2389
                                                        Messages
2390
                                                                        .getString("Error_reading_andami_config_New_file_created_A_backup_was_made_on_")
2391
                                                                        + backupFile, new ConfigurationException(e));
2392
                        xml.renameTo(new File(backupFile));
2393
                        andamiConfig = getDefaultAndamiConfig();
2394
                } catch (ValidationException e) {
2395
                        throw new ConfigurationException(e);
2396
                }
2397
        }
2398

    
2399
        private static AndamiConfig getDefaultAndamiConfig() {
2400
                AndamiConfig andamiConfig = new AndamiConfig();
2401

    
2402
                Andami andami = new Andami();
2403
                andami.setUpdate(true);
2404
                andamiConfig.setAndami(andami);
2405
                andamiConfig.setLocaleCountry(Locale.getDefault().getCountry());
2406
                andamiConfig.setLocaleLanguage(Locale.getDefault().getLanguage());
2407
                andamiConfig.setLocaleVariant(Locale.getDefault().getVariant());
2408

    
2409
                if (System.getProperty("javawebstart.version") != null) // Es java web
2410
                // start)
2411
                {
2412
                        andamiConfig
2413
                                        .setPluginsDirectory(new File(appHomeDir, "extensiones")
2414
                                                        .getAbsolutePath());
2415
                } else {
2416
                        andamiConfig.setPluginsDirectory(new File(appName, "extensiones")
2417
                                        .getAbsolutePath());
2418
                }
2419

    
2420
                andamiConfig.setPlugin(new Plugin[0]);
2421
                return andamiConfig;
2422
        }
2423

    
2424
        private static XMLEntity persistenceFromXML() throws ConfigurationException {
2425
                File xml = getPluginsPersistenceFile(true);
2426

    
2427
                if (xml.exists()) {
2428
                        InputStreamReader reader = null;
2429

    
2430
                        try {
2431
                                reader = XMLEncodingUtils.getReader(xml);
2432
                                XmlTag tag = (XmlTag) XmlTag.unmarshal(reader);
2433
                                return new XMLEntity(tag);
2434
                        } catch (FileNotFoundException e) {
2435
                                throw new ConfigurationException(e);
2436
                        } catch (MarshalException e) {
2437

    
2438
                                // try to reopen with default encoding (for backward
2439
                                // compatibility)
2440
                                try {
2441
                                        reader = new FileReader(xml);
2442
                                        XmlTag tag = (XmlTag) XmlTag.unmarshal(reader);
2443
                                        return new XMLEntity(tag);
2444

    
2445
                                } catch (MarshalException ex) {
2446
                                        // try to close the stream, maybe it remains open
2447
                                        if (reader != null) {
2448
                                                try {
2449
                                                        reader.close();
2450
                                                } catch (IOException e1) {
2451
                                                }
2452
                                        }
2453
                                        // backup the old file
2454
                                        String backupFile = getPluginsPersistenceFile(true)
2455
                                                        .getPath()
2456
                                                        + "-" + DateTime.getCurrentDate().getTime();
2457
                                        NotificationManager
2458
                                                        .addError(
2459
                                                                        Messages
2460
                                                                                        .getString("Error_reading_plugin_persinstence_New_file_created_A_backup_was_made_on_")
2461
                                                                                        + backupFile,
2462
                                                                        new ConfigurationException(e));
2463
                                        xml.renameTo(new File(backupFile));
2464
                                        // create a new, empty configuration
2465
                                        return new XMLEntity();
2466
                                } catch (FileNotFoundException ex) {
2467
                                        return new XMLEntity();
2468
                                } catch (ValidationException ex) {
2469
                                        throw new ConfigurationException(e);
2470
                                }
2471
                        } catch (ValidationException e) {
2472
                                throw new ConfigurationException(e);
2473
                        }
2474
                } else {
2475
                        return new XMLEntity();
2476
                }
2477
        }
2478

    
2479
        private static File getPluginsPersistenceFile(boolean read) {
2480
                if (read) {
2481
                        File pluginsPersistenceFile = new File(getAppHomeDir(),
2482
                                        "plugins-persistence-2_0.xml");
2483
                        if (pluginsPersistenceFile.exists()) {
2484
                                return pluginsPersistenceFile;
2485
                        }
2486
                        pluginsPersistenceFile = new File(getAppHomeDir(),
2487
                                        "plugins-persistence.xml");
2488
                        if (pluginsPersistenceFile.exists()) {
2489
                                return pluginsPersistenceFile;
2490
                        }
2491
                }
2492
                return new File(getAppHomeDir(), "plugins-persistence-2_0.xml");
2493

    
2494
        }
2495

    
2496
        private static void persistenceToXML(XMLEntity entity)
2497
                        throws ConfigurationException {
2498
                // write on a temporary file in order to not destroy current file if
2499
                // there is some problem while marshaling
2500
                File tmpFile = new File(getPluginsPersistenceFile(false).getPath()
2501
                                + "-" + DateTime.getCurrentDate().getTime());
2502

    
2503
                File xml = getPluginsPersistenceFile(false);
2504
                OutputStreamWriter writer = null;
2505

    
2506
                try {
2507
                        writer = new OutputStreamWriter(new FileOutputStream(tmpFile),
2508
                                        CASTORENCODING);
2509
                        entity.getXmlTag().marshal(writer);
2510
                        writer.close();
2511

    
2512
                        // if marshaling process finished correctly, move the file to the
2513
                        // correct one
2514
                        xml.delete();
2515
                        if (!tmpFile.renameTo(xml)) {
2516
                                // if rename was not succesful, try copying it
2517
                                FileChannel sourceChannel = new FileInputStream(tmpFile)
2518
                                                .getChannel();
2519
                                FileChannel destinationChannel = new FileOutputStream(xml)
2520
                                                .getChannel();
2521
                                sourceChannel.transferTo(0, sourceChannel.size(),
2522
                                                destinationChannel);
2523
                                sourceChannel.close();
2524
                                destinationChannel.close();
2525

    
2526
                        }
2527
                } catch (FileNotFoundException e) {
2528
                        throw new ConfigurationException(e);
2529
                } catch (MarshalException e) {
2530
                        // try to close the stream, maybe it remains open
2531
                        if (writer != null) {
2532
                                try {
2533
                                        writer.close();
2534
                                } catch (IOException e1) {
2535
                                }
2536
                        }
2537
                } catch (ValidationException e) {
2538
                        throw new ConfigurationException(e);
2539
                } catch (IOException e) {
2540
                        throw new ConfigurationException(e);
2541
                }
2542
        }
2543

    
2544
        static MDIFrame getFrame() {
2545
                return frame;
2546
        }
2547

    
2548
        /**
2549
         * Gracefully closes the application. It shows dialogs to save data, finish
2550
         * processes, etc, then it terminates the extensions, removes temporal files
2551
         * and finally exits.
2552
         */
2553
        public synchronized static void closeApplication() {
2554
                TerminationProcess terminationProcess = (new Launcher()).new TerminationProcess();
2555
                terminationProcess.run();
2556
        }
2557

    
2558
        static HashMap getClassesExtensions() {
2559
                return classesExtensions;
2560
        }
2561

    
2562
        private static Extensions[] getExtensions() {
2563
                List<Extensions> array = new ArrayList<Extensions>();
2564
                Iterator<PluginConfig> iter = pluginsConfig.values().iterator();
2565

    
2566
                while (iter.hasNext()) {
2567
                        array.add(iter.next().getExtensions());
2568
                }
2569

    
2570
                return array.toArray(new Extensions[array.size()]);
2571
        }
2572

    
2573
        public static Iterator getExtensionIterator() {
2574
                return extensions.iterator();
2575
        }
2576

    
2577
        public static HashMap getPluginConfig() {
2578
                return pluginsConfig;
2579
        }
2580

    
2581
        public static Extension getExtension(String s) {
2582
                Extensions[] exts = getExtensions();
2583

    
2584
                for (int i = 0; i < exts.length; i++) {
2585
                        for (int j = 0; j < exts[i].getExtensionCount(); j++) {
2586
                                if (exts[i].getExtension(j).getClassName().equals(s)) {
2587
                                        return exts[i].getExtension(j);
2588
                                }
2589
                        }
2590
                }
2591

    
2592
                return null;
2593
        }
2594

    
2595
        public static AndamiConfig getAndamiConfig() {
2596
                return andamiConfig;
2597
        }
2598

    
2599
        private static class ExtensionComparator implements Comparator {
2600

    
2601
                public int compare(Object o1, Object o2) {
2602
                        Extension e1 = (Extension) o1;
2603
                        Extension e2 = (Extension) o2;
2604

    
2605
                        if (!e1.hasPriority() && !e2.hasPriority()) {
2606
                                return -1;
2607
                        }
2608

    
2609
                        if (e1.hasPriority() && !e2.hasPriority()) {
2610
                                return Integer.MIN_VALUE;
2611
                        }
2612

    
2613
                        if (e2.hasPriority() && !e1.hasPriority()) {
2614
                                return Integer.MAX_VALUE;
2615
                        }
2616

    
2617
                        if (e1.getPriority() != e2.getPriority()) {
2618
                                return e2.getPriority() - e1.getPriority();
2619
                        } else {
2620
                                return (e2.toString().compareTo(e1.toString()));
2621
                        }
2622
                }
2623
        }
2624

    
2625
        private static class MenuComparator implements Comparator<SortableMenu> {
2626

    
2627
                private static ExtensionComparator extComp = new ExtensionComparator();
2628

    
2629
                public int compare(SortableMenu e1, SortableMenu e2) {
2630

    
2631
                        if (!e1.menu.hasPosition() && !e2.menu.hasPosition()) {
2632
                                if (e1.extension instanceof SkinExtensionType) {
2633
                                        return 1;
2634
                                } else if (e2.extension instanceof SkinExtensionType) {
2635
                                        return -1;
2636
                                } else {
2637
                                        return extComp.compare(e1.extension, e2.extension);
2638
                                }
2639
                        }
2640

    
2641
                        if (e1.menu.hasPosition() && !e2.menu.hasPosition()) {
2642
                                return Integer.MIN_VALUE;
2643
                        }
2644

    
2645
                        if (e2.menu.hasPosition() && !e1.menu.hasPosition()) {
2646
                                return Integer.MAX_VALUE;
2647
                        }
2648
                        
2649
                        if( e1.menu.getPosition() == e2.menu.getPosition() ) {
2650
                                // we don't return 0 unless both objects are the same, otherwise
2651
                                // the objects get overwritten in the treemap
2652
                                return (e1.toString().compareTo(e2.toString()));
2653
                        }
2654
                    if( e1.menu.getPosition() > e2.menu.getPosition() ) {
2655
                                return Integer.MAX_VALUE;
2656
                        }
2657
                    return Integer.MIN_VALUE;
2658
                    
2659
                }
2660
        }
2661

    
2662
        private static class SortableMenu {
2663

    
2664
                public PluginClassLoader loader;
2665
                public Menu menu;
2666
                public SkinExtensionType extension;
2667

    
2668
                public SortableMenu(PluginClassLoader loader,
2669
                                SkinExtensionType skinExt, Menu menu2) {
2670
                        extension = skinExt;
2671
                        menu = menu2;
2672
                        this.loader = loader;
2673
                }
2674
                
2675
        }
2676

    
2677
        private static class SortableTool {
2678

    
2679
                public PluginClassLoader loader;
2680
                public ToolBar toolbar;
2681
                public ActionTool actiontool;
2682
                public SelectableTool selectabletool;
2683
                public SkinExtensionType extension;
2684

    
2685
                public SortableTool(PluginClassLoader loader,
2686
                                SkinExtensionType skinExt, ToolBar toolbar2,
2687
                                ActionTool actiontool2) {
2688
                        extension = skinExt;
2689
                        toolbar = toolbar2;
2690
                        actiontool = actiontool2;
2691
                        this.loader = loader;
2692
                }
2693

    
2694
                public SortableTool(PluginClassLoader loader,
2695
                                SkinExtensionType skinExt, ToolBar toolbar2,
2696
                                SelectableTool selectabletool2) {
2697
                        extension = skinExt;
2698
                        toolbar = toolbar2;
2699
                        selectabletool = selectabletool2;
2700
                        this.loader = loader;
2701
                }
2702
        }
2703

    
2704
        private static class ToolBarComparator implements Comparator<SortableTool> {
2705

    
2706
                private static ExtensionComparator extComp = new ExtensionComparator();
2707

    
2708
                public int compare(SortableTool e1, SortableTool e2) {
2709

    
2710
                        // if the toolbars have the same name, they are considered to be
2711
                        // the same toolbar, so we don't need to do further comparing
2712
                        if (e1.toolbar.getName().equals(e2.toolbar.getName())) {
2713
                                return 0;
2714
                        }
2715

    
2716
                        if (!e1.toolbar.hasPosition() && !e2.toolbar.hasPosition()) {
2717
                                if (e1.extension instanceof SkinExtensionType) {
2718
                                        return 1;
2719
                                } else if (e2.extension instanceof SkinExtensionType) {
2720
                                        return -1;
2721
                                } else {
2722
                                        return extComp.compare(e1.extension, e2.extension);
2723
                                }
2724
                        }
2725

    
2726
                        if (e1.toolbar.hasPosition() && !e2.toolbar.hasPosition()) {
2727
                                return Integer.MIN_VALUE;
2728
                        }
2729

    
2730
                        if (e2.toolbar.hasPosition() && !e1.toolbar.hasPosition()) {
2731
                                return Integer.MAX_VALUE;
2732
                        }
2733
                        if (e1.toolbar.getPosition() != e2.toolbar.getPosition()) {
2734
                                return e1.toolbar.getPosition() - e2.toolbar.getPosition();
2735
                        }
2736

    
2737
                        if (e1.toolbar.getActionTool().equals(e2.toolbar.getActionTool())
2738
                                        && e1.toolbar.getSelectableTool().equals(
2739
                                                        e2.toolbar.getSelectableTool())) {
2740
                                return 0;
2741
                        }
2742
                        return (e1.toolbar.toString().compareTo(e2.toolbar.toString()));
2743
                }
2744
        }
2745

    
2746
        /**
2747
         * <p>
2748
         * This class is used to compare tools (selectabletool and actiontool),
2749
         * using the "position" attribute.
2750
         * </p>
2751
         * <p>
2752
         * The ordering criteria are:
2753
         * </p>
2754
         * <ul>
2755
         * <li>If the tools are placed in different toolbars, they use the toolbars'
2756
         * order. (using the ToolBarComparator).</li>
2757
         * <li></li>
2758
         * <li>If any of the tools has not 'position' attribute, the tool which
2759
         * <strong>has</strong> the attribute will be placed first.</li>
2760
         * <li>If both tools have the same position (or they don't have a 'position'
2761
         * attribute), the priority of the extensions where the tool is defined.</li>
2762
         * </ul>
2763
         * 
2764
         * @author cesar
2765
         * @version $Revision: 40305 $
2766
         */
2767
        private static class ToolComparator implements Comparator<SortableTool> {
2768

    
2769
                private static ToolBarComparator toolBarComp = new ToolBarComparator();
2770

    
2771
                public int compare(SortableTool e1, SortableTool e2) {
2772
                        // compare the toolbars which contain the tools
2773
                        long result = toolBarComp.compare(e1, e2);
2774
                        if (result != 0) { // if the toolbars are different, use their order
2775
                                return result>0? 1:-1;
2776
                        }
2777
                        // otherwise, compare the tools
2778
                        long e1Position = -1, e2Position = -1;
2779

    
2780
                        if (e1.actiontool != null) {
2781
                                if (e1.actiontool.hasPosition()) {
2782
                                        e1Position = e1.actiontool.getPosition();
2783
                                }
2784
                        } else if (e1.selectabletool != null) {
2785
                                if (e1.selectabletool.hasPosition()) {
2786
                                        e1Position = e1.selectabletool.getPosition();
2787
                                }
2788
                        }
2789

    
2790
                        if (e2.actiontool != null) {
2791
                                if (e2.actiontool.hasPosition()) {
2792
                                        e2Position = e2.actiontool.getPosition();
2793
                                }
2794
                        } else if (e2.selectabletool != null) {
2795
                                if (e2.selectabletool.hasPosition()) {
2796
                                        e2Position = e2.selectabletool.getPosition();
2797
                                }
2798
                        }
2799

    
2800
                        if ((e1Position == -1) && (e2Position != -1)) {
2801
                                return 1;
2802
                        }
2803
                        if ((e1Position != -1) && (e2Position == -1)) {
2804
                                return -1;
2805
                        }
2806
                        if ((e1Position != -1) && (e2Position != -1)) {
2807
                                result = e1Position - e2Position;
2808
                                // we don't return 0 unless both objects are the same, otherwise
2809
                                // the objects get overwritten in the treemap
2810
                                if (result != 0) {
2811
                                        return  result>0? 1:-1;
2812
                                }
2813
                        }
2814
                        return e1.toString().compareTo(e2.toString());
2815
                }
2816
        }
2817

    
2818
        /**
2819
         * validates the user before starting gvsig
2820
         * 
2821
         */
2822
        private static void validate() {
2823

    
2824
                IAuthentication session = null;
2825
                try {
2826
                        session = (IAuthentication) Class.forName(
2827
                                        "com.iver.andami.authentication.Session").newInstance();
2828

    
2829
                } catch (ClassNotFoundException e) {
2830
                        return;
2831
                } catch (InstantiationException e) {
2832
                        return;
2833
                } catch (IllegalAccessException e) {
2834
                        return;
2835
                }
2836

    
2837
                session.setPluginDirectory(andamiConfig.getPluginsDirectory());
2838
                if (session.validationRequired()) {
2839
                        if (session.Login()) {
2840
                                logger.info("You are logged in");
2841
                        } else {
2842
                                JOptionPane.showMessageDialog((Component) PluginServices
2843
                                                .getMainFrame(), "You are not logged in");
2844
                        }
2845
                        PluginServices.setAuthentication(session);
2846
                }
2847
        }
2848

    
2849
        public static String getDefaultLookAndFeel() {
2850
                String osName = (String) System.getProperty("os.name");
2851

    
2852
                if ((osName.length() > 4)
2853
                                && osName.substring(0, 5).toLowerCase().equals("linux")) {
2854
                        return nonWinDefaultLookAndFeel;
2855
                }
2856
                if (osName.toLowerCase().startsWith("mac os x")) {
2857
                        return "ch.randelshofer.quaqua.QuaquaLookAndFeel";
2858
                }
2859

    
2860
                return UIManager.getSystemLookAndFeelClassName();
2861
        }
2862

    
2863
        /**
2864
         * Gets the ISO 839 two-characters-long language code matching the provided
2865
         * language code (which may be an ISO 839-2/T three-characters-long code or
2866
         * an ISO 839-1 two-characters-long code).
2867
         * 
2868
         * If the provided parameter is already two characters long, it returns the
2869
         * parameter without any modification.
2870
         * 
2871
         * @param langCode
2872
         *            A language code representing either an ISO 839-2/T language
2873
         *            code or an ISO 839-1 code.
2874
         * @return A two-characters-long code specifying an ISO 839 language code.
2875
         */
2876
        private static String normalizeLanguageCode(String langCode) {
2877
                final String fileName = "iso_639.tab";
2878
                if (langCode.length() == 2) {
2879
                        return langCode;
2880
                } else if (langCode.length() == 3) {
2881
                        if (langCode.equals("va") || langCode.equals("val")) { // special
2882
                                // case
2883
                                // for
2884
                                // Valencian
2885
                                return "ca";
2886
                        }
2887
                        URL isoCodes = Launcher.class.getClassLoader()
2888
                                        .getResource(fileName);
2889
                        if (isoCodes != null) {
2890
                                try {
2891
                                        BufferedReader reader = new BufferedReader(
2892
                                                        new InputStreamReader(isoCodes.openStream(),
2893
                                                                        "ISO-8859-1"));
2894
                                        String line;
2895

    
2896
                                        while ((line = reader.readLine()) != null) {
2897
                                                String[] language = line.split("\t");
2898
                                                if (language[0].equals(langCode)) {
2899
                                                        // the three
2900
                                                        // characters code
2901
                                                        return language[2]; // third column i the two
2902
                                                        // characters code
2903
                                                }
2904
                                        }
2905
                                } catch (IOException ex) {
2906
                                        logger.error(Messages
2907
                                                        .getString("Error_reading_isocodes_file"), ex);
2908
                                        return "es";
2909
                                }
2910
                        } else {
2911
                                logger.error(Messages.getString("Error_reading_isocodes_file"));
2912
                                return "es";
2913
                        }
2914
                }
2915
                return "es";
2916
        }
2917

    
2918
        /**
2919
         * Configures the locales (languages and local resources) to be used by the
2920
         * application.
2921
         * 
2922
         * First it tries to get the locale from the command line parameters, then
2923
         * the andami-config file is checked.
2924
         * 
2925
         * The locale name is normalized to get a two characters language code as
2926
         * defined by ISO-639-1 (although ISO-639-2/T three characters codes are
2927
         * also accepted from the command line or the configuration file).
2928
         * 
2929
         * Finally, the gvsig-i18n library and the default locales for Java and
2930
         * Swing are configured.
2931
         * 
2932
         */
2933
        private static void configureLocales(String[] args) {
2934
                // Configurar el locale
2935
                String localeStr = null;
2936
                /*
2937
                 * for (int i=2; i < args.length; i++) { int index =
2938
                 * args[i].indexOf("language="); if (index != -1) localeStr =
2939
                 * args[i].substring(index+9); }
2940
                 */
2941
                localeStr = PluginServices.getArgumentByName("language");
2942
                if (localeStr == null) {
2943
                        localeStr = andamiConfig.getLocaleLanguage();
2944
                }
2945
                localeStr = normalizeLanguageCode(localeStr);
2946
                locale = getLocale(localeStr, andamiConfig.getLocaleCountry(),
2947
                                andamiConfig.getLocaleVariant());
2948
                Locale.setDefault(locale);
2949
                JComponent.setDefaultLocale(locale);
2950
                org.gvsig.i18n.Messages.addLocale(locale);
2951
                // add english and spanish as fallback languages
2952
                if (localeStr.equals("es") || localeStr.equals("ca")
2953
                                || localeStr.equals("gl") || localeStr.equals("eu")
2954
                                || localeStr.equals("va")) {
2955
                        // prefer Spanish for languages spoken in Spain
2956
                        org.gvsig.i18n.Messages.addLocale(new Locale("es"));
2957
                        org.gvsig.i18n.Messages.addLocale(new Locale("en"));
2958
                } else {
2959
                        // prefer English for the rest
2960
                        org.gvsig.i18n.Messages.addLocale(new Locale("en"));
2961
                        org.gvsig.i18n.Messages.addLocale(new Locale("es"));
2962
                }
2963

    
2964
        // Create classloader for the i18n resources in the
2965
        // andami and user i18n folder. Those values will have
2966
        // precedence over any other values added afterwards
2967
        File andamiI18nFolder =
2968
            new File(System.getProperty("user.dir"), "i18n");
2969
        File userI18nFolder = new File(getAppHomeDir(), "i18n");
2970

    
2971
        logger.info("Loading i18n resources from the application and user "
2972
            + "folders: {}, {}", andamiI18nFolder, userI18nFolder);
2973

    
2974
        URL[] i18nURLs;
2975
        try {
2976
            i18nURLs =
2977
                new URL[] { userI18nFolder.toURI().toURL(),
2978
                    andamiI18nFolder.toURI().toURL() };
2979
            ClassLoader i18nClassLoader = new URLClassLoader(i18nURLs);
2980
            org.gvsig.i18n.Messages.addResourceFamily("text", i18nClassLoader,
2981
                "Andami Launcher");
2982
        } catch (MalformedURLException e) {
2983
            logger.error("Error loading i18n resources from the application "
2984
                + "and user folders: " + andamiI18nFolder + ", "
2985
                + userI18nFolder, e);
2986
        }
2987

    
2988
        // Finally load the andami own i18n resources
2989
        org.gvsig.i18n.Messages.addResourceFamily("org.gvsig.andami.text",
2990
            "Andami Launcher");
2991
        }
2992

    
2993
        /**
2994
         * Gets Home Directory location of the application into users home folder.
2995
         * 
2996
         * May be set from outside the aplication by means of
2997
         * -DgvSIG.home=C:/data/gvSIG, where gvSIG its the name of the application
2998
         * 
2999
         * @return
3000
         */
3001
        public static String getAppHomeDir() {
3002
                return appHomeDir;
3003
        }
3004
        
3005
    public static File getApplicationHomeFolder() {
3006
        return new File(getAppHomeDir());
3007
    }
3008

    
3009
        /**
3010
         * Sets Home Directory location of the application. May be set from outside
3011
         * the aplication by means of -DgvSIG.home=C:/data/gvSIG, where gvSIG its
3012
         * the name of the application
3013
         * 
3014
         * @param appHomeDir
3015
         */
3016
        public static void setAppHomeDir(String appHomeDir) {
3017
                Launcher.appHomeDir = appHomeDir;
3018
        }
3019

    
3020
        /**
3021
         * Initialize the extesion that have to take the control of the state of
3022
         * action controls of the UI of all extensions. <br>
3023
         * <br>
3024
         * For use this option you have to add an argument to the command line like
3025
         * this: <br>
3026
         * <br>
3027
         * -exclusiveUI={pathToExtensionClass} <br>
3028
         * 
3029
         * @see org.gvsig.andami.plugins.IExtension#isEnabled(IExtension extension)
3030
         * @see org.gvsig.andami.plugins.IExtension#isVisible(IExtension extension)
3031
         */
3032
        private static void initializeExclusiveUIExtension() {
3033
                String name = PluginServices.getArgumentByName("exclusiveUI");
3034
                if (name == null) {
3035
                        return;
3036
                }
3037

    
3038
                Iterator<Class<? extends IExtension>> iter = classesExtensions.keySet()
3039
                                .iterator();
3040
                int charIndex;
3041
                Class<? extends IExtension> key;
3042
                while (iter.hasNext()) {
3043
                        key = iter.next();
3044
                        charIndex = key.getName().indexOf(name);
3045
                        // System.out.println("key='"+key.getName()+"' name='"+name+"' charIndex="+charIndex);
3046
                        if (charIndex == 0) {
3047
                                IExtension ext = classesExtensions.get(key);
3048
                                if (ext instanceof ExtensionDecorator) {
3049
                                        ext = ((ExtensionDecorator) ext).getExtension();
3050
                                }
3051
                                if (ext instanceof ExclusiveUIExtension) {
3052
                                        PluginServices
3053
                                                        .setExclusiveUIExtension((ExclusiveUIExtension) ext);
3054
                                }
3055
                                break;
3056
                        }
3057
                }
3058

    
3059
                logger
3060
                                .error(Messages
3061
                                                .getString("No_se_encontro_la_extension_especificada_en_el_parametro_exclusiveUI")
3062
                                                + " '" + name + "'");
3063
        }
3064

    
3065
        // public static void initIconThemes() {
3066
        // // load the iconTheme
3067
        // IconThemeManager iconManager = new IconThemeManager();
3068
        // PluginServices.setIconThemeManager(iconManager);
3069
        // IconThemeInfo selectedTheme = iconManager.readConfig();
3070
        // if (selectedTheme!=null) {
3071
        // iconManager.setDefault(selectedTheme);
3072
        // logger.info("Setting the icon theme: "+selectedTheme.toVerboseString());
3073
        // }
3074
        // else {
3075
        // // set the default dir and try to load the default theme
3076
        // try {
3077
        // iconManager.setThemesDir(new File("iconThemes"));
3078
        // IconThemeInfo[] list = iconManager.list();
3079
        //
3080
        // for (int i=0; i<list.length; i++) {
3081
        // if (list[i].getResourceName().equals("iconThemes/icons")) {
3082
        // iconManager.setDefault(list[i]);
3083
        // logger.info("Setting the default icon theme: "+list[i].toVerboseString());
3084
        // return;
3085
        // }
3086
        // }
3087
        // } catch (FileNotFoundException e) {
3088
        // logger.info("IconTheme basedir does not exist");
3089
        // }
3090
        // // create an empty theme
3091
        // IconThemeInfo info = new IconThemeInfo();
3092
        // info.setName("No theme loaded");
3093
        // info.setResource(null); // null resource means that no real theme is
3094
        // loaded
3095
        // info.setDescription("No theme loaded");
3096
        // info.setVersion("0");
3097
        // iconManager.setDefault(new IconTheme(info));
3098
        // logger.info("Setting an empty icon theme");
3099
        //
3100
        // }
3101
        // }
3102

    
3103
        public static void initIconThemes() {
3104
                PluginsManager pluginsManager = PluginsLocator.getManager();
3105
                IconThemeManager iconManager = ToolsSwingLocator.getIconThemeManager();
3106
                
3107
                File f = new File(pluginsManager.getApplicationFolder(),"icon-theme");
3108
                if( !f.exists() ) { 
3109
                        try {
3110
                                f.mkdir();
3111
                        } catch(Exception ex) {
3112
                                // Do nothing
3113
                        }
3114
                }
3115
                iconManager.getRepository().add(f,"_Global");
3116
                
3117
                f = new File(pluginsManager.getApplicationHomeFolder(),"icon-theme");
3118
                if( !f.exists() ) {
3119
                        try {
3120
                                f.mkdir();
3121
                        } catch(Exception ex) {
3122
                                // Do nothing
3123
                        }
3124
                }
3125
                iconManager.getRepository().add(f,"_User");
3126
                
3127
                Preferences prefs = Preferences.userRoot().node("gvsig.icontheme");
3128
                String defaultThemeID = prefs.get("default-theme", null);
3129
                if( defaultThemeID != null ) {
3130
                        IconTheme iconTheme = iconManager.get(defaultThemeID);
3131
                        if( iconTheme != null ) {
3132
                                iconManager.setCurrent(iconTheme);
3133
                        }
3134
                }
3135
        }
3136

    
3137
        /**
3138
         * Manages Andami termination process
3139
         * 
3140
         * @author Cesar Martinez Izquierdo <cesar.martinez@iver.es>
3141
         */
3142
        public class TerminationProcess {
3143

    
3144
                private boolean proceed = false;
3145
                private UnsavedDataPanel panel = null;
3146

    
3147
                public void run() {
3148
                        try {
3149
                                int exit = manageUnsavedData();
3150
                                if ((exit == JOptionPane.NO_OPTION)
3151
                                                || (exit == JOptionPane.CLOSED_OPTION)) {
3152
                                        // the user doesn't want to exit
3153
                                        return;
3154
                                }
3155
                                closeAndami();
3156
                        } catch (Exception e) {
3157
                                // It is not possible to close the application.
3158
                                // this exception has been registered before
3159
                        }
3160
                }
3161

    
3162
                /**
3163
                 * Finishes the application without asking user if want or not to save
3164
                 * unsaved data.
3165
                 */
3166
                public void closeAndami() {
3167
                        try {
3168
                                saveAndamiConfig();
3169
                        } catch (Exception ex) {
3170
                                logger
3171
                                                .error(
3172
                                                                "There was an error exiting application, can't save andami-config.xml",
3173
                                                                ex);
3174
                        }
3175

    
3176
                        try {
3177
                                // Persistencia de los plugins
3178
                                savePluginPersistence();
3179
                                savePluginsProperties();
3180
                        } catch (Exception ex) {
3181
                                logger
3182
                                                .error(
3183
                                                                "There was an error exiting application, can't save plugins properties",
3184
                                                                ex);
3185
                        }
3186

    
3187
                        // Finalize all the extensions
3188
                        finalizeExtensions();
3189

    
3190
                        try {
3191
                                // Clean any temp data created
3192
                                Utilities.cleanUpTempFiles();
3193
                        } catch (Exception ex) {
3194
                                logger
3195
                                                .error(
3196
                                                                "There was an error exiting application, can't remove temporary files",
3197
                                                                ex);
3198
                        }
3199

    
3200
                        logger.info("Quiting application.");
3201

    
3202
                        // Para la depuraci?n de memory leaks
3203
                        System.gc();
3204

    
3205
                        System.exit(0);
3206
                }
3207

    
3208
                /**
3209
         * 
3210
         */
3211
                public void saveAndamiConfig() {
3212
                        // Configuraci?n de Andami
3213
                        try {
3214
                                andamiConfigToXML(andamiConfigPath);
3215
                        } catch (MarshalException e) {
3216
                                logger
3217
                                                .error(
3218
                                                                Messages
3219
                                                                                .getString("Launcher.No_se_pudo_guardar_la_configuracion_de_andami"),
3220
                                                                e);
3221
                        } catch (ValidationException e) {
3222
                                logger
3223
                                                .error(
3224
                                                                Messages
3225
                                                                                .getString("Launcher.No_se_pudo_guardar_la_configuracion_de_andami"),
3226
                                                                e);
3227
                        } catch (IOException e) {
3228
                                logger
3229
                                                .error(
3230
                                                                Messages
3231
                                                                                .getString("Launcher.No_se_pudo_guardar_la_configuracion_de_andami"),
3232
                                                                e);
3233
                        }
3234
                }
3235

    
3236
                private void savePluginsProperties() {
3237
                        PluginsManager manager = PluginsLocator.getManager();
3238
                        List<PluginServices> plugins = manager.getPlugins();
3239
                        for (PluginServices plugin : plugins) {
3240
                                if (plugin != null) {
3241
                                        plugin.savePluginProperties();
3242
                                }
3243
                        }
3244
                }
3245

    
3246
                /**
3247
                 * Exectutes the terminate method for all the extensions, in the reverse
3248
                 * order they were initialized
3249
                 * 
3250
                 */
3251
                private void finalizeExtensions() {
3252
                        for (int i = extensions.size() - 1; i >= 0; i--) {
3253
                                org.gvsig.andami.plugins.IExtension extensionInstance = (org.gvsig.andami.plugins.IExtension) extensions
3254
                                                .get(i);
3255
                                String extensionName = "(unknow)";
3256
                                try {
3257
                                        extensionName = extensionInstance.getClass().getName();
3258
                                        extensionInstance.terminate();
3259
                                } catch (Exception ex) {
3260
                                        logger.error(MessageFormat.format(
3261
                                                        "There was an error extension ending {0}",
3262
                                                        extensionName), ex);
3263
                                }
3264
                        }
3265
                }
3266

    
3267
                private IUnsavedData[] getUnsavedData() throws Exception {
3268
                        List<IUnsavedData> unsavedDataList = new ArrayList<IUnsavedData>();
3269
                        IExtension exclusiveExtension = PluginServices
3270
                                        .getExclusiveUIExtension();
3271

    
3272
                        for (int i = extensions.size() - 1; i >= 0; i--) {
3273
                                org.gvsig.andami.plugins.IExtension extensionInstance = (org.gvsig.andami.plugins.IExtension) extensions
3274
                                                .get(i);
3275
                                IExtensionStatus status = null;
3276
                                if (exclusiveExtension != null) {
3277
                                        status = exclusiveExtension.getStatus(extensionInstance);
3278
                                } else {
3279
                                        status = extensionInstance.getStatus();
3280
                                }
3281
                                if (status != null) {
3282
                                        try {
3283
                                                if (status.hasUnsavedData()) {
3284
                                                        IUnsavedData[] array = status.getUnsavedData();
3285
                                                        for (int element = 0; element < array.length; element++) {
3286
                                                                unsavedDataList.add(array[element]);
3287
                                                        }
3288
                                                }
3289
                                        } catch (Exception e) {
3290
                                                logger.info("Error calling the hasUnsavedData method",
3291
                                                                new Exception());
3292
                                                int option = JOptionPane
3293
                                                                .showConfirmDialog(
3294
                                                                                frame,
3295
                                                                                Messages
3296
                                                                                                .getString("error_getting_unsaved_data"),
3297
                                                                                Messages.getString("MDIFrame.salir"),
3298
                                                                                JOptionPane.YES_NO_OPTION);
3299
                                                if (option == JOptionPane.NO_OPTION) {
3300
                                                        throw e;
3301
                                                }
3302
                                        }
3303
                                }
3304
                        }
3305
                        return unsavedDataList.toArray(new IUnsavedData[unsavedDataList
3306
                                        .size()]);
3307
                }
3308

    
3309
                public UnsavedDataPanel getUnsavedDataPanel() {
3310
                        if (panel == null) {
3311
                                panel = new UnsavedDataPanel(new IUnsavedData[0]);
3312
                        }
3313
                        return panel;
3314
                }
3315

    
3316
                /**
3317
                 * Checks if the extensions have some unsaved data, and shows a dialog
3318
                 * to allow saving it. This dialog also allows to don't exit Andami.
3319
                 * 
3320
                 * @return true if the user confirmed he wishes to exit, false otherwise
3321
                 * @throws Exception
3322
                 */
3323
                public int manageUnsavedData() throws Exception {
3324
                        IUnsavedData[] unsavedData = getUnsavedData();
3325

    
3326
                        // there was no unsaved data
3327
                        if (unsavedData.length == 0) {
3328
                                int option = JOptionPane
3329
                                                .showConfirmDialog(frame, Messages
3330
                                                                .getString("MDIFrame.quiere_salir"), Messages
3331
                                                                .getString("MDIFrame.salir"),
3332
                                                                JOptionPane.YES_NO_OPTION);
3333
                                return option;
3334
                        }
3335

    
3336
                        UnsavedDataPanel panel = getUnsavedDataPanel();
3337
                        panel.setUnsavedDataArray(unsavedData);
3338

    
3339
                        panel.addActionListener(panel.new UnsavedDataPanelListener() {
3340

    
3341
                                public void cancel(UnsavedDataPanel panel) {
3342
                                        proceed(false);
3343
                                        PluginServices.getMDIManager().closeWindow(panel);
3344

    
3345
                                }
3346

    
3347
                                public void discard(UnsavedDataPanel panel) {
3348
                                        proceed(true);
3349
                                        PluginServices.getMDIManager().closeWindow(panel);
3350

    
3351
                                }
3352

    
3353
                                public void accept(UnsavedDataPanel panel) {
3354
                                        IUnsavedData[] unsavedDataArray = panel
3355
                                                        .getSelectedsUnsavedData();
3356
                                        boolean saved;
3357
                                        for (int i = 0; i < unsavedDataArray.length; i++) {
3358
                                                try {
3359
                                                        saved = unsavedDataArray[i].saveData();
3360
                                                } catch (Exception ex) {
3361
                                                        PluginServices.getLogger().error(
3362
                                                                        "Error saving"
3363
                                                                                        + unsavedDataArray[i]
3364
                                                                                                        .getResourceName(), ex);
3365
                                                        saved = false;
3366
                                                }
3367
                                                if (!saved) {
3368
                                                        JOptionPane
3369
                                                                        .showMessageDialog(
3370
                                                                                        panel,
3371
                                                                                        PluginServices
3372
                                                                                                        .getText(this,
3373
                                                                                                                        "The_following_resource_could_not_be_saved_")
3374
                                                                                                        + "\n"
3375
                                                                                                        + unsavedDataArray[i]
3376
                                                                                                                        .getResourceName()
3377
                                                                                                        + " -- "
3378
                                                                                                        + unsavedDataArray[i]
3379
                                                                                                                        .getDescription(),
3380
                                                                                        PluginServices.getText(this,
3381
                                                                                                        "Resource_was_not_saved"),
3382
                                                                                        JOptionPane.ERROR_MESSAGE);
3383

    
3384
                                                        try {
3385
                                                                unsavedDataArray = getUnsavedData();
3386
                                                        } catch (Exception e) {
3387
                                                                // This exception has been registered before
3388
                                                        }
3389
                                                        panel.setUnsavedDataArray(unsavedDataArray);
3390
                                                        return;
3391
                                                }
3392
                                        }
3393
                                        proceed(true);
3394
                                        PluginServices.getMDIManager().closeWindow(panel);
3395
                                }
3396
                        });
3397

    
3398
                        PluginServices.getMDIManager().addWindow(panel);
3399
                        if (proceed) {
3400
                                return JOptionPane.YES_OPTION;
3401
                        } else {
3402
                                return JOptionPane.NO_OPTION;
3403
                        }
3404
                }
3405

    
3406
                private void proceed(boolean proceed) {
3407
                        this.proceed = proceed;
3408
                }
3409

    
3410
        }
3411

    
3412
        public static TerminationProcess getTerminationProcess() {
3413
                return (new Launcher()).new TerminationProcess();
3414
        }
3415

    
3416
        private PackageInfo getPackageInfo(String pluginsFolder) {
3417
                try {
3418
                    PluginsManager pm = PluginsLocator.getManager();
3419

    
3420
                        File packageInfoFile = new File(
3421
                            pm.getApplicationFolder(), "package.info");
3422
                        if (packageInfoFile.exists()) {
3423
                                InstallerManager installerManager = InstallerLocator.getInstallerManager();
3424
                                FileInputStream fis = new FileInputStream(packageInfoFile);
3425
                                PackageInfo packageInfo = installerManager.createPackageInfo(fis);
3426
                                return packageInfo;
3427
                        }
3428
                        return null;
3429
                } catch (Exception e) {
3430
                        logger.info("Can't locate PackageInfo from plugin org.gvsig.app",e);
3431
                        return null;
3432
                }
3433
        }
3434

    
3435
        /**
3436
         * Launch the gvSIG package installer.
3437
         * 
3438
         * @throws Exception
3439
         *             if there is any error
3440
         */
3441
        private void doInstall(String[] args) throws Exception {
3442
                String installURL = null;
3443
                String installURLFile = null;
3444
                String gvSIGVersion = null;
3445
                String[] myArgs = new String[3];
3446
                PackageInfo packageInfo = null; 
3447

    
3448
                Options options = new Options();
3449
                options.addOption("i", "install", false, "install");
3450
                options.addOption("u", "installURL", true, "installURL");
3451
                options.addOption("f", "installURLFile", true, "installURLFile");
3452
                options.addOption("v", "installVersion", true, "installVersion");
3453
                options.addOption("A", "applicationName", true, "applicationName");
3454
                options.addOption("P", "pluginsFolder", true, "pluginsFolder");
3455
                options.addOption("l", "language", true, "language");
3456

    
3457
                
3458
                /*
3459
                 * Los parametros que deberian pasarse en el instalador oficial de gvSIG serian:
3460
                 * 
3461
                 * --install
3462
                 * --applicationName=gvSIG
3463
                 * --language=es
3464
                 * --pluginsFolder=gvSIG/extensiones
3465
                 * 
3466
                 * Opcionales (casi mejor que dejar los de por defecto y no pasarselos):
3467
                 * --installVersion=2.0.0
3468
                 * --installURL=http://downloads.gvsig.org/download/gvsig-desktop/dists
3469
                 * --installURLFile=gvSIG/extensiones/org.gvsig.installer.app.extension/defaultDownloadsURLs
3470
                 * 
3471
                 */
3472
                CommandLineParser parser = new PosixParser();
3473
                CommandLine line = null;
3474
                try {
3475
                        line = parser.parse(options, args);
3476
                        boolean hasAllMandatoryOptions = true;
3477
                        if (!line.hasOption("install")) {
3478
                                hasAllMandatoryOptions = false;
3479
                        }
3480
                        
3481
                        if (line.hasOption("installVersion")) {
3482
                                gvSIGVersion = line.getOptionValue("installVersion");
3483
                        }
3484
                        if (line.hasOption("applicationName")) {
3485
                                myArgs[0] = line.getOptionValue("applicationName");
3486
                        } else {
3487
                                hasAllMandatoryOptions = false;
3488
                        }
3489
                        if (line.hasOption("pluginsFolder")) {
3490
                                myArgs[1] = line.getOptionValue("pluginsFolder");
3491
                        } else {
3492
                                myArgs[1] = "gvSIG/extensiones";
3493
                                hasAllMandatoryOptions = false;
3494
                        }
3495
                        if (line.hasOption("language")) {
3496
                                myArgs[2] = "language=" + line.getOptionValue("language");
3497
                        } else {
3498
                            // prevent null
3499
                            myArgs[2] = "";
3500
                        }
3501
                        
3502
                        if (line.hasOption("installURL")) {
3503
                                installURL = line.getOptionValue("installURL");
3504
                        } else {
3505
                                installURL = "http://downloads.gvsig.org/download/gvsig-desktop/";
3506
                        }
3507
                        
3508
                        if (line.hasOption("installURLFile")) {
3509
                                installURLFile = line.getOptionValue("installURLFile");
3510
                        } else {
3511
                                installURLFile = myArgs[1] + "/org.gvsig.installer.app.extension/defaultDownloadsURLs";
3512
                        }
3513

    
3514
                        if (!hasAllMandatoryOptions) {
3515
                                System.err
3516
                                                .println(Messages.get("usage")
3517
                                                                + ": Launcher --applicationName=appName --pluginsFolder=plugins-directory "
3518
                                                                + "[--installURLFile=File] "
3519
                                                                + "--install [--installURL=URL] [language=locale]");
3520
                                return;
3521
                        }
3522
                } catch (ParseException exp) {
3523
                        System.out.println("Unexpected exception:" + exp.getMessage());
3524
                }
3525

    
3526
                initializeApp(myArgs);
3527
                initializeLibraries();
3528
                AndamiConfig config = getAndamiConfig();
3529
                config.setLocaleLanguage(locale.getLanguage());
3530
                config.setLocaleCountry(locale.getCountry());
3531
                config.setLocaleVariant(locale.getVariant());
3532
                
3533
                InstallerManager installerManager = InstallerLocator.getInstallerManager();
3534
                
3535
                packageInfo = getPackageInfo(myArgs[1]);
3536
                
3537
                // set the gvSIG version to the install manager, to compose the download URL
3538
                if( packageInfo!=null ) {
3539
                        installerManager.setVersion(packageInfo.getVersion());
3540
                } else {
3541
                        installerManager.setVersion(gvSIGVersion);
3542
                }
3543
                if( !installURL.contains(";") &&
3544
                        !installURL.endsWith(InstallerManager.PACKAGE_EXTENSION) && 
3545
                        !installURL.endsWith(InstallerManager.PACKAGE_INDEX_EXTENSION) ) {
3546
                        if( packageInfo!=null && (packageInfo.getState().startsWith(InstallerManager.STATE.BETA) ||
3547
                                 packageInfo.getState().startsWith(InstallerManager.STATE.RC) ||
3548
                                 packageInfo.getState().equalsIgnoreCase(InstallerManager.STATE.FINAL)) ) {
3549
                                installURL = installURL + "dists/<%Version%>/builds/<%Build%>/packages.gvspki";                        
3550
                        }
3551
                }
3552
                // Configure default index download URL
3553
                SwingInstallerLocator.getSwingInstallerManager().setDefaultDownloadURL(installURL);
3554

    
3555
                SwingInstallerLocator.getSwingInstallerManager().setDefaultDownloadURL(new File(installURLFile));
3556

    
3557
                // Launch installer
3558
                PluginsManager manager = PluginsLocator.getManager();
3559

    
3560
                File defaultAddonsRepository = PluginsLocator.getManager()
3561
                                .getPluginsFolder();
3562
                installerManager.addLocalAddonRepository(defaultAddonsRepository);
3563
                installerManager
3564
                                .setDefaultLocalAddonRepository(defaultAddonsRepository);
3565

    
3566
                AbstractInstallPackageWizard installPackageWizard = SwingInstallerLocator
3567
                                .getSwingInstallerManager().createInstallPackageWizard(
3568
                                                manager.getApplicationFolder(),
3569
                                                manager.getInstallFolder());
3570
                installPackageWizard
3571
                                .setWizardActionListener(new InstallerWizardActionListener() {
3572

    
3573
                                        public void finish(InstallerWizardPanel installerWizard) {
3574
                                                System.exit(0);
3575
                                        }
3576

    
3577
                                        public void cancel(InstallerWizardPanel installerWizard) {
3578
                                                System.exit(0);
3579
                                        }
3580
                                });
3581

    
3582
                // the wizard will show the Typical or Advanced mode option.
3583
                installPackageWizard.setAskTypicalOrCustom(true);
3584
                // default packages will be selected.
3585
                installPackageWizard.setSelectDefaultPackages(true);
3586

    
3587

    
3588
                // 1. Create the frame.
3589
                JFrame frame = new JFrame(Messages.get("gvsig_package_installer"));
3590

    
3591
                // 2. What happens when the frame closes?
3592
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
3593
                Runtime.getRuntime().addShutdownHook(new Thread() {
3594

    
3595
                        @Override
3596
                        public void run() {
3597
                                getTerminationProcess().saveAndamiConfig();
3598
                        }
3599
                });
3600

    
3601
                // 3. Add the installer panel to the frame
3602
                frame.getContentPane().add(installPackageWizard, BorderLayout.CENTER);
3603

    
3604
                // 4. Size the frame and center on the screen
3605
                frame.pack();
3606
                frame.setLocationRelativeTo(null);
3607

    
3608
                // 5. Show it.
3609
                frame.setVisible(true);
3610
        }
3611

    
3612
        public static String getInformation() {
3613
                PluginsManager pluginmgr = PluginsLocator.getManager();
3614
                InstallerManager installmgr = InstallerLocator.getInstallerManager();
3615

    
3616
                StringWriter writer = new StringWriter();
3617

    
3618
                Properties props = System.getProperties();
3619

    
3620
                // OS information
3621
                String osName = props.getProperty("os.name");
3622
                writer.write("OS\n");
3623
                writer.write("    name   : " + osName + "\n");
3624
                writer.write("    arch   : " + props.get("os.arch") + "\n");
3625
                writer.write("    version: " + props.get("os.version") + "\n");
3626
                if (osName.startsWith("Linux")) {
3627
                        try {
3628
                                String[] command = { "lsb_release", "-a" };
3629
                                Process p = Runtime.getRuntime().exec(command);
3630
                                InputStream is = p.getInputStream();
3631
                                BufferedReader reader = new BufferedReader(
3632
                                                new InputStreamReader(is));
3633
                                String line;
3634
                                while ((line = reader.readLine()) != null) {
3635
                                        writer.write("    " + line + "\n");
3636
                                }
3637
                        } catch (Exception ex) {
3638
                                writer
3639
                                                .write("Can't get detailled os information (lsb_release -a).");
3640
                        }
3641
                }
3642

    
3643
                // JRE information
3644
                writer.write("JRE\n");
3645
                writer.write("    vendor : " + props.get("java.vendor") + "\n");
3646
                writer.write("    version: " + props.get("java.version") + "\n");
3647
                writer.write("    home   : " + props.get("java.home") + "\n");
3648

    
3649
                writer.write("HTTP Proxy\n");
3650
                writer.write("    http.proxyHost     : " + props.get("http.proxyHost")
3651
                                + "\n");
3652
                writer.write("    http.proxyPort     : " + props.get("http.proxyPort")
3653
                                + "\n");
3654
                writer.write("    http.proxyUserName : "
3655
                                + props.get("http.proxyUserName") + "\n");
3656
                writer.write("    http.proxyPassword : "
3657
                                + props.get("http.proxyPassword") + "\n");
3658

    
3659
                String skinName = "(unknow)";
3660
                try {
3661
                        skinName = MDIManagerFactory.getSkinExtension().getClassName();
3662
                } catch (Throwable e) {
3663
                        // Ignore
3664
                }
3665
                writer.write("Application\n");
3666
                writer.write("    locale language         : "
3667
                                + Launcher.getAndamiConfig().getLocaleLanguage() + "\n");
3668
                writer.write("    application forlder     : "
3669
                                + pluginmgr.getApplicationFolder() + "\n");
3670
                writer.write("    application home forlder: "
3671
                                + pluginmgr.getApplicationHomeFolder() + "\n");
3672
                writer.write("    install forlder         : "
3673
                                + pluginmgr.getInstallFolder() + "\n");
3674
                writer.write("    plugins forlder         : "
3675
                                + pluginmgr.getPluginsFolder() + "\n");
3676
                writer.write("    theme                   : "
3677
                                + Launcher.theme.getSource() + "\n");
3678
                writer.write("    Skin                    : " + skinName + "\n");
3679

    
3680
                try {
3681
                        PackageInfo[] pkgs = installmgr.getInstalledPackages(pluginmgr
3682
                                        .getPluginsFolder());
3683
                        writer.write("Installed packages\n");
3684
                        for (int i = 0; i < pkgs.length; i++) {
3685
                                writer.write("    ");
3686
                                writer.write(pkgs[i].toStringCompact());
3687
                                writer.write("\n");
3688
                        }
3689
                } catch (Throwable e) {
3690
                        writer.write("Can't get installed package information.");
3691
                }
3692
                return writer.toString();
3693
        }
3694

    
3695
        private void logger_info(String msg) {
3696
                String info[] = msg.split("\n");
3697
                for (int i = 0; i < info.length; i++) {
3698
                        logger.info(info[i]);
3699
                }
3700
        }
3701
        
3702
        private void saveEnvironInformation() {
3703
                PluginsManager manager = PluginsLocator.getManager();
3704
                File fout = new File( manager.getApplicationHomeFolder(), "gvSIG-environ.info");
3705
                try {
3706
                        FileUtils.write(fout, getInformation());
3707
                } catch (IOException e) {
3708
                        logger.info("Can't create '"+fout.getAbsolutePath()+"'");
3709
                }
3710
        }
3711

    
3712
}