Statistics
| Revision:

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

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
                                this.addError(Messages
2175
                                                .getString("Launcher.Hay_dependencias_circulares"));
2176

    
2177
                                break;
2178
                        }
2179
                }
2180

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

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

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

    
2197
        private void pluginsMessages() {
2198
                Iterator<String> iterator = pluginsOrdered.iterator();
2199
                PluginConfig config;
2200
                PluginServices ps;
2201

    
2202
                while (iterator.hasNext()) {
2203
                        String pluginName = iterator.next();
2204
                        config = pluginsConfig.get(pluginName);
2205
                        ps = pluginsServices.get(pluginName);
2206

    
2207
                        if ((config.getResourceBundle() != null)
2208
                                        && !config.getResourceBundle().getName().equals("")) {
2209
                                // add the locale files associated with the plugin
2210
                                org.gvsig.i18n.Messages.addResourceFamily(config
2211
                                                .getResourceBundle().getName(), ps.getClassLoader(),
2212
                                                pluginName);
2213
                                org.gvsig.i18n.Messages.addResourceFamily("i18n."+config
2214
                                                .getResourceBundle().getName(), ps.getClassLoader(),
2215
                                                pluginName);
2216
                        }
2217
                }
2218
        }
2219

    
2220
        static public PluginServices getPluginServices(String name) {
2221
                return (PluginServices) pluginsServices.get(name);
2222
        }
2223

    
2224
        static String getPluginsDir() {
2225
                return andamiConfig.getPluginsDirectory();
2226
        }
2227

    
2228
        static void setPluginsDir(String s) {
2229
                andamiConfig.setPluginsDirectory(s);
2230
        }
2231

    
2232
        static MDIFrame getMDIFrame() {
2233
                return frame;
2234
        }
2235

    
2236
        private void loadPlugins(String pluginsDirectory) {
2237
                File pDir = new File(pluginsDirectory);
2238

    
2239
                if (!pDir.exists()) {
2240
                        logger
2241
                                        .error("\n\tPlugins directory not found: "
2242
                                                        + pDir.getAbsolutePath()
2243
                                                        + "\n\tDid you specify the correct directory in the Launch Configuration parameters?\n\tExiting now...");
2244
                        System.exit(-1);
2245
                        return;
2246
                }
2247

    
2248
                File[] pluginDirs = pDir.listFiles();
2249
                if (pluginDirs.length == 0) {
2250
                        logger
2251
                                        .error("\n\tPlugins directory is empty: "
2252
                                                        + pDir.getAbsolutePath()
2253
                                                        + "Did you specify the correct directory in the Launch Configuration parameters?\n\tExiting now...");
2254
                        System.exit(-1);
2255
                        return;
2256
                }
2257

    
2258
                for (int i = 0; i < pluginDirs.length; i++) {
2259
                        if (pluginDirs[i].isDirectory()) {
2260
                                String pluginName =  pluginDirs[i].getName();
2261
                                File configXml = new File(pluginDirs[i].getAbsolutePath(),
2262
                                                "config.xml");
2263

    
2264
                                try {
2265
                                        FileInputStream is = new FileInputStream(configXml);
2266
                                        Reader xml = org.gvsig.utils.xml.XMLEncodingUtils.getReader(is);
2267
                                        if (xml == null) {
2268
                                                // the encoding was not correctly detected, use system
2269
                                                // default
2270
                                                xml = new FileReader(configXml);
2271
                                        } else {
2272
                                                // use a buffered reader to improve performance
2273
                                                xml = new BufferedReader(xml);
2274
                                        }
2275
                                        PluginConfig pConfig = (PluginConfig) PluginConfig.unmarshal(xml);
2276
                                        pluginsConfig.put(pluginDirs[i].getName(), pConfig);
2277
                                } catch (FileNotFoundException e) {
2278
                                        logger.info("Plugin '"+pluginName+"' without config.xml ("
2279
                                                                        + pluginDirs[i].getAbsolutePath() + ").");
2280
                                } catch (MarshalException e) {
2281
                                        this.addError("Can't load plugin '"+pluginName+"', incorrect config.xml." + e.getMessage() +" ("
2282
                                                        + pluginDirs[i].getAbsolutePath() + ").", e);
2283
                                } catch (ValidationException e) {
2284
                                        this.addError("Can't load plugin '"+pluginName+"', invalid config.xml." + e.getMessage() +" ("
2285
                                                        + pluginDirs[i].getAbsolutePath() + ").", e);
2286
                                }
2287
                        }
2288
                }
2289

    
2290
                if (pluginsConfig.size() == 0) {
2291
                        logger.error("No valid plugin was found. The plugins directory currently is: "
2292
                                                        + pDir.getAbsolutePath()
2293
                                                        + "\n\tDid you specify the correct directory in the Launch Configuration parameters?\n\tExiting now...");
2294
                        System.exit(-1);
2295
                        return;
2296
                }
2297
        }
2298

    
2299
        private static Locale getLocale(String language, String country,
2300
                        String variant) {
2301
                if (variant != null) {
2302
                        return new Locale(language, country, variant);
2303
                } else if (country != null) {
2304
                        return new Locale(language, country);
2305
                } else if (language != null) {
2306
                        return new Locale(language);
2307
                } else {
2308
                        return new Locale("es");
2309
                }
2310
        }
2311

    
2312
        private static void andamiConfigToXML(String file) throws IOException,
2313
                        MarshalException, ValidationException {
2314
                // write on a temporary file in order to not destroy current file if
2315
                // there is some problem while marshaling
2316
                File tmpFile = new File(file + "-"
2317
                                + DateTime.getCurrentDate().getTime());
2318
                File xml = new File(file);
2319
                File parent = xml.getParentFile();
2320
                parent.mkdirs();
2321

    
2322
                BufferedOutputStream os = new BufferedOutputStream(
2323
                                new FileOutputStream(tmpFile));
2324
                OutputStreamWriter writer = new OutputStreamWriter(os, CASTORENCODING);
2325
                andamiConfig.marshal(writer);
2326
                writer.close();
2327

    
2328
                // if marshaling process finished correctly, move the file to the
2329
                // correct one
2330
                xml.delete();
2331
                if (!tmpFile.renameTo(xml)) {
2332
                        // if rename was not succesful, try copying it
2333
                        FileChannel sourceChannel = new FileInputStream(tmpFile)
2334
                                        .getChannel();
2335
                        FileChannel destinationChannel = new FileOutputStream(xml)
2336
                                        .getChannel();
2337
                        sourceChannel.transferTo(0, sourceChannel.size(),
2338
                                        destinationChannel);
2339
                        sourceChannel.close();
2340
                        destinationChannel.close();
2341
                }
2342
        }
2343

    
2344
        private static void andamiConfigFromXML(String file)
