Statistics
| Revision:

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

History | View | Annotate | Download (111 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
                Launcher.class.getClassLoader().getResource(".");
799
                PropertyConfigurator.configure("log4j.properties");
800

    
801
                PatternLayout l = new PatternLayout("%p %t %C - %m%n");
802
                RollingFileAppender fa = new RollingFileAppender(l, appHomeDir
803
                                + File.separator + appName + ".log", false);
804
                fa.setMaxFileSize("512KB");
805
                fa.setMaxBackupIndex(3);
806
                org.apache.log4j.Logger.getRootLogger().addAppender(fa);
807
        }
808

    
809
        private class NotificationAppender extends AppenderSkeleton {
810

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

    
831
                  
832
                @Override
833
                public void close() {
834
                        // TODO Auto-generated method stub
835

    
836
                }
837

    
838
                @Override
839
                public boolean requiresLayout() {
840
                        // TODO Auto-generated method stub
841
                        return false;
842
                }
843

    
844
        }
845

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

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

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

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

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

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

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

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

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

    
975
                System.getProperties().put("http.proxyHost", host);
976
                System.getProperties().put("http.proxyPort", port);
977

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

    
985
                        Authenticator.setDefault(new ProxyAuth(proxyUser, proxyPassword));
986
                } else {
987
                        Authenticator.setDefault(new ProxyAuth("", ""));
988
                }
989
        }