2345
                        throws ConfigurationException {
2346
                File xml = new File(file);
2347

    
2348
                InputStreamReader reader = null;
2349
                try {
2350
                        // Se lee la configuraci?n
2351
                        reader = XMLEncodingUtils.getReader(xml);
2352
                        andamiConfig = (AndamiConfig) AndamiConfig.unmarshal(reader);
2353
                } catch (FileNotFoundException e) {
2354
                        // Si no existe se ponen los valores por defecto
2355
                        andamiConfig = getDefaultAndamiConfig();
2356
                } catch (MarshalException e) {
2357
                        // try to close the stream, maybe it remains open
2358
                        if (reader != null) {
2359
                                try {
2360
                                        reader.close();
2361
                                } catch (IOException e1) {
2362
                                }
2363
                        }
2364
                        // if there was a problem reading the file, backup it and create a
2365
                        // new one with default values
2366
                        String backupFile = file + "-"
2367
                                        + DateTime.getCurrentDate().getTime();
2368
                        NotificationManager
2369
                                        .addError(
2370
                                                        Messages
2371
                                                                        .getString("Error_reading_andami_config_New_file_created_A_backup_was_made_on_")
2372
                                                                        + backupFile, new ConfigurationException(e));
2373
                        xml.renameTo(new File(backupFile));
2374
                        andamiConfig = getDefaultAndamiConfig();
2375
                } catch (ValidationException e) {
2376
                        throw new ConfigurationException(e);
2377
                }
2378
        }
2379

    
2380
        private static AndamiConfig getDefaultAndamiConfig() {
2381
                AndamiConfig andamiConfig = new AndamiConfig();
2382

    
2383
                Andami andami = new Andami();
2384
                andami.setUpdate(true);
2385
                andamiConfig.setAndami(andami);
2386
                andamiConfig.setLocaleCountry(Locale.getDefault().getCountry());
2387
                andamiConfig.setLocaleLanguage(Locale.getDefault().getLanguage());
2388
                andamiConfig.setLocaleVariant(Locale.getDefault().getVariant());
2389

    
2390
                if (System.getProperty("javawebstart.version") != null) // Es java web
2391
                // start)
2392
                {
2393
                        andamiConfig
2394
                                        .setPluginsDirectory(new File(appHomeDir, "extensiones")
2395
                                                        .getAbsolutePath());
2396
                } else {
2397
                        andamiConfig.setPluginsDirectory(new File(appName, "extensiones")
2398
                                        .getAbsolutePath());
2399
                }
2400

    
2401
                andamiConfig.setPlugin(new Plugin[0]);
2402
                return andamiConfig;
2403
        }
2404

    
2405
        private static XMLEntity persistenceFromXML() throws ConfigurationException {
2406
                File xml = getPluginsPersistenceFile(true);
2407

    
2408
                if (xml.exists()) {
2409
                        InputStreamReader reader = null;
2410

    
2411
                        try {
2412
                                reader = XMLEncodingUtils.getReader(xml);
2413
                                XmlTag tag = (XmlTag) XmlTag.unmarshal(reader);
2414
                                return new XMLEntity(tag);
2415
                        } catch (FileNotFoundException e) {
2416
                                throw new ConfigurationException(e);
2417
                        } catch (MarshalException e) {
2418

    
2419
                                // try to reopen with default encoding (for backward
2420
                                // compatibility)
2421
                                try {
2422
                                        reader = new FileReader(xml);
2423
                                        XmlTag tag = (XmlTag) XmlTag.unmarshal(reader);
2424
                                        return new XMLEntity(tag);
2425

    
2426
                                } catch (MarshalException ex) {
2427
                                        // try to close the stream, maybe it remains open
2428
                                        if (reader != null) {
2429
                                                try {
2430
                                                        reader.close();
2431
                                                } catch (IOException e1) {
2432
                                                }
2433
                                        }
2434
                                        // backup the old file
2435
                                        String backupFile = getPluginsPersistenceFile(true)
2436
                                                        .getPath()
2437
                                                        + "-" + DateTime.getCurrentDate().getTime();
2438
                                        NotificationManager
2439
                                                        .addError(
2440
                                                                        Messages
2441
                                                                                        .getString("Error_reading_plugin_persinstence_New_file_created_A_backup_was_made_on_")
2442
                                                                                        + backupFile,
2443
                                                                        new ConfigurationException(e));
2444
                                        xml.renameTo(new File(backupFile));
2445
                                        // create a new, empty configuration
2446
                                        return new XMLEntity();
2447
                                } catch (FileNotFoundException ex) {
2448
                                        return new XMLEntity();
2449
                                } catch (ValidationException ex) {
2450
                                        throw new ConfigurationException(e);
2451
                                }
2452
                        } catch (ValidationException e) {
2453
                                throw new ConfigurationException(e);
2454
                        }
2455
                } else {
2456
                        return new XMLEntity();
2457
                }
2458
        }
2459

    
2460
        private static File getPluginsPersistenceFile(boolean read) {
2461
                if (read) {
2462
                        File pluginsPersistenceFile = new File(getAppHomeDir(),
2463
                                        "plugins-persistence-2_0.xml");
2464
                        if (pluginsPersistenceFile.exists()) {
2465
                                return pluginsPersistenceFile;
2466
                        }
2467
                        pluginsPersistenceFile = new File(getAppHomeDir(),
2468
                                        "plugins-persistence.xml");
2469
                        if (pluginsPersistenceFile.exists()) {
2470
                                return pluginsPersistenceFile;
2471
                        }
2472
                }
2473
                return new File(getAppHomeDir(), "plugins-persistence-2_0.xml");
2474

    
2475
        }
2476

    
2477
        private static void persistenceToXML(XMLEntity entity)
2478
                        throws ConfigurationException {
2479
                // write on a temporary file in order to not destroy current file if
2480
                // there is some problem while marshaling
2481
                File tmpFile = new File(getPluginsPersistenceFile(false).getPath()
2482
                                + "-" + DateTime.getCurrentDate().getTime());
2483

    
2484
                File xml = getPluginsPersistenceFile(false);
2485
                OutputStreamWriter writer = null;
2486

    
2487
                try {
2488
                        writer = new OutputStreamWriter(new FileOutputStream(tmpFile),
2489
                                        CASTORENCODING);
2490
                        entity.getXmlTag().marshal(writer);
2491
                        writer.close();
2492

    
2493
                        // if marshaling process finished correctly, move the file to the
2494
                        // correct one
2495
                        xml.delete();
2496
                        if (!tmpFile.renameTo(xml)) {
2497
                                // if rename was not succesful, try copying it
2498
                                FileChannel sourceChannel = new FileInputStream(tmpFile)
2499
                                                .getChannel();
2500
                                FileChannel destinationChannel = new FileOutputStream(xml)
2501
                                                .getChannel();
2502
                                sourceChannel.transferTo(0, sourceChannel.size(),
2503
                                                destinationChannel);
2504
                                sourceChannel.close();
2505
                                destinationChannel.close();
2506

    
2507
                        }
2508
                } catch (FileNotFoundException e) {
2509
                        throw new ConfigurationException(e);
2510
                } catch (MarshalException e) {
2511
                        // try to close the stream, maybe it remains open
2512
                        if (writer != null) {
2513
                                try {
2514
                                        writer.close();
2515
                                } catch (IOException e1) {
2516
                                }
2517
                        }
2518
                } catch (ValidationException e) {
2519
                        throw new ConfigurationException(e);
2520
                } catch (IOException e) {
2521
                        throw new ConfigurationException(e);
2522
                }
2523
        }
2524

    
2525
        static MDIFrame getFrame() {
2526
                return frame;
2527
        }
2528

    
2529
        /**
2530
         * Gracefully closes the application. It shows dialogs to save data, finish
2531
         * processes, etc, then it terminates the extensions, removes temporal files
2532
         * and finally exits.
2533
         */
2534
        public synchronized static void closeApplication() {
2535
                TerminationProcess terminationProcess = (new Launcher()).new TerminationProcess();
2536
                terminationProcess.run();
2537
        }
2538

    
2539
        static HashMap getClassesExtensions() {
2540
                return classesExtensions;
2541
        }
2542

    
2543
        private static Extensions[] getExtensions() {
2544
                List<Extensions> array = new ArrayList<Extensions>();
2545
                Iterator<PluginConfig> iter = pluginsConfig.values().iterator();
2546

    
2547
                while (iter.hasNext()) {
2548
                        array.add(iter.next().getExtensions());
2549
                }
2550

    
2551
                return array.toArray(new Extensions[array.size()]);
2552
        }
2553

    
2554
        public static Iterator getExtensionIterator() {
2555
                return extensions.iterator();
2556
        }
2557

    
2558
        public static HashMap getPluginConfig() {
2559
                return pluginsConfig;
2560
        }
2561

    
2562
        public static Extension getExtension(String s) {
2563
                Extensions[] exts = getExtensions();
2564

    
2565
                for (int i = 0; i < exts.length; i++) {
2566
                        for (int j = 0; j < exts[i].getExtensionCount(); j++) {
2567
                                if (exts[i].getExtension(j).getClassName().equals(s)) {
2568
                                        return exts[i].getExtension(j);
2569
                                }
2570
                        }
2571
                }
2572

    
2573
                return null;
2574
        }
2575

    
2576
        public static AndamiConfig getAndamiConfig() {
2577
                return andamiConfig;
2578
        }
2579

    
2580
        private static class ExtensionComparator implements Comparator {
2581

    
2582
                public int compare(Object o1, Object o2) {
2583
                        Extension e1 = (Extension) o1;
2584
                        Extension e2 = (Extension) o2;
2585

    
2586
                        if (!e1.hasPriority() && !e2.hasPriority()) {
2587
                                return -1;
2588
                        }
2589

    
2590
                        if (e1.hasPriority() && !e2.hasPriority()) {
2591
                                return Integer.MIN_VALUE;
2592
                        }
2593

    
2594
                        if (e2.hasPriority() && !e1.hasPriority()) {
2595
                                return Integer.MAX_VALUE;
2596
                        }
2597

    
2598
                        if (e1.getPriority() != e2.getPriority()) {
2599
                                return e2.getPriority() - e1.getPriority();
2600
                        } else {
2601
                                return (e2.toString().compareTo(e1.toString()));
2602
                        }
2603
                }
2604
        }
2605

    
2606
        private static class MenuComparator implements Comparator<SortableMenu> {
2607

    
2608
                private static ExtensionComparator extComp = new ExtensionComparator();
2609

    
2610
                public int compare(SortableMenu e1, SortableMenu e2) {
2611

    
2612
                        if (!e1.menu.hasPosition() && !e2.menu.hasPosition()) {
2613
                                if (e1.extension instanceof SkinExtensionType) {
2614
                                        return 1;
2615
                                } else if (e2.extension instanceof SkinExtensionType) {
2616
                                        return -1;
2617
                                } else {
2618
                                        return extComp.compare(e1.extension, e2.extension);
2619
                                }
2620
                        }
2621

    
2622
                        if (e1.menu.hasPosition() && !e2.menu.hasPosition()) {
2623
                                return Integer.MIN_VALUE;
2624
                        }
2625

    
2626
                        if (e2.menu.hasPosition() && !e1.menu.hasPosition()) {
2627
                                return Integer.MAX_VALUE;
2628
                        }
2629
                        
2630
                        if( e1.menu.getPosition() == e2.menu.getPosition() ) {
2631
                                // we don't return 0 unless both objects are the same, otherwise
2632
                                // the objects get overwritten in the treemap
2633
                                return (e1.toString().compareTo(e2.toString()));
2634
                        }
2635
                    if( e1.menu.getPosition() > e2.menu.getPosition() ) {
2636
                                return Integer.MAX_VALUE;
2637
                        }
2638
                    return Integer.MIN_VALUE;
2639
                    
2640
                }
2641
        }
2642

    
2643
        private static class SortableMenu {
2644

    
2645
                public PluginClassLoader loader;
2646
                public Menu menu;
2647
                public SkinExtensionType extension;
2648

    
2649
                public SortableMenu(PluginClassLoader loader,
2650
                                SkinExtensionType skinExt, Menu menu2) {
2651
                        extension = skinExt;
2652
                        menu = menu2;
2653
                        this.loader = loader;
2654
                }
2655
                
2656
        }
2657

    
2658
        private static class SortableTool {
2659

    
2660
                public PluginClassLoader loader;
2661
                public ToolBar toolbar;
2662
                public ActionTool actiontool;
2663
                public SelectableTool selectabletool;
2664
                public SkinExtensionType extension;
2665

    
2666
                public SortableTool(PluginClassLoader loader,
2667
                                SkinExtensionType skinExt, ToolBar toolbar2,
2668
                                ActionTool actiontool2) {
2669
                        extension = skinExt;
2670
                        toolbar = toolbar2;
2671
                        actiontool = actiontool2;
2672
                        this.loader = loader;
2673
                }
2674

    
2675
                public SortableTool(PluginClassLoader loader,
2676
                                SkinExtensionType skinExt, ToolBar toolbar2,
2677
                                SelectableTool selectabletool2) {
2678
                        extension = skinExt;
2679
                        toolbar = toolbar2;
2680
                        selectabletool = selectabletool2;
2681
                        this.loader = loader;
2682
                }
2683
        }
2684

    
2685
        private static class ToolBarComparator implements Comparator<SortableTool> {
2686

    
2687
                private static ExtensionComparator extComp = new ExtensionComparator();
2688

    
2689
                public int compare(SortableTool e1, SortableTool e2) {
2690

    
2691
                        // if the toolbars have the same name, they are considered to be
2692
                        // the same toolbar, so we don't need to do further comparing
2693
                        if (e1.toolbar.getName().equals(e2.toolbar.getName())) {
2694
                                return 0;
2695
                        }
2696

    
2697
                        if (!e1.toolbar.hasPosition() && !e2.toolbar.hasPosition()) {
2698
                                if (e1.extension instanceof SkinExtensionType) {
2699
                                        return 1;
2700
                                } else if (e2.extension instanceof SkinExtensionType) {
2701
                                        return -1;
2702
                                } else {
2703
                                        return extComp.compare(e1.extension, e2.extension);
2704
                                }
2705
                        }
2706

    
2707
                        if (e1.toolbar.hasPosition() && !e2.toolbar.hasPosition()) {
2708
                                return Integer.MIN_VALUE;
2709
                        }
2710

    
2711
                        if (e2.toolbar.hasPosition() && !e1.toolbar.hasPosition()) {
2712
                                return Integer.MAX_VALUE;
2713
                        }
2714
                        if (e1.toolbar.getPosition() != e2.toolbar.getPosition()) {
2715
                                return e1.toolbar.getPosition() - e2.toolbar.getPosition();
2716
                        }
2717

    
2718
                        if (e1.toolbar.getActionTool().equals(e2.toolbar.getActionTool())
2719
                                        && e1.toolbar.getSelectableTool().equals(
2720
                                                        e2.toolbar.getSelectableTool())) {
2721
                                return 0;
2722
                        }
2723
                        return (e1.toolbar.toString().compareTo(e2.toolbar.toString()));
2724
                }
2725
        }