990

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

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

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

    
1058
        private void loadPluginsPersistence() throws ConfigurationException {
1059
                XMLEntity entity = persistenceFromXML();
1060

    
1061
                for (int i = 0; i < entity.getChildrenCount(); i++) {
1062
                        XMLEntity plugin = entity.getChild(i);
1063
                        String pName = plugin
1064
                                        .getStringProperty("com.iver.andami.pluginName");
1065

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

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

    
1088
                XMLEntity entity = new XMLEntity();
1089

    
1090
                while (i.hasNext()) {
1091
                        String pName = i.next();
1092
                        PluginServices ps = (PluginServices) pluginsServices.get(pName);
1093
                        XMLEntity ent = ps.getPersistentXML();
1094

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

    
1116
        private void installPluginsLabels() {
1117
                Iterator<String> i = pluginsConfig.keySet().iterator();
1118

    
1119
                while (i.hasNext()) {
1120
                        String name = i.next();
1121
                        PluginConfig pc = pluginsConfig.get(name);
1122
                        PluginServices ps = (PluginServices) pluginsServices.get(name);
1123

    
1124
                        LabelSet[] ls = pc.getLabelSet();
1125

    
1126
                        for (int j = 0; j < ls.length; j++) {
1127
                                PluginClassLoader loader = ps.getClassLoader();
1128

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

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

    
1154
        private void fixSkin(SkinExtension skinExtension,
1155
                        PluginClassLoader pluginClassLoader) throws MDIManagerLoadException {
1156
                // now insert the skin selected.
1157
                MDIManagerFactory.setSkinExtension(skinExtension, pluginClassLoader);
1158
                // MDIManagerFactory.setSkinExtension(se,
1159
                // ps.getClassLoader());
1160

    
1161
                Class<? extends IExtension> skinClass;
1162

    
1163
                try {
1164
                        skinClass = (Class<? extends IExtension>) pluginClassLoader
1165
                                        .loadClass(skinExtension.getClassName());
1166

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

    
1192
        }
1193

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

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

    
1217
                        if (pc.getExtensions().getSkinExtension() != null) {
1218
                                // if (MDIManagerFactory.getSkinExtension() != null) {
1219
                                // logger.warn(Messages.getString(
1220
                                // "Launcher.Dos_skin_extension"));
1221
                                // }
1222

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

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

    
1255
        }
1256

    
1257
        private static void frameIcon(Theme theme) {
1258
                Iterator<String> i = pluginsConfig.keySet().iterator();
1259

    
1260
                while (i.hasNext()) {
1261
                        String pName = i.next();
1262
                        PluginConfig pc = pluginsConfig.get(pName);
1263
                        if (pc.getIcon() != null) {
1264
                                if (theme.getIcon() != null) {
1265
                                        frame.setIconImage(theme.getIcon().getImage());
1266
                                } else {
1267

    
1268
                                        ImageIcon icon = PluginServices.getIconTheme().get(
1269
                                                        pc.getIcon().getSrc());
1270
                                        frame.setIconImage(icon.getImage());
1271

    
1272
                                }
1273
                                if (theme.getName() != null) {
1274
                                        frame.setTitlePrefix(theme.getName());
1275
                                } else {
1276
                                        frame.setTitlePrefix(pc.getIcon().getText());
1277
                                }
1278
                                if (theme.getBackgroundImage() != null) {
1279

    
1280
                                        PluginServices.getMDIManager().setBackgroundImage(
1281
                                                        theme.getBackgroundImage(), theme.getTypeDesktop());
1282
                                }
1283
                        }
1284
                }
1285
        }
1286

    
1287
        private void initializeExtensions() {
1288

    
1289
                List<ClassLoader> classLoaders = new ArrayList<ClassLoader>(
1290
                                pluginsOrdered.size());
1291
                classLoaders.add(getClass().getClassLoader());
1292
                Iterator<String> iter = pluginsOrdered.iterator();
1293

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

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

    
1319
                        Extension[] exts = pc.getExtensions().getExtension();
1320

    
1321
                        TreeSet<Extension> orderedExtensions = new TreeSet<Extension>(
1322
                                        new ExtensionComparator());
1323

    
1324
                        for (int j = 0; j < exts.length; j++) {
1325
                                if (!exts[j].getActive()) {
1326
                                        continue;
1327
                                }
1328

    
1329
                                if (orderedExtensions.contains(exts[j])) {
1330
                                        logger.warn("Two extensions with the same priority ("
1331
                                                        + exts[j].getClassName() + ")");
1332
                                }
1333

    
1334
                                orderedExtensions.add(exts[j]);
1335
                        }
1336

    
1337
                        Iterator<Extension> e = orderedExtensions.iterator();
1338

    
1339
                        logger.info("Initializing extensions of plugin " + pName + ": ");
1340
                        while (e.hasNext()) {
1341
                                Extension extension = e.next();
1342
                                org.gvsig.andami.plugins.IExtension extensionInstance;
1343

    
1344
                                try {
1345
                                        logger.info("Initializing " + extension.getClassName()
1346
                                                        + "...");
1347
                                        Class<? extends IExtension> extensionClass = (Class<? extends IExtension>) ps
1348
                                                        .getClassLoader().loadClass(
1349
                                                                        extension.getClassName());
1350
                                        extensionInstance = extensionClass.newInstance();
1351

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

    
1370
                                        extensionInstance.initialize();
1371
                                        extensions.add(extensionInstance);
1372

    
1373
                                } catch (NoClassDefFoundError e1) {
1374
                                        this.addError("Can't find class extension ("
1375
                                                        + extension.getClassName() + ")", e1);
1376
                                } catch (Throwable e1) {
1377
                                        this.addError("Can't initialize extension '"
1378
                                                        + extension.getClassName() + "'.", e1);
1379
                                }
1380
                        }
1381
                }
1382
        }
1383

    
1384
        private void postInitializeExtensions() {
1385
                logger.info("PostInitializing extensions: ");
1386

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

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

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

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

    
1455
                                }
1456
                                Enumeration<ToolBar> toolBars = extension.enumerateToolBar();
1457
                                while (toolBars.hasMoreElements()) {
1458
                                        ToolBar toolBar = toolBars.nextElement();
1459

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

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

    
1517
                ActionInfoManager actionManager = PluginsLocator.getActionInfoManager();
1518
                Iterator<String> it = pluginsConfig.keySet().iterator();
1519

    
1520
                while (it.hasNext()) {
1521
                        String pluginName = it.next();
1522
                        PluginConfig pluginConfig = pluginsConfig.get(pluginName);
1523
                        PluginServices pluginService = pluginsServices.get(pluginName);
1524
                        PluginClassLoader loader =  pluginService.getClassLoader();
1525

    
1526
                        logger.info("registerActions of plugin '"+pluginName+"'.");
1527

    
1528
                        Extensions extensionConfig = pluginConfig.getExtensions();
1529
                        
1530
                        
1531
                        Enumeration<SkinExtensionType> extensiones = extensionConfig.enumerateExtension();
1532
                        registerActionOfExtensions(actionManager, extensiones, loader);
1533

    
1534
                        Enumeration<SkinExtensionType> skinSxtensiones = extensionConfig.enumerateSkinExtension();
1535
                        registerActionOfExtensions(actionManager, skinSxtensiones, loader);
1536

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

    
1565
                }
1566
        }
1567
        
1568

    
1569
        private TreeSet<SortableMenu> getOrderedMenus() { 
1570

    
1571
                TreeSet<SortableMenu> orderedMenus = new TreeSet<SortableMenu>(
1572
                                new MenuComparator());
1573

    
1574
                Iterator<String> i = pluginsConfig.keySet().iterator();
1575

    
1576
                while (i.hasNext()) {
1577
                        String pName = i.next();
1578
                        try {
1579
                                PluginServices ps = pluginsServices.get(pName);
1580
                                PluginConfig pc = pluginsConfig.get(pName);
1581

    
1582
                                Extension[] exts = pc.getExtensions().getExtension();
1583

    
1584
                                for (int j = 0; j < exts.length; j++) {
1585
                                        if (!exts[j].getActive()) {
1586
                                                continue;
1587
                                        }
1588

    
1589
                                        Menu[] menus = exts[j].getMenu();
1590

    
1591
                                        for (int k = 0; k < menus.length; k++) {
1592
                                                SortableMenu sm = new SortableMenu(ps.getClassLoader(),
1593
                                                                exts[j], menus[k]);
1594

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

    
1604
                                                orderedMenus.add(sm);
1605
                                        }
1606
                                }
1607

    
1608
                                // Se instalan las extensiones de MDI
1609
                                SkinExtension[] skinExts = pc.getExtensions()
1610
                                                .getSkinExtension();
1611
                                for (int j = 0; j < skinExts.length; j++) {
1612

    
1613
                                        if (skinExts[j] != null) {
1614
                                                Menu[] menu = skinExts[j].getMenu();
1615

    
1616
                                                for (int k = 0; k < menu.length; k++) {
1617
                                                        SortableMenu sm = new SortableMenu(ps
1618
                                                                        .getClassLoader(), skinExts[j], menu[k]);
1619

    
1620
                                                        if (orderedMenus.contains(sm)) {
1621
                                                                this
1622
                                                                                .addError(Messages
1623
                                                                                                .getString("Launcher.Two_menus_with_the_same_position")
1624
                                                                                                + skinExts[j].getClassName());
1625
                                                        }
1626

    
1627
                                                        orderedMenus.add(sm);
1628
                                                }
1629
                                        }
1630
                                }
1631

    
1632
                        } catch (Throwable e) {
1633
                                addError("Error initializing menus of plugin '" + pName + "'",
1634
                                                e);
1635
                        }
1636

    
1637
                }
1638

    
1639
                return orderedMenus;
1640
        }
1641

    
1642
        private void installPluginsMenus() {
1643
                logger.info("installPluginsMenus");
1644

    
1645
                TreeSet<SortableMenu> orderedMenus = getOrderedMenus();
1646

    
1647
                // Se itera por los menus ordenados
1648
                Iterator<SortableMenu> e = orderedMenus.iterator();
1649

    
1650
                // Se ordenan los menues
1651
                while (e.hasNext()) {
1652
                        try {
1653
                                SortableMenu sm = e.next();
1654

    
1655
                                logger.info(sm.menu.getPosition()+":"+sm.menu.getText()+":"+sm.loader.getPluginName()+":"+sm.extension.getClassName());
1656
                                
1657
                                frame.addMenu(sm.loader, sm.extension, sm.menu);
1658

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

    
1681
        public class PluginMenuItem {
1682
                private Menu menu;
1683
                private PluginClassLoader loader;
1684
                private SkinExtensionType extension;
1685

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

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

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

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

    
1759
                Iterator<String> i = pluginsConfig.keySet().iterator();
1760

    
1761
                Map<Extension, PluginServices> extensionPluginServices = new HashMap<Extension, PluginServices>();
1762
                Map<Extension, PluginConfig> extensionPluginConfig = new HashMap<Extension, PluginConfig>();
1763
                Set<Extension> orderedExtensions = new TreeSet<Extension>(
1764
                                new ExtensionComparator());
1765

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

    
1776
                                Extension[] exts = pc.getExtensions().getExtension();
1777

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

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

    
1808
                TreeSet<SortableTool> orderedTools = new TreeSet<SortableTool>(
1809
                                new ToolComparator());
1810
                Iterator<Extension> e = orderedExtensions.iterator();
1811

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

    
1822
                                // get tools from toolbars
1823
                                for (int k = 0; k < toolbars.length; k++) {
1824
                                        ActionTool[] tools = toolbars[k].getActionTool();
1825

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

    
1834
                                        SelectableTool[] sTools = toolbars[k].getSelectableTool();
1835

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

    
1845
                                // get controls for statusBar
1846
                                PluginServices ps = extensionPluginServices.get(ext);
1847
                                PluginClassLoader loader = ps.getClassLoader();
1848

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

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

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

    
1952
                                SkinExtension[] skinExts = pc.getExtensions()
1953
                                                .getSkinExtension();
1954
                                for (int j = 0; j < skinExts.length; j++) {
1955

    
1956
                                        if (skinExts[j] != null) {
1957
                                                ToolBar[] toolbars = skinExts[j].getToolBar();
1958

    
1959
                                                for (int k = 0; k < toolbars.length; k++) {
1960
                                                        ActionTool[] tools = toolbars[k].getActionTool();
1961

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

    
1969
                                                        SelectableTool[] sTools = toolbars[k]
1970
                                                                        .getSelectableTool();
1971

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

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

    
2027
        /**
2028
         * Adds new plugins to the the andami-config file.
2029
         */
2030
        private void updateAndamiConfig() {
2031
                Set<String> olds = new HashSet<String>();
2032

    
2033
                Plugin[] plugins = andamiConfig.getPlugin();
2034

    
2035
                for (int i = 0; i < plugins.length; i++) {
2036
                        olds.add(plugins[i].getName());
2037
                }
2038

    
2039
                Iterator<PluginServices> i = pluginsServices.values().iterator();
2040

    
2041
                while (i.hasNext()) {
2042
                        PluginServices ps = i.next();
2043

    
2044
                        if (!olds.contains(ps.getPluginName())) {
2045
                                Plugin p = new Plugin();
2046
                                p.setName(ps.getPluginName());
2047
                                p.setUpdate(false);
2048

    
2049
                                andamiConfig.addPlugin(p);
2050
                        }
2051
                }
2052
        }
2053

    
2054
        private void pluginsClassLoaders() {
2055
                Set<String> installed = new HashSet<String>();
2056

    
2057
                // Se itera hasta que est?n todos instalados
2058
                while (installed.size() != pluginsConfig.size()) {
2059
                        boolean circle = true;
2060

    
2061
                        // Hacemos una pasada por todos los plugins
2062
                        Iterator<String> i = pluginsConfig.keySet().iterator();
2063

    
2064
                        while (i.hasNext()) {
2065
                                String pluginName = i.next();
2066
                                PluginConfig config = (PluginConfig) pluginsConfig
2067
                                                .get(pluginName);
2068

    
2069
                                if (installed.contains(pluginName)) {
2070
                                        continue;
2071
                                }
2072

    
2073
                                // Se obtienen las dependencias y sus class loaders
2074
                                boolean ready = true;
2075
                                Depends[] dependencies = config.getDepends();
2076
                                PluginClassLoader[] loaders = new PluginClassLoader[dependencies.length];
2077

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

    
2107
                                // Si no est?n sus dependencias satisfechas se aborta la
2108
                                // instalaci?n
2109
                                if (!ready) {
2110
                                        continue;
2111
                                }
2112

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

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

    
2145
                                try {
2146
                                        loader = new PluginClassLoader(urls, andamiConfig
2147
                                                        .getPluginsDirectory()
2148
                                                        + File.separator + pluginName, Launcher.class
2149
                                                        .getClassLoader(), loaders);
2150

    
2151
                                        PluginServices ps = new PluginServices(loader, PluginsConfig.getAlternativeNames(config));
2152

    
2153
                                        pluginsServices.put(ps.getPluginName(), ps);
2154

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

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

    
2173
                        if (circle) {
2174
                                dumpPluginsDependencyInformation();
2175
                                this.addError("Has circular dependencies betewn plugins");
2176
                                break;
2177
                        }
2178
                }
2179

    
2180
                // Se eliminan los plugins que no fueron instalados
2181
                Iterator<String> i = pluginsConfig.keySet().iterator();
2182

    
2183
                while (i.hasNext()) {
2184
                        String pluginName = i.next();
2185
                        PluginServices ps = (PluginServices) pluginsServices
2186
                                        .get(pluginName);
2187

    
2188
                        if (ps == null) {
2189
                                pluginsConfig.remove(pluginName);
2190
                                i = pluginsConfig.keySet().iterator();
2191
                        }
2192
                }
2193
                registerActions();
2194
        }
2195

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

    
2217
                while (iterator.hasNext()) {
2218
                        String pluginName = iterator.next();
2219
                        config = pluginsConfig.get(pluginName);
2220
                        ps = pluginsServices.get(pluginName);
2221

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

    
2235
        static public PluginServices getPluginServices(String name) {
2236
                return (PluginServices) pluginsServices.get(name);
2237
        }
2238

    
2239
        static String getPluginsDir() {
2240
                return andamiConfig.getPluginsDirectory();
2241
        }
2242

    
2243
        static void setPluginsDir(String s) {
2244
                andamiConfig.setPluginsDirectory(s);
2245
        }
2246

    
2247
        static MDIFrame getMDIFrame() {
2248
                return frame;
2249
        }
2250

    
2251
        private void loadPlugins(String pluginsDirectory) {
2252
                File pDir = new File(pluginsDirectory);
2253

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

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

    
2273
                for (int i = 0; i < pluginDirs.length; i++) {
2274
                        if (pluginDirs[i].isDirectory()) {
2275
                                String pluginName =  pluginDirs[i].getName();
2276
                                File configXml = new File(pluginDirs[i].getAbsolutePath(),
2277
                                                "config.xml");
2278

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

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

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

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

    
2337
                BufferedOutputStream os = new BufferedOutputStream(
2338
                                new FileOutputStream(tmpFile));
2339
                OutputStreamWriter writer = new OutputStreamWriter(os, CASTORENCODING);
2340
                andamiConfig.marshal(writer);
2341
                writer.close();
2342

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

    
2359
        private static void andamiConfigFromXML(String file)
2360
                        throws ConfigurationException {
2361
                File xml = new File(file);
2362

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

    
2395
        private static AndamiConfig getDefaultAndamiConfig() {
2396
                AndamiConfig andamiConfig = new AndamiConfig();
2397

    
2398
                Andami andami = new Andami();
2399
                andami.setUpdate(true);
2400
                andamiConfig.setAndami(andami);
2401
                andamiConfig.setLocaleCountry(Locale.getDefault().getCountry());
2402
                andamiConfig.setLocaleLanguage(Locale.getDefault().getLanguage());
2403
                andamiConfig.setLocaleVariant(Locale.getDefault().getVariant());
2404

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

    
2416
                andamiConfig.setPlugin(new Plugin[0]);
2417
                return andamiConfig;
2418
        }
2419

    
2420
        private static XMLEntity persistenceFromXML() throws ConfigurationException {
2421
                File xml = getPluginsPersistenceFile(true);
2422

    
2423
                if (xml.exists()) {
2424
                        InputStreamReader reader = null;
2425

    
2426
                        try {
2427
                                reader = XMLEncodingUtils.getReader(xml);
2428
                                XmlTag tag = (XmlTag) XmlTag.unmarshal(reader);
2429
                                return new XMLEntity(tag);
2430
                        } catch (FileNotFoundException e) {
2431
                                throw new ConfigurationException(e);
2432
                        } catch (MarshalException e) {
2433

    
2434
                                // try to reopen with default encoding (for backward
2435
                                // compatibility)
2436
                                try {
2437
                                        reader = new FileReader(xml);
2438
                                        XmlTag tag = (XmlTag) XmlTag.unmarshal(reader);
2439
                                        return new XMLEntity(tag);
2440

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

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

    
2490
        }
2491

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

    
2499
                File xml = getPluginsPersistenceFile(false);
2500
                OutputStreamWriter writer = null;
2501

    
2502
                try {
2503
                        writer = new OutputStreamWriter(new FileOutputStream(tmpFile),
2504
                                        CASTORENCODING);
2505
                        entity.getXmlTag().marshal(writer);
2506
                        writer.close();
2507

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

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

    
2540
        static MDIFrame getFrame() {
2541
                return frame;
2542
        }
2543

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

    
2554
        static HashMap getClassesExtensions() {
2555
                return classesExtensions;
2556
        }
2557

    
2558
        private static Extensions[] getExtensions() {
2559
                List<Extensions> array = new ArrayList<Extensions>();
2560
                Iterator<PluginConfig> iter = pluginsConfig.values().iterator();
2561

    
2562
                while (iter.hasNext()) {
2563
                        array.add(iter.next().getExtensions());
2564
                }
2565

    
2566
                return array.toArray(new Extensions[array.size()]);
2567
        }
2568

    
2569
        public static Iterator getExtensionIterator() {
2570
                return extensions.iterator();
2571
        }
2572

    
2573
        public static HashMap getPluginConfig() {
2574
                return pluginsConfig;
2575
        }
2576

    
2577
        public static Extension getExtension(String s) {
2578
                Extensions[] exts = getExtensions();
2579

    
2580
                for (int i = 0; i < exts.length; i++) {
2581
                        for (int j = 0; j < exts[i].getExtensionCount(); j++) {
2582
                                if (exts[i].getExtension(j).getClassName().equals(s)) {
2583
                                        return exts[i].getExtension(j);
2584
                                }
2585
                        }
2586
                }
2587

    
2588
                return null;
2589
        }
2590

    
2591
        public static AndamiConfig getAndamiConfig() {
2592
                return andamiConfig;
2593
        }
2594

    
2595
        private static class ExtensionComparator implements Comparator {
2596

    
2597
                public int compare(Object o1, Object o2) {
2598
                        Extension e1 = (Extension) o1;
2599
                        Extension e2 = (Extension) o2;
2600

    
2601
                        if (!e1.hasPriority() && !e2.hasPriority()) {
2602
                                return -1;
2603
                        }
2604

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

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

    
2613
                        if (e1.getPriority() != e2.getPriority()) {
2614
                                return e2.getPriority() - e1.getPriority();
2615
                        } else {
2616
                                return (e2.toString().compareTo(e1.toString()));
2617
                        }
2618
                }
2619
        }
2620

    
2621
        private static class MenuComparator implements Comparator<SortableMenu> {
2622

    
2623
                private static ExtensionComparator extComp = new ExtensionComparator();
2624

    
2625
                public int compare(SortableMenu e1, SortableMenu e2) {
2626

    
2627
                        if (!e1.menu.hasPosition() && !e2.menu.hasPosition()) {
2628
                                if (e1.extension instanceof SkinExtensionType) {
2629
                                        return 1;
2630
                                } else if (e2.extension instanceof SkinExtensionType) {
2631
                                        return -1;
2632
                                } else {
2633
                                        return extComp.compare(e1.extension, e2.extension);
2634
                                }
2635
                        }
2636

    
2637
                        if (e1.menu.hasPosition() && !e2.menu.hasPosition()) {
2638
                                return Integer.MIN_VALUE;
2639
                        }
2640

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

    
2658
        private static class SortableMenu {
2659

    
2660
                public PluginClassLoader loader;
2661
                public Menu menu;
2662
                public SkinExtensionType extension;
2663

    
2664
                public SortableMenu(PluginClassLoader loader,
2665
                                SkinExtensionType skinExt, Menu menu2) {
2666
                        extension = skinExt;
2667
                        menu = menu2;
2668
                        this.loader = loader;
2669
                }
2670
                
2671
        }
2672

    
2673
        private static class SortableTool {
2674

    
2675
                public PluginClassLoader loader;
2676
                public ToolBar toolbar;
2677
                public ActionTool actiontool;
2678
                public SelectableTool selectabletool;
2679
                public SkinExtensionType extension;
2680

    
2681
                public SortableTool(PluginClassLoader loader,
2682
                                SkinExtensionType skinExt, ToolBar toolbar2,
2683
                                ActionTool actiontool2) {
2684
                        extension = skinExt;
2685
                        toolbar = toolbar2;
2686
                        actiontool = actiontool2;
2687
                        this.loader = loader;
2688
                }
2689

    
2690
                public SortableTool(PluginClassLoader loader,
2691
                                SkinExtensionType skinExt, ToolBar toolbar2,
2692
                                SelectableTool selectabletool2) {
2693
                        extension = skinExt;
2694
                        toolbar = toolbar2;
2695
                        selectabletool = selectabletool2;
2696
                        this.loader = loader;
2697
                }
2698
        }
2699

    
2700
        private static class ToolBarComparator implements Comparator<SortableTool> {
2701

    
2702
                private static ExtensionComparator extComp = new ExtensionComparator();
2703

    
2704
                public int compare(SortableTool e1, SortableTool e2) {
2705

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

    
2712
                        if (!e1.toolbar.hasPosition() && !e2.toolbar.hasPosition()) {
2713
                                if (e1.extension instanceof SkinExtensionType) {
2714
                                        return 1;
2715
                                } else if (e2.extension instanceof SkinExtensionType) {
2716
                                        return -1;
2717
                                } else {
2718
                                        return extComp.compare(e1.extension, e2.extension);
2719
                                }
2720
                        }
2721

    
2722
                        if (e1.toolbar.hasPosition() && !e2.toolbar.hasPosition()) {
2723
                                return Integer.MIN_VALUE;
2724
                        }
2725

    
2726
                        if (e2.toolbar.hasPosition() && !e1.toolbar.hasPosition()) {
2727
                                return Integer.MAX_VALUE;
2728
                        }
2729
                        if (e1.toolbar.getPosition() != e2.toolbar.getPosition()) {
2730
                                return e1.toolbar.getPosition() - e2.toolbar.getPosition();
2731
                        }
2732

    
2733
                        if (e1.toolbar.getActionTool().equals(e2.toolbar.getActionTool())
2734
                                        && e1.toolbar.getSelectableTool().equals(
2735
                                                        e2.toolbar.getSelectableTool())) {
2736
                                return 0;
2737
                        }
2738
                        return (e1.toolbar.toString().compareTo(e2.toolbar.toString()));
2739
                }
2740
        }
2741

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

    
2765
                private static ToolBarComparator toolBarComp = new ToolBarComparator();
2766

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

    
2776
                        if (e1.actiontool != null) {
2777
                                if (e1.actiontool.hasPosition()) {
2778
                                        e1Position = e1.actiontool.getPosition();
2779
                                }
2780
                        } else if (e1.selectabletool != null) {
2781
                                if (e1.selectabletool.hasPosition()) {
2782
                                        e1Position = e1.selectabletool.getPosition();
2783
                                }
2784
                        }
2785

    
2786
                        if (e2.actiontool != null) {
2787
                                if (e2.actiontool.hasPosition()) {
2788
                                        e2Position = e2.actiontool.getPosition();
2789
                                }
2790
                        } else if (e2.selectabletool != null) {
2791
                                if (e2.selectabletool.hasPosition()) {
2792
                                        e2Position = e2.selectabletool.getPosition();
2793
                                }
2794
                        }
2795

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

    
2814
        /**
2815
         * validates the user before starting gvsig
2816
         * 
2817
         */
2818
        private static void validate() {
2819

    
2820
                IAuthentication session = null;
2821
                try {
2822
                        session = (IAuthentication) Class.forName(
2823
                                        "com.iver.andami.authentication.Session").newInstance();
2824

    
2825
                } catch (ClassNotFoundException e) {
2826
                        return;
2827
                } catch (InstantiationException e) {
2828
                        return;
2829
                } catch (IllegalAccessException e) {
2830
                        return;
2831
                }
2832

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

    
2845
        public static String getDefaultLookAndFeel() {
2846
                String osName = (String) System.getProperty("os.name");
2847

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

    
2856
                return UIManager.getSystemLookAndFeelClassName();
2857
        }
2858

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

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

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

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

    
2967
        logger.info("Loading i18n resources from the application and user "
2968
            + "folders: {}, {}", andamiI18nFolder, userI18nFolder);
2969

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

    
2984
        // Finally load the andami own i18n resources
2985
        org.gvsig.i18n.Messages.addResourceFamily("org.gvsig.andami.text",
2986
            "Andami Launcher");
2987
        }
2988

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

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

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

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

    
3055
                logger
3056
                                .error(Messages
3057
                                                .getString("No_se_encontro_la_extension_especificada_en_el_parametro_exclusiveUI")
3058
                                                + " '" + name + "'");
3059
        }
3060

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

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

    
3133
        /**
3134
         * Manages Andami termination process
3135
         * 
3136
         * @author Cesar Martinez Izquierdo <cesar.martinez@iver.es>
3137
         */
3138
        public class TerminationProcess {
3139

    
3140
                private boolean proceed = false;
3141
                private UnsavedDataPanel panel = null;
3142

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

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

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

    
3183
                        // Finalize all the extensions
3184
                        finalizeExtensions();
3185

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

    
3196
                        logger.info("Quiting application.");
3197

    
3198
                        // Para la depuraci?n de memory leaks
3199
                        System.gc();
3200

    
3201
                        System.exit(0);
3202
                }
3203

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

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

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

    
3263
                private IUnsavedData[] getUnsavedData() throws Exception {
3264
                        List<IUnsavedData> unsavedDataList = new ArrayList<IUnsavedData>();
3265
                        IExtension exclusiveExtension = PluginServices
3266
                                        .getExclusiveUIExtension();
3267

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

    
3305
                public UnsavedDataPanel getUnsavedDataPanel() {
3306
                        if (panel == null) {
3307
                                panel = new UnsavedDataPanel(new IUnsavedData[0]);
3308
                        }
3309
                        return panel;
3310
                }
3311

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

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

    
3332
                        UnsavedDataPanel panel = getUnsavedDataPanel();
3333
                        panel.setUnsavedDataArray(unsavedData);
3334

    
3335
                        panel.addActionListener(panel.new UnsavedDataPanelListener() {
3336

    
3337
                                public void cancel(UnsavedDataPanel panel) {
3338
                                        proceed(false);
3339
                                        PluginServices.getMDIManager().closeWindow(panel);
3340

    
3341
                                }
3342

    
3343
                                public void discard(UnsavedDataPanel panel) {
3344
                                        proceed(true);
3345
                                        PluginServices.getMDIManager().closeWindow(panel);
3346

    
3347
                                }
3348

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

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

    
3394
                        PluginServices.getMDIManager().addWindow(panel);
3395
                        if (proceed) {
3396
                                return JOptionPane.YES_OPTION;
3397
                        } else {
3398
                                return JOptionPane.NO_OPTION;
3399
                        }
3400
                }
3401

    
3402
                private void proceed(boolean proceed) {
3403
                        this.proceed = proceed;
3404
                }
3405

    
3406
        }
3407

    
3408
        public static TerminationProcess getTerminationProcess() {
3409
                return (new Launcher()).new TerminationProcess();
3410
        }
3411

    
3412
        private PackageInfo getPackageInfo(String pluginsFolder) {
3413
                try {
3414
                    PluginsManager pm = PluginsLocator.getManager();
3415

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

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

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

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

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

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

    
3551
                SwingInstallerLocator.getSwingInstallerManager().setDefaultDownloadURL(new File(installURLFile));
3552

    
3553
                // Launch installer
3554
                PluginsManager manager = PluginsLocator.getManager();
3555

    
3556
                File defaultAddonsRepository = PluginsLocator.getManager()
3557
                                .getPluginsFolder();
3558
                installerManager.addLocalAddonRepository(defaultAddonsRepository);
3559
                installerManager
3560
                                .setDefaultLocalAddonRepository(defaultAddonsRepository);
3561

    
3562
                AbstractInstallPackageWizard installPackageWizard = SwingInstallerLocator
3563
                                .getSwingInstallerManager().createInstallPackageWizard(
3564
                                                manager.getApplicationFolder(),
3565
                                                manager.getInstallFolder());
3566
                installPackageWizard
3567
                                .setWizardActionListener(new InstallerWizardActionListener() {
3568

    
3569
                                        public void finish(InstallerWizardPanel installerWizard) {
3570
                                                System.exit(0);
3571
                                        }
3572

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

    
3578
                // the wizard will show the Typical or Advanced mode option.
3579
                installPackageWizard.setAskTypicalOrCustom(true);
3580
                // default packages will be selected.
3581
                installPackageWizard.setSelectDefaultPackages(true);
3582

    
3583

    
3584
                // 1. Create the frame.
3585
                JFrame frame = new JFrame(Messages.get("gvsig_package_installer"));
3586

    
3587
                // 2. What happens when the frame closes?
3588
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
3589
                Runtime.getRuntime().addShutdownHook(new Thread() {
3590

    
3591
                        @Override
3592
                        public void run() {
3593
                                getTerminationProcess().saveAndamiConfig();
3594
                        }
3595
                });
3596

    
3597
                // 3. Add the installer panel to the frame
3598
                frame.getContentPane().add(installPackageWizard, BorderLayout.CENTER);
3599

    
3600
                // 4. Size the frame and center on the screen
3601
                frame.pack();
3602
                frame.setLocationRelativeTo(null);
3603

    
3604
                // 5. Show it.
3605
                frame.setVisible(true);
3606
        }
3607

    
3608
        public static String getInformation() {
3609
                PluginsManager pluginmgr = PluginsLocator.getManager();
3610
                InstallerManager installmgr = InstallerLocator.getInstallerManager();
3611

    
3612
                StringWriter writer = new StringWriter();
3613

    
3614
                Properties props = System.getProperties();
3615

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

    
3639
                // JRE information
3640
                writer.write("JRE\n");
3641
                writer.write("    vendor : " + props.get("java.vendor") + "\n");
3642
                writer.write("    version: " + props.get("java.version") + "\n");
3643
                writer.write("    home   : " + props.get("java.home") + "\n");
3644

    
3645
                writer.write("HTTP Proxy\n");
3646
                writer.write("    http.proxyHost     : " + props.get("http.proxyHost")
3647
                                + "\n");
3648
                writer.write("    http.proxyPort     : " + props.get("http.proxyPort")
3649
                                + "\n");
3650
                writer.write("    http.proxyUserName : "
3651
                                + props.get("http.proxyUserName") + "\n");
3652
                writer.write("    http.proxyPassword : "
3653
                                + props.get("http.proxyPassword") + "\n");
3654

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

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

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

    
3708
}