2726

    
2727
        /**
2728
         * <p>
2729
         * This class is used to compare tools (selectabletool and actiontool),
2730
         * using the "position" attribute.
2731
         * </p>
2732
         * <p>
2733
         * The ordering criteria are:
2734
         * </p>
2735
         * <ul>
2736
         * <li>If the tools are placed in different toolbars, they use the toolbars'
2737
         * order. (using the ToolBarComparator).</li>
2738
         * <li></li>
2739
         * <li>If any of the tools has not 'position' attribute, the tool which
2740
         * <strong>has</strong> the attribute will be placed first.</li>
2741
         * <li>If both tools have the same position (or they don't have a 'position'
2742
         * attribute), the priority of the extensions where the tool is defined.</li>
2743
         * </ul>
2744
         * 
2745
         * @author cesar
2746
         * @version $Revision: 40305 $
2747
         */
2748
        private static class ToolComparator implements Comparator<SortableTool> {
2749

    
2750
                private static ToolBarComparator toolBarComp = new ToolBarComparator();
2751

    
2752
                public int compare(SortableTool e1, SortableTool e2) {
2753
                        // compare the toolbars which contain the tools
2754
                        long result = toolBarComp.compare(e1, e2);
2755
                        if (result != 0) { // if the toolbars are different, use their order
2756
                                return result>0? 1:-1;
2757
                        }
2758
                        // otherwise, compare the tools
2759
                        long e1Position = -1, e2Position = -1;
2760

    
2761
                        if (e1.actiontool != null) {
2762
                                if (e1.actiontool.hasPosition()) {
2763
                                        e1Position = e1.actiontool.getPosition();
2764
                                }
2765
                        } else if (e1.selectabletool != null) {
2766
                                if (e1.selectabletool.hasPosition()) {
2767
                                        e1Position = e1.selectabletool.getPosition();
2768
                                }
2769
                        }
2770

    
2771
                        if (e2.actiontool != null) {
2772
                                if (e2.actiontool.hasPosition()) {
2773
                                        e2Position = e2.actiontool.getPosition();
2774
                                }
2775
                        } else if (e2.selectabletool != null) {
2776
                                if (e2.selectabletool.hasPosition()) {
2777
                                        e2Position = e2.selectabletool.getPosition();
2778
                                }
2779
                        }
2780

    
2781
                        if ((e1Position == -1) && (e2Position != -1)) {
2782
                                return 1;
2783
                        }
2784
                        if ((e1Position != -1) && (e2Position == -1)) {
2785
                                return -1;
2786
                        }
2787
                        if ((e1Position != -1) && (e2Position != -1)) {
2788
                                result = e1Position - e2Position;
2789
                                // we don't return 0 unless both objects are the same, otherwise
2790
                                // the objects get overwritten in the treemap
2791
                                if (result != 0) {
2792
                                        return  result>0? 1:-1;
2793
                                }
2794
                        }
2795
                        return e1.toString().compareTo(e2.toString());
2796
                }
2797
        }
2798

    
2799
        /**
2800
         * validates the user before starting gvsig
2801
         * 
2802
         */
2803
        private static void validate() {
2804

    
2805
                IAuthentication session = null;
2806
                try {
2807
                        session = (IAuthentication) Class.forName(
2808
                                        "com.iver.andami.authentication.Session").newInstance();
2809

    
2810
                } catch (ClassNotFoundException e) {
2811
                        return;
2812
                } catch (InstantiationException e) {
2813
                        return;
2814
                } catch (IllegalAccessException e) {
2815
                        return;
2816
                }
2817

    
2818
                session.setPluginDirectory(andamiConfig.getPluginsDirectory());
2819
                if (session.validationRequired()) {
2820
                        if (session.Login()) {
2821
                                logger.info("You are logged in");
2822
                        } else {
2823
                                JOptionPane.showMessageDialog((Component) PluginServices
2824
                                                .getMainFrame(), "You are not logged in");
2825
                        }
2826
                        PluginServices.setAuthentication(session);
2827
                }
2828
        }
2829

    
2830
        public static String getDefaultLookAndFeel() {
2831
                String osName = (String) System.getProperty("os.name");
2832

    
2833
                if ((osName.length() > 4)
2834
                                && osName.substring(0, 5).toLowerCase().equals("linux")) {
2835
                        return nonWinDefaultLookAndFeel;
2836
                }
2837
                if (osName.toLowerCase().startsWith("mac os x")) {
2838
                        return "ch.randelshofer.quaqua.QuaquaLookAndFeel";
2839
                }
2840

    
2841
                return UIManager.getSystemLookAndFeelClassName();
2842
        }
2843

    
2844
        /**
2845
         * Gets the ISO 839 two-characters-long language code matching the provided
2846
         * language code (which may be an ISO 839-2/T three-characters-long code or
2847
         * an ISO 839-1 two-characters-long code).
2848
         * 
2849
         * If the provided parameter is already two characters long, it returns the
2850
         * parameter without any modification.
2851
         * 
2852
         * @param langCode
2853
         *            A language code representing either an ISO 839-2/T language
2854
         *            code or an ISO 839-1 code.
2855
         * @return A two-characters-long code specifying an ISO 839 language code.
2856
         */
2857
        private static String normalizeLanguageCode(String langCode) {
2858
                final String fileName = "iso_639.tab";
2859
                if (langCode.length() == 2) {
2860
                        return langCode;
2861
                } else if (langCode.length() == 3) {
2862
                        if (langCode.equals("va") || langCode.equals("val")) { // special
2863
                                // case
2864
                                // for
2865
                                // Valencian
2866
                                return "ca";
2867
                        }
2868
                        URL isoCodes = Launcher.class.getClassLoader()
2869
                                        .getResource(fileName);
2870
                        if (isoCodes != null) {
2871
                                try {
2872
                                        BufferedReader reader = new BufferedReader(
2873
                                                        new InputStreamReader(isoCodes.openStream(),
2874
                                                                        "ISO-8859-1"));
2875
                                        String line;
2876

    
2877
                                        while ((line = reader.readLine()) != null) {
2878
                                                String[] language = line.split("\t");
2879
                                                if (language[0].equals(langCode)) {
2880
                                                        // the three
2881
                                                        // characters code
2882
                                                        return language[2]; // third column i the two
2883
                                                        // characters code
2884
                                                }
2885
                                        }
2886
                                } catch (IOException ex) {
2887
                                        logger.error(Messages
2888
                                                        .getString("Error_reading_isocodes_file"), ex);
2889
                                        return "es";
2890
                                }
2891
                        } else {
2892
                                logger.error(Messages.getString("Error_reading_isocodes_file"));
2893
                                return "es";
2894
                        }
2895
                }
2896
                return "es";
2897
        }
2898

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

    
2945
        // Create classloader for the i18n resources in the
2946
        // andami and user i18n folder. Those values will have
2947
        // precedence over any other values added afterwards
2948
        File andamiI18nFolder =
2949
            new File(System.getProperty("user.dir"), "i18n");
2950
        File userI18nFolder = new File(getAppHomeDir(), "i18n");
2951

    
2952
        logger.info("Loading i18n resources from the application and user "
2953
            + "folders: {}, {}", andamiI18nFolder, userI18nFolder);
2954

    
2955
        URL[] i18nURLs;
2956
        try {
2957
            i18nURLs =
2958
                new URL[] { userI18nFolder.toURI().toURL(),
2959
                    andamiI18nFolder.toURI().toURL() };
2960
            ClassLoader i18nClassLoader = new URLClassLoader(i18nURLs);
2961
            org.gvsig.i18n.Messages.addResourceFamily("text", i18nClassLoader,
2962
                "Andami Launcher");
2963
        } catch (MalformedURLException e) {
2964
            logger.error("Error loading i18n resources from the application "
2965
                + "and user folders: " + andamiI18nFolder + ", "
2966
                + userI18nFolder, e);
2967
        }
2968

    
2969
        // Finally load the andami own i18n resources
2970
        org.gvsig.i18n.Messages.addResourceFamily("org.gvsig.andami.text",
2971
            "Andami Launcher");
2972
        }
2973

    
2974
        /**
2975
         * Gets Home Directory location of the application into users home folder.
2976
         * 
2977
         * May be set from outside the aplication by means of
2978
         * -DgvSIG.home=C:/data/gvSIG, where gvSIG its the name of the application
2979
         * 
2980
         * @return
2981
         */
2982
        public static String getAppHomeDir() {
2983
                return appHomeDir;
2984
        }
2985
        
2986
    public static File getApplicationHomeFolder() {
2987
        return new File(getAppHomeDir());
2988
    }
2989

    
2990
        /**
2991
         * Sets Home Directory location of the application. May be set from outside
2992
         * the aplication by means of -DgvSIG.home=C:/data/gvSIG, where gvSIG its
2993
         * the name of the application
2994
         * 
2995
         * @param appHomeDir
2996
         */
2997
        public static void setAppHomeDir(String appHomeDir) {
2998
                Launcher.appHomeDir = appHomeDir;
2999
        }
3000

    
3001
        /**
3002
         * Initialize the extesion that have to take the control of the state of
3003
         * action controls of the UI of all extensions. <br>
3004
         * <br>
3005
         * For use this option you have to add an argument to the command line like
3006
         * this: <br>
3007
         * <br>
3008
         * -exclusiveUI={pathToExtensionClass} <br>
3009
         * 
3010
         * @see org.gvsig.andami.plugins.IExtension#isEnabled(IExtension extension)
3011
         * @see org.gvsig.andami.plugins.IExtension#isVisible(IExtension extension)
3012
         */
3013
        private static void initializeExclusiveUIExtension() {
3014
                String name = PluginServices.getArgumentByName("exclusiveUI");
3015
                if (name == null) {
3016
                        return;
3017
                }
3018

    
3019
                Iterator<Class<? extends IExtension>> iter = classesExtensions.keySet()
3020
                                .iterator();
3021
                int charIndex;
3022
                Class<? extends IExtension> key;
3023
                while (iter.hasNext()) {
3024
                        key = iter.next();
3025
                        charIndex = key.getName().indexOf(name);
3026
                        // System.out.println("key='"+key.getName()+"' name='"+name+"' charIndex="+charIndex);
3027
                        if (charIndex == 0) {
3028
                                IExtension ext = classesExtensions.get(key);
3029
                                if (ext instanceof ExtensionDecorator) {
3030
                                        ext = ((ExtensionDecorator) ext).getExtension();
3031
                                }
3032
                                if (ext instanceof ExclusiveUIExtension) {
3033
                                        PluginServices
3034
                                                        .setExclusiveUIExtension((ExclusiveUIExtension) ext);
3035
                                }
3036
                                break;
3037
                        }
3038
                }
3039

    
3040
                logger
3041
                                .error(Messages
3042
                                                .getString("No_se_encontro_la_extension_especificada_en_el_parametro_exclusiveUI")
3043
                                                + " '" + name + "'");
3044
        }
3045

    
3046
        // public static void initIconThemes() {
3047
        // // load the iconTheme
3048
        // IconThemeManager iconManager = new IconThemeManager();
3049
        // PluginServices.setIconThemeManager(iconManager);
3050
        // IconThemeInfo selectedTheme = iconManager.readConfig();
3051
        // if (selectedTheme!=null) {
3052
        // iconManager.setDefault(selectedTheme);
3053
        // logger.info("Setting the icon theme: "+selectedTheme.toVerboseString());
3054
        // }
3055
        // else {
3056
        // // set the default dir and try to load the default theme
3057
        // try {
3058
        // iconManager.setThemesDir(new File("iconThemes"));
3059
        // IconThemeInfo[] list = iconManager.list();
3060
        //
3061
        // for (int i=0; i<list.length; i++) {
3062
        // if (list[i].getResourceName().equals("iconThemes/icons")) {
3063
        // iconManager.setDefault(list[i]);
3064
        // logger.info("Setting the default icon theme: "+list[i].toVerboseString());
3065
        // return;
3066
        // }
3067
        // }
3068
        // } catch (FileNotFoundException e) {
3069
        // logger.info("IconTheme basedir does not exist");
3070
        // }
3071
        // // create an empty theme
3072
        // IconThemeInfo info = new IconThemeInfo();
3073
        // info.setName("No theme loaded");
3074
        // info.setResource(null); // null resource means that no real theme is
3075
        // loaded
3076
        // info.setDescription("No theme loaded");
3077
        // info.setVersion("0");
3078
        // iconManager.setDefault(new IconTheme(info));
3079
        // logger.info("Setting an empty icon theme");
3080
        //
3081
        // }
3082
        // }
3083

    
3084
        public static void initIconThemes() {
3085
                PluginsManager pluginsManager = PluginsLocator.getManager();
3086
                IconThemeManager iconManager = ToolsSwingLocator.getIconThemeManager();
3087
                
3088
                File f = new File(pluginsManager.getApplicationFolder(),"icon-theme");
3089
                if( !f.exists() ) { 
3090
                        try {
3091
                                f.mkdir();
3092
                        } catch(Exception ex) {
3093
                                // Do nothing
3094
                        }
3095
                }
3096
                iconManager.getRepository().add(f,"_Global");
3097
                
3098
                f = new File(pluginsManager.getApplicationHomeFolder(),"icon-theme");
3099
                if( !f.exists() ) {
3100
                        try {
3101
                                f.mkdir();
3102
                        } catch(Exception ex) {
3103
                                // Do nothing
3104
                        }
3105
                }
3106
                iconManager.getRepository().add(f,"_User");
3107
                
3108
                Preferences prefs = Preferences.userRoot().node("gvsig.icontheme");
3109
                String defaultThemeID = prefs.get("default-theme", null);
3110
                if( defaultThemeID != null ) {
3111
                        IconTheme iconTheme = iconManager.get(defaultThemeID);
3112
                        if( iconTheme != null ) {
3113
                                iconManager.setCurrent(iconTheme);
3114
                        }
3115
                }
3116
        }
3117

    
3118
        /**
3119
         * Manages Andami termination process
3120
         * 
3121
         * @author Cesar Martinez Izquierdo <cesar.martinez@iver.es>
3122
         */
3123
        public class TerminationProcess {
3124

    
3125
                private boolean proceed = false;
3126
                private UnsavedDataPanel panel = null;
3127

    
3128
                public void run() {
3129
                        try {
3130
                                int exit = manageUnsavedData();
3131
                                if ((exit == JOptionPane.NO_OPTION)
3132
                                                || (exit == JOptionPane.CLOSED_OPTION)) {
3133
                                        // the user doesn't want to exit
3134
                                        return;
3135
                                }
3136
                                closeAndami();
3137
                        } catch (Exception e) {
3138
                                // It is not possible to close the application.
3139
                                // this exception has been registered before
3140
                        }
3141
                }
3142

    
3143
                /**
3144
                 * Finishes the application without asking user if want or not to save
3145
                 * unsaved data.
3146
                 */
3147
                public void closeAndami() {
3148
                        try {
3149
                                saveAndamiConfig();
3150
                        } catch (Exception ex) {
3151
                                logger
3152
                                                .error(
3153
                                                                "There was an error exiting application, can't save andami-config.xml",
3154
                                                                ex);
3155
                        }
3156

    
3157
                        try {
3158
                                // Persistencia de los plugins
3159
                                savePluginPersistence();
3160
                                savePluginsProperties();
3161
                        } catch (Exception ex) {
3162
                                logger
3163
                                                .error(
3164
                                                                "There was an error exiting application, can't save plugins properties",
3165
                                                                ex);
3166
                        }
3167

    
3168
                        // Finalize all the extensions
3169
                        finalizeExtensions();
3170

    
3171
                        try {
3172
                                // Clean any temp data created
3173
                                Utilities.cleanUpTempFiles();
3174
                        } catch (Exception ex) {
3175
                                logger
3176
                                                .error(
3177
                                                                "There was an error exiting application, can't remove temporary files",
3178
                                                                ex);
3179
                        }
3180

    
3181
                        logger.info("Quiting application.");
3182

    
3183
                        // Para la depuraci?n de memory leaks
3184
                        System.gc();
3185

    
3186
                        System.exit(0);
3187
                }
3188

    
3189
                /**
3190
         * 
3191
         */
3192
                public void saveAndamiConfig() {
3193
                        // Configuraci?n de Andami
3194
                        try {
3195
                                andamiConfigToXML(andamiConfigPath);
3196
                        } catch (MarshalException e) {
3197
                                logger
3198
                                                .error(
3199
                                                                Messages
3200
                                                                                .getString("Launcher.No_se_pudo_guardar_la_configuracion_de_andami"),
3201
                                                                e);
3202
                        } catch (ValidationException e) {
3203
                                logger
3204
                                                .error(
3205
                                                                Messages
3206
                                                                                .getString("Launcher.No_se_pudo_guardar_la_configuracion_de_andami"),
3207
                                                                e);
3208
                        } catch (IOException e) {
3209
                                logger
3210
                                                .error(
3211
                                                                Messages
3212
                                                                                .getString("Launcher.No_se_pudo_guardar_la_configuracion_de_andami"),
3213
                                                                e);
3214
                        }
3215
                }
3216

    
3217
                private void savePluginsProperties() {
3218
                        PluginsManager manager = PluginsLocator.getManager();
3219
                        List<PluginServices> plugins = manager.getPlugins();
3220
                        for (PluginServices plugin : plugins) {
3221
                                if (plugin != null) {
3222
                                        plugin.savePluginProperties();
3223
                                }
3224
                        }
3225
                }
3226

    
3227
                /**
3228
                 * Exectutes the terminate method for all the extensions, in the reverse
3229
                 * order they were initialized
3230
                 * 
3231
                 */
3232
                private void finalizeExtensions() {
3233
                        for (int i = extensions.size() - 1; i >= 0; i--) {
3234
                                org.gvsig.andami.plugins.IExtension extensionInstance = (org.gvsig.andami.plugins.IExtension) extensions
3235
                                                .get(i);
3236
                                String extensionName = "(unknow)";
3237
                                try {
3238
                                        extensionName = extensionInstance.getClass().getName();
3239
                                        extensionInstance.terminate();
3240
                                } catch (Exception ex) {
3241
                                        logger.error(MessageFormat.format(
3242
                                                        "There was an error extension ending {0}",
3243
                                                        extensionName), ex);
3244
                                }
3245
                        }
3246
                }
3247

    
3248
                private IUnsavedData[] getUnsavedData() throws Exception {
3249
                        List<IUnsavedData> unsavedDataList = new ArrayList<IUnsavedData>();
3250
                        IExtension exclusiveExtension = PluginServices
3251
                                        .getExclusiveUIExtension();
3252

    
3253
                        for (int i = extensions.size() - 1; i >= 0; i--) {
3254
                                org.gvsig.andami.plugins.IExtension extensionInstance = (org.gvsig.andami.plugins.IExtension) extensions
3255
                                                .get(i);
3256
                                IExtensionStatus status = null;
3257
                                if (exclusiveExtension != null) {
3258
                                        status = exclusiveExtension.getStatus(extensionInstance);
3259
                                } else {
3260
                                        status = extensionInstance.getStatus();
3261
                                }
3262
                                if (status != null) {
3263
                                        try {
3264
                                                if (status.hasUnsavedData()) {
3265
                                                        IUnsavedData[] array = status.getUnsavedData();
3266
                                                        for (int element = 0; element < array.length; element++) {
3267
                                                                unsavedDataList.add(array[element]);
3268
                                                        }
3269
                                                }
3270
                                        } catch (Exception e) {
3271
                                                logger.info("Error calling the hasUnsavedData method",
3272
                                                                new Exception());
3273
                                                int option = JOptionPane
3274
                                                                .showConfirmDialog(
3275
                                                                                frame,
3276
                                                                                Messages
3277
                                                                                                .getString("error_getting_unsaved_data"),
3278
                                                                                Messages.getString("MDIFrame.salir"),
3279
                                                                                JOptionPane.YES_NO_OPTION);
3280
                                                if (option == JOptionPane.NO_OPTION) {
3281
                                                        throw e;
3282
                                                }
3283
                                        }
3284
                                }
3285
                        }
3286
                        return unsavedDataList.toArray(new IUnsavedData[unsavedDataList
3287
                                        .size()]);
3288
                }
3289

    
3290
                public UnsavedDataPanel getUnsavedDataPanel() {
3291
                        if (panel == null) {
3292
                                panel = new UnsavedDataPanel(new IUnsavedData[0]);
3293
                        }
3294
                        return panel;
3295
                }
3296

    
3297
                /**
3298
                 * Checks if the extensions have some unsaved data, and shows a dialog
3299
                 * to allow saving it. This dialog also allows to don't exit Andami.
3300
                 * 
3301
                 * @return true if the user confirmed he wishes to exit, false otherwise
3302
                 * @throws Exception
3303
                 */
3304
                public int manageUnsavedData() throws Exception {
3305
                        IUnsavedData[] unsavedData = getUnsavedData();
3306

    
3307
                        // there was no unsaved data
3308
                        if (unsavedData.length == 0) {
3309
                                int option = JOptionPane
3310
                                                .showConfirmDialog(frame, Messages
3311
                                                                .getString("MDIFrame.quiere_salir"), Messages
3312
                                                                .getString("MDIFrame.salir"),
3313
                                                                JOptionPane.YES_NO_OPTION);
3314
                                return option;
3315
                        }
3316

    
3317
                        UnsavedDataPanel panel = getUnsavedDataPanel();
3318
                        panel.setUnsavedDataArray(unsavedData);
3319

    
3320
                        panel.addActionListener(panel.new UnsavedDataPanelListener() {
3321

    
3322
                                public void cancel(UnsavedDataPanel panel) {
3323
                                        proceed(false);
3324
                                        PluginServices.getMDIManager().closeWindow(panel);
3325

    
3326
                                }
3327

    
3328
                                public void discard(UnsavedDataPanel panel) {
3329
                                        proceed(true);
3330
                                        PluginServices.getMDIManager().closeWindow(panel);
3331

    
3332
                                }
3333

    
3334
                                public void accept(UnsavedDataPanel panel) {
3335
                                        IUnsavedData[] unsavedDataArray = panel
3336
                                                        .getSelectedsUnsavedData();
3337
                                        boolean saved;
3338
                                        for (int i = 0; i < unsavedDataArray.length; i++) {
3339
                                                try {
3340
                                                        saved = unsavedDataArray[i].saveData();
3341
                                                } catch (Exception ex) {
3342
                                                        PluginServices.getLogger().error(
3343
                                                                        "Error saving"
3344
                                                                                        + unsavedDataArray[i]
3345
                                                                                                        .getResourceName(), ex);
3346
                                                        saved = false;
3347
                                                }
3348
                                                if (!saved) {
3349
                                                        JOptionPane
3350
                                                                        .showMessageDialog(
3351
                                                                                        panel,
3352
                                                                                        PluginServices
3353
                                                                                                        .getText(this,
3354
                                                                                                                        "The_following_resource_could_not_be_saved_")
3355
                                                                                                        + "\n"
3356
                                                                                                        + unsavedDataArray[i]
3357
                                                                                                                        .getResourceName()
3358
                                                                                                        + " -- "
3359
                                                                                                        + unsavedDataArray[i]
3360
                                                                                                                        .getDescription(),
3361
                                                                                        PluginServices.getText(this,
3362
                                                                                                        "Resource_was_not_saved"),
3363
                                                                                        JOptionPane.ERROR_MESSAGE);
3364

    
3365
                                                        try {
3366
                                                                unsavedDataArray = getUnsavedData();
3367
                                                        } catch (Exception e) {
3368
                                                                // This exception has been registered before
3369
                                                        }
3370
                                                        panel.setUnsavedDataArray(unsavedDataArray);
3371
                                                        return;
3372
                                                }
3373
                                        }
3374
                                        proceed(true);
3375
                                        PluginServices.getMDIManager().closeWindow(panel);
3376
                                }
3377
                        });
3378

    
3379
                        PluginServices.getMDIManager().addWindow(panel);
3380
                        if (proceed) {
3381
                                return JOptionPane.YES_OPTION;
3382
                        } else {
3383
                                return JOptionPane.NO_OPTION;
3384
                        }
3385
                }
3386

    
3387
                private void proceed(boolean proceed) {
3388
                        this.proceed = proceed;
3389
                }
3390

    
3391
        }
3392

    
3393
        public static TerminationProcess getTerminationProcess() {
3394
                return (new Launcher()).new TerminationProcess();
3395
        }
3396

    
3397
        private PackageInfo getPackageInfo(String pluginsFolder) {
3398
                try {
3399
                    PluginsManager pm = PluginsLocator.getManager();
3400

    
3401
                        File packageInfoFile = new File(
3402
                            pm.getApplicationFolder(), "package.info");
3403
                        if (packageInfoFile.exists()) {
3404
                                InstallerManager installerManager = InstallerLocator.getInstallerManager();
3405
                                FileInputStream fis = new FileInputStream(packageInfoFile);
3406
                                PackageInfo packageInfo = installerManager.createPackageInfo(fis);
3407
                                return packageInfo;
3408
                        }
3409
                        return null;
3410
                } catch (Exception e) {
3411
                        logger.info("Can't locate PackageInfo from plugin org.gvsig.app",e);
3412
                        return null;
3413
                }
3414
        }
3415

    
3416
        /**
3417
         * Launch the gvSIG package installer.
3418
         * 
3419
         * @throws Exception
3420
         *             if there is any error
3421
         */
3422
        private void doInstall(String[] args) throws Exception {
3423
                String installURL = null;
3424
                String installURLFile = null;
3425
                String gvSIGVersion = null;
3426
                String[] myArgs = new String[3];
3427
                PackageInfo packageInfo = null; 
3428

    
3429
                Options options = new Options();
3430
                options.addOption("i", "install", false, "install");
3431
                options.addOption("u", "installURL", true, "installURL");
3432
                options.addOption("f", "installURLFile", true, "installURLFile");
3433
                options.addOption("v", "installVersion", true, "installVersion");
3434
                options.addOption("A", "applicationName", true, "applicationName");
3435
                options.addOption("P", "pluginsFolder", true, "pluginsFolder");
3436
                options.addOption("l", "language", true, "language");
3437

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

    
3495
                        if (!hasAllMandatoryOptions) {
3496
                                System.err
3497
                                                .println(Messages.get("usage")
3498
                                                                + ": Launcher --applicationName=appName --pluginsFolder=plugins-directory "
3499
                                                                + "[--installURLFile=File] "
3500
                                                                + "--install [--installURL=URL] [language=locale]");
3501
                                return;
3502
                        }
3503
                } catch (ParseException exp) {
3504
                        System.out.println("Unexpected exception:" + exp.getMessage());
3505
                }
3506

    
3507
                initializeApp(myArgs);
3508
                initializeLibraries();
3509
                AndamiConfig config = getAndamiConfig();
3510
                config.setLocaleLanguage(locale.getLanguage());
3511
                config.setLocaleCountry(locale.getCountry());
3512
                config.setLocaleVariant(locale.getVariant());
3513
                
3514
                InstallerManager installerManager = InstallerLocator.getInstallerManager();
3515
                
3516
                packageInfo = getPackageInfo(myArgs[1]);
3517
                
3518
                // set the gvSIG version to the install manager, to compose the download URL
3519
                if( packageInfo!=null ) {
3520
                        installerManager.setVersion(packageInfo.getVersion());
3521
                } else {
3522
                        installerManager.setVersion(gvSIGVersion);
3523
                }
3524
                if( !installURL.contains(";") &&
3525
                        !installURL.endsWith(InstallerManager.PACKAGE_EXTENSION) && 
3526
                        !installURL.endsWith(InstallerManager.PACKAGE_INDEX_EXTENSION) ) {
3527
                        if( packageInfo!=null && (packageInfo.getState().startsWith(InstallerManager.STATE.BETA) ||
3528
                                 packageInfo.getState().startsWith(InstallerManager.STATE.RC) ||
3529
                                 packageInfo.getState().equalsIgnoreCase(InstallerManager.STATE.FINAL)) ) {
3530
                                installURL = installURL + "dists/<%Version%>/builds/<%Build%>/packages.gvspki";                        
3531
                        }
3532
                }
3533
                // Configure default index download URL
3534
                SwingInstallerLocator.getSwingInstallerManager().setDefaultDownloadURL(installURL);
3535

    
3536
                SwingInstallerLocator.getSwingInstallerManager().setDefaultDownloadURL(new File(installURLFile));
3537

    
3538
                // Launch installer
3539
                PluginsManager manager = PluginsLocator.getManager();
3540

    
3541
                File defaultAddonsRepository = PluginsLocator.getManager()
3542
                                .getPluginsFolder();
3543
                installerManager.addLocalAddonRepository(defaultAddonsRepository);
3544
                installerManager
3545
                                .setDefaultLocalAddonRepository(defaultAddonsRepository);
3546

    
3547
                AbstractInstallPackageWizard installPackageWizard = SwingInstallerLocator
3548
                                .getSwingInstallerManager().createInstallPackageWizard(
3549
                                                manager.getApplicationFolder(),
3550
                                                manager.getInstallFolder());
3551
                installPackageWizard
3552
                                .setWizardActionListener(new InstallerWizardActionListener() {
3553

    
3554
                                        public void finish(InstallerWizardPanel installerWizard) {
3555
                                                System.exit(0);
3556
                                        }
3557

    
3558
                                        public void cancel(InstallerWizardPanel installerWizard) {
3559
                                                System.exit(0);
3560
                                        }
3561
                                });
3562

    
3563
                // the wizard will show the Typical or Advanced mode option.
3564
                installPackageWizard.setAskTypicalOrCustom(true);
3565
                // default packages will be selected.
3566
                installPackageWizard.setSelectDefaultPackages(true);
3567

    
3568

    
3569
                // 1. Create the frame.
3570
                JFrame frame = new JFrame(Messages.get("gvsig_package_installer"));
3571

    
3572
                // 2. What happens when the frame closes?
3573
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
3574
                Runtime.getRuntime().addShutdownHook(new Thread() {
3575

    
3576
                        @Override
3577
                        public void run() {
3578
                                getTerminationProcess().saveAndamiConfig();
3579
                        }
3580
                });
3581

    
3582
                // 3. Add the installer panel to the frame
3583
                frame.getContentPane().add(installPackageWizard, BorderLayout.CENTER);
3584

    
3585
                // 4. Size the frame and center on the screen
3586
                frame.pack();
3587
                frame.setLocationRelativeTo(null);
3588

    
3589
                // 5. Show it.
3590
                frame.setVisible(true);
3591
        }
3592

    
3593
        public static String getInformation() {
3594
                PluginsManager pluginmgr = PluginsLocator.getManager();
3595
                InstallerManager installmgr = InstallerLocator.getInstallerManager();
3596

    
3597
                StringWriter writer = new StringWriter();
3598

    
3599
                Properties props = System.getProperties();
3600

    
3601
                // OS information
3602
                String osName = props.getProperty("os.name");
3603
                writer.write("OS\n");
3604
                writer.write("    name   : " + osName + "\n");
3605
                writer.write("    arch   : " + props.get("os.arch") + "\n");
3606
                writer.write("    version: " + props.get("os.version") + "\n");
3607
                if (osName.startsWith("Linux")) {
3608
                        try {
3609
                                String[] command = { "lsb_release", "-a" };
3610
                                Process p = Runtime.getRuntime().exec(command);
3611
                                InputStream is = p.getInputStream();
3612
                                BufferedReader reader = new BufferedReader(
3613
                                                new InputStreamReader(is));
3614
                                String line;
3615
                                while ((line = reader.readLine()) != null) {
3616
                                        writer.write("    " + line + "\n");
3617
                                }
3618
                        } catch (Exception ex) {
3619
                                writer
3620
                                                .write("Can't get detailled os information (lsb_release -a).");
3621
                        }
3622
                }
3623

    
3624
                // JRE information
3625
                writer.write("JRE\n");
3626
                writer.write("    vendor : " + props.get("java.vendor") + "\n");
3627
                writer.write("    version: " + props.get("java.version") + "\n");
3628
                writer.write("    home   : " + props.get("java.home") + "\n");
3629

    
3630
                writer.write("HTTP Proxy\n");
3631
                writer.write("    http.proxyHost     : " + props.get("http.proxyHost")
3632
                                + "\n");
3633
                writer.write("    http.proxyPort     : " + props.get("http.proxyPort")
3634
                                + "\n");
3635
                writer.write("    http.proxyUserName : "
3636
                                + props.get("http.proxyUserName") + "\n");
3637
                writer.write("    http.proxyPassword : "
3638
                                + props.get("http.proxyPassword") + "\n");
3639

    
3640
                String skinName = "(unknow)";
3641
                try {
3642
                        skinName = MDIManagerFactory.getSkinExtension().getClassName();
3643
                } catch (Throwable e) {
3644
                        // Ignore
3645
                }
3646
                writer.write("Application\n");
3647
                writer.write("    locale language         : "
3648
                                + Launcher.getAndamiConfig().getLocaleLanguage() + "\n");
3649
                writer.write("    application forlder     : "
3650
                                + pluginmgr.getApplicationFolder() + "\n");
3651
                writer.write("    application home forlder: "
3652
                                + pluginmgr.getApplicationHomeFolder() + "\n");
3653
                writer.write("    install forlder         : "
3654
                                + pluginmgr.getInstallFolder() + "\n");
3655
                writer.write("    plugins forlder         : "
3656
                                + pluginmgr.getPluginsFolder() + "\n");
3657
                writer.write("    theme                   : "
3658
                                + Launcher.theme.getSource() + "\n");
3659
                writer.write("    Skin                    : " + skinName + "\n");
3660

    
3661
                try {
3662
                        PackageInfo[] pkgs = installmgr.getInstalledPackages(pluginmgr
3663
                                        .getPluginsFolder());
3664
                        writer.write("Installed packages\n");
3665
                        for (int i = 0; i < pkgs.length; i++) {
3666
                                writer.write("    ");
3667
                                writer.write(pkgs[i].toStringCompact());
3668
                                writer.write("\n");
3669
                        }
3670
                } catch (Throwable e) {
3671
                        writer.write("Can't get installed package information.");
3672
                }
3673
                return writer.toString();
3674
        }
3675

    
3676
        private void logger_info(String msg) {
3677
                String info[] = msg.split("\n");
3678
                for (int i = 0; i < info.length; i++) {
3679
                        logger.info(info[i]);
3680
                }
3681
        }
3682
        
3683
        private void saveEnvironInformation() {
3684
                PluginsManager manager = PluginsLocator.getManager();
3685
                File fout = new File( manager.getApplicationHomeFolder(), "gvSIG-environ.info");
3686
                try {
3687
                        FileUtils.write(fout, getInformation());
3688
                } catch (IOException e) {
3689
                        logger.info("Can't create '"+fout.getAbsolutePath()+"'");
3690
                }
3691
        }
3692

    
3693
